'use client'

import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import zh, { type Translations } from './locales/zh'
import en from './locales/en'

type Lang = 'zh' | 'en'
const STORAGE_KEY = 'yuzhiran-lang'

const translations: Record<Lang, Translations> = { zh, en }

const I18nContext = createContext<{
  lang: Lang
  t: Translations
  setLang: (lang: Lang) => void
}>({ lang: 'zh', t: zh, setLang: () => {} })

export function I18nProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Lang>('zh')
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY) as Lang | null
    if (stored === 'en' || stored === 'zh') setLangState(stored)
    setMounted(true)
  }, [])

  useEffect(() => {
    document.documentElement.lang = lang
  }, [lang])

  function setLang(lang: Lang) {
    setLangState(lang)
    localStorage.setItem(STORAGE_KEY, lang)
  }

  if (!mounted) {
    return <>{children}</>
  }

  return (
    <I18nContext.Provider value={{ lang, t: translations[lang], setLang }}>
      <div lang={lang}>{children}</div>
    </I18nContext.Provider>
  )
}

export function useI18n() {
  return useContext(I18nContext)
}
