'use client';

import { createContext, useContext, useEffect, useState } from 'react';
import type { CurrencyCode } from './currency';

type CurrencyContextValue = {
  currency: CurrencyCode;
  setCurrency: (c: CurrencyCode) => void;
};

const CurrencyContext = createContext<CurrencyContextValue>({
  currency: 'GBP',
  setCurrency: () => {},
});

export function CurrencyProvider({ children }: { children: React.ReactNode }) {
  const [currency, setCurrencyState] = useState<CurrencyCode>('GBP');

  useEffect(() => {
    const stored = localStorage.getItem('currency') as CurrencyCode | null;
    if (stored) setCurrencyState(stored);
  }, []);

  const setCurrency = (c: CurrencyCode) => {
    setCurrencyState(c);
    localStorage.setItem('currency', c);
  };

  return <CurrencyContext.Provider value={{ currency, setCurrency }}>{children}</CurrencyContext.Provider>;
}

export function useCurrency() {
  return useContext(CurrencyContext);
}
