(function () {
  var CFG = window.paintopsPwaCfg || {};
  var SW_URL = CFG.swUrl;
  var PRECACHE_URL = CFG.precacheUrl;
  var SCOPE = CFG.scope;
  if (!SW_URL) { return; }

  // --- Offline banner -----------------------------------------------
  var banner = document.getElementById('paintops-offline-banner');
  function paintOffline() {
    if (!banner) return;
    if (navigator.onLine) { banner.classList.remove('is-visible'); }
    else { banner.classList.add('is-visible'); }
  }
  window.addEventListener('online', paintOffline);
  window.addEventListener('offline', paintOffline);
  paintOffline();

  // --- Service worker -----------------------------------------------
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register(SW_URL, { scope: SCOPE })
        .catch(function (err) {
          if (window.console && console.warn) {
            console.warn('[PaintOps] service worker registration failed', err);
          }
        });

      if (document.querySelector('.paintops-login-required')) {
        // Signed out on a shared device: clear cached job pages.
        navigator.serviceWorker.ready.then(function (reg) {
          if (reg && reg.active) {
            reg.active.postMessage({ type: 'paintops-clear-pages' });
          }
        }).catch(function () {});
      } else {
        // Logged in: pre-cache today's jobs once per session while online.
        paintopsPrecacheToday();
      }
    });
  }

  // --- Pre-cache today's scheduled jobs (tier 2) ---------------------
  function paintopsPrecacheToday() {
    if (!navigator.onLine) { return; }
    try { if (sessionStorage.getItem('paintops_precached') === '1') { return; } } catch (e) {}
    navigator.serviceWorker.ready.then(function (reg) {
      if (!reg || !reg.active) { return; }
      fetch(PRECACHE_URL, { credentials: 'same-origin' })
        .then(function (r) { return r.ok ? r.json() : null; })
        .then(function (data) {
          if (data && Array.isArray(data.urls) && data.urls.length) {
            reg.active.postMessage({ type: 'paintops-precache', urls: data.urls });
          }
          try { sessionStorage.setItem('paintops_precached', '1'); } catch (e) {}
        })
        .catch(function () {});
    }).catch(function () {});
  }

  // --- Install chip (Add to Home Screen) ----------------------------
  var chip = document.getElementById('paintops-install-chip');
  var deferredPrompt = null;
  // Remembered dismissal (restored 2026-07-22, the v1.0.106 fix was lost
  // in a later rewrite of this file): without this, the X only hid the
  // chip for the current page load and it came back on every navigation.
  // try/catch: localStorage can throw in private browsing.
  function chipDismissed() {
    try { return localStorage.getItem('paintops_install_dismissed') === '1'; } catch (err) { return false; }
  }
  window.addEventListener('beforeinstallprompt', function (e) {
    e.preventDefault();
    deferredPrompt = e;
    if (chip && !chipDismissed()) { chip.classList.add('is-visible'); }
  });
  if (chip) {
    chip.addEventListener('click', function (e) {
      // The little x dismisses the chip without prompting, and remembers.
      if (e.target && e.target.getAttribute('data-role') === 'dismiss') {
        try { localStorage.setItem('paintops_install_dismissed', '1'); } catch (err) {}
        chip.classList.remove('is-visible');
        return;
      }
      if (!deferredPrompt) { chip.classList.remove('is-visible'); return; }
      deferredPrompt.prompt();
      deferredPrompt.userChoice.finally(function () {
        deferredPrompt = null;
        chip.classList.remove('is-visible');
      });
    });
  }
  window.addEventListener('appinstalled', function () {
    if (chip) { chip.classList.remove('is-visible'); }
  });
})();
