import { useCallback, useEffect, useState } from "react";
import type { BeforeInstallPromptEvent } from "../types/pwa";

/**
 * Captures the beforeinstallprompt event and exposes install capability.
 * Also detects iOS devices where the native install prompt is unavailable.
 */
export function useInstallPrompt(): {
  canInstall: boolean;
  promptInstall: () => Promise<void>;
  isIOS: boolean;
} {
  const [deferredPrompt, setDeferredPrompt] =
    useState<BeforeInstallPromptEvent | null>(null);

  // Detect iOS Safari (excludes Chrome on iOS which uses CriOS)
  const isIOS =
    typeof navigator !== "undefined" &&
    /iPhone|iPad/.test(navigator.userAgent) &&
    !/CriOS/.test(navigator.userAgent);

  // Check if already installed (running in standalone mode)
  const isInstalled =
    typeof window !== "undefined" &&
    window.matchMedia("(display-mode: standalone)").matches;

  useEffect(() => {
    const handler = (e: BeforeInstallPromptEvent) => {
      e.preventDefault();
      setDeferredPrompt(e);
    };

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

  const promptInstall = useCallback(async () => {
    if (!deferredPrompt) return;
    await deferredPrompt.prompt();
    await deferredPrompt.userChoice;
    setDeferredPrompt(null);
  }, [deferredPrompt]);

  const canInstall = !!deferredPrompt && !isInstalled;

  return { canInstall, promptInstall, isIOS };
}
