"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";

type Currency = "USD" | "THB";

// `properties.price` is stored in THB. `format` accepts that THB value and
// converts to USD only when the user toggles the currency switcher.
type Ctx = {
  currency: Currency;
  setCurrency: (c: Currency) => void;
  format: (priceThb: number) => string;
  rateTHB: number; // THB per 1 USD
};

const CurrencyContext = createContext<Ctx | null>(null);
const FALLBACK_THB = 36.5;

export function CurrencyProvider({ children }: { children: React.ReactNode }) {
  // Default to THB: prices are stored in THB and the listings are in
  // Thailand. USD remains one toggle-click away for foreign buyers.
  const [currency, setCurrencyState] = useState<Currency>("THB");
  const [rateTHB, setRate] = useState<number>(FALLBACK_THB);

  useEffect(() => {
    const saved = localStorage.getItem("currency") as Currency | null;
    if (saved === "USD" || saved === "THB") setCurrencyState(saved);
    fetch("https://open.er-api.com/v6/latest/USD", { cache: "force-cache" })
      .then((r) => r.json())
      .then((d) => {
        const t = d?.rates?.THB;
        if (typeof t === "number" && t > 0) setRate(t);
      })
      .catch(() => {});
  }, []);

  const setCurrency = useCallback((c: Currency) => {
    setCurrencyState(c);
    try {
      localStorage.setItem("currency", c);
    } catch {}
  }, []);

  const format = useCallback(
    (priceThb: number) => {
      if (currency === "THB") {
        return `฿${Math.round(priceThb).toLocaleString()}`;
      }
      const usd = rateTHB > 0 ? priceThb / rateTHB : priceThb;
      return `$${Math.round(usd).toLocaleString()}`;
    },
    [currency, rateTHB],
  );

  const value = useMemo(
    () => ({ currency, setCurrency, format, rateTHB }),
    [currency, setCurrency, format, rateTHB],
  );
  return (
    <CurrencyContext.Provider value={value}>
      {children}
    </CurrencyContext.Provider>
  );
}

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

export function CurrencyToggle() {
  const { currency, setCurrency } = useContext(CurrencyContext) ?? {
    currency: "USD",
    setCurrency: () => {},
  };
  return (
    <div className="inline-flex items-center gap-0.5 rounded-full border border-border bg-surface p-0.5 text-[12px]">
      {(["USD", "THB"] as const).map((c) => (
        <button
          key={c}
          type="button"
          onClick={() => setCurrency(c)}
          className={`rounded-full px-3 py-1 transition ${currency === c ? "bg-text text-bg" : "text-text-muted hover:text-text"}`}
        >
          {c}
        </button>
      ))}
    </div>
  );
}

export function Price({ thb }: { thb: number }) {
  const ctx = useContext(CurrencyContext);
  if (!ctx) return <>฿{Math.round(thb).toLocaleString()}</>;
  return <>{ctx.format(thb)}</>;
}
