import React, { createContext, useContext, useEffect, useState, ReactNode, } from 'react'; import { CURRENCY } from '../utils/constants'; import systemSettingsService from '../services/api/systemSettingsService'; type CurrencyContextValue = { currency: string; isLoading: boolean; supportedCurrencies: string[]; refreshCurrency: () => Promise; }; const CurrencyContext = createContext(undefined); export const useCurrency = () => { const context = useContext(CurrencyContext); if (!context) { throw new Error('useCurrency must be used within CurrencyProvider'); } return context; }; interface CurrencyProviderProps { children: ReactNode; } export const CurrencyProvider: React.FC = ({ children }) => { const [currency, setCurrencyState] = useState(CURRENCY.VND); const [isLoading, setIsLoading] = useState(true); const supportedCurrencies = [ CURRENCY.VND, CURRENCY.USD, CURRENCY.EUR, 'GBP', 'JPY', 'CNY', 'KRW', 'SGD', 'THB', 'AUD', 'CAD', ]; // Load platform currency from system settings const loadCurrency = async () => { try { setIsLoading(true); const response = await systemSettingsService.getPlatformCurrency(); if (response.data?.currency && supportedCurrencies.includes(response.data.currency)) { const platformCurrency = response.data.currency; setCurrencyState(platformCurrency); // Store in localStorage so formatCurrency can access it localStorage.setItem('currency', platformCurrency); } else { // Fallback to default setCurrencyState(CURRENCY.VND); localStorage.setItem('currency', CURRENCY.VND); } } catch (error) { console.error('Error loading platform currency:', error); // Fallback to default setCurrencyState(CURRENCY.VND); localStorage.setItem('currency', CURRENCY.VND); } finally { setIsLoading(false); } }; useEffect(() => { loadCurrency(); }, []); const refreshCurrency = async () => { await loadCurrency(); // Dispatch a custom event to notify all components of currency change if (typeof window !== 'undefined') { window.dispatchEvent(new CustomEvent('currencyChanged', { detail: { currency: localStorage.getItem('currency') || CURRENCY.VND } })); } }; return ( {children} ); };