/**
 * WKMSReact PWA service worker (Phase 78).
 *
 * This is the PWA-install service worker, distinct from the MV3 extension
 * background SW. It provides an offline app-shell cache so the installed PWA
 * launches without the network; live data still flows through the relay mesh
 * (NATS WSS) at runtime. Network-first for navigations (fresh shell when
 * online), cache-first for hashed static assets.
 */
const CACHE = "wkmsreact-shell-v1";
const SHELL = ["./src/sidepanel/index.html", "./manifest.webmanifest", "./icon-192.png", "./icon-512.png"];

self.addEventListener("install", (e) => {
  e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
});

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

self.addEventListener("fetch", (e) => {
  const req = e.request;
  if (req.method !== "GET") return;
  const url = new URL(req.url);
  // never cache the relay mesh / API calls
  if (url.protocol === "wss:" || url.pathname.startsWith("/api/")) return;

  if (req.mode === "navigate") {
    e.respondWith(
      fetch(req).then((res) => { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); return res; })
        .catch(() => caches.match("./src/sidepanel/index.html").then((r) => r || caches.match(req)))
    );
    return;
  }
  // hashed assets: cache-first
  e.respondWith(
    caches.match(req).then((hit) => hit || fetch(req).then((res) => {
      if (res.ok && (url.pathname.includes("/assets/") || url.pathname.endsWith(".png") || url.pathname.endsWith(".css"))) {
        const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy));
      }
      return res;
    }))
  );
});
