// ===== SWIFTPOS SERVICE WORKER – FINAL OFFLINE-PAGE VERSION =====

const CACHE_VERSION = "swiftpos-v9"; // bump version
const APP_CACHE = `${CACHE_VERSION}-app`;
const RUNTIME_CACHE = `${CACHE_VERSION}-runtime`;

const OFFLINE_PAGE = "/offline/";
const POS_PAGE = "/sales/pos/";

// Pre-cache all required shell assets
const APP_SHELL = [
  "/",
  OFFLINE_PAGE,
  "/accounts/login/",
  POS_PAGE,                // POS must load offline
  "/sales/pos/index.html", // HTML fallback for some servers

  // Static assets
  "/static/css/style.css",
  "/static/js/pwa.js",
  "/static/js/product-cache.js",
  "/static/js/pos-cart.js",
  "/static/js/order-sync.js",
  "/static/js/offline-queue.js",

  // PWA assets
  "/static/core/manifest.webmanifest",
  "/static/core/icons/icon-192.png",
  "/static/core/icons/icon-512.png",
];

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

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

// Helper functions
function isHTML(req) {
  return req.mode === "navigate" ||
    (req.headers.get("accept") || "").includes("text/html");
}

function isStatic(req) {
  return req.url.includes("/static/");
}

function isProductAPI(req) {
  return req.url.includes("/inventory/api/products");
}

// Fetch handler
self.addEventListener("fetch", (event) => {
  const req = event.request;

  if (req.method !== "GET") return;

  // HTML pages: cache-first with network update
  if (isHTML(req)) {
    event.respondWith(
      caches.match(req).then((cached) => {
        const networkFetch = fetch(req)
          .then((response) => {
            caches.open(APP_CACHE).then((cache) =>
              cache.put(req, response.clone())
            );
            return response;
          })
          .catch(() => cached || caches.match(OFFLINE_PAGE));

        return cached || networkFetch;
      })
    );
    return;
  }

  // Static assets
  if (isStatic(req)) {
    event.respondWith(
      caches.match(req).then((cached) => cached || fetch(req))
    );
    return;
  }

  // Product JSON API: SWR
  if (isProductAPI(req)) {
    event.respondWith(
      caches.match(req).then((cached) => {
        const fetchPromise = fetch(req)
          .then((response) => {
            caches.open(RUNTIME_CACHE).then((cache) =>
              cache.put(req, response.clone())
            );
            return response;
          })
          .catch(() => cached);

        return cached || fetchPromise;
      })
    );
    return;
  }

  // Default: try cache first
  event.respondWith(
    caches.match(req).then((cached) => cached || fetch(req))
  );
});

// Background sync
self.addEventListener("sync", (event) => {
  if (event.tag === "swiftpos-sync") {
    event.waitUntil(
      self.clients.matchAll().then((clients) => {
        clients.forEach((client) =>
          client.postMessage({ type: "SYNC_OFFLINE" })
        );
      })
    );
  }
});