// src/components/site/single-combobox.tsx
// Single-select searchable combobox with flags (Base UI). Exposes a string code.
"use client";

import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
} from "@/components/ui/combobox";
import { Flag } from "@/components/ui/flag";
import type { ComboOption } from "@/lib/sites/options";

export function SingleCombobox({
  options,
  value,
  onValueChange,
  placeholder,
  ariaLabel,
  withFlag,
}: {
  options: ComboOption[];
  value: string;
  onValueChange: (next: string) => void;
  placeholder?: string;
  ariaLabel?: string;
  /** Country pickers only: prefix each item with a <Flag> derived from value. */
  withFlag?: boolean;
}) {
  const selected = options.find((o) => o.value === value) ?? null;

  return (
    <Combobox
      items={options}
      autoHighlight
      value={selected}
      onValueChange={(item: ComboOption | null) => {
        // ignore null (cleared input): the field is required, keep last value
        if (item) onValueChange(item.value);
      }}
      itemToStringLabel={(item: ComboOption) => item.label}
      isItemEqualToValue={(a: ComboOption, b: ComboOption) =>
        a.value === b.value
      }
    >
      <ComboboxInput
        className="w-full"
        placeholder={placeholder}
        aria-label={ariaLabel}
      />
      <ComboboxContent>
        <ComboboxEmpty>Aucun résultat.</ComboboxEmpty>
        <ComboboxList>
          {(item: ComboOption) => (
            <ComboboxItem key={item.value} value={item}>
              {withFlag ? (
                <span className="inline-flex items-center gap-1.5">
                  <Flag code={item.value} className="h-3.5" />
                  {item.label}
                </span>
              ) : (
                item.label
              )}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  );
}
