<template>
  <div class="flex flex-col">
    <p class="text-sm">Language:</p>
    <USelectMenu v-model="locale" :items="langs"
      class="w-40 bg-(--main-light) dark:bg-(--black) rounded-md shadow-sm  hover:none!" valueKey="iso_code"
      :searchInput="false">
      <template #default="{ modelValue }">
        <div class="flex items-center gap-1">
          <!-- <span class="text-md dark:text-white text-black">{{langs.find(x => x.iso_code == modelValue)?.flag}}</span> -->
          <span class="font-medium dark:text-white text-black">{{langs.find(x => x.iso_code ==
            modelValue)?.name}}</span>
        </div>
      </template>
      <template #item-leading="{ item }">
        <div class="flex items-center rounded-md cursor-pointer transition-colors">
          <!-- <span class="text-md ">{{ item.flag }}</span> -->
          <span class="ml-2 dark:text-white text-black font-medium">{{ item.name }}</span>
        </div>
      </template>
    </USelectMenu>
  </div>
</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 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>
