import { useEffect, useRef, useState } from 'react';

/** 最小类型（TS lib 可能未包含） */
interface BeforeInstallPromptEvent extends Event {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
}

function isStandaloneMode() {
  return (
    window.matchMedia('(display-mode: standalone)').matches ||
    (window.navigator as Navigator & { standalone?: boolean }).standalone === true
  );
}

/** PWA 安装按钮：beforeinstallprompt / appinstalled */
export function useInstallPrompt(showToast: (msg: string, type?: 'success' | 'error') => void) {
  const [visible, setVisible] = useState(false);
  const deferredRef = useRef<BeforeInstallPromptEvent | null>(null);

  useEffect(() => {
    if (isStandaloneMode()) return;

    const onBeforeInstall = (e: Event) => {
      e.preventDefault();
      deferredRef.current = e as BeforeInstallPromptEvent;
      setVisible(true);
    };

    const onInstalled = () => {
      deferredRef.current = null;
      setVisible(false);
      showToast('应用安装成功');
    };

    window.addEventListener('beforeinstallprompt', onBeforeInstall);
    window.addEventListener('appinstalled', onInstalled);
    return () => {
      window.removeEventListener('beforeinstallprompt', onBeforeInstall);
      window.removeEventListener('appinstalled', onInstalled);
    };
  }, [showToast]);

  async function triggerInstall() {
    const ev = deferredRef.current;
    if (!ev) return;
    await ev.prompt();
    const choice = await ev.userChoice;
    if (choice.outcome === 'accepted') showToast('已触发安装流程');
    deferredRef.current = null;
    setVisible(false);
  }

  return { installVisible: visible, triggerInstall };
}
