import { createContext, useContext, useState, useEffect } from 'react';

const CurrencyContext = createContext();

export const useCurrency = () => {
  const context = useContext(CurrencyContext);
  if (!context) {
    throw new Error('useCurrency must be used within a CurrencyProvider');
  }
  return context;
};

export const CurrencyProvider = ({ children }) => {
  const [currency, setCurrency] = useState(() => {
    // Check localStorage first
    if (typeof window !== 'undefined') {
      const savedCurrency = localStorage.getItem('currency');
      if (savedCurrency) {
        return savedCurrency;
      }
      // Try to detect currency from browser locale
      const locale = navigator.language || navigator.userLanguage;
      if (locale.includes('en-CA') || locale.includes('fr-CA')) {
        return 'CAD';
      }
      if (locale.includes('en-GB')) {
        return 'GBP';
      }
      if (locale.includes('en-AU')) {
        return 'AUD';
      }
      if (locale.includes('eu') || locale.includes('de') || locale.includes('fr') || locale.includes('es') || locale.includes('it')) {
        return 'EUR';
      }
      if (locale.includes('ja') || locale.includes('JP')) {
        return 'JPY';
      }
      if (locale.includes('zh') || locale.includes('CN')) {
        return 'CNY';
      }
    }
    return 'CAD'; // Default to CAD
  });

  const [exchangeRates, setExchangeRates] = useState(null);

  // Preload exchange rates on mount
  useEffect(() => {
    import('../utils/currencyService').then(({ getExchangeRates }) => {
      getExchangeRates().then(rates => {
        setExchangeRates(rates);
      });
    });
  }, []);

  // Update exchange rates when currency changes
  useEffect(() => {
    if (currency && typeof window !== 'undefined') {
      import('../utils/currencyService').then(({ getExchangeRates }) => {
        getExchangeRates().then(rates => {
          setExchangeRates(rates);
        });
      });
    }
  }, [currency]);

  useEffect(() => {
    // Save to localStorage
    if (typeof window !== 'undefined') {
      localStorage.setItem('currency', currency);
    }
  }, [currency]);

  const setCurrencyWithSave = (newCurrency) => {
    setCurrency(newCurrency);
    localStorage.setItem('currency', newCurrency);
  };

  return (
    <CurrencyContext.Provider value={{ currency, setCurrency: setCurrencyWithSave, exchangeRates }}>
      {children}
    </CurrencyContext.Provider>
  );
};
