import { createContext, useContext, useState, useEffect } from "react";
import { usePage, router } from "@inertiajs/react";

const LanguageContext = createContext();

export function LanguageProvider({ children }) {
  const { locale, translations, language } = usePage().props;

  

  const [currentLocale, setCurrentLocale] = useState(locale || "en");
  const [currentTranslations, setCurrentTranslations] = useState(translations || {});
  const [direction, setDirection] = useState(language?.ltr === "0" ? "rtl" : "ltr");

  useEffect(() => {
    document.documentElement.setAttribute("dir", direction);
  }, [direction]);

  useEffect(() => {
    setCurrentLocale(locale);
    setCurrentTranslations(translations);
    setDirection(language?.ltr === "0" ? "rtl" : "ltr");
  }, [locale, translations, language]);


  const switchLanguage = (code) => {
    router.post(route("user.language.switch"), { code: code }, {
      preserveScroll: true,

    });
  };

  return (
    <LanguageContext.Provider
      value={{
        currentLocale,
        currentTranslations,
        direction,
        switchLanguage,
      }}
    >
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  return useContext(LanguageContext);
}
