"use client";

import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useSyncExternalStore,
  type ReactNode,
} from "react";

export type Currency = "BDT" | "USD" | "INR";

// Prices are stored in BDT; approximate display conversion rates.
const RATES: Record<Currency, { symbol: string; perBdt: number }> = {
  BDT: { symbol: "৳", perBdt: 1 },
  USD: { symbol: "$", perBdt: 1 / 120 },
  INR: { symbol: "₹", perBdt: 0.72 },
};

type CurrencyContextValue = {
  currency: Currency;
  setCurrency: (c: Currency) => void;
  format: (bdtAmount: number) => string;
  symbol: string;
};

const CurrencyContext = createContext<CurrencyContextValue | null>(null);

const STORAGE_KEY = "gbs-currency";

function subscribe(callback: () => void) {
  window.addEventListener("storage", callback);
  window.addEventListener("gbs-currency-change", callback);
  return () => {
    window.removeEventListener("storage", callback);
    window.removeEventListener("gbs-currency-change", callback);
  };
}

function getSnapshot(): Currency {
  const saved = window.localStorage.getItem(STORAGE_KEY);
  return saved === "USD" || saved === "INR" || saved === "BDT" ? saved : "BDT";
}

export function CurrencyProvider({ children }: { children: ReactNode }) {
  const currency = useSyncExternalStore(subscribe, getSnapshot, () => "BDT" as Currency);

  const setCurrency = useCallback((c: Currency) => {
    window.localStorage.setItem(STORAGE_KEY, c);
    window.dispatchEvent(new Event("gbs-currency-change"));
  }, []);

  const value = useMemo<CurrencyContextValue>(() => {
    const { symbol, perBdt } = RATES[currency];
    return {
      currency,
      setCurrency,
      symbol,
      format: (bdt: number) => {
        const amount = bdt * perBdt;
        const rounded =
          currency === "BDT" ? amount : Math.round(amount * 100) / 100;
        return `${symbol} ${rounded.toLocaleString(undefined, {
          maximumFractionDigits: currency === "BDT" ? 0 : 2,
        })}`;
      },
    };
  }, [currency, setCurrency]);

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

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

export function Price({ bdt, className }: { bdt: number; className?: string }) {
  const { format } = useCurrency();
  return <span className={className}>{format(bdt)}</span>;
}
