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

// 全局状态，在模块加载时就创建
const deferredPrompt = ref<BeforeInstallPromptEvent | null>(null);
const canInstall = ref(false);
const isInstalled = ref(false);

// 检测是否是 iOS 设备
function isIOS() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
}

// 检测是否是 iOS Safari（未安装）
function isIOSSafari() {
  return isIOS() && !(window.navigator as any).standalone;
}

// 在模块加载时就设置监听器（不等待组件挂载）
if (typeof window !== "undefined") {
  // 检查是否已安装
  if (window.matchMedia("(display-mode: standalone)").matches) {
    isInstalled.value = true;
    console.log("[PWA] Already installed (standalone mode)");
  }
  else if ((window.navigator as any).standalone === true) {
    isInstalled.value = true;
    console.log("[PWA] Already installed (iOS standalone)");
  }
  else {
    // 监听安装提示事件（仅 Android/Chrome）
    window.addEventListener("beforeinstallprompt", (e: Event) => {
      console.log("[PWA] beforeinstallprompt event fired");
      e.preventDefault();
      deferredPrompt.value = e as BeforeInstallPromptEvent;
      canInstall.value = true;
    });

    // 监听安装成功事件
    window.addEventListener("appinstalled", () => {
      console.log("[PWA] App installed successfully");
      deferredPrompt.value = null;
      canInstall.value = false;
      isInstalled.value = true;
    });

    // iOS 设备也显示安装按钮（iOS 不支持 beforeinstallprompt）
    if (isIOSSafari()) {
      console.log("[PWA] iOS Safari detected, showing install button");
      canInstall.value = true;
    }
  }
}

export function usePWAInstall() {
  onMounted(() => {
    console.log("[PWA] usePWAInstall mounted");
    console.log("[PWA] canInstall:", canInstall.value);
    console.log("[PWA] isInstalled:", isInstalled.value);
  });

  async function install() {
    // iOS 设备返回特殊标识，由组件处理
    if (isIOSSafari()) {
      console.log("[PWA] iOS: Showing manual install guide");
      return { outcome: "ios-instruction" as const, success: false };
    }

    // Android/Chrome 设备
    if (!deferredPrompt.value) {
      console.log("[PWA] No deferred prompt available");
      return { outcome: "not-available" as const, success: false };
    }

    try {
      console.log("[PWA] Showing install prompt");
      await deferredPrompt.value.prompt();
      const { outcome } = await deferredPrompt.value.userChoice;
      console.log("[PWA] User choice:", outcome);

      if (outcome === "accepted") {
        canInstall.value = false;
        deferredPrompt.value = null;
        return { outcome, success: true };
      }

      return { outcome, success: false };
    }
    catch (error) {
      console.error("[PWA] Install failed:", error);
      return { outcome: "error" as const, success: false };
    }
  }

  return {
    canInstall,
    isInstalled,
    install,
    isIOS: isIOS(),
    isIOSSafari: isIOSSafari(),
  };
}
