// Simple offline cache for kiosk usage
const CACHE = "wfw-aushang-2025.12.24.2";

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(
    caches.open(CACHE).then((c) => c.addAll(ASSETS)).then(() => 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))));
      await self.clients.claim();
    })()
  );
});

// Network-first for version.json + list, cache-first for static assets
self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);

  // Only handle same-origin requests
  if (url.origin !== self.location.origin) return;

  const isVersion = url.pathname.endsWith("/zuss/version.json");

  if (isVersion) {
    event.respondWith(
      fetch(event.request, { cache: "no-store" }).catch(() => caches.match(event.request))
    );
    return;
  }

  // Cache-first for our own static assets
  if (url.pathname.startsWith("/zuss/")) {
    event.respondWith(
      caches.match(event.request).then((cached) => {
        if (cached) return cached;
        return fetch(event.request).then((resp) => {
          const copy = resp.clone();
          caches.open(CACHE).then((c) => c.put(event.request, copy));
          return resp;
        });
      })
    );
  }
});
