import { useEffect, useState } from "react";
import type { Language } from "./LanguageContext.types";
import i18next from "i18next";
import { LanguageContext } from "./LanguageContext";

export const LanguageProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [language, setLanguage] = useState<Language>("ru");

  const changeLanguage = (newLanguage: Language) => {
    setLanguage(newLanguage);
    i18next.changeLanguage(newLanguage);
    localStorage.setItem("i18nextLng", newLanguage);
  };

  useEffect(() => {
    const savedLanguage =
      (localStorage.getItem("i18nextLng") as Language) || "ru";
    setLanguage(savedLanguage);
    i18next.changeLanguage(savedLanguage);
  }, []);

  return (
    <LanguageContext.Provider value={{ language, changeLanguage }}>
      {children}
    </LanguageContext.Provider>
  );
};
