<script setup lang="ts">
import type { AcceptableValue } from 'reka-ui'

import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import type { Language } from '@/plugins/i18n'

import { appLocale, DEFAULT_LOCALE, SUPPORTED_LOCALES } from '@/plugins/i18n'

const { locale } = useI18n()

function setDefaultLanguage() {
  locale.value = DEFAULT_LOCALE
  appLocale.value = DEFAULT_LOCALE
}

function handleLocaleChange(val: AcceptableValue) {
  if (typeof val !== 'string' || !SUPPORTED_LOCALES.has(val as Language)) {
    setDefaultLanguage()
    return
  }

  locale.value = val as Language
  appLocale.value = val as Language
}

const currentFlagCode = computed(() => {
  return locale.value === 'zh' ? 'cn' : 'us'
})
</script>

<template>
  <UiDropdownMenu>
    <UiDropdownMenuTrigger as-child>
      <UiButton variant="ghost" size="icon" class="h-9 w-9">
        <span
          class="flag-icon"
          :class="`flag-icon-${currentFlagCode}`"
          :style="{ width: '20px', height: '15px' }"
        />
        <span class="sr-only">{{ $t('changeLanguage') }}</span>
      </UiButton>
    </UiDropdownMenuTrigger>
    <UiDropdownMenuContent align="end">
      <UiDropdownMenuLabel>{{ $t('changeLanguage') }}</UiDropdownMenuLabel>
      <UiDropdownMenuSeparator />
      <UiDropdownMenuRadioGroup
        v-model="locale"
        @update:model-value="handleLocaleChange"
      >
        <UiDropdownMenuRadioItem value="en">
          <span class="flag-icon flag-icon-us" :style="{ width: '18px', height: '13.5px' }" />
          <span class="ml-2">English</span>
        </UiDropdownMenuRadioItem>
        <UiDropdownMenuRadioItem value="zh">
          <span class="flag-icon flag-icon-cn" :style="{ width: '18px', height: '13.5px' }" />
          <span class="ml-2">中文</span>
        </UiDropdownMenuRadioItem>
      </UiDropdownMenuRadioGroup>
    </UiDropdownMenuContent>
  </UiDropdownMenu>
</template>
