/* TTS Voice Creator — network-first service worker.
   Always tries the network first (so live edits/new versions show immediately) and
   only falls back to cache when offline. Never touches the API or cross-origin
   requests, so it can't serve stale data or break audio/streaming. */
const CACHE = 'tts-vc-v1';

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

self.addEventListener('activate', (e) => {
  e.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)));
    await self.clients.claim();
  })());
});

self.addEventListener('fetch', (e) => {
  const req = e.request;
  if (req.method !== 'GET') return;
  const url = new URL(req.url);
  if (url.origin !== self.location.origin) return;   // ignore CDN / cross-origin
  if (url.pathname.startsWith('/api/')) return;       // never cache the API
  e.respondWith((async () => {
    try {
      const net = await fetch(req);
      // Cache only successful static shell assets for offline fallback
      if (net && net.ok && (url.pathname === '/' || url.pathname.startsWith('/static/'))) {
        const c = await caches.open(CACHE);
        c.put(req, net.clone());
      }
      return net;
    } catch (err) {
      const cached = await caches.match(req);
      if (cached) return cached;
      throw err;
    }
  })());
});
