(() => {
  "use strict";

  const TICKET_PATTERN = /^[A-Za-z0-9_-]{40,128}$/;
  const ANDROID_INSTALL_URL = "__ANDROID_INSTALL_URL__";
  const message = document.querySelector("#handoff-message");
  const openButton = document.querySelector("#open-app");
  const installLink = document.querySelector("#install-app");
  const invalidLink = document.querySelector("#invalid-link");
  const isAndroid = /Android/i.test(navigator.userAgent);
  const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);

  const parameters = new URLSearchParams(location.hash.slice(1));
  const ticket = parameters.get("handoff") || "";
  history.replaceState(null, "", `${location.pathname}${location.search}`);

  const valid = TICKET_PATTERN.test(ticket);
  const appUrl = valid ? `htportal-vpn://connect#handoff=${encodeURIComponent(ticket)}` : "";
  if (isAndroid && !ANDROID_INSTALL_URL.startsWith("__")) {
    installLink.href = ANDROID_INSTALL_URL;
    installLink.rel = "noopener noreferrer";
  }

  function showInvalid() {
    message.textContent = "Non posso aprire questa richiesta VPN.";
    invalidLink.hidden = false;
    openButton.hidden = true;
  }

  function openApp() {
    if (!valid) {
      showInvalid();
      return;
    }
    message.textContent = "Passaggio della richiesta all'app...";
    location.assign(appUrl);
    window.setTimeout(() => {
      message.textContent = isIOS
        ? "HT Portal VPN per iOS è al momento disponibile solo in distribuzione interna."
        : "Se l'app non si è aperta, installala oppure riprova.";
      if (isAndroid && !ANDROID_INSTALL_URL.startsWith("__")) installLink.hidden = false;
    }, 1_200);
  }

  openButton.addEventListener("click", openApp);
  if (!valid) showInvalid();
  else window.setTimeout(openApp, 120);
})();
