// PWA install prompt UI. Two flows:
//   - Chromium / Android: catch beforeinstallprompt, defer it, and surface a
//     small dismissible banner that triggers .prompt() on user action.
//   - iOS Safari (which never fires beforeinstallprompt): one-time hint
//     showing the native share-sheet → "Zum Home-Bildschirm" instructions.
//
// Dismissals are persisted in localStorage so users don't see the banner on
// every visit. The same key is checked at the top of init() so opening a
// cached page after a dismissal stays clean.

const DISMISS_KEY = "paliad-install-dismissed";
const SHOWN_KEY = "paliad-install-ios-shown";
const SHOW_AFTER_MS = 1500;

type BeforeInstallPromptEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
};

let deferredPrompt: BeforeInstallPromptEvent | null = null;

export function initInstallPrompt(): void {
  if (localStorage.getItem(DISMISS_KEY) === "1") return;

  // The install prompt is part of the PWA mobile shell — same audience as
  // the BottomNav. On desktop, partners use the sidebar nav and don't want
  // an install banner overlapping their work area. Gate on the same 768px
  // breakpoint as global.css's mobile media queries.
  if (window.matchMedia("(min-width: 768px)").matches) return;

  // Skip when already running as an installed PWA.
  if (window.matchMedia("(display-mode: standalone)").matches) return;
  // Safari iOS exposes navigator.standalone for the same signal.
  if ((navigator as { standalone?: boolean }).standalone === true) return;

  window.addEventListener("beforeinstallprompt", (e) => {
    e.preventDefault();
    deferredPrompt = e as BeforeInstallPromptEvent;
    // Defer banner reveal so it never competes with the page's first paint.
    window.setTimeout(() => showAndroidBanner(), SHOW_AFTER_MS);
  });

  window.addEventListener("appinstalled", () => {
    deferredPrompt = null;
    persistDismissal();
    removeBanner();
  });

  if (isIOSSafari() && localStorage.getItem(SHOWN_KEY) !== "1") {
    window.setTimeout(() => showIOSHint(), SHOW_AFTER_MS);
  }
}

function isIOSSafari(): boolean {
  const ua = navigator.userAgent;
  const isIOS = /iPad|iPhone|iPod/.test(ua) ||
    (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
  if (!isIOS) return false;
  // Exclude Chrome/Firefox on iOS — they can't install PWAs and the share
  // sheet hint would be misleading.
  if (/CriOS|FxiOS|EdgiOS/.test(ua)) return false;
  return true;
}

function getLang(): "de" | "en" {
  const stored = localStorage.getItem("paliad-lang");
  if (stored === "de" || stored === "en") return stored;
  const html = document.documentElement.lang;
  return html === "en" ? "en" : "de";
}

function showAndroidBanner(): void {
  if (!deferredPrompt) return;
  if (document.getElementById("pwa-install-banner")) return;

  const lang = getLang();
  const banner = document.createElement("div");
  banner.id = "pwa-install-banner";
  banner.className = "pwa-install-banner";
  banner.setAttribute("role", "dialog");
  banner.setAttribute("aria-live", "polite");
  banner.innerHTML = `
    <div class="pwa-install-icon" aria-hidden="true">p</div>
    <div class="pwa-install-text">
      <div class="pwa-install-title">${lang === "en" ? "Install Paliad" : "Paliad installieren"}</div>
      <div class="pwa-install-sub">${lang === "en" ? "Add to your home screen for quick access." : "Zum Home-Bildschirm hinzufügen für schnellen Zugriff."}</div>
    </div>
    <button type="button" class="pwa-install-cta" id="pwa-install-cta">${lang === "en" ? "Install" : "Installieren"}</button>
    <button type="button" class="pwa-install-dismiss" id="pwa-install-dismiss" aria-label="${lang === "en" ? "Dismiss" : "Schließen"}">&times;</button>
  `;
  document.body.appendChild(banner);

  banner.querySelector<HTMLButtonElement>("#pwa-install-cta")?.addEventListener("click", async () => {
    if (!deferredPrompt) return;
    try {
      await deferredPrompt.prompt();
      const choice = await deferredPrompt.userChoice;
      if (choice.outcome === "accepted") {
        persistDismissal();
      }
    } finally {
      deferredPrompt = null;
      removeBanner();
    }
  });

  banner.querySelector<HTMLButtonElement>("#pwa-install-dismiss")?.addEventListener("click", () => {
    persistDismissal();
    removeBanner();
  });
}

function showIOSHint(): void {
  if (document.getElementById("pwa-install-banner")) return;

  const lang = getLang();
  const banner = document.createElement("div");
  banner.id = "pwa-install-banner";
  banner.className = "pwa-install-banner pwa-install-ios";
  banner.setAttribute("role", "dialog");
  banner.setAttribute("aria-live", "polite");
  const shareIcon =
    '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
    '<path d="M12 16V4"/><polyline points="7 9 12 4 17 9"/><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7"/></svg>';
  banner.innerHTML = `
    <div class="pwa-install-icon" aria-hidden="true">p</div>
    <div class="pwa-install-text">
      <div class="pwa-install-title">${lang === "en" ? "Install Paliad" : "Paliad installieren"}</div>
      <div class="pwa-install-sub">${lang === "en"
        ? "Tap <span class=\"pwa-install-share\">" + shareIcon + "</span> then “Add to Home Screen”."
        : "Tippen Sie auf <span class=\"pwa-install-share\">" + shareIcon + "</span> und dann auf „Zum Home-Bildschirm“."}</div>
    </div>
    <button type="button" class="pwa-install-dismiss" id="pwa-install-dismiss" aria-label="${lang === "en" ? "Dismiss" : "Schließen"}">&times;</button>
  `;
  document.body.appendChild(banner);

  banner.querySelector<HTMLButtonElement>("#pwa-install-dismiss")?.addEventListener("click", () => {
    localStorage.setItem(SHOWN_KEY, "1");
    removeBanner();
  });
}

function persistDismissal(): void {
  localStorage.setItem(DISMISS_KEY, "1");
  localStorage.setItem(SHOWN_KEY, "1");
}

function removeBanner(): void {
  document.getElementById("pwa-install-banner")?.remove();
}
