"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import { CurrencyCode, getUserCurrency, DEFAULT_CURRENCY } from "@/lib/geo";

interface CurrencyContextType {
  currency: CurrencyCode;
  loading: boolean;
}

const CurrencyContext = createContext<CurrencyContextType>({
  currency: DEFAULT_CURRENCY,
  loading: true,
});

export function CurrencyProvider({ children }: { children: React.ReactNode }) {
  const [currency, setCurrency] = useState<CurrencyCode>(DEFAULT_CURRENCY);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getUserCurrency()
      .then(setCurrency)
      .finally(() => setLoading(false));
  }, []);

  return (
    <CurrencyContext.Provider value={{ currency, loading }}>
      {children}
    </CurrencyContext.Provider>
  );
}

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