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

export const useLanguageStore = defineStore('language', () => {
  // 当前语言 - 与 Nuxt i18n 同步
  const currentLocale = ref('en')
  
  // 可用语言列表
  const availableLocales = [
    { code: 'en', name: 'English', nativeName: 'English' },
    { code: 'cn', name: '简体中文', nativeName: '简体中文' }
  ]
  
  // 计算属性
  const isChinese = computed(() => currentLocale.value === 'cn')
  const isEnglish = computed(() => currentLocale.value === 'en')
  
  // 设置语言 - 简化逻辑，主要依赖 Nuxt i18n
  const setLocale = (locale) => {
    if (availableLocales.some(lang => lang.code === locale)) {
      currentLocale.value = locale
      console.log('Language store updated:', locale)
    }
  }
  
  // 初始化语言 - 简化初始化逻辑
  const initLocale = () => {
    if (process.client) {
      try {
        // 从 cookie 获取语言设置（Nuxt i18n 自动管理）
        const cookieLanguage = document.cookie
          .split('; ')
          .find(row => row.startsWith('i18n_redirected='))
          ?.split('=')[1]
        
        if (cookieLanguage && availableLocales.some(lang => lang.code === cookieLanguage)) {
          currentLocale.value = cookieLanguage
          console.log('Language initialized from cookie:', cookieLanguage)
          return
        }
        
        // 如果没有 cookie，使用默认语言
        currentLocale.value = 'en'
        console.log('Using default language: en')
      } catch (error) {
        console.warn('Language initialization failed:', error)
        currentLocale.value = 'en'
      }
    }
  }
  
  // 切换语言 - 简化切换逻辑
  const toggleLanguage = () => {
    const newLocale = currentLocale.value === 'en' ? 'cn' : 'en'
    setLocale(newLocale)
    return newLocale
  }
  
  return {
    currentLocale: computed(() => currentLocale.value),
    availableLocales,
    isChinese,
    isEnglish,
    setLocale,
    initLocale,
    toggleLanguage
  }
})
