"use client";

import { useEffect, useState } from "react";

type PromptEvent = Event & { prompt: () => Promise<void>; userChoice?: Promise<unknown> };

/**
 * Real, working PWA install trigger.
 * - Chrome/Edge/Android: captures `beforeinstallprompt` and calls prompt().
 * - iOS Safari: shows the manual "Add to Home Screen" instructions.
 * - Already installed: opens the app / shows a confirmation.
 */
export function InstallButton({ variant = "button" }: { variant?: "button" | "menu" | "page" }) {
  const [deferred, setDeferred] = useState<PromptEvent | null>(null);
  const [installed, setInstalled] = useState(false);
  const [showIos, setShowIos] = useState(false);

  useEffect(() => {
    const onPrompt = (event: Event) => {
      event.preventDefault();
      setDeferred(event as PromptEvent);
    };
    const onInstalled = () => {
      setInstalled(true);
      setDeferred(null);
    };
    window.addEventListener("beforeinstallprompt", onPrompt);
    window.addEventListener("appinstalled", onInstalled);
    if (window.matchMedia("(display-mode: standalone)").matches || (window.navigator as unknown as { standalone?: boolean }).standalone) {
      setInstalled(true);
    }
    return () => {
      window.removeEventListener("beforeinstallprompt", onPrompt);
      window.removeEventListener("appinstalled", onInstalled);
    };
  }, []);

  const install = async () => {
    if (deferred) {
      await deferred.prompt();
      setDeferred(null);
      return;
    }
    const isIos = /iphone|ipad|ipod/i.test(window.navigator.userAgent);
    if (isIos) {
      setShowIos(true);
      return;
    }
    setShowIos(true);
  };

  const label = installed ? "App installed" : "Install app";

  if (variant === "menu") {
    return (
      <>
        <button onClick={install} className="flex w-full items-center gap-4 rounded-lg px-3 py-2 text-sm hover:bg-surface">
          <span aria-hidden>📲</span>
          {label}
        </button>
        {showIos ? <IosHelp onClose={() => setShowIos(false)} /> : null}
      </>
    );
  }

  if (variant === "page") {
    return (
      <div className="space-y-4">
        <button
          onClick={install}
          disabled={installed}
          className="inline-flex items-center gap-2 rounded-full bg-brand px-6 py-3 font-semibold text-white transition hover:bg-brand-hover disabled:opacity-60"
        >
          📲 {installed ? "PlayTube is installed" : "Install PlayTube"}
        </button>
        {showIos || installed ? <IosHelp onClose={() => setShowIos(false)} embedded /> : null}
      </div>
    );
  }

  return (
    <>
      <button
        onClick={install}
        className="hidden items-center gap-2 rounded-full border border-line px-3 py-1.5 text-sm font-medium transition hover:bg-surface sm:inline-flex"
      >
        <span aria-hidden>📲</span>
        {installed ? "Installed" : "Install app"}
      </button>
      {showIos ? <IosHelp onClose={() => setShowIos(false)} /> : null}
    </>
  );
}

function IosHelp({ onClose, embedded }: { onClose: () => void; embedded?: boolean }) {
  const body = (
    <ol className="list-decimal space-y-2 pl-5 text-sm text-muted">
      <li>Open playtube in Safari (iOS) or Chrome / Edge (Android &amp; desktop).</li>
      <li>
        Tap the <strong>Share</strong> button (iOS) or the <strong>⋮ menu</strong> (Android/desktop).
      </li>
      <li>
        Choose <strong>Add to Home Screen</strong> / <strong>Install app</strong>.
      </li>
      <li>Launch PlayTube from your home screen — it runs full-screen and works offline.</li>
    </ol>
  );
  if (embedded) return body;
  return (
    <div className="fixed bottom-24 left-1/2 z-[130] w-[min(92vw,26rem)] -translate-x-1/2 rounded-2xl border border-line bg-bg-elevated p-4 shadow-2xl">
      <h3 className="mb-2 font-semibold">Add PlayTube to your home screen</h3>
      {body}
      <button onClick={onClose} className="mt-3 rounded-full bg-surface px-4 py-1.5 text-sm font-medium">
        Got it
      </button>
    </div>
  );
}
