"use client";

import { useEffect, useState } from "react";

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

function isIOS() {
  if (typeof navigator === "undefined") return false;
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as unknown as Record<string, unknown>).MSStream;
}

function isStandalone() {
  if (typeof window === "undefined") return false;
  return window.matchMedia("(display-mode: standalone)").matches
    || (navigator as unknown as Record<string, boolean>).standalone === true;
}

export default function PwaInstallPrompt() {
  const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
  const [showBanner, setShowBanner] = useState(false);
  const [isApple, setIsApple] = useState(false);

  useEffect(() => {
    // SW registration moved to <ServiceWorkerRegistrar /> mounted in
    // layout.tsx unconditionally. This component now only handles the
    // beforeinstallprompt UX, which can stay gated behind age-verify.

    // Already installed or dismissed
    if (isStandalone()) return;
    if (localStorage.getItem("pwa-dismissed")) return;

    // iOS: show manual instructions after 3 seconds
    if (isIOS()) {
      setIsApple(true);
      setTimeout(() => setShowBanner(true), 3000);
      return;
    }

    // Chrome/Edge: capture install prompt
    const handler = (e: Event) => {
      e.preventDefault();
      setDeferredPrompt(e as BeforeInstallPromptEvent);
      setTimeout(() => setShowBanner(true), 3000);
    };

    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  async function handleInstall() {
    if (deferredPrompt) {
      deferredPrompt.prompt();
      const { outcome } = await deferredPrompt.userChoice;
      if (outcome === "accepted") setShowBanner(false);
      setDeferredPrompt(null);
    }
  }

  function handleDismiss() {
    setShowBanner(false);
    localStorage.setItem("pwa-dismissed", "1");
  }

  if (!showBanner) return null;

  return (
    <div className="fixed bottom-4 left-4 right-4 z-[9997] sm:left-auto sm:right-4 sm:max-w-sm"
      style={{ animation: "slideUp 0.3s ease-out" }}>
      <style>{`@keyframes slideUp { from { transform: translateY(100px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }`}</style>
      <div className="bg-zinc-900 border border-zinc-700 rounded-2xl p-4 shadow-2xl">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 rounded-xl bg-red-600 flex items-center justify-center shrink-0">
            <span className="text-white font-bold text-lg">AW</span>
          </div>
          <div className="flex-1 min-w-0">
            <p className="font-semibold text-white text-sm">Install AdultWorld</p>
            <p className="text-zinc-400 text-xs">
              {isApple ? "Add to your home screen for the best experience" : "Get quick access from your home screen"}
            </p>
          </div>
        </div>
        {isApple ? (
          <div className="mt-3 bg-zinc-800 rounded-lg p-3 text-xs text-zinc-400">
            Tap the <span className="text-white font-medium">Share</span> button
            <span className="mx-1">↗</span> then select
            <span className="text-white font-medium"> Add to Home Screen</span>
          </div>
        ) : null}
        <div className="flex gap-2 mt-3 justify-end">
          <button
            onClick={handleDismiss}
            className="text-zinc-500 hover:text-zinc-300 text-xs px-3 py-1.5"
          >
            Not now
          </button>
          {!isApple && (
            <button
              onClick={handleInstall}
              className="bg-red-600 hover:bg-red-700 text-white text-xs font-medium px-4 py-1.5 rounded-lg transition-colors"
            >
              Install App
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
