"use client";

import { useRouter } from "next/navigation";
import { useTransition } from "react";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  CURRENCY_COOKIE_NAME,
  isSupportedCurrency,
  SUPPORTED_CURRENCIES,
  type Currency,
} from "@/lib/billing/currency";

type Props = {
  value: Currency;
  /* Optional callback so the parent can react locally to the new currency
     in addition to the server refresh triggered by router.refresh(). */
  onChange?: (next: Currency) => void;
};

/* Client-side currency picker.

   Writes the user's choice to a non-httpOnly cookie (Path=/, 30 days,
   SameSite=Lax) so the server-side detection in detectCurrencyFromHeaders()
   can read it on subsequent renders, then calls router.refresh() inside a
   transition to re-render server components (prices) with the new value. */
export function CurrencySelector({ value, onChange }: Props) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  function handleChange(next: string) {
    if (!isSupportedCurrency(next)) return;
    document.cookie = `${CURRENCY_COOKIE_NAME}=${next}; Path=/; Max-Age=2592000; SameSite=Lax`;
    onChange?.(next);
    startTransition(() => {
      router.refresh();
    });
  }

  return (
    <Select value={value} onValueChange={handleChange} disabled={isPending}>
      <SelectTrigger className="w-[120px]">
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {SUPPORTED_CURRENCIES.map((c) => (
          <SelectItem key={c.code} value={c.code}>
            {c.code.toUpperCase()} {c.symbol}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
