(function () {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register('/sw.js').catch(function () {});
    });
  }

  var installButton = document.getElementById('pwaInstallButton');
  var deferredPrompt = null;
  var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
  if (isStandalone && installButton) installButton.classList.add('d-none');

  window.addEventListener('beforeinstallprompt', function (event) {
    if (isStandalone) return;
    event.preventDefault();
    deferredPrompt = event;
    if (installButton) installButton.classList.remove('d-none');
  });

  if (installButton) {
    installButton.addEventListener('click', function () {
      if (!deferredPrompt) return;
      deferredPrompt.prompt();
      deferredPrompt.userChoice.finally(function () {
        deferredPrompt = null;
        installButton.classList.add('d-none');
      });
    });
  }

  window.addEventListener('appinstalled', function () {
    if (installButton) installButton.classList.add('d-none');
  });
})();
