<template>
  <a-dropdown :trigger="['click']" placement="bottomRight">
    <a-button type="text" class="lang-btn">
      <template #icon>
        <GlobalOutlined />
      </template>
      <span class="current-lang">{{ currentLocaleName }}</span>
      <DownOutlined class="ml-1" />
    </a-button>
    <template #overlay>
      <a-menu @click="switchLocale">
        <a-menu-item v-for="loc in availableLocales" :key="loc.code">
          <div class="flex items-center justify-between gap-4">
            <span>{{ loc.name }}</span>
            <CheckOutlined v-if="loc.code === currentLocale" class="text-green-500" />
          </div>
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>

<script setup lang="ts">
import { GlobalOutlined, DownOutlined, CheckOutlined } from '@ant-design/icons-vue'

const { locale: currentLocale, locales, setLocale } = useI18n()

const availableLocales = computed(() => {
  return (locales.value as Array<{ code: string; name: string }>).map((l) => ({
    code: l.code,
    name: l.name
  }))
})

const currentLocaleName = computed(() => {
  const found = availableLocales.value.find((l) => l.code === currentLocale.value)
  return found?.name || currentLocale.value
})

async function switchLocale({ key }: { key: string }) {
  await setLocale(key)
}
</script>

<style scoped>
.lang-btn {
  @apply text-gray-300 hover:text-white;
}

.current-lang {
  @apply text-sm;
}
</style>
