import { cn } from '@/lib/cn';
import { ChevronDown } from 'lucide-react';
import type { CurrencyRow } from './types';

type Props = {
    currencies: CurrencyRow[];
    value: number;
    onChange: (currencyId: number) => void;
    /** Subscriber lock — pinned to the existing sub's currency. */
    disabled?: boolean;
    /** Hover/focus tooltip when locked. */
    lockReason?: string;
};

/**
 * Currency dropdown. Plain `<select>` styled to match the editor/form chrome
 * — no popover/combobox so keyboard + screen-reader behavior is the native
 * one without us reimplementing a11y. Subscribers are pinned to the sub's
 * currency (controlled via `disabled`); the `?switch_provider=1` flag on the
 * URL bypasses the lock by suppressing `currentSubscription` server-side.
 */
export default function CurrencyPicker({
    currencies,
    value,
    onChange,
    disabled = false,
    lockReason,
}: Props) {
    if (currencies.length === 0) return null;

    // No visible label — the `aria-label` on the select keeps screen-reader
    // semantics intact while the page's "Pick your plan." hero already gives
    // the pricing context. The wrapper is `relative` so we can absolutely
    // position our own chevron on the right; native `<select>` renders its
    // browser-default chevron flush against the element edge regardless of
    // `padding-right`, which clashes with the rounded-pill chrome. The
    // `appearance-none` class hides that native chevron; we draw a lucide
    // ChevronDown in its place with proper spacing.
    return (
        <div className="relative" title={disabled ? lockReason : undefined}>
            <select
                value={value}
                onChange={(e) => onChange(Number(e.target.value))}
                disabled={disabled}
                aria-label="Currency"
                data-testid="pricing-currency-picker"
                className={cn(
                    'h-9 min-w-[14rem] appearance-none rounded-full border border-border bg-card pl-5 pr-10 text-sm font-medium text-foreground shadow-sm transition-colors',
                    'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
                    disabled && 'cursor-not-allowed opacity-60',
                )}
            >
                {currencies.map((c) => (
                    <option key={c.id} value={c.id}>
                        {c.symbol} {c.code} — {c.name}
                    </option>
                ))}
            </select>
            <ChevronDown
                aria-hidden
                className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
            />
        </div>
    );
}
