'use client'

import { useEffect, useState } from 'react'
import { I18nextProvider } from 'react-i18next'
import i18n from '@/i18n/config'

type Props = { children: any }

export default function I18nProvider({ children }: Props) {
    const [langReady, setLangReady] = useState(false)

    useEffect(() => {
        try {
            const readCookie = () => {
                if (typeof document === 'undefined') return undefined
                const m = document.cookie
                    .split(';')
                    .map((s) => s.trim())
                    .find((s) => s.startsWith('i18nextLng='))
                return m ? m.split('=')[1] : undefined
            }
            const fromCookie = readCookie()
            const fromStorage =
                typeof window !== 'undefined' ? localStorage.getItem('i18nextLng') : null
            const initial = (fromCookie || fromStorage || '').trim()
            if (initial && initial !== i18n.language) {
                i18n.changeLanguage(initial).finally(() => setLangReady(true))
            } else {
                setLangReady(true)
            }
        } catch {
            setLangReady(true)
        }
    }, [])

    if (!langReady) return null

    return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>
}

