<template>
  <div class="min-h-screen bg-black text-white">
    <!-- Full Width Header -->
    <div class="h-[80px] md:h-[114px]">
      <div class="fixed z-50 w-full bg-black pt-[20px] pb-[20px] md:pt-[34px]">
        <div class="container">
          <header
            class="flex h-[40px] items-center justify-between rounded-full bg-[#ADFF5B] pr-[30px] pl-5 md:h-[60px] md:pr-[58px] md:pl-[41px]"
          >
            <router-link to="/" class="flex items-center gap-2">
              <!-- Desktop Logo -->
              <!--              <Logo :src="Logo" alt="Hi快VPN" class="hidden h-10 w-auto text-black md:block" />-->
              <!-- Mobile Logo -->
              <MobileLogo alt="Hi快VPN" class="block h-[22px] text-black md:h-[36px]" />
            </router-link>
            <RightText class="block h-[12px] text-black md:h-[24px]" />
          </header>
        </div>
      </div>
    </div>
    <div class="">
      <div class="w-full bg-black">
        <div class="m-auto w-[340px] pb-[10px] md:w-[760px]">
          <div
            class="pb-[15px] text-center text-xl font-[900] md:pt-[20px] md:pb-[30px] md:text-2xl"
          >
            请选择适用您情形的选项
          </div>
          <div class="flex items-center justify-between">
            <div
              class="w-1/2 rounded-full border-5 p-[6px] md:border-[10px] md:p-[10px]"
              :class="[activeIndex === 0 ? 'border-white' : 'border-black']"
              @click="changeActiveIndex(0)"
            >
              <Button
                class="h-[30px] w-full cursor-pointer rounded-full bg-[#ADFF5B] text-xs text-black hover:bg-[#ADFF5B]/90 md:h-[40px] md:text-xl"
              >
                我只有中国大陆Apple ID
              </Button>
            </div>
            <div
              class="w-1/2 rounded-full border-5 p-[6px] md:border-[10px] md:p-[10px]"
              :class="[activeIndex === 1 ? 'border-white' : 'border-black']"
              @click="changeActiveIndex(1)"
            >
              <Button
                class="h-[30px] w-full cursor-pointer rounded-full bg-[#ADFF5B] text-xs text-black hover:bg-[#ADFF5B]/90 md:h-[40px] md:text-xl"
              >
                我有海外Apple ID
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="m-auto w-[340px] md:w-[760px]">
      <Transition name="fade" mode="out-in">
        <!--  tab1    -->
        <div v-if="activeIndex === 0" key="tab1">
          <div class="pt-[15px] pb-[15px] text-center text-xl font-[900] md:pb-[39px] md:text-2xl">
            Hi快提供三种下载方式
          </div>
          <DownloadMethodList />
        </div>
        <!--  tab2    -->
        <div v-else-if="activeIndex === 1" key="tab2">
          <div
            class="mx-auto flex w-[237px] items-center justify-center pt-[34px] text-center text-xl font-[900] md:w-full md:gap-[18px] md:text-2xl"
          >
            <ChatIcon class="h-[60px] w-[50px]" />登录海外 Apple ID 后再点击下方下载按钮
          </div>
          <div class="mx-auto h-[101px] w-[247px] md:h-[202px] md:w-[494px]">
            <div
              @click="handleDownload('ios')"
              class="relative block h-full w-full cursor-pointer transition-transform active:scale-95"
            >
              <img src="./Group%20100.png" class="h-full w-full" alt="下载" />
              <!-- Loading Overlay -->
              <div
                v-if="isLoadingIos"
                class="absolute inset-0 flex items-center justify-center rounded-[20px] bg-black/40"
              >
                <div
                  class="h-8 w-8 animate-spin rounded-full border-4 border-[#ADFF5B] border-t-transparent md:h-12 md:w-12"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </div>

    <div class="container md:px-[92px]">
      <div class="pt-[56px] pb-[15px] text-center text-xl font-[900] md:text-2xl">
        常见问题与解答
      </div>
      <div class="px-[24px]">
        <FAQAccordion />
      </div>
    </div>

    <div class="container px-[92px] pt-[34px]">
      <div class="mx-auto w-[240px] text-center font-black text-[#757575] md:w-full md:text-xl">
        若您在下载过程中遇到任何问题，
        <br class="md:hidden" />
        点击右下角在线客服按钮，
        <br class="md:hidden" />
        会有专业客服帮您解决问题
      </div>
    </div>

    <div class="px-[18px] pt-[34px] pb-[calc(50px+env(safe-area-inset-bottom))]">
      <div class="pb-[15px] text-center text-xl font-[900] md:pb-[30px] md:text-3xl">
        其他客户端下载
      </div>
      <div class="flex justify-center gap-4">
        <template v-for="client in otherClients" :key="client.type">
          <div
            @click="handleDownload(client.type)"
            class="relative cursor-pointer transition-transform hover:brightness-110 active:scale-95"
          >
            <MacosIcon v-if="client.type === 'mac'" />
            <WindowsIcon v-if="client.type === 'window'" />
            <AndroidIcon v-if="client.type === 'android'" />

            <!-- Loading Overlay for Android -->
            <div
              v-if="client.type === 'android' && isLoadingAndroid"
              class="absolute inset-0 flex items-center justify-center rounded-lg bg-black/40"
            >
              <div
                class="h-6 w-6 animate-spin rounded-full border-2 border-[#ADFF5B] border-t-transparent"
              ></div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
