"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Download, X } from "lucide-react";

interface BeforeInstallPromptEvent extends Event {
  prompt(): Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
}

export function InstallPrompt() {
  const [prompt, setPrompt] = useState<BeforeInstallPromptEvent | null>(null);
  const [dismissed, setDismissed] = useState(false);
  const [isIOS, setIsIOS] = useState(false);
  const [isStandalone, setIsStandalone] = useState(false);

  useEffect(() => {
    const standalone =
      window.matchMedia("(display-mode: standalone)").matches ||
      (navigator as Navigator & { standalone?: boolean }).standalone === true;
    setIsStandalone(standalone);

    const ios =
      /iphone|ipad|ipod/i.test(navigator.userAgent) &&
      !("MSStream" in window);
    setIsIOS(ios);

    const stored = sessionStorage.getItem("pwa-install-dismissed");
    if (stored) setDismissed(true);

    const handler = (e: Event) => {
      e.preventDefault();
      setPrompt(e as BeforeInstallPromptEvent);
    };
    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  function dismiss() {
    sessionStorage.setItem("pwa-install-dismissed", "1");
    setDismissed(true);
    setPrompt(null);
  }

  async function install() {
    if (!prompt) return;
    await prompt.prompt();
    const { outcome } = await prompt.userChoice;
    if (outcome === "accepted") setPrompt(null);
    else dismiss();
  }

  // Already installed or dismissed
  if (isStandalone || dismissed) return null;

  // Android/Chrome — native install prompt available
  if (prompt) {
    return (
      <div className="mx-4 mb-4 flex items-center gap-3 bg-blue-600 text-white px-4 py-3 rounded-xl shadow-lg">
        <div className="w-9 h-9 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
          <Download className="h-5 w-5" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold">Install ShotTrack</p>
          <p className="text-xs text-blue-100">Works offline, faster access</p>
        </div>
        <Button size="sm" variant="secondary" onClick={install} className="flex-shrink-0">
          Install
        </Button>
        <button onClick={dismiss} className="text-white/70 hover:text-white flex-shrink-0">
          <X className="h-4 w-4" />
        </button>
      </div>
    );
  }

  // iOS — manual instructions
  if (isIOS) {
    return (
      <div className="mx-4 mb-4 flex items-start gap-3 bg-slate-100 border border-slate-200 px-4 py-3 rounded-xl">
        <div className="w-9 h-9 bg-blue-50 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
          <Download className="h-5 w-5 text-blue-600" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-slate-900">Install ShotTrack</p>
          <p className="text-xs text-slate-500 mt-0.5">
            Tap <strong>Share</strong> then <strong>Add to Home Screen</strong>
          </p>
        </div>
        <button onClick={dismiss} className="text-slate-400 hover:text-slate-600 flex-shrink-0">
          <X className="h-4 w-4" />
        </button>
      </div>
    );
  }

  return null;
}
