import { useState, type ReactNode } from "react"
import { fr } from "./fr"
import { en } from "./en"
import {
  I18nContext,
  LANG_KEY,
  detectLang,
  type Dict,
  type Lang,
} from "./context"

export function I18nProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Lang>(detectLang)
  const dicts: Record<Lang, Dict> = { fr, en }

  function setLang(next: Lang) {
    try {
      localStorage.setItem(LANG_KEY, next)
    } catch {
      // ignore
    }
    setLangState(next)
  }

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