import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { defaultLanguage, translate, writeSavedLanguage } from "./i18n.js";

const I18nContext = createContext({ language: "en", setLanguage: () => {}, t: (key) => key });

export function I18nProvider({ children }) {
  const [language, setLanguageState] = useState(() => defaultLanguage());
  const setLanguage = (nextLanguage) => setLanguageState(nextLanguage);
  useEffect(() => { writeSavedLanguage(undefined, language); document.documentElement.lang = language; }, [language]);
  const value = useMemo(() => ({ language, setLanguage, t: (key, values) => translate(language, key, values) }), [language]);
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

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