const CACHE_NAME = "pedidos-pwa-v1";
const BASE = "/lanchonete/public";

const APP_SHELL = [
  `${BASE}/app/index.php`,
  `${BASE}/app/offline.html`,
  `${BASE}/app/manifest.json`
];

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

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

self.addEventListener("fetch", (event) => {
  const req = event.request;
  if (req.method !== "GET") return;

  // navegação HTML: network-first + fallback offline
  if (req.mode === "navigate") {
    event.respondWith(
      fetch(req).catch(() => caches.match(`${BASE}/app/offline.html`))
    );
    return;
  }

  // demais: cache-first para shell, senão rede
  event.respondWith(
    caches.match(req).then((cached) => cached || fetch(req))
  );
});
