<template>
  <cwg-dropdown :menu-list="customMenuList" @menuClick="handleMenuClick">
    <view class="lang-select">
      <cwg-icon name="cwg-lang" color="#141d22" />
    </view>
  </cwg-dropdown>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { localesList, LANG_MAP } from '@/locale/index'
import { lang } from '@/composables/config'

const { t, locale } = useI18n()

const currentLang = computed(() => lang.value || locale.value)
const currentLabel = computed(() => t(`language.${currentLang.value}`))
const currentFlag = computed(() => getFlagSrc(currentLang.value))

const customMenuList = computed(() =>
  localesList.map((code) => ({
    label: t(`language.${code}`),
    type: code
  })),
)

function handleMenuClick({ value }: { value: any }) {
  const type = value?.type ?? value
  if (!type) return
  locale.value = type
  lang.value = type
  const localeValue = LANG_MAP[type] || 'zh-Hans'
  uni.setLocale(localeValue)
}

function getFlagSrc(code: string) {
  switch (code) {
    case 'en':
      return '/static/flag-en.png'
    case 'cn':
      return '/static/flag-cn.png'
    case 'zhHant':
      return '/static/flag-zhHant.png'
    case 'es':
      return '/static/flag-es.png'
    default:
      return '/static/flag-en.png'
  }
}
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.lang-select {
  width: px2rpx(40);
  height: px2rpx(40);
  border-radius: px2rpx(4);
  border: 1px solid rgba(108, 133, 149, 0);
  display: flex;
  align-items: center;
  font-size: px2rpx(14);
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
    background: rgba(108, 133, 149, 0.12);
    border-color: rgb(145, 163, 176);
  }
}

.flag {
  width: 22px;
  height: 16px;
  margin-right: 6px;
}

.arrow {
  margin-left: 4px;
  font-size: 12px;
}

:deep(.cwg-dropdown-menu-container .menu .menu-item) {
  min-height: px2rpx(36);
}

:deep(.cwg-dropdown) {
  overflow: visible !important;
}
</style>
