<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { environmentUtils } from '@deotaland/utils'
import { ArrowRight, Refresh, CircleCheck, Location } from '@element-plus/icons-vue'
import LanguageToggle from '@/components/ui/LanguageToggle.vue'

const { t } = useI18n()
const router = useRouter()

const isDetecting = ref(true)
const environmentInfo = ref(null)
const redirectTimeout = ref(null)
const hasTimeout = ref(false)

const isDomestic = computed(() => {
  return environmentInfo.value?.isDomestic ?? false
})

const environmentText = computed(() => {
  return isDomestic.value ? t('kefuReduce.domestic') : t('kefuReduce.international')
})

const confidenceText = computed(() => {
  const confidence = environmentInfo.value?.confidence || 'unknown'
  const confidenceMap = {
    high: t('kefuReduce.confidenceLevels.high'),
    medium: t('kefuReduce.confidenceLevels.medium'),
    low: t('kefuReduce.confidenceLevels.low'),
    unknown: t('kefuReduce.confidenceLevels.unknown')
  }
  return confidenceMap[confidence] || confidenceMap.unknown
})

const methodsText = computed(() => {
  const methods = environmentInfo.value?.methods || {}
  const methodNames = []
  if (methods.ip) methodNames.push(t('kefuReduce.methodNames.ip'))
  if (methods.language) methodNames.push(t('kefuReduce.methodNames.language'))
  if (methods.timezone) methodNames.push(t('kefuReduce.methodNames.timezone'))
  return methodNames.join(t('kefuReduce.separator')) || '-'
})

const detectEnvironment = async () => {
  try {
    isDetecting.value = true
    hasTimeout.value = false
    
    const result = await environmentUtils.detectEnvironment({
      useCache: true,
      ipDetection: true,
      timeout: 5000
    })
    environmentInfo.value = result
    isDetecting.value = false
    if (result.isDomestic) {
      handleDomesticRedirect()
    } else {
      handleInternationalRedirect()
    }
    
    redirectTimeout.value = setTimeout(() => {
      hasTimeout.value = true
    }, 5000)
  } catch (error) {
    console.error('环境检测失败:', error)
    isDetecting.value = false
    hasTimeout.value = true
  }
}
const handleDomesticRedirect = () => {
window.location.href = 'https://discord.gg/Q2EaEGYW'
}
const handleInternationalRedirect = () => {
    window.location.href = 'https://discord.gg/Q2EaEGYW'
}
const handleRetry = () => {
  clearTimeout(redirectTimeout.value)
  hasTimeout.value = false
  detectEnvironment()
}

onMounted(() => {
  detectEnvironment()
})
</script>

