import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { SUPPORTED_LOCALES, LOCALE_STORAGE_KEY, type SupportedLocale } from '@/locales'
import { i18n } from '@/main'

export const useI18nStore = defineStore('i18n', () => {
  const current = ref<SupportedLocale>(i18n.global.locale.value as SupportedLocale)

  const currentLang = computed(() =>
    SUPPORTED_LOCALES.find(l => l.code === current.value) ?? SUPPORTED_LOCALES[0]
  )

  function setLocale(code: SupportedLocale) {
    current.value = code
    i18n.global.locale.value = code
    document.documentElement.lang = code
    try {
      localStorage.setItem(LOCALE_STORAGE_KEY, code)
    } catch {
      // ignore
    }
  }

  return { current, currentLang, setLocale, locales: SUPPORTED_LOCALES }
})