// Help page logic
import MobileLogo from '@/pages/Home/mobile-logo.svg?component'
import RightText from './right-text.svg?component'
import ChatIcon from './Vector.svg?component'
import MacosIcon from './macos.svg?component'
import WindowsIcon from './windows.svg?component'
import AndroidIcon from './android.svg?component'
import request from '@/utils/request'
import { getAllQueryString } from '@/utils/url-utils.ts'
import { toast } from 'vue-sonner'

import DownloadMethodList from './DownloadMethodList/DownloadMethodList.vue'
import FAQAccordion from './FAQAccordion/index.vue'
import { Button } from '@/components/ui/button'

const handleDownload = async (key: string) => {
  const platformMap: Record<string, string> = {
    window: 'windows',
    mac: 'mac',
    android: 'android',
    ios: 'ios',
  }
  const platform = platformMap[key] || 'windows'
  const ic = getAllQueryString('ic') || sessionStorage.getItem('ic') || 'uSSfg1Y1vt'

  // 设备环境检测
  const ua = navigator.userAgent
  const isAndroidDevice = /Android/i.test(ua)
  const isIosDevice =
    /iPhone|iPod|iPad/i.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
  const isMobileDevice = isAndroidDevice || isIosDevice

  // 1. 安卓下载逻辑
  if (key === 'android') {
    if (isAndroidDevice) {
      isLoadingAndroid.value = true
      await triggerOpenInstall(ic)
      isLoadingAndroid.value = false
      return
    } else {
      window.open(
        'https://api.hifast.biz/v1/common/client/download/file/Hi%E5%BF%ABVPN-android-1.0.0.apk',
        '_blank',
      )
      return
    }
  }

  // 2. iOS/Mac 下载逻辑
  if (key === 'ios' || key === 'mac') {
    if (isMobileDevice) {
      if (key === 'ios') isLoadingIos.value = true
      await triggerOpenInstall(ic)
      isLoadingIos.value = false
      return
    } else {
      window.open(
        'https://apps.apple.com/us/app/hi%E5%BF%ABvpn/id6755683167?l=zh-Hans-CN',
        '_blank',
      )
      return
    }
  }

  // 3. 原有逻辑 (如 Windows)
  try {
    const res: any = await request.get('/api/v1/common/client/download', {
      invite_code: ic,
      platform: platform,
    })
    if (res.url) {
      window.open(res.url, '_blank')
    }
  } catch (error) {
    console.error('Download fetch failed', error)
  }
}

// 提取 OpenInstall 触发逻辑
const triggerOpenInstall = async (ic: string) => {
  if (!(window as any).OI_SDK?.isReady && (window as any).OI_SDK_PROMISE) {
    try {
      await Promise.race([
        (window as any).OI_SDK_PROMISE,
        new Promise((_, reject) => setTimeout(() => reject(new Error('OpenInstall timeout')), 3000)),
      ])
    } catch (e) {
      console.warn('OpenInstall readiness wait failed or timeout:', e)
    }
  }

  if ((window as any).OI_SDK && (window as any).OI_SDK.OI) {
    ;(window as any).OI_SDK.OI.wakeupOrInstall({ data: { platform: 'download', inviteCode: ic } })
  }
}

const activeIndex = ref(0)
const isLoadingIos = ref(false)
const isLoadingAndroid = ref(false)

const otherClients = computed(() => {
  return [
    { icon: WindowsIcon, type: 'window' },
    { icon: MacosIcon, type: 'mac' },
    { icon: AndroidIcon, type: 'android' },
  ]
})

function changeActiveIndex(index: number) {
  activeIndex.value = index
  window.scrollTo(0, 0)
}
</script>

<style scoped></style>
