const CACHE_NAME = 'oi-overlay-v1';

function isCacheable(url) {
  const { pathname } = new URL(url);
  return pathname === '/overlay.html'
    || pathname.startsWith('/assets/')
    || /\.(png|svg|woff2?)$/.test(pathname);
}

self.addEventListener('install', () => self.skipWaiting());

self.addEventListener('activate', (event) => {
  event.waitUntil(
    Promise.all([
      clients.claim(),
      // Remove old cache versions on update
      caches.keys().then(keys =>
        Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
      ),
    ])
  );
});

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

  event.respondWith(
    caches.open(CACHE_NAME).then(async (cache) => {
      try {
        const response = await fetch(event.request);
        if (response.ok) cache.put(event.request, response.clone());
        return response;
      } catch {
        const cached = await cache.match(event.request);
        if (cached) return cached;
        return new Response('Overlay offline — server not running', { status: 503 });
      }
    })
  );
});
