// static/js/pwa.js – FINAL VERSION

if ("serviceWorker" in navigator) {
  window.addEventListener("load", async () => {
    try {
      const reg = await navigator.serviceWorker.register("/static/service-worker.js");
      console.log("SwiftPOS SW Registered:", reg);

      if ("sync" in reg) {
        window.swiftposRegisterSync = () => reg.sync.register("swiftpos-sync");
      }
    } catch (err) {
      console.error("SW registration failed", err);
    }
  });
}

let deferredPrompt = null;

window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault();
  deferredPrompt = e;
  const btn = document.querySelector("[data-swiftpos-install]");
  if (btn) btn.classList.remove("d-none");
});

document.addEventListener("click", async (e) => {
  const btn = e.target.closest("[data-swiftpos-install]");
  if (!btn || !deferredPrompt) return;

  deferredPrompt.prompt();
  const res = await deferredPrompt.userChoice;
  console.log("Install choice:", res.outcome);

  deferredPrompt = null;
  btn.classList.add("d-none");
});

if ("serviceWorker" in navigator) {
  navigator.serviceWorker.addEventListener("message", (event) => {
    if (event.data?.type === "SYNC_OFFLINE") {
      if (window.swiftposSyncOrders) {
        window.swiftposSyncOrders();
      }
    }
  });
}