'use client'

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import i18nConfig from '@/i18nConfig'

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

export default function HomeRedirector() {
  console.log('home-redirecting 1==========================>')
  const router = useRouter()

  useEffect(() => {
    const preferred = localStorage.getItem('preferred-language')
    const currentPath = window.location.pathname
  
    console.log('[HomeRedirector] 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 年
  
    const pathLocale = currentPath.split('/')[1]
    const hasLocaleInPath = isValidLocale(pathLocale)
  
    if (!hasLocaleInPath) {
      const newPath = `/${preferred}${currentPath}`
      console.log('[HomeRedirector] Redirecting to:', newPath)
      router.replace(newPath)
    } else {
      console.log('[HomeRedirector] Already has valid locale in path, skipping redirect.')
    }
  }, [])
  

  return null
}
