'use client'

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import i18nConfig from '@/i18nConfig'
import { useTranslation } from 'react-i18next' // 引入 useTranslation

const isValidLocale = (locale: string): locale is (typeof i18nConfig.locales)[number] => {
  return (i18nConfig.locales as readonly string[]).includes(locale)
}

export default function HomeRedirector() {
  const router = useRouter()
  const { i18n } = useTranslation() // 获取 i18n 实例

  useEffect(() => {
    const preferred = localStorage.getItem('preferred-language')
    const currentPath = window.location.pathname
  
    console.log('[HomeRedirector] localStorage preferred:', preferred)
    console.log('[HomeRedirector] currentPath:', currentPath)
  
    if (!preferred || !isValidLocale(preferred)) {
      console.log('[HomeRedirector] No valid preferred language found.')
      return
    }
  
    // ✅ 同步写入 cookie
    //document.cookie = `preferred-language=${preferred}; path=/; max-age=31536000` // 1 年

    // 修改 i18n 中的语言
    i18n.changeLanguage(preferred) // 更新 i18n 的 locale
  
    const pathLocale = currentPath.split('/')[1]
    const hasLocaleInPath = isValidLocale(pathLocale)
  
    if (!hasLocaleInPath) {
      const newPath = `/${preferred}${currentPath}`
      console.log('......[HomeRedirector] Redirecting to:', newPath)

      // 添加延迟跳转，延迟时间为 2 秒（2000 毫秒）
      setTimeout(() => {
        router.replace(newPath)
      }, 2000)  // 这里的 2000 毫秒是 2 秒的延时，你可以根据需要调整

    } else {
      console.log('......[HomeRedirector] Already has valid locale in path, skipping redirect.')
    }
  }, [])
  

  return null
}
