<script setup lang="ts">
import { computed, ref } from 'vue';

import { loadLocaleMessages } from '@velofex/locales';
import { preferences, updatePreferences } from '@velofex/preferences';

import { changeLanguageApi } from '@/api/account';
import { Dropdown } from 'antdv-next';

const items = [
  {
    key: 'en-US',
    label: 'English',
  },
  {
    key: 'zh-CN',
    label: '中文',
  },
];

const show = ref(false);

const currentLabel = computed(() => {
  const selected = items.find((item) => item.key === preferences.app.locale);
  return selected?.label ?? 'Language';
});

const onOpenChange = (open: boolean) => {
  show.value = open;
};

const onMenuClick = async (info: any) => {
  if (preferences.app.locale === info.key) {
    return;
  }

  const nextLocale = info.key;
  try {
    await changeLanguageApi({ langId: nextLocale === 'en-US' ? 1 : 0 });

    updatePreferences({
      app: {
        locale: nextLocale,
      },
    });

    await loadLocaleMessages(nextLocale);
  } catch (error) {
    console.error('web-b', error);
  }
};
</script>

<template>
  <Dropdown
    :menu="{ items }"
    placement="bottom"
    @menu-click="onMenuClick"
    @open-change="onOpenChange"
  >
    <div class="flex cursor-pointer items-center gap-2">
      <img
        alt="earth"
        height="20px"
        src="@/assets/image/earth_18301626@2x.png"
        width="20px"
      />
      <span>{{ currentLabel }}</span>
      <img
        :class="show ? 'rotate-180' : ''"
        alt="polygon"
        height="6px"
        src="@/assets/image/Polygon 2.png"
        width="7px"
      />
    </div>
  </Dropdown>
</template>

<style scoped></style>
