<script lang='ts' setup>
import { alertController } from "@ionic/vue";
import IconParkOutlineApplication from "~icons/icon-park-outline/application";
import IconParkOutlineCheckOne from "~icons/icon-park-outline/check-one";
import IconParkOutlineDownload from "~icons/icon-park-outline/download";
import IconParkOutlinePhone from "~icons/icon-park-outline/phone";
import IconParkOutlineShare from "~icons/icon-park-outline/share";

const { t } = useI18n();
const { canInstall, isInstalled, install, isIOS, isIOSSafari } = usePWAInstall();
const platform = usePlatform();

const appName = "Riwsan 瑞讯";
const isLoading = ref(false);

// 调试日志
onMounted(() => {
  console.log("[Download Page] Mounted");
  console.log("[Download Page] platform:", platform);
  console.log("[Download Page] canInstall:", canInstall.value);
  console.log("[Download Page] isInstalled:", isInstalled.value);
  console.log("[Download Page] isIOS:", isIOS);
  console.log("[Download Page] isIOSSafari:", isIOSSafari);
});

// 检测用户是否卸载过应用
const wasUninstalled = computed(() => {
  const wasInstalled = localStorage.getItem("pwa-was-installed");
  return wasInstalled === "true" && !isInstalled.value;
});

// 显示下载按钮的条件
const shouldShowDownloadButton = computed(() => {
  const result = platform === "browser" && !isInstalled.value && (canInstall.value || isIOSSafari);
  console.log("[Download Page] shouldShowDownloadButton:", result);
  return result;
});

// 处理安装
async function handleInstall() {
  if (isIOSSafari) {
    const alert = await alertController.create({
      header: t("pwa.download.iosInstallHeader"),
      message: t("pwa.download.iosInstallMessage"),
      buttons: [t("pwa.download.iosInstallButton")],
    });
    await alert.present();
    return;
  }

  isLoading.value = true;
  try {
    const result = await install();

    if (result.success && result.outcome === "accepted") {
      localStorage.setItem("pwa-was-installed", "true");

      const alert = await alertController.create({
        header: t("pwa.download.installSuccessHeader"),
        message: t("pwa.download.installSuccessMessage"),
        buttons: [t("pwa.download.installSuccessButton")],
      });
      await alert.present();
    }
    else if (result.outcome === "ios-instruction") {
      const alert = await alertController.create({
        header: t("pwa.download.iosInstallHeader"),
        message: t("pwa.download.iosInstallMessage"),
        buttons: [t("pwa.download.iosInstallButton")],
      });
      await alert.present();
    }
  }
  catch (error) {
    console.error("Installation error:", error);
  }
  finally {
    isLoading.value = false;
  }
}

