<template>
  <USelectMenu v-model="locale" :items="langs" value-key="iso_code"
    class="w-48 bg-(--main-light) dark:bg-(--black) rounded-md shadow-sm" :searchInput="false">
    <template #default>
      <div class="flex items-center gap-2">
        <!-- <span class="text-lg">{{ selectedLang?.flag }}</span> -->

        <div class="flex flex-col leading-tight items-start">
          <span class="text-xs text-gray-400">
            Language
          </span>
          <span class="font-medium dark:text-white text-black">
            {{ selectedLang?.name || 'Select language' }}
          </span>
        </div>
      </div>
    </template>

    <template #item-leading="{ item }">
      <div class="flex items-center gap-2">
        <span class="text-lg">{{ item.flag }}</span>
        <span class="font-medium dark:text-white text-black">
          {{ item.name }}
        </span>
      </div>
    </template>
  </USelectMenu>
</template>

<script setup lang="ts">
import { langs, currentLang, switchLocalization } from '@/router/langs'
import { useRouter, useRoute } from 'vue-router'
import { useCookie } from '@/composable/useCookie'
import { computed, watch } from 'vue'
import { i18n } from '@/plugins/02_i18n'

const router = useRouter()
const route = useRoute()

const selectedLang = computed(() =>
  langs.find(item => item.iso_code === locale.value)
)

const cookie = useCookie()
const locale = computed({
  get() {
    return currentLang.value?.iso_code || i18n.locale.value
  },
  set(value: string) {
    i18n.locale.value = value
    currentLang.value = langs.find((x) => x.iso_code == value)

    const currentPath = route.path
    const pathParts = currentPath.split('/').filter(Boolean)

    cookie.setCookie('lang_id', `${langs.find((x) => x.iso_code == value)?.id}`, { days: 60, secure: true, sameSite: 'Lax' })
    if (pathParts.length > 0) {
      const isLocale = langs.some((l) => l.lang_code === pathParts[0])
      if (isLocale) {
        pathParts[0] = value
        router.replace({ path: '/' + pathParts.join('/'), query: route.query })
      } else {
        router.replace({ path: '/' + value + currentPath, query: route.query })
      }
    }

    switchLocalization()
  },
})

watch(
  () => route.params.locale,
  (newLocale) => {
    if (newLocale && typeof newLocale === 'string') {
      i18n.locale.value = newLocale
      currentLang.value = langs.find((x) => x.iso_code == newLocale)
    }
  },
  { immediate: true },
)
</script>
