<template>
  <el-dropdown trigger="click" @command="handleLanguageChange" class="lang-select">
    <span class="el-dropdown-link">
      <!-- <el-icon><Global /></el-icon> -->
      {{ currentLangName }}
      <el-icon class="el-icon--right"><arrow-down /></el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="lang in langOptions"
          :key="lang.value"
          :command="lang.value"
          :disabled="currentLanguage === lang.value"
        >
          {{ lang.label }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const { locale, t } = useI18n()

// 语言选项配置
const langOptions = [
  { label: '简体中文', value: 'zh-CN' },
  // { label: '繁體中文', value: 'zh-TW' },
  { label: 'English', value: 'en-US' }
  // { label: '日本語', value: 'ja-JP' },
  // { label: '한국어', value: 'ko-KR' }
]

// 使用 ref 来管理当前语言，避免直接使用 i18n 的响应式对象
const currentLanguage = ref(locale.value)

// 计算当前显示的语言名称
const currentLangName = computed(() => {
  const currentLang = langOptions.find(lang => lang.value === currentLanguage.value)
  return currentLang ? currentLang.label : '简体中文'
})

// 处理语言切换
const handleLanguageChange = async lang => {
  try {
    // 更新当前语言
    currentLanguage.value = lang
    locale.value = lang
    localStorage.setItem('lang', lang)

    // 使用 setTimeout 避免在同一个 tick 中触发更新
    setTimeout(() => {
      ElMessage.success({
        message: t('common.languageChanged'),
        duration: 1500
      })
    }, 100)
  } catch (error) {
    console.error('Language change error:', error)
    ElMessage.error('语言切换失败')
  }
}
</script>

<style scoped>
.lang-select {
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 0 12px;
  height: 48px;
  color: var(--el-text-color-primary);
}

.lang-select:hover {
  background-color: var(--el-color-primary-light-9);
}

.el-icon {
  font-size: 18px;
  margin-right: 5px;
}
</style>
