<script lang="ts" setup>
import { useLocale } from 'vuetify';
import { $cookie } from '@/plugins/cookie';
import { onBeforeMount } from 'vue';
import { COOKIE_LOCALE } from '../constants/static';
import Moment from '@/plugins/moment';

const { current } = useLocale();
const languages = [
  {
    title: 'Русский',
    locale: 'ru',
  },
  {
    title: 'English',
    locale: 'en',
  },
];
const key = COOKIE_LOCALE;

const get = (): string => {
  const v = $cookie.get(key);
  Moment.$moment.locale(v);
  return v;
};
const set = (locale: string): void => {
  current.value = locale;
  Moment.$moment.locale(locale);
  $cookie.set(key, locale);
};
const setLocaleFromExistCookie = (): void => {
  const v = get();
  if (v?.length && typeof v === 'string') {
    set(v);
  }
};
onBeforeMount(setLocaleFromExistCookie);
</script>

<template>
  <v-menu transition="none" close-delay="0" open-delay="0">
    <template v-slot:activator="{ props }">
      <v-btn icon density="comfortable">
        <span class="mso" v-bind="props">language</span>
      </v-btn>
    </template>
    <v-list density="compact" class="mt-3 accent-modal" elevation="0">
      <v-list-item
        v-for="(item, i) in languages"
        :key="i"
        class="cm-mini"
        @click="set(item.locale)"
      >
        <template v-slot:prepend>
          <img class="flag mr-2" :src="`/images/flag_${item.locale}.svg`" />
        </template>
        <v-list-item-title>{{ item.title }}</v-list-item-title>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<style scoped>
.flag {
  height: 14px;
  border-radius: 4px;
}
</style>
