const CACHE = "wfw-aushang-2025.12.24.8";

const ASSETS = [
  "/zuss/",
  "/zuss/index.html",
  "/zuss/app.js",
  "/zuss/manifest.webmanifest",
  "/zuss/version.json",
  "/zuss/icons/icon-192.png",
  "/zuss/icons/icon-512.png"
];

self.addEventListener("install", (event) => {
  event.waitUntil((async () => {
    const cache = await caches.open(CACHE);
    await cache.addAll(ASSETS);
    self.skipWaiting();
  })());
});

self.addEventListener("activate", (event) => {
  event.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.map(k => (k === CACHE ? null : caches.delete(k))));
    self.clients.claim();
  })());
});

self.addEventListener("fetch", (event) => {
  const req = event.request;
  const url = new URL(req.url);

  // Network-first for version.json (so updates are found)
  if (url.pathname.endsWith("/zuss/version.json")) {
    event.respondWith((async () => {
      try {
        const fresh = await fetch(req, { cache: "no-store" });
        const cache = await caches.open(CACHE);
        cache.put(req, fresh.clone());
        return fresh;
      } catch {
        const cached = await caches.match(req);
        return cached || new Response('{"version":"2025.12.24.8"}', { headers: { "Content-Type": "application/json" } });
      }
    })());
    return;
  }

  // Cache-first for app shell
  if (url.pathname.startsWith("/zuss/")) {
    event.respondWith((async () => {
      const cached = await caches.match(req);
      if (cached) return cached;
      const fresh = await fetch(req);
      const cache = await caches.open(CACHE);
      cache.put(req, fresh.clone());
      return fresh;
    })());
    return;
  }
});
