'use client'

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

export default function HomeRedirector() {
  const router = useRouter()

  useEffect(() => {
    const preferred = localStorage.getItem('preferred-language')
    const currentPath = window.location.pathname

    console.log('[HomeRedirector] currentPath:', currentPath)
    console.log('[HomeRedirector] preferred-language from storage:', preferred)

    const isValidLocale = (lang: string) =>
      (i18nConfig.locales as string[]).includes(lang)

    // 若路径中已经有 locale 前缀，或 preferred 为空 / 非法，跳过
    if (
      preferred &&
      isValidLocale(preferred) &&
      !currentPath.startsWith(`/${preferred}/`) &&
      !i18nConfig.locales.some(locale => currentPath.startsWith(`/${locale}/`))
    ) {
      const newPath = `/${preferred}${currentPath}`
      console.log('[HomeRedirector] Redirecting to:', newPath)
      router.replace(newPath)
    } else {
      console.log('[HomeRedirector] No redirection triggered')
    }
  }, [])

  return null
}