// 监听安装状态变化
watch(isInstalled, (installed) => {
  if (installed) {
    localStorage.setItem("pwa-was-installed", "true");
  }
});
</script>

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ion-title>{{ t("pwa.download.title") }}</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <div class="flex flex-col items-center min-h-full px-6 py-12">
        <!-- App Logo & Name -->
        <div class="flex flex-col items-center mb-8">
          <img alt="Riwsan 瑞讯" src="/favicon.svg" class="w-16 h-16">
          <h1 class="text-3xl font-bold mb-2">
            {{ appName }}
          </h1>
          <p class="text-text-500 text-center text-sm">
            {{ t("pwa.download.subtitle") }}
          </p>
        </div>

        <!-- 已安装状态 -->
        <div v-if="isInstalled && !wasUninstalled" class="w-full max-w-md">
          <div class="bg-success/10 border border-success/20 rounded-2xl p-6 text-center">
            <IconParkOutlineCheckOne class="text-5xl text-success mx-auto mb-4" />
            <h2 class="text-lg font-semibold text-success mb-2">
              {{ t("pwa.download.installed") }}
            </h2>
            <p class="text-sm text-text-500">
              {{ t("pwa.download.installedDesc") }}
            </p>
          </div>
        </div>

        <!-- iOS 安装指引 -->
        <div v-else-if="isIOSSafari || (platform === 'browser' && isIOS)" class="w-full max-w-md">
          <div class="bg-background-secondary rounded-2xl p-6 mb-6">
            <div class="flex items-center mb-4">
              <IconParkOutlinePhone class="text-2xl text-primary mr-3" />
              <h2 class="text-lg font-semibold">
                {{ t("pwa.download.iosInstallTitle") }}
              </h2>
            </div>

            <div class="space-y-4">
              <!-- Step 1 -->
              <div class="flex-center">
                <div class="w-8 h-8 rounded-full bg-text-900 text-text-300 flex items-center justify-center font-bold text-sm mr-3 shrink-0">
                  1
                </div>
                <div class="flex-1">
                  <p class="text-sm">
                    {{ t("pwa.download.iosStep1") }}
                    <IconParkOutlineShare class="inline-block text-primary mx-1" />
                    <strong>{{ t("pwa.download.iosStep1Button") }}</strong> 按钮
                  </p>
                </div>
              </div>

              <!-- Step 2 -->
              <div class="flex-center">
                <div class="w-8 h-8 rounded-full bg-text-900 text-text-300 flex items-center justify-center font-bold text-sm mr-3 shrink-0">
                  2
                </div>
                <div class="flex-1">
                  <p class="text-sm">
                    {{ t("pwa.download.iosStep2") }}
                    <strong>"{{ t("pwa.download.iosStep2Option") }}"</strong>
                  </p>
                </div>
              </div>

              <!-- Step 3 -->
              <div class="flex-center">
                <div class="w-8 h-8 rounded-full bg-text-900 text-text-300 flex items-center justify-center font-bold text-sm mr-3 shrink-0">
                  3
                </div>
                <div class="flex-1">
                  <p class="text-sm">
                    {{ t("pwa.download.iosStep3") }} <strong>"{{ t("pwa.download.iosStep3Button") }}"</strong> {{ t("pwa.download.iosStep3Complete") }}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <!-- 提示卡片 -->
          <div class="bg-warning/10 border border-warning/20 rounded-xl p-4 text-sm text-text-600">
            <p class="flex-center">
              <span class="mr-2">💡</span>
              <span>{{ t("pwa.download.iosTip") }}</span>
            </p>
          </div>
        </div>

        <!-- Android/Chrome 下载按钮 -->
        <div v-else-if="shouldShowDownloadButton" class="w-full max-w-md">
          <div class="bg-background-secondary rounded-2xl p-6 mb-6 text-center">
            <IconParkOutlineDownload class="text-5xl text-primary mx-auto mb-4" />
            <h2 class="text-xl font-semibold mb-2">
              {{ wasUninstalled ? t("pwa.download.reinstallButton") : t("pwa.download.installButton") }}
            </h2>
            <p class="text-sm text-text-500 mb-6">
              {{ wasUninstalled ? t("pwa.download.reinstallDesc") : t("pwa.download.installDesc") }}
            </p>

            <ion-button
              expand="block"
              size="large"
              class="font-semibold"
              :disabled="isLoading"
              @click="handleInstall"
            >
              <IconParkOutlineDownload v-if="!isLoading" class="mr-2" />
              <ion-spinner v-if="isLoading" name="crescent" class="mr-2" />
              {{ isLoading ? t("pwa.download.installing") : wasUninstalled ? t("pwa.download.reinstall") : t("pwa.download.install") }}
            </ion-button>
          </div>

          <!-- 优势列表 -->
          <div class="space-y-3">
            <div class="flex items-center text-sm">
              <div class="w-8 h-8 rounded-full bg-success/10 flex items-center justify-center mr-3">
                <IconParkOutlineCheckOne class="text-success" />
              </div>
              <span class="text-text-600">{{ t("pwa.download.advantage1") }}</span>
            </div>
            <div class="flex items-center text-sm">
              <div class="w-8 h-8 rounded-full bg-success/10 flex items-center justify-center mr-3">
                <IconParkOutlineCheckOne class="text-success" />
              </div>
              <span class="text-text-600">{{ t("pwa.download.advantage2") }}</span>
            </div>
            <div class="flex items-center text-sm">
              <div class="w-8 h-8 rounded-full bg-success/10 flex items-center justify-center mr-3">
                <IconParkOutlineCheckOne class="text-success" />
              </div>
              <span class="text-text-600">{{ t("pwa.download.advantage3") }}</span>
            </div>
          </div>
        </div>

        <!-- 原生应用提示 -->
        <div v-else-if="platform !== 'browser'" class="w-full max-w-md">
          <div class="bg-background-secondary rounded-2xl p-6 text-center">
            <IconParkOutlineCheckOne class="text-5xl text-success mx-auto mb-4" />
            <h2 class="text-lg font-semibold mb-2">
              {{ t("pwa.download.nativeAppTitle") }}
            </h2>
            <p class="text-sm text-text-500">
              {{ t("pwa.download.nativeAppDesc") }}
            </p>
          </div>
        </div>

        <!-- 浏览器不支持提示 -->
        <div v-else class="w-full max-w-md">
          <div class="bg-warning/10 border border-warning/20 rounded-2xl p-6 text-center">
            <p class="text-sm text-text-600">
              {{ t("pwa.download.notSupportedTitle") }}
            </p>
            <p class="text-xs text-text-500 mt-2">
              {{ t("pwa.download.notSupportedDesc") }}
            </p>
          </div>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
ion-content {
  --background: var(--ion-background-color);
}
</style>
