import { defineStore } from 'pinia'
import { elementLocales, LOCALE_STORAGE_KEY, setI18nLocale } from '@/i18n'
import { isLocaleCode, SUPPORTED_LOCALES, type LocaleCode } from '@/i18n/types'

export const useLocaleStore = defineStore('locale', {
  state: () => ({
    locale: (localStorage.getItem(LOCALE_STORAGE_KEY) || 'zh-CN') as LocaleCode,
  }),
  getters: {
    elementLocale: (state) => elementLocales[state.locale],
    options: () => SUPPORTED_LOCALES,
  },
  actions: {
    setLocale(locale: LocaleCode, persist = true) {
      if (!isLocaleCode(locale)) return
      this.locale = locale
      setI18nLocale(locale)
      if (persist) {
        localStorage.setItem(LOCALE_STORAGE_KEY, locale)
      }
    },
    applyFromSettings(uiLocale?: string) {
      if (uiLocale && isLocaleCode(uiLocale)) {
        this.setLocale(uiLocale)
      }
    },
  },
})
