import { useLanguageStore } from '@/stores/language.js'

export const useLanguageSwitch = () => {
  const languageStore = useLanguageStore()
  
  // 切换语言 - 简化逻辑，主要依赖 Nuxt i18n 的路由处理
  const switchLanguage = async (newLocale, locale, router) => {
    if (!newLocale || newLocale === locale.value) {
      console.log('Language switch skipped:', { newLocale, current: locale.value })
      return
    }
    
    console.log('Language switch started:', { from: locale.value, to: newLocale })
    
    try {
      // 更新 store 中的语言状态
      languageStore.setLocale(newLocale)
      console.log('Store updated:', newLocale)
      
      // 更新 i18n locale
      locale.value = newLocale
      console.log('I18n locale updated:', newLocale)
      
      // 使用 Nuxt i18n 的 switchLocalePath 获取新语言的路径
      const currentRoute = router.currentRoute.value
      const currentPath = currentRoute.path
      console.log('Current path:', currentPath)
      
      // 构建新语言的路径
      let newPath = currentPath
      
      if (newLocale === 'cn') {
        // 切换到中文，需要添加 /cn 前缀
        if (!currentPath.startsWith('/cn')) {
          newPath = `/cn${currentPath === '/' ? '' : currentPath}`
        }
      } else {
        // 切换到英文，需要移除 /cn 前缀
        if (currentPath.startsWith('/cn')) {
          newPath = currentPath.replace('/cn', '') || '/'
        }
      }
      
      console.log('New path:', newPath)
      
      // 跳转到新语言的对应页面
      if (newPath !== currentPath) {
        try {
          await router.push(newPath)
          console.log('Navigation completed')
        } catch (error) {
          console.warn('Language switch navigation failed:', error)
          // 如果路由跳转失败，至少确保语言状态已更新
        }
      } else {
        console.log('No navigation needed')
      }
      
      console.log('Language switch completed successfully')
    } catch (error) {
      console.error('Language switch failed:', error)
      // 出错时回退到默认语言
      languageStore.setLocale('en')
      locale.value = 'en'
    }
  }
  
  // 获取当前语言显示名称
  const getCurrentLanguageName = (locale) => {
    try {
      const currentLang = languageStore.availableLocales.find(
        lang => lang.code === locale.value
      )
      return currentLang ? currentLang.name : 'English'
    } catch (error) {
      console.warn('Get language name failed:', error)
      return 'English'
    }
  }
  
  // 初始化语言 - 简化初始化逻辑
  const initLanguage = (locale, router) => {
    console.log('Language initialization started')
    try {
      // 确保语言 store 已初始化
      languageStore.initLocale()
      console.log('Store initialized')
      
      // 同步 store 和 i18n 的语言状态
      const storeLocale = languageStore.currentLocale.value
      console.log('Store locale:', storeLocale, 'I18n locale:', locale.value)
      
      if (storeLocale && storeLocale !== locale.value) {
        locale.value = storeLocale
        console.log('I18n locale synced:', storeLocale)
      }
      
      console.log('Language initialization completed')
    } catch (error) {
      console.error('Language initialization failed:', error)
      // 出错时使用默认语言
      languageStore.setLocale('en')
      locale.value = 'en'
    }
  }
  
  return {
    switchLanguage,
    getCurrentLanguageName,
    initLanguage,
    currentLocale: languageStore.currentLocale,
    availableLocales: languageStore.availableLocales
  }
}
