"use client";

import { useEffect, useState } from "react";
import { SUPPORTED_CURRENCIES, type Currency, isSupportedCurrency } from "@/lib/fx-rates";

// R14 E.1: small dropdown that writes the user's preferred display currency
// to a `display_currency` cookie. Server components can read the cookie
// and pass it to formatCurrency() to render locale-aware prices. Stripe
// still charges EUR — this is display only.
export default function CurrencySelector() {
  const [current, setCurrent] = useState<Currency>("EUR");

  useEffect(() => {
    if (typeof document === "undefined") return;
    const m = document.cookie.match(/display_currency=([^;]+)/);
    if (m && isSupportedCurrency(m[1])) {
      setCurrent(m[1]);
    }
  }, []);

  function handleChange(e: React.ChangeEvent<HTMLSelectElement>) {
    const next = e.target.value;
    if (!isSupportedCurrency(next)) return;
    setCurrent(next);
    // 1-year cookie, root path, lax so it survives most navigations.
    document.cookie = `display_currency=${next}; path=/; max-age=31536000; SameSite=Lax`;
    // Force a re-render of any server-rendered prices on the page.
    window.location.reload();
  }

  return (
    <select
      value={current}
      onChange={handleChange}
      aria-label="Display currency"
      className="bg-surface border border-surface-light rounded-lg px-2 py-1 text-xs text-text-muted hover:text-text focus:outline-none focus:ring-1 focus:ring-primary"
    >
      {SUPPORTED_CURRENCIES.map((c) => (
        <option key={c} value={c}>
          {c}
        </option>
      ))}
    </select>
  );
}
