import { defineStore } from 'pinia'
import { setAppLocale, type AppLocale } from '@/i18n'

export const UI_PREFS_STORAGE_KEY = 'jgjs-ui-prefs-v1'

type UiPrefsState = {
  locale: AppLocale | null
  hasLocaleOverride: boolean
}

const isAppLocale = (value: unknown): value is AppLocale =>
  value === 'zh-CN' || value === 'en-US'

const readPersistedPrefs = (): Partial<UiPrefsState> | null => {
  if (typeof window === 'undefined') return null
  const raw = localStorage.getItem(UI_PREFS_STORAGE_KEY)
  if (!raw) return null
  try {
    const parsed = JSON.parse(raw) as Partial<UiPrefsState>
    return parsed && typeof parsed === 'object' ? parsed : null
  } catch {
    return null
  }
}

const writePersistedPrefs = (state: UiPrefsState) => {
  if (typeof window === 'undefined') return
  localStorage.setItem(UI_PREFS_STORAGE_KEY, JSON.stringify(state))
}

export const useUiPrefsStore = defineStore('uiPrefs', {
  state: (): UiPrefsState => ({
    locale: null,
    hasLocaleOverride: false
  }),
  actions: {
    initFromStorage() {
      const persisted = readPersistedPrefs()
      if (!persisted) return
      if (persisted.hasLocaleOverride === true && isAppLocale(persisted.locale)) {
        this.locale = persisted.locale
        this.hasLocaleOverride = true
        setAppLocale(persisted.locale)
      }
    },
    setLocale(locale: AppLocale) {
      this.locale = locale
      this.hasLocaleOverride = true
      setAppLocale(locale)
      writePersistedPrefs({
        locale: this.locale,
        hasLocaleOverride: this.hasLocaleOverride
      })
    }
  }
})

