const CACHE_NAME = "tmarket-pos-v5.8.20";
const APP_SHELL = [
  "/",
  "/Tmarket%20Cortes%209.5.html",
  "/manifest.webmanifest",
  "/tmarket-app.ico",
  "/tmarket-logo.jfif",
  "/tmarket-logo-watermark.jpg",
  "/customer-display.html",
  "/modules/ventas.js",
  "/modules/sections-v57.js",
  "/vendor/tesseract.min.js",
  "/vendor/xlsx.full.min.js",
  "/vendor/jspdf.umd.min.js",
  "/vendor/JsBarcode.all.min.js",
  "/vendor/lucide.min.js"
];

self.addEventListener("install", event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(APP_SHELL.map(path => new Request(path, { cache: "reload" }))))
      .then(() => self.skipWaiting())
      .catch(() => self.skipWaiting())
  );
});

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

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

  const url = new URL(request.url);
  if(url.origin !== self.location.origin) return;
  if(url.pathname.startsWith("/api/")) return;

  if(request.mode === "navigate") {
    event.respondWith(
      fetch(request)
        .then(response => {
          const copy = response.clone();
          caches.open(CACHE_NAME).then(cache => {
            cache.put("/", copy.clone());
            cache.put("/Tmarket%20Cortes%209.5.html", copy);
          });
          return response;
        })
        .catch(async () => {
          return (await caches.match(request)) ||
            (await caches.match("/")) ||
            (await caches.match("/Tmarket%20Cortes%209.5.html")) ||
            new Response("<!doctype html><meta charset=\"utf-8\"><title>T Market POS offline</title><body><h1>T Market POS</h1><p>Servidor no disponible. Abre de nuevo cuando regrese la red.</p></body>", {
              headers: { "Content-Type": "text/html; charset=utf-8" }
            });
        })
    );
    return;
  }

  event.respondWith(
    caches.match(request).then(cached => {
      if(cached) return cached;
      return fetch(request).then(response => {
        if(response && response.ok) {
          const copy = response.clone();
          caches.open(CACHE_NAME).then(cache => cache.put(request, copy));
        }
        return response;
      });
    })
  );
});
