<template>
  <USelectMenu v-model="country" :items="countries" value-key="id"
    class="w-48 bg-(--main-light) dark:bg-(--black) rounded-md shadow-sm" :searchInput="false">
    <template #default>
      <div class="flex flex-col items-start leading-tight">
        <span class="text-xs text-gray-400">
          Country/Currency
        </span>
        <span class="font-medium dark:text-white text-black">
          {{ country?.name }} / {{ country?.ps_currency.iso_code }}
        </span>
      </div>
    </template>

    <template #item-leading="{ item }">
      <div class="flex items-center gap-2 cursor-pointer">
        <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 { countries, currentCountry, switchLocalization } from '@/router/langs'
import { useCookie } from '@/composable/useCookie'
import { computed, watch } from 'vue'

const cookie = useCookie()
const country = computed({
  get() {
    return currentCountry.value
  },
  set(value: string) {
    currentCountry.value = countries.find((x) => x.id == Number(value))
    cookie.setCookie('country_id', `${countries.find((x) => x.id == Number(value))?.id}`, { days: 60, secure: true, sameSite: 'Lax' })

    switchLocalization()
  },
})

watch(
  () => country,
  (newCountry) => {
    if (newCountry) {
      currentCountry.value = countries.find((x) => x.id == Number(newCountry.value?.id))
    }
  },
  { immediate: true },
)
</script>
