<template>
  <div class="language-switcher relative">
    <button 
      @click="toggleDropdown"
      class="flex items-center space-x-2 px-3 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors"
    >
      <span class="text-sm font-medium">{{ currentLanguageLabel }}</span>
      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
      </svg>
    </button>
    
    <div 
      v-if="dropdownOpen"
      class="absolute top-full mt-1 right-0 bg-white rounded-lg shadow-lg border border-gray-200 z-50 min-w-[120px]"
    >
      <ul class="py-1">
        <li v-for="lang in languages" :key="lang.code">
          <button
            @click="switchLanguage(lang.code)"
            class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center justify-between"
            :class="{ 'bg-blue-50 text-blue-700': lang.code === currentLanguage }"
          >
            <span>{{ lang.label }}</span>
            <span v-if="lang.code === currentLanguage" class="text-blue-500">✓</span>
          </button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppModeStore } from '../stores/appModeStore'

const { locale } = useI18n()
const appModeStore = useAppModeStore()

const dropdownOpen = ref(false)

const languages = [
  { code: 'en', label: 'English' },
  { code: 'hu', label: 'Magyar' },
  { code: 'de', label: 'Deutsch' },
  { code: 'fr', label: 'Français' }
]

const currentLanguage = computed(() => locale.value)
const currentLanguageLabel = computed(() => {
  const lang = languages.find(l => l.code === currentLanguage.value)
  return lang ? lang.label : 'EN'
})

function toggleDropdown() {
  dropdownOpen.value = !dropdownOpen.value
}

async function switchLanguage(langCode: string) {
  locale.value = langCode
  await appModeStore.setLanguage(langCode)
  dropdownOpen.value = false
}

// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
  const target = e.target as HTMLElement
  if (!target.closest('.language-switcher')) {
    dropdownOpen.value = false
  }
})
</script>

<style scoped>
.language-switcher {
  font-family: 'Inter', sans-serif;
}
</style>