<template>
  <div class="kefu-reduce-container">
    <div class="controls-wrapper">
      <LanguageToggle position="top-right" class="language-toggle-wrapper" />
      <!-- <ThemeToggle class="theme-toggle-wrapper" /> -->
    </div>
    <div class="kefu-reduce-card">
      <div class="header">
        <el-icon class="header-icon" :size="48">
          <Location />
        </el-icon>
        <h1 class="title">{{ t('kefuReduce.title') }}</h1>
        <p class="description">{{ t('kefuReduce.description') }}</p>
      </div>

      <div v-if="isDetecting" class="detecting-section">
        <el-icon class="loading-icon" :size="32">
          <Refresh class="is-loading" />
        </el-icon>
        <p class="detecting-text">{{ t('kefuReduce.detecting') }}</p>
      </div>

      <div v-else-if="environmentInfo" class="environment-section">
        <div class="environment-info">
          <div class="info-item">
            <span class="info-label">{{ t('kefuReduce.environmentInfo', { env: environmentText }) }}</span>
            <el-icon class="status-icon" :size="20" color="#10B981">
              <CircleCheck />
            </el-icon>
          </div>
          <div class="info-item">
            <span class="info-label">{{ t('kefuReduce.confidence', { level: confidenceText }) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">{{ t('kefuReduce.methods', { methods: methodsText }) }}</span>
          </div>
        </div>

        <div v-if="!hasTimeout" class="redirecting-section">
          <el-icon class="redirecting-icon" :size="24">
            <Refresh class="is-loading" />
          </el-icon>
          <p class="redirecting-text">{{ t('kefuReduce.redirecting') }}</p>
        </div>

        <div v-else class="manual-redirect-section">
          <p class="timeout-text">{{ t('kefuReduce.redirectTimeout') }}</p>
          <div class="redirect-buttons">
            <el-button 
              type="primary" 
              size="large"
              @click="handleDomesticRedirect"
              class="redirect-button"
            >
              {{ t('kefuReduce.domesticService') }}
              <el-icon class="button-icon">
                <ArrowRight />
              </el-icon>
            </el-button>
            <el-button 
              type="default" 
              size="large"
              @click="handleInternationalRedirect"
              class="redirect-button"
            >
              {{ t('kefuReduce.internationalService') }}
              <el-icon class="button-icon">
                <ArrowRight />
              </el-icon>
            </el-button>
          </div>
          <el-button 
            text 
            @click="handleRetry"
            class="retry-button"
          >
            <el-icon class="retry-icon">
              <Refresh />
            </el-icon>
            {{ t('kefuReduce.manualRedirect') }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.kefu-reduce-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
}

.language-toggle-wrapper {
  position: absolute;
  top: 24px;
  right: 24px;
  z-index: 1000;
}

.theme-toggle-wrapper {
  position: absolute;
  top: 24px;
  right: 90px;
  z-index: 1000;
}

.kefu-reduce-card {
  background: white;
  border-radius: 16px;
  padding: 48px;
  max-width: 500px;
  width: 100%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.5s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header-icon {
  color: #6B46C1;
  margin-bottom: 16px;
}

.title {
  font-size: 28px;
  font-weight: 700;
  color: #1F2937;
  margin: 0 0 12px 0;
  line-height: 1.2;
}

.description {
  font-size: 16px;
  color: #6B7280;
  margin: 0;
  line-height: 1.5;
}

.detecting-section {
  text-align: center;
  padding: 40px 0;
}

.loading-icon {
  color: #6B46C1;
  margin-bottom: 16px;
}

.loading-icon.is-loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.detecting-text {
  font-size: 16px;
  color: #6B7280;
  margin: 0;
}

.environment-section {
  padding: 20px 0;
}

.environment-info {
  background: #F3F4F6;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #E5E7EB;
}

.info-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.info-item:first-child {
  padding-top: 0;
}

.info-label {
  font-size: 14px;
  color: #4B5563;
  font-weight: 500;
}

.status-icon {
  flex-shrink: 0;
}

.redirecting-section {
  text-align: center;
  padding: 20px 0;
}

.redirecting-icon {
  color: #6B46C1;
  margin-bottom: 12px;
}

.redirecting-icon.is-loading {
  animation: rotate 1s linear infinite;
}

.redirecting-text {
  font-size: 16px;
  color: #6B7280;
  margin: 0;
}

.manual-redirect-section {
  text-align: center;
}

.timeout-text {
  font-size: 14px;
  color: #EF4444;
  margin-bottom: 20px;
}

.redirect-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
  align-items: center;
  justify-content: center;
}

.redirect-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
  margin-left: 0 !important;
}

.redirect-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(107, 70, 193, 0.4);
}

.button-icon {
  margin-left: 8px;
}

.retry-button {
  font-size: 14px;
  color: #6B46C1;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.retry-button:hover {
  background: #F3F4F6;
}

.retry-icon {
  margin-right: 6px;
}

@media (max-width: 768px) {
  .kefu-reduce-card {
    padding: 32px 24px;
    border-radius: 12px;
  }

  .language-toggle-wrapper {
    top: 16px;
    right: 16px;
  }

  .theme-toggle-wrapper {
    top: 16px;
    right: 70px;
  }

  .title {
    font-size: 24px;
  }

  .description {
    font-size: 14px;
  }

  .header-icon {
    font-size: 40px;
  }

  .info-label {
    font-size: 13px;
  }

  .redirect-button {
    height: 44px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .kefu-reduce-container {
    padding: 16px;
  }

  .language-toggle-wrapper {
    top: 12px;
    right: 12px;
  }

  .theme-toggle-wrapper {
    top: 12px;
    right: 60px;
  }

  .kefu-reduce-card {
    padding: 24px 20px;
  }

  .title {
    font-size: 22px;
  }

  .description {
    font-size: 13px;
  }

  .header-icon {
    font-size: 36px;
  }

  .detecting-section {
    padding: 32px 0;
  }

  .environment-info {
    padding: 16px;
  }

  .info-item {
    padding: 10px 0;
  }

  .info-label {
    font-size: 12px;
  }

  .redirect-button {
    height: 42px;
    font-size: 14px;
  }
}

@media (min-width: 768px) and (max-width: 1024px) {
  .kefu-reduce-card {
    padding: 40px 32px;
  }

  .redirect-buttons {
    flex-direction: row;
  }

  .redirect-button {
    flex: 1;
  }
}
</style>