import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

import { applyDayjsLocale } from 'src/i18n/dayjsLocale'
import { DEFAULT_LOCALE, normalizeLocale, toBackendLangCode } from 'src/i18n/languages'

const STORAGE_KEY = 'bss.locale'

function readInitialLocale() {
  if (typeof window === 'undefined') return DEFAULT_LOCALE
  return normalizeLocale(window.localStorage.getItem(STORAGE_KEY))
}

export const useLocaleStore = defineStore('locale', () => {
  const locale = ref(readInitialLocale())

  function setLocale(nextLocale) {
    const normalized = normalizeLocale(nextLocale)
    locale.value = normalized
    applyDayjsLocale(normalized)
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, normalized)
    }
  }

  const backendLangCode = computed(() => toBackendLangCode(locale.value))

  applyDayjsLocale(locale.value)

  return {
    locale,
    backendLangCode,
    setLocale
  }
})
