import React, { createContext, useState, useEffect, useRef } from 'react';
import getLocalizedData from '../LocalizationUtil';
export const LanguageContext = createContext();

export const LanguageProvider = ({ children }) => {
  const [currentLocale, setCurrentLocale] = useState(localStorage.getItem('currentLocale') ? localStorage.getItem('currentLocale') : 'id-ID');
  const [localeData, setLocaleData] = useState('id');
  const cancelToken = useRef(null); 

  useEffect(() => {
    const fetchData = async () => {
      const token = { cancelled: false };
      cancelToken.current = token;

      try {
        const data = await getLocalizedData(currentLocale);
        if (!cancelToken.current.cancelled) {
          setLocaleData(data);
        }
      } catch (error) {
        console.error('Error fetching localized data:', error);
        // Tangani kesalahan jika diperlukan
      }
    };

    fetchData();

    return () => {
      cancelToken.current.cancelled = true;
    };
  }, [currentLocale]);

  return (
    <LanguageContext.Provider value={{ currentLocale, setCurrentLocale, localeData }}>
      {children}
    </LanguageContext.Provider>
  );
};
