// Pass-through service worker — does NOT cache responses (response caching is what
// made us disable the previous SW; assets must always come fresh from the network).
//
// Its only job: add the `ngrok-skip-browser-warning` header to top-level navigation
// requests, so ngrok's free-tier browser interstitial ("You are about to visit …")
// doesn't appear on repeat visits / PWA launches. ngrok skips the warning whenever
// that header is present (verified). The very first visit on a fresh browser still
// shows it once — the SW can't exist before that initial load — but ngrok's own
// cookie also suppresses it after a single "Visit Site" click.
self.addEventListener('install', () => self.skipWaiting());

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    // Drop any caches left behind by the old caching SW so nothing serves stale.
    const keys = await caches.keys();
    await Promise.all(keys.map((k) => caches.delete(k)));
    await self.clients.claim();
  })());
});

self.addEventListener('fetch', (event) => {
  const req = event.request;
  // Only top-level navigations trigger ngrok's interstitial. Leave everything else
  // (assets, /api, POST, WebSocket upgrades) completely untouched — no rewrite and
  // no caching — so behaviour is otherwise identical to having no SW at all.
  if (req.mode !== 'navigate') return;

  const headers = new Headers(req.headers);
  headers.set('ngrok-skip-browser-warning', 'true');
  event.respondWith(
    fetch(
      new Request(req.url, {
        method: 'GET',
        headers,
        credentials: req.credentials,
        redirect: 'manual',
      })
    ).catch(() => fetch(req))
  );
});
