<template>
  <div class="flex w-full flex-col items-center justify-center md:justify-start">
    <!-- 主下载按钮 -->
    <div
      class="relative mx-auto flex h-[60px] w-[210px] items-center justify-center overflow-hidden rounded-full bg-[#ADFF5B] px-[16px] md:mb-4 md:ml-0 md:h-[83px] md:w-[300px] md:px-[24px]"
    >
      <router-link
        v-if="mainButton?.link && !mainButton.link.startsWith('http')"
        :to="mainButton.link"
        class="flex h-full w-full items-center justify-center transition-transform hover:brightness-110 active:scale-95"
      >
        <component
          :is="mainButton.mainIcon"
          class="h-auto w-full text-black transition-transform"
        />
      </router-link>
      <a
        v-else-if="mainButton?.link"
        :href="mainButton.link"
        target="_blank"
        :aria-label="mainButton.label"
        class="flex h-full w-full items-center justify-center transition-transform hover:brightness-110 active:scale-95"
      >
        <component
          :is="mainButton.mainIcon"
          class="h-auto w-full text-black transition-transform"
        />
      </a>
      <div
        v-else
        :id="mainButton?.id"
        :aria-label="mainButton?.label"
        @click="handleDownload(mainButton.key)"
        class="flex h-full w-full cursor-pointer items-center justify-center transition-transform hover:brightness-110 active:scale-95"
      >
        <component
          :is="mainButton?.mainIcon"
          class="h-auto w-full text-black transition-transform"
        />
      </div>
    </div>

    <!-- 其他版本下载 -->
    <div class="mt-2 w-full">
      <div class="mb-3 text-center md:text-left">
        <span class="text-xs whitespace-nowrap md:text-sm">其他版本下载</span>
      </div>

      <div class="flex items-center justify-center gap-4 md:justify-start">
        <template v-for="(item, index) in otherButtons" :key="index">
          <router-link
            v-if="item.link && !item.link.startsWith('http')"
            :to="item.link"
            class="transition-transform hover:brightness-110 active:scale-95"
          >
            <component :is="item.secondaryIcon" class="h-[24px] text-white md:h-[34px]" />
          </router-link>
          <a
            v-else-if="item.link"
            :href="item.link"
            target="_blank"
            :aria-label="item.label"
            class="transition-transform hover:brightness-110 active:scale-95"
          >
            <component :is="item.secondaryIcon" class="h-[24px] text-white md:h-[34px]" />
          </a>
          <div
            v-else
            :id="item.id"
            :aria-label="item.label"
            @click="handleDownload(item.key)"
            class="cursor-pointer transition-transform hover:brightness-110 active:scale-95"
          >
            <component :is="item.secondaryIcon" class="h-[24px] text-white md:h-[34px]" />
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Icon1 from './Group 105.svg?component'
import Icon2 from './Group 106.svg?component'
import Icon3 from './Group 107.svg?component'
import Icon4 from './Group 108.svg?component'
import WinIcon from './WinIcon.svg?component'
import MacIcon from './MacIcon.svg?component'
import AppleIcon from './AppleIcon.svg?component'
import AndroidIcon from './AndroidIcon.svg?component'

import request from '@/utils/request'
import { computed, ref, onMounted } from 'vue'
import { getAllQueryString } from '@/utils/url-utils.ts'

const currentPlatform = ref('win')

onMounted(() => {
  const ua = navigator.userAgent
  const platform = navigator.platform || '' // 辅助判断

  // 1. 先判断 Android (通常比较稳定)
  if (/Android/i.test(ua)) {
    currentPlatform.value = 'android'
  }
  // 2. 判断 iOS 设备 (iPhone, iPod)
  else if (/iPhone|iPod/i.test(ua)) {
    currentPlatform.value = 'ios'
  }
  // 3. 核心改进：区分 Mac 和 iPad
  else if (/Macintosh|Mac OS X/i.test(ua)) {
    // iPadOS 桌面模式下，支持多点触控（通常 > 1）
    // 而真正的 Mac 电脑通常 maxTouchPoints 为 0 或 undefined
    if (navigator.maxTouchPoints > 1) {
      currentPlatform.value = 'ios' // 归类为 iOS 端（iPad）
    } else {
      currentPlatform.value = 'mac'
    }
  }
  // 4. 其他情况默认为 Windows
  else {
    currentPlatform.value = 'win'
  }

  console.log('Detected Platform:', currentPlatform.value)
})

// request.get('/api/v1/common/client/download', {
//   invite_code: getAllQueryString('ic'),
//   platform: 'mac',
// }).then((res: any) => {
//   downLoadMac.value = res.url
// })

const downLoadWin = ref('')

const handleDownload = async (key: string) => {
  const platformMap: Record<string, string> = {
    win: '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) {
      await triggerOpenInstall(ic)
      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) {
      await triggerOpenInstall(ic)
      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) {
      if (key === 'win') {
        downLoadWin.value = 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 allDownloadOptions = computed(() => [
  {
    key: 'win',
    mainIcon: Icon1,
    secondaryIcon: WinIcon,
    link: downLoadWin.value,
    label: 'Windows',
    id: 'downloadButton_win',
  },
  {
    key: 'mac',
    mainIcon: Icon3,
    secondaryIcon: MacIcon,
    link: '/help',
    label: 'macOS',
  },
  {
    key: 'ios',
    mainIcon: Icon2,
    secondaryIcon: AppleIcon,
    link: '/help',
    label: 'iOS',
  },
  {
    key: 'android',
    mainIcon: Icon4,
    secondaryIcon: AndroidIcon,
    label: 'Android',
    id: 'downloadButton_android',
  },
])

const mainButton = computed(() => {
  const platform = currentPlatform.value
  return allDownloadOptions.value.find((opt) => opt.key === platform) || allDownloadOptions.value[0]
})

const otherButtons = computed(() => {
  return allDownloadOptions.value.filter((opt) => opt.key !== currentPlatform.value)
})
</script>
