<template>
  <cwg-dropdown :menu-list="customMenuList" @menuClick="handleMenuClick">
    <view class="lang-select">
      <image class="img flag" :src="currentFlag" alt="lang" />
      <text>{{ currentLabel }}</text>
      <text class="arrow">▼</text>
    </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 {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 18px;
  padding: 4px 12px;
  font-size: 14px;
  cursor: pointer;
}

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

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

:deep(.cwg-dropdown-menu-container) {
  top: px2rpx(40) !important;
  left: 0 !important;
  right: auto !important;
  z-index: 1000 !important;
}

:deep(.cwg-dropdown-menu-container .menu) {
  min-width: px2rpx(180);
}

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

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