const CACHE_NAME = "epicure-v1";
const SHELL_ASSETS = ["/", "/recipes", "/offline"];

self.addEventListener("install", event => {
  event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(SHELL_ASSETS)));
  self.skipWaiting();
});

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

self.addEventListener("fetch", event => {
  const { request } = event;
  if (request.method !== "GET") return;
  const url = new URL(request.url);
  // Skip API routes
  if (url.pathname.startsWith("/api/")) return;
  // Cache-first for cook mode pages
  if (url.pathname.includes("/cook")) {
    event.respondWith(
      caches.match(request).then(cached =>
        cached ??
        fetch(request).then(res => {
          const clone = res.clone();
          caches.open(CACHE_NAME).then(c => c.put(request, clone));
          return res;
        })
      )
    );
    return;
  }
  // Network-first for other pages
  event.respondWith(
    fetch(request).catch(() =>
      caches.match(request).then(cached => cached ?? caches.match("/offline"))
    )
  );
});
