/**
 * ================================================================
 * NEOMORPH PLAYER – Service Worker (sw.js)
 * Mengaktifkan kemampuan offline & caching untuk PWA
 * ================================================================
 */

const CACHE_NAME = 'neumorphplayer-v1';
const CACHE_URLS = [
  './',
  './index.html',
  './style.css',
  './script.js',
  './login.html',
  './login.js',
  './admin.html',
  './admin.css',
  './admin.js',
  './manifest.json',
  './assets/images/icon-192.png',
  './assets/images/icon-512.png',
  'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
  'https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap'
];

/* ── Install: Simpan file ke cache ──────────────────── */
self.addEventListener('install', (event) => {
  console.log('[SW] Installing Service Worker...');
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      console.log('[SW] Caching app shell...');
      return cache.addAll(CACHE_URLS);
    }).catch((err) => {
      console.warn('[SW] Cache addAll error (beberapa URL mungkin tidak tersedia):', err);
    })
  );
  self.skipWaiting();
});

/* ── Activate: Hapus cache lama ─────────────────────── */
self.addEventListener('activate', (event) => {
  console.log('[SW] Activating Service Worker...');
  event.waitUntil(
    caches.keys().then((keyList) => {
      return Promise.all(
        keyList.map((key) => {
          if (key !== CACHE_NAME) {
            console.log('[SW] Removing old cache:', key);
            return caches.delete(key);
          }
        })
      );
    })
  );
  self.clients.claim();
});

/* ── Fetch: Strategi Cache-First, fallback ke Network ─ */
self.addEventListener('fetch', (event) => {
  // Lewati permintaan non-GET dan permintaan ke server lain
  if (event.request.method !== 'GET') return;
  if (event.request.url.includes('upload.php')) return;

  event.respondWith(
    caches.match(event.request).then((cachedResponse) => {
      if (cachedResponse) {
        return cachedResponse;
      }
      return fetch(event.request).then((networkResponse) => {
        // Simpan respons baru ke cache (hanya untuk file lokal)
        if (networkResponse && networkResponse.status === 200 &&
            event.request.url.startsWith(self.location.origin)) {
          const responseToCache = networkResponse.clone();
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, responseToCache);
          });
        }
        return networkResponse;
      });
    }).catch(() => {
      // Fallback ke index.html jika semua gagal
      return caches.match('./index.html');
    })
  );
});
