// Deliberately minimal service worker: caches the offline fallback page
// and static assets, and falls back to it when a navigation fails while
// offline. This is NOT a full offline-first game-catalog cache (that would
// need a real caching/storage strategy for a growing, changing dataset —
// see README > Phase 2: PWA). What's here makes the site installable and
// gives a graceful offline state, which is what was actually needed for
// "PWA / installable / offline support" without overclaiming more.

const CACHE_NAME = 'gamesji-shell-v1';
const OFFLINE_URL = '/offline';
const PRECACHE_URLS = [OFFLINE_URL, '/manifest.json'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS)).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) => {
  if (event.request.mode !== 'navigate') return;

  event.respondWith(
    fetch(event.request).catch(() => caches.match(OFFLINE_URL).then((res) => res ?? Response.error())),
  );
});
