import LanguageManager, { Language } from './manager';
import React, {
    createContext,
    useContext,
    useEffect,
    useMemo,
    useState,
} from 'react';

type LanguageContextProps = {
    language: Language;
    $: LanguageManager;
    setLanguage: (lang: Language) => void;
};

const LanguageContext = createContext<LanguageContextProps>({
    language: 'en-US',
    setLanguage: () => {},
    $: new LanguageManager('en-US'),
});

type LanguageProviderProps = {
    children: React.ReactNode;
};

const LanguageProvider: React.FC<LanguageProviderProps> = ({ children }) => {
    const [language, setLanguageState] = useState<Language>(() => {
        const saved = localStorage.getItem('language');
        return (saved as Language) || 'en-US';
    });

    useEffect(() => {
        localStorage.setItem('language', language);
    }, [language]);

    const setLanguage = (lang: Language) => setLanguageState(lang);

    const $ = useMemo(() =>
        new LanguageManager(language),
        [language]
    );

    return <LanguageContext.Provider value={{ language, setLanguage, $ }}>
        {children}
    </LanguageContext.Provider>;
};

const useLanguage = () => useContext(LanguageContext);

export { LanguageProvider, useLanguage };