import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import dayjs from 'dayjs'
import { type LanguageCode, getLanguage, getTranslation } from '../locales'

interface LanguageState {
  currentLanguage: LanguageCode
  setLanguage: (code: LanguageCode) => void
  getLanguageInfo: () => any
  t: (key: string) => string
}

export const useLanguageStore = create<LanguageState>()(
  persist(
    (set, get) => ({
      currentLanguage: 'zh-CN',
      
      setLanguage: (code: LanguageCode) => {
        set({ currentLanguage: code })
        // 更新dayjs语言
        import('dayjs/locale/zh-cn')
        import('dayjs/locale/th')
        const localeMap: Record<LanguageCode, string> = {
          'zh-CN': 'zh-cn',
          'th-TH': 'th',
          'lo-LA': 'en',
          'en-US': 'en'
        }
        dayjs.locale(localeMap[code])
      },
      
      getLanguageInfo: () => {
        return getLanguage(get().currentLanguage)
      },
      
      t: (key: string): string => {
        const translation = getTranslation(get().currentLanguage)
        const keys = key.split('.')
        let result: any = translation
        
        for (const k of keys) {
          if (result && typeof result === 'object') {
            result = result[k]
          } else {
            return key // 找不到翻译，返回key
          }
        }
        
        return typeof result === 'string' ? result : key
      }
    }),
    {
      name: 'language-storage',
    }
  )
)
