const CACHE_NAME = 'gamesji-updates-v1';
const OFFLINE_URL = '/updates/offline.html';

const PRECACHE = [
  '/updates/index.php',
  '/updates/assets/css/style.css',
  '/updates/assets/js/app.js',
  '/updates/manifest.json',
  '/updates/assets/icons/icon.svg',
  OFFLINE_URL
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE)).then(() => self.skipWaiting())
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', (event) => {
  const req = event.request;
  if (req.method !== 'GET') return;

  // Static assets: cache-first
  if (req.destination === 'style' || req.destination === 'script' || req.destination === 'image' || req.destination === 'font') {
    event.respondWith(
      caches.match(req).then((cached) => cached || fetch(req).then((res) => {
        const clone = res.clone();
        caches.open(CACHE_NAME).then((c) => c.put(req, clone));
        return res;
      }).catch(() => cached))
    );
    return;
  }

  // Pages: network-first, fall back to cache, then offline page
  event.respondWith(
    fetch(req).then((res) => {
      const clone = res.clone();
      caches.open(CACHE_NAME).then((c) => c.put(req, clone));
      return res;
    }).catch(() =>
      caches.match(req).then((cached) => cached || caches.match(OFFLINE_URL))
    )
  );
});
