<template>
  <div class="relative">
    <button 
      @click="toggleDropdown" 
      class="flex items-center text-white/85 hover:text-secondary transition-colors duration-300"
    >
      <span class="mr-1">{{ currentLocale === 'zh' ? 'EN' : '中' }}</span>
      <i class="fas fa-chevron-down text-xs"></i>
    </button>
    
    <div 
      v-if="dropdownOpen" 
      class="absolute right-0 mt-2 bg-white rounded-md shadow-lg py-1 min-w-[100px] z-50"
    >
      <button 
        @click="changeLocale('zh')" 
        class="block w-full text-left px-4 py-2 text-gray-800 hover:bg-gray-100"
        :class="{ 'bg-gray-100': currentLocale === 'zh' }"
      >
        中文
      </button>
      <button 
        @click="changeLocale('en')" 
        class="block w-full text-left px-4 py-2 text-gray-800 hover:bg-gray-100"
        :class="{ 'bg-gray-100': currentLocale === 'en' }"
      >
        English
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();
const dropdownOpen = ref(false);

const currentLocale = computed(() => i18n.locale.value);

const toggleDropdown = () => {
  dropdownOpen.value = !dropdownOpen.value;
};

const changeLocale = (locale: string) => {
  i18n.locale.value = locale;
  dropdownOpen.value = false;
  // 保存用户语言偏好到本地存储
  localStorage.setItem('user-locale', locale);
};

// 点击其他地方关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (!target.closest('.relative')) {
    dropdownOpen.value = false;
  }
};

// 从本地存储加载用户语言偏好
onMounted(() => {
  const savedLocale = localStorage.getItem('user-locale');
  if (savedLocale) {
    i18n.locale.value = savedLocale;
  }
  
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script> 