// src/components/site/multi-combobox.tsx
// Multi-select combobox with chips (Base UI). Exposes string[] of codes.
"use client";

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

export function MultiCombobox({
  options,
  value,
  onValueChange,
  placeholder,
  withFlag,
}: {
  options: ComboOption[];
  value: string[];
  onValueChange: (next: string[]) => void;
  placeholder?: string;
  /** Country pickers only: prefix each item/chip with a <Flag> from value. */
  withFlag?: boolean;
}) {
  const anchor = useComboboxAnchor();
  const selected = options.filter((o) => value.includes(o.value));

  return (
    <Combobox
      items={options}
      multiple
      autoHighlight
      value={selected}
      onValueChange={(items: ComboOption[]) =>
        onValueChange(items.map((i) => i.value))
      }
      itemToStringLabel={(item: ComboOption) => item.label}
      isItemEqualToValue={(a: ComboOption, b: ComboOption) =>
        a.value === b.value
      }
    >
      <ComboboxChips ref={anchor}>
        <ComboboxValue>
          {(items: ComboOption[]) => (
            <>
              {items.map((item) => (
                <ComboboxChip key={item.value}>
                  {withFlag ? (
                    <span className="inline-flex items-center gap-1.5">
                      <Flag code={item.value} className="h-3" />
                      {item.label}
                    </span>
                  ) : (
                    item.label
                  )}
                </ComboboxChip>
              ))}
              <ComboboxChipsInput
                placeholder={items.length ? undefined : placeholder}
              />
            </>
          )}
        </ComboboxValue>
      </ComboboxChips>
      <ComboboxContent anchor={anchor}>
        <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>
  );
}
