<template>
  <div class="relative">
    <button
      @click="toggleDropdown"
      class="flex items-center space-x-1 p-2 rounded-lg bg-card hover:bg-block-hover text-secondary hover:text-primary transition-all duration-200"
    >
      <span class="text-sm font-medium">{{ language.toUpperCase() }}</span>
      <FontAwesomeIcon 
        :icon="['fas', 'chevron-down']" 
        :class="['w-3 h-3 transition-transform duration-200', isOpen && 'rotate-180']"
      />
    </button>
    
    <div
      v-if="isOpen"
      class="absolute right-0 mt-2 w-20 bg-card border border-opacity-15 border-primary-500 rounded-lg shadow-lg z-50"
    >
      <button
        @click="() => selectLanguage('zh')"
        :class="[
          'w-full px-3 py-2 text-left text-sm transition-colors duration-200 rounded-t-lg',
          language === 'zh' ? 'bg-primary-500 text-white' : 'text-secondary hover:bg-block-hover hover:text-primary'
        ]"
      >
        中文
      </button>
      <button
        @click="() => selectLanguage('en')"
        :class="[
          'w-full px-3 py-2 text-left text-sm transition-colors duration-200 rounded-b-lg',
          language === 'en' ? 'bg-primary-500 text-white' : 'text-secondary hover:bg-block-hover hover:text-primary'
        ]"
      >
        EN
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useLanguage } from '@/composables/useLanguage'
import type { Language } from '@/types/tools'

const { language, switchLanguage } = useLanguage()
const isOpen = ref(false)

const toggleDropdown = () => {
  isOpen.value = !isOpen.value
}

const selectLanguage = (lang: Language) => {
  switchLanguage(lang)
  isOpen.value = false
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as Element
  if (!target.closest('.relative')) {
    isOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

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