import { createContext, useEffect, useState } from "react";

export const UserContext = createContext();

export function UserContextProvider({ children }) {
	const [language, setLanguage] = useState("FR");
	const [country, setCountry] = useState({ name: "belgique", iso: "BE" });
	const [profile, setProfile] = useState("lhoist_employee");
	const [screensTranslations, setScreensTranslations] = useState({});

	useEffect(() => {
		if (!language) return;
		const loadTranslations = async (language) => {
			try {
				const translations = await import(`../data/screensTranslations_${language}.json`);
				setScreensTranslations(translations.default);
			} catch (error) {
				console.error("Could not load translations", error);
			}
		};

		// Appeler la fonction loadTranslations avec la langue actuelle
		loadTranslations(language);
	}, [language]);

	function changeLanguage() {
		if (language === "FR") {
			setLanguage("EN");
		} else {
			setLanguage("FR");
		}
	}

	function changeCountry(newCountry) {
		setCountry(newCountry);
	}

	function changeProfile(newProfile) {
		setProfile(newProfile);
	}
	return (
		<UserContext.Provider
			value={{
				language,
				screensTranslations,
				changeLanguage,
				country,
				changeCountry,
				profile,
				changeProfile,
			}}>
			{children}
		</UserContext.Provider>
	);
}
