(function () {
  let installPrompt = null;

  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => {
      navigator.serviceWorker.register("/service-worker.js").catch(() => {
        /* Service workers are progressive enhancement here. */
      });
    });
  }

  window.addEventListener("beforeinstallprompt", (event) => {
    const button = document.querySelector("[data-install-pwa]");
    if (!button) {
      return;
    }
    event.preventDefault();
    installPrompt = event;
    button.hidden = false;
    button.addEventListener("click", async () => {
      if (!installPrompt) {
        return;
      }
      button.disabled = true;
      try {
        await installPrompt.prompt();
        await installPrompt.userChoice;
      } finally {
        installPrompt = null;
        button.hidden = true;
        button.disabled = false;
      }
    }, { once: true });
  });

  window.addEventListener("appinstalled", () => {
    const button = document.querySelector("[data-install-pwa]");
    if (button) {
      button.hidden = true;
    }
    installPrompt = null;
  });
})();
