/**
 * register-sw.js
 * Inventory Counter — Service Worker registration
 * Injected as <script defer> from every page via templates/footer.php
 */
(function registerServiceWorker() {
  if (!('serviceWorker' in navigator)) {
    console.info('[PWARegister] Service Worker not supported in this browser.');
    return;
  }

  const SW_URL = '/invcount/assets/js/sw.js';

  navigator.serviceWorker
    .register(SW_URL, { scope: '/invcount/' })
    .then(registration => {
      console.info('[PWARegister] Service Worker registered.', {
        scriptURL:   registration.scriptURL,
        scope:       registration.scope,
        state:       registration.active?.state ?? 'unknown',
      });

      registration.addEventListener('updatefound', () => {
        const installing = registration.installing;
        console.info('[PWARegister] SW update in progress; installing =', installing);

        installing.addEventListener('statechange', () => {
          if (installing.state === 'installed' && navigator.serviceWorker.controller) {
            console.info('[SW] New version ready. Page will reload when activated.');
            // An in-app banner could be surfaced here instead of auto-reload
          }
        });
      });

      // Reload the page when a new SW takes over lifecycle
      navigator.serviceWorker.addEventListener('controllerchange', () => {
        console.info('[PWARegister] New SW controller active — reloading.');
        window.location.reload();
      });
    })
    .catch(error => {
      console.error('[PWARegister] Service Worker registration failed:', error);
    });
})();
