"use client";

import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { currencies, type Currency } from "@alterra/shared";

const STORAGE_KEY = "alterra-currency";

const CurrencyContext = createContext<{ currency: Currency; setCurrency: (c: Currency) => void }>({
  currency: "USD",
  setCurrency: () => {},
});

export const useCurrency = () => useContext(CurrencyContext);

/** Remembers the visitor's currency; defaults to USD in English and COP in Spanish. */
export function CurrencyProvider({ initial, children }: { initial: Currency; children: React.ReactNode }) {
  const [currency, setCurrencyState] = useState<Currency>(initial);

  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved === "COP" || saved === "USD") setCurrencyState(saved);
    } catch {}
  }, []);

  const setCurrency = useCallback((next: Currency) => {
    setCurrencyState(next);
    try {
      localStorage.setItem(STORAGE_KEY, next);
    } catch {}
  }, []);

  return <CurrencyContext.Provider value={{ currency, setCurrency }}>{children}</CurrencyContext.Provider>;
}

export function CurrencySwitch({ label, className = "" }: { label: string; className?: string }) {
  const { currency, setCurrency } = useCurrency();
  return (
    <div role="group" aria-label={label} className={`flex items-center gap-1 text-[0.68rem] font-semibold tracking-[0.18em] ${className}`}>
      {currencies.map((c, i) => (
        <span key={c} className="flex items-center gap-1">
          {i > 0 && <span className="opacity-30">/</span>}
          <button
            type="button"
            onClick={() => setCurrency(c)}
            aria-pressed={currency === c}
            className={`px-0.5 py-1 transition ${currency === c ? "text-gold-light" : "opacity-60 hover:opacity-100"}`}
          >
            {c}
          </button>
        </span>
      ))}
    </div>
  );
}
