/*
  pwa.js — Save Pet
  Registers the service worker, listens for updates (shows a small
  "New version available" banner instead of silently refreshing
  under the player), and wraps the native install prompt.
*/
window.SP = window.SP || {};

SP.PWA = (function () {
  "use strict";
  let deferredPrompt = null;
  let waitingWorker = null;

  function registerSW() {
    if (!("serviceWorker" in navigator)) return;
    window.addEventListener("load", function () {
      navigator.serviceWorker.register("./sw.js").then(function (reg) {
        reg.addEventListener("updatefound", function () {
          const nw = reg.installing;
          if (!nw) return;
          nw.addEventListener("statechange", function () {
            if (nw.state === "installed" && navigator.serviceWorker.controller) {
              waitingWorker = nw;
              if (SP.UI) SP.UI.showUpdateBanner();
            }
          });
        });
      }).catch(function (err) { console.warn("[SavePet] Service worker registration failed:", err); });

      let refreshing = false;
      navigator.serviceWorker.addEventListener("controllerchange", function () {
        if (refreshing) return;
        refreshing = true;
        window.location.reload();
      });
    });
  }

  function applyUpdate() {
    if (waitingWorker) waitingWorker.postMessage({ type: "SKIP_WAITING" });
    else window.location.reload();
  }

  function initInstallPrompt() {
    window.addEventListener("beforeinstallprompt", function (e) {
      e.preventDefault();
      deferredPrompt = e;
      if (SP.UI) SP.UI.showInstallBanner();
    });
    window.addEventListener("appinstalled", function () {
      deferredPrompt = null;
      if (SP.UI) SP.UI.hideInstallBanner();
      if (SP.Analytics) SP.Analytics.track("pwa_installed", {});
    });
  }

  function isStandalone() {
    try {
      return window.matchMedia("(display-mode: standalone)").matches || window.navigator.standalone === true;
    } catch (e) { return false; }
  }

  function isIOS() {
    return /iphone|ipad|ipod/i.test(navigator.userAgent || "") && !window.MSStream;
  }

  function promptInstall() {
    if (!deferredPrompt) {
      if (isIOS() && !isStandalone() && SP.UI) {
        SP.UI.showToast("On iPhone/iPad: tap Share \u2192 Add to Home Screen");
      }
      return;
    }
    deferredPrompt.prompt();
    deferredPrompt.userChoice.then(function () {
      deferredPrompt = null;
      if (SP.UI) SP.UI.hideInstallBanner();
    });
  }

  function init() {
    registerSW();
    initInstallPrompt();
    if (isIOS() && !isStandalone() && SP.UI) {
      setTimeout(function () { SP.UI.showInstallBanner(); }, 4000);
    }
  }

  return { init: init, promptInstall: promptInstall, applyUpdate: applyUpdate };
})();
