import React, {useState, useEffect, createContext} from 'react';
import { IntlProvider } from 'react-intl';
import enMessages from '../translations/en.json';
import cnMessages from '../translations/zh-CN.json';
import hkMessages from '../translations/zh-HK.json';

const LocaleContext = createContext();

export const I18nProvider = ({ children }) => {
    const systemMessages = {
        "en": enMessages,
        "zh": hkMessages,
        "zh-HK": hkMessages,
        "zh-CN": cnMessages
    };

    const [locale, setLocale] = useState('en'); // Default locale, you can change this as per your requirement
    const [isAdvanceDisplay, setIsAdvanceDisplay] = useState(true); // Default locale, you can change this as per your requirement

    const [messages, setMessages] = useState(systemMessages[locale]);

    useEffect(() => {
        if(localStorage.getItem('locale') === null){
            //no locale case
            localStorage.setItem('locale','en');
        }
        else{
            setLocale(localStorage.getItem('locale'));
        }
    }, []);
    useEffect(() => {
        // Load the messages for the selected locale
        const fetchMessages = async () => {
            setMessages(systemMessages[locale]);
        };

        fetchMessages();
    }, [locale]);

    return (
        <LocaleContext.Provider  value={{ locale, setLocale, isAdvanceDisplay, setIsAdvanceDisplay }} >
            <IntlProvider locale={locale} messages={messages}>
                {children}
            </IntlProvider>
        </LocaleContext.Provider>
    );
}

export default LocaleContext;