<template>
  <ULocaleSelect
    :model-value="locale"
    :locales="availableLocales"
    @update:model-value="setLanguage($event as LanguageCode)"
  />
</template>

<script setup lang="ts">
import * as allLocales from '@nuxt/ui/locale'
import type { LanguageCode } from '~/types/i18n.types'
import type { UsersLanguageOptions } from '~/types/pocketbase.types'

const { locale, locales, setLocale } = useI18n()
const availableLocales = computed(() =>
  locales.value.map(l => allLocales[l.code])
)

const { updateUser } = useUser()

const setLanguage = (language: LanguageCode) => {
  setLocale(language)
  updateUser({ language: language as UsersLanguageOptions })
}
</script>
