'use strict';

var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var SelectFieldWrapper = require('./SelectFieldWrapper-DKkizQNM.js');
var utils = require('./utils-BhM0B89p.js');
var primitives_Combobox = require('./Combobox-C3PiYYF-.js');
var primitives_Spinner = require('./primitives/Spinner.js');
var x = require('./x-Brw3FJst.js');
var chevronDown = require('./chevron-down-CPsWSS51.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

function hyphenize(str) {
  return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
}

function buildAriaDescribedBy(error, errorId, helpText, helpTextId) {
  return [error ? errorId : null, helpText ? helpTextId : null].filter(Boolean).join(" ") || void 0;
}
function buildTestIdPrefix(dataTestId, label) {
  return dataTestId ?? (label ? hyphenize(label) : void 0);
}

function useAsyncOptions({
  loadOptions,
  defaultOptions = false,
  cacheOptions = false
}) {
  const [asyncOptions, setAsyncOptions] = React.useState(
    () => Array.isArray(defaultOptions) ? defaultOptions : []
  );
  const [isLoading, setIsLoading] = React.useState(false);
  const cacheRef = React.useRef({});
  const debounceRef = React.useRef(null);
  const latestRequestRef = React.useRef(0);
  const mountedRef = React.useRef(true);
  React.useEffect(() => {
    if (!loadOptions || defaultOptions !== true) return;
    let cancelled = false;
    setIsLoading(true);
    loadOptions("").then((results) => {
      if (cancelled) return;
      setAsyncOptions(results);
      if (cacheOptions) cacheRef.current[""] = results;
      setIsLoading(false);
    }).catch(() => {
      if (!cancelled) setIsLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  React.useEffect(() => {
    return () => {
      mountedRef.current = false;
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, []);
  const handleAsyncInputChange = React.useCallback(
    (value) => {
      if (!loadOptions) return;
      const query = value.trim();
      if (cacheOptions && query in cacheRef.current) {
        setAsyncOptions(cacheRef.current[query]);
        return;
      }
      if (debounceRef.current) clearTimeout(debounceRef.current);
      debounceRef.current = setTimeout(() => {
        const requestId = ++latestRequestRef.current;
        setIsLoading(true);
        loadOptions(query).then((results) => {
          if (requestId !== latestRequestRef.current || !mountedRef.current)
            return;
          setAsyncOptions(results);
          if (cacheOptions) cacheRef.current[query] = results;
          setIsLoading(false);
        }).catch(() => {
          if (requestId === latestRequestRef.current && mountedRef.current) {
            setIsLoading(false);
          }
        });
      }, 300);
    },
    [loadOptions, cacheOptions]
  );
  return { asyncOptions, isLoading, handleAsyncInputChange };
}

function useLazyLoadSentinel({
  fetchMore,
  isEnabled
}) {
  const observerRef = React.useRef(null);
  const fetchMoreRef = React.useRef(fetchMore);
  fetchMoreRef.current = fetchMore;
  const sentinelRef = React.useCallback(
    (node) => {
      observerRef.current?.disconnect();
      observerRef.current = null;
      if (!node || !isEnabled) return;
      const observer = new IntersectionObserver(
        (entries) => {
          if (entries[0]?.isIntersecting) fetchMoreRef.current?.();
        },
        { root: null, rootMargin: "0px", threshold: 0.1 }
      );
      observer.observe(node);
      observerRef.current = observer;
    },
    [isEnabled]
  );
  React.useEffect(() => {
    return () => {
      observerRef.current?.disconnect();
    };
  }, []);
  return sentinelRef;
}

const CREATE_PREFIX = "__create__:";
const isCreateValue = (val) => typeof val === "string" && val.startsWith(CREATE_PREFIX);
function useCreatableItems({
  isCreatable,
  isGrouped,
  flatOptions,
  selectedValues,
  baseUiItems,
  onCreateOption,
  onChange,
  onAsyncInputChange,
  children
}) {
  const [inputValue, setInputValue] = React.useState("");
  const handleInputValueChange = React.useCallback(
    (value) => {
      setInputValue(value);
      onAsyncInputChange?.(value);
    },
    [onAsyncInputChange]
  );
  const trimmedInput = inputValue.trim();
  const showCreateOption = React.useMemo(() => {
    if (!isCreatable || trimmedInput.length === 0) return false;
    const lower = trimmedInput.toLowerCase();
    return !flatOptions.some(
      (o) => o.label.toLowerCase() === lower || o.value.toLowerCase() === lower
    ) && !selectedValues.includes(trimmedInput);
  }, [isCreatable, trimmedInput, flatOptions, selectedValues]);
  const effectiveItems = React__default.default.useMemo(
    () => computeEffectiveItems(
      children,
      baseUiItems,
      showCreateOption,
      isGrouped,
      trimmedInput
    ),
    [baseUiItems, children, isGrouped, showCreateOption, trimmedInput]
  );
  const creatableFilter = React.useCallback(
    (itemValue, query, itemToString) => {
      if (isCreateValue(itemValue)) return true;
      const label = itemToString?.(itemValue) ?? itemValue;
      return label.toLowerCase().includes(query.toLowerCase());
    },
    []
  );
  const handleValueChange = React.useCallback(
    (next) => {
      const raw = next ?? [];
      const createEntry = raw.find((v) => isCreateValue(v));
      if (createEntry) {
        const newValue = createEntry.slice(CREATE_PREFIX.length);
        const withNewValue = raw.map((v) => v === createEntry ? newValue : v);
        onCreateOption?.(newValue);
        onChange?.(withNewValue);
        return;
      }
      onChange?.(raw);
    },
    [onChange, onCreateOption]
  );
  return {
    inputValue,
    showCreateOption,
    effectiveItems,
    creatableFilter,
    handleInputValueChange,
    handleValueChange
  };
}

function isOptionGroup(opt) {
  return "options" in opt && Array.isArray(opt.options);
}

function normalizeOption(option, getValue, getLabel) {
  if (!getValue && !getLabel) return option;
  return {
    ...option,
    value: getValue ? getValue(option) : option?.value,
    label: getLabel ? getLabel(option) : option?.label
  };
}
function normalizeOptions(options, getValue, getLabel) {
  if (!options) return options;
  if (!getValue && !getLabel) return options;
  return options.map(
    (opt) => opt && Array.isArray(opt.options) ? {
      ...opt,
      options: opt.options.map(
        (o) => normalizeOption(o, getValue, getLabel)
      )
    } : normalizeOption(opt, getValue, getLabel)
  );
}
function flattenOptions(options) {
  return options.flatMap((opt) => isOptionGroup(opt) ? opt.options : [opt]);
}
function hasGroups(options) {
  return options.some(isOptionGroup);
}
function toBaseUiItems(options) {
  if (hasGroups(options)) {
    return options.filter(isOptionGroup).map((g) => ({
      label: g.label,
      items: g.options.map((o) => o.value)
    }));
  }
  return options.map((o) => o.value);
}
function computeEffectiveItems(children, baseUiItems, showCreateOption, isGrouped, trimmedInput) {
  if (children) return void 0;
  const createValue = showCreateOption ? `${CREATE_PREFIX}${trimmedInput}` : null;
  if (!baseUiItems && !createValue) return void 0;
  const base = baseUiItems ?? [];
  if (!createValue) return base;
  if (!isGrouped) {
    return [...base, createValue];
  }
  return [
    ...base,
    { label: "", items: [createValue] }
  ];
}

function useMultiSelectOptions(props) {
  const isAsync = !!props.loadOptions;
  const { asyncOptions, isLoading, handleAsyncInputChange } = useAsyncOptions({
    loadOptions: props.loadOptions,
    defaultOptions: props.defaultOptions ?? false,
    cacheOptions: props.cacheOptions ?? false
  });
  const resolvedOptions = isAsync ? asyncOptions : props.options ?? [];
  const flatOptions = flattenOptions(resolvedOptions);
  const isGrouped = hasGroups(resolvedOptions);
  const baseUiItems = React__default.default.useMemo(
    () => resolvedOptions.length > 0 ? toBaseUiItems(resolvedOptions) : void 0,
    [resolvedOptions]
  );
  const hasMoreLazy = (props.isAsyncLoadOptionEnabled ?? false) && typeof props.totalOptionsCount === "number" && flatOptions.length < props.totalOptionsCount;
  const loaderCallbackRef = useLazyLoadSentinel({
    fetchMore: props.fetchMore,
    isEnabled: props.isAsyncLoadOptionEnabled ?? false
  });
  return {
    isAsync,
    resolvedOptions,
    flatOptions,
    isGrouped,
    isLoading,
    handleAsyncInputChange,
    baseUiItems,
    hasMoreLazy,
    loaderCallbackRef
  };
}

const SIZE_CONFIG = {
  small: {
    chips: "min-h-8 md:min-h-7 text-base md:text-xs gap-0.5 px-1 py-0.5",
    input: "text-base md:text-xs",
    chip: "h-4.5 text-[0.6875rem] px-1",
    icon: "size-3.5"
  },
  medium: {
    chips: "min-h-8 text-base md:text-sm gap-1 px-2.5 py-1",
    input: "text-base md:text-sm",
    chip: "h-5.25 text-xs px-1.5",
    icon: "size-4"
  },
  large: {
    chips: "min-h-10 text-base md:text-sm gap-1 px-2.5 py-1.5",
    input: "text-base md:text-sm",
    chip: "h-6 text-xs px-2",
    icon: "size-5"
  }
};

const defaultFormatCreateLabel$1 = (v) => `Create "${v}"`;
function useSelectState(props) {
  const {
    id: idProp,
    size = "medium",
    label = "",
    error = "",
    helpText = "",
    value: valueProp,
    defaultValue,
    onChange,
    dataTestId,
    isCreatable = false,
    onCreateOption,
    formatCreateLabel = defaultFormatCreateLabel$1,
    formatOptionLabel,
    formatTriggerLabel,
    isClearable = false,
    isDisabled = false,
    required = false,
    isSearchable = true,
    autoHighlight = true,
    onOpenChange,
    children
  } = props;
  const opt = useMultiSelectOptions(props);
  const generatedId = React.useId();
  const id = idProp ?? generatedId;
  const errorId = `error_${id}`;
  const helpTextId = `helpText_${id}`;
  const sizeConfig = SIZE_CONFIG[size];
  const isControlled = valueProp !== void 0;
  const [internalValue, setInternalValue] = React.useState(
    defaultValue ?? ""
  );
  const currentValue = isControlled ? valueProp ?? "" : internalValue;
  const applyValue = React.useCallback(
    (next) => {
      if (!isControlled) setInternalValue(next);
      onChange?.(next);
    },
    [isControlled, onChange]
  );
  const handleValueChange = React.useCallback(
    (next) => {
      const raw = next ?? "";
      if (raw.startsWith(CREATE_PREFIX)) {
        const newValue = raw.slice(CREATE_PREFIX.length);
        onCreateOption?.(newValue);
        applyValue(newValue);
        return;
      }
      applyValue(raw);
    },
    [applyValue, onCreateOption]
  );
  const [inputValue, setInputValueState] = React.useState("");
  const trimmedInput = inputValue.trim();
  const combinedHandleInputValueChange = React.useCallback(
    (value) => {
      setInputValueState(value);
      if (opt.isAsync) opt.handleAsyncInputChange(value);
    },
    [opt.isAsync, opt.handleAsyncInputChange]
  );
  const handleClear = React.useCallback(() => {
    applyValue("");
  }, [applyValue]);
  const showCreateOption = React.useMemo(() => {
    if (!isCreatable || trimmedInput.length === 0 || currentValue === trimmedInput)
      return false;
    const lower = trimmedInput.toLowerCase();
    return !opt.flatOptions.some(
      (o) => o.label.toLowerCase() === lower || o.value.toLowerCase() === lower
    );
  }, [isCreatable, trimmedInput, currentValue, opt.flatOptions]);
  const effectiveItems = React.useMemo(() => {
    if (children) return void 0;
    const base = opt.baseUiItems;
    if (!showCreateOption) return base;
    const createValue = `${CREATE_PREFIX}${trimmedInput}`;
    if (!opt.isGrouped) {
      return [...base ?? [], createValue];
    }
    return [
      ...base ?? [],
      { label: "", items: [createValue] }
    ];
  }, [
    children,
    opt.baseUiItems,
    opt.isGrouped,
    showCreateOption,
    trimmedInput
  ]);
  const creatableFilter = React.useCallback(
    (itemValue, query, itemToString) => {
      if (isCreateValue(itemValue)) return true;
      const label2 = itemToString?.(itemValue) ?? itemValue;
      return label2.toLowerCase().includes(query.toLowerCase());
    },
    []
  );
  const ariaDescribedBy = buildAriaDescribedBy(
    error,
    errorId,
    helpText,
    helpTextId
  );
  const testIdPrefix = buildTestIdPrefix(dataTestId, label);
  const showClearButton = isClearable && !!currentValue && !isDisabled;
  const flatOptionsMap = React.useMemo(
    () => new Map(opt.flatOptions.map((o) => [o.value, o])),
    [opt.flatOptions]
  );
  const labelForValue = React.useCallback(
    (val) => {
      if (isCreateValue(val)) {
        return formatCreateLabel(val.slice(CREATE_PREFIX.length));
      }
      return flatOptionsMap.get(val)?.label ?? val ?? "";
    },
    [flatOptionsMap, formatCreateLabel]
  );
  const renderOption = React.useCallback(
    (val) => {
      if (formatOptionLabel && !isCreateValue(val)) {
        const option = flatOptionsMap.get(val);
        if (option) return formatOptionLabel(option);
      }
      return labelForValue(val);
    },
    [formatOptionLabel, flatOptionsMap, labelForValue]
  );
  const renderTrigger = React.useCallback(
    (val) => {
      if (formatTriggerLabel && !isCreateValue(val)) {
        const option = flatOptionsMap.get(val);
        if (option) return formatTriggerLabel(option);
      }
      return renderOption(val);
    },
    [formatTriggerLabel, flatOptionsMap, renderOption]
  );
  return {
    ...opt,
    id,
    errorId,
    helpTextId,
    sizeConfig,
    isControlled,
    currentValue,
    effectiveItems,
    creatableFilter,
    handleValueChange,
    handleInputValueChange: combinedHandleInputValueChange,
    handleClear,
    showCreateOption,
    showClearButton,
    ariaDescribedBy,
    testIdPrefix,
    labelForValue,
    renderOption,
    renderTrigger,
    flatOptionsMap,
    label,
    error,
    helpText,
    isDisabled,
    required,
    isSearchable,
    autoHighlight,
    onOpenChange,
    isClearable
  };
}

const defaultFormatCreateLabel = (v) => `Create "${v}"`;
function useMultiSelectState(props) {
  const {
    id: idProp,
    size = "medium",
    label = "",
    error = "",
    helpText = "",
    value: valueProp,
    defaultValue,
    onChange,
    dataTestId,
    isCreatable = false,
    onCreateOption,
    formatCreateLabel = defaultFormatCreateLabel,
    formatOptionLabel,
    children
  } = props;
  const opt = useMultiSelectOptions(props);
  const generatedId = React.useId();
  const id = idProp ?? generatedId;
  const errorId = `error_${id}`;
  const helpTextId = `helpText_${id}`;
  const sizeConfig = SIZE_CONFIG[size];
  const isControlled = valueProp !== void 0;
  const [internalValue, setInternalValue] = React.useState(
    defaultValue ?? []
  );
  const selectedValues = isControlled ? valueProp : internalValue;
  const handleChange = React.useCallback(
    (values) => {
      setInternalValue(values);
      onChange?.(values);
    },
    [onChange]
  );
  const {
    showCreateOption,
    effectiveItems,
    creatableFilter,
    handleInputValueChange,
    handleValueChange
  } = useCreatableItems({
    isCreatable,
    isGrouped: opt.isGrouped,
    flatOptions: opt.flatOptions,
    selectedValues,
    baseUiItems: opt.baseUiItems,
    onCreateOption,
    onChange: handleChange,
    onAsyncInputChange: opt.isAsync ? opt.handleAsyncInputChange : void 0,
    children
  });
  const ariaDescribedBy = buildAriaDescribedBy(
    error,
    errorId,
    helpText,
    helpTextId
  );
  const testIdPrefix = buildTestIdPrefix(dataTestId, label);
  const flatOptionsMap = React.useMemo(
    () => new Map(opt.flatOptions.map((o) => [o.value, o])),
    [opt.flatOptions]
  );
  const labelForValue = React.useCallback(
    (val) => {
      if (isCreateValue(val)) {
        return formatCreateLabel(val.slice(CREATE_PREFIX.length));
      }
      return flatOptionsMap.get(val)?.label ?? val ?? "";
    },
    [flatOptionsMap, formatCreateLabel]
  );
  const renderOption = React.useCallback(
    (val) => {
      if (formatOptionLabel && !isCreateValue(val)) {
        const option = flatOptionsMap.get(val);
        if (option) return formatOptionLabel(option);
      }
      return labelForValue(val);
    },
    [formatOptionLabel, flatOptionsMap, labelForValue]
  );
  return {
    ...opt,
    id,
    errorId,
    helpTextId,
    sizeConfig,
    isControlled,
    selectedValues,
    effectiveItems,
    creatableFilter,
    handleInputValueChange,
    handleValueChange,
    showCreateOption,
    ariaDescribedBy,
    testIdPrefix,
    labelForValue,
    renderOption,
    flatOptionsMap,
    label,
    error,
    helpText
  };
}

function OptionItem({
  val,
  flatOptionsMap,
  renderOption,
  testIdPrefix
}) {
  const isCreateItem = isCreateValue(val);
  return /* @__PURE__ */ jsxRuntime.jsx(
    primitives_Combobox.ComboboxItem,
    {
      value: val,
      disabled: !isCreateItem && flatOptionsMap.get(val)?.disabled,
      className: isCreateItem ? "text-primary" : void 0,
      ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-option` } : {},
      children: renderOption(val)
    },
    val
  );
}

function MultiSelectDropdown({
  resolvedOptions,
  flatOptionsMap,
  isGrouped,
  isLoading,
  loadingMessage,
  emptyMessage,
  showCreateOption,
  renderOption,
  testIdPrefix,
  hasMoreLazy,
  loaderCallbackRef,
  children
}) {
  return /* @__PURE__ */ jsxRuntime.jsxs(
    primitives_Combobox.ComboboxList,
    {
      ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-menu` } : {},
      children: [
        isLoading && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex w-full justify-center py-2 text-center text-sm text-muted-foreground", children: loadingMessage }),
        !isLoading && !showCreateOption && /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxEmpty, { children: emptyMessage }),
        children ?? (resolvedOptions.length > 0 || showCreateOption ? isGrouped ? /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxCollection, { children: (group) => /* @__PURE__ */ jsxRuntime.jsxs(
          primitives_Combobox.ComboboxGroup,
          {
            items: group.items,
            children: [
              group.label && /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxLabel, { children: group.label }),
              /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxCollection, { children: (val) => /* @__PURE__ */ jsxRuntime.jsx(
                OptionItem,
                {
                  val,
                  flatOptionsMap,
                  renderOption,
                  testIdPrefix
                },
                val
              ) })
            ]
          },
          group.label || "__create__"
        ) }) : /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxCollection, { children: (val) => /* @__PURE__ */ jsxRuntime.jsx(
          OptionItem,
          {
            val,
            flatOptionsMap,
            renderOption,
            testIdPrefix
          },
          val
        ) }) : null),
        hasMoreLazy && /* @__PURE__ */ jsxRuntime.jsx(
          "div",
          {
            ref: loaderCallbackRef,
            className: "flex w-full items-center justify-center py-3",
            "data-testid": testIdPrefix ? `${testIdPrefix}-lazy-loader` : "lazy-loader",
            children: /* @__PURE__ */ jsxRuntime.jsx(primitives_Spinner.Spinner, {})
          }
        )
      ]
    }
  );
}

const SelectAnchor = React.forwardRef(
  ({ isSearchable, className, dataTestId, children }, ref) => {
    if (isSearchable) {
      return /* @__PURE__ */ jsxRuntime.jsx(
        "div",
        {
          ref,
          className,
          ...dataTestId ? { "data-testid": dataTestId } : {},
          children
        }
      );
    }
    return /* @__PURE__ */ jsxRuntime.jsx(
      primitives_Combobox.ComboboxTrigger$1,
      {
        nativeButton: false,
        render: (props) => /* @__PURE__ */ jsxRuntime.jsx(
          "div",
          {
            ...props,
            ref,
            className,
            ...dataTestId ? { "data-testid": dataTestId } : {}
          }
        ),
        children
      }
    );
  }
);
SelectAnchor.displayName = "SelectAnchor";

const SelectCombobox = React.forwardRef(
  ({
    name,
    id,
    effectiveItems,
    labelForValue,
    renderOption,
    renderTrigger,
    isSearchable,
    isAsync,
    isCreatable,
    creatableFilter,
    currentValue,
    handleValueChange,
    handleInputValueChange,
    handleClear,
    onOpenChange,
    isDisabled,
    autoHighlight,
    required,
    showClearButton,
    sizeConfig,
    error,
    placeholder,
    ariaDescribedBy,
    testIdPrefix,
    inputClassName,
    contentProps,
    dropdownProps,
    children
  }, ref) => {
    const [anchorEl, setAnchorEl] = React.useState(null);
    const handleClearClick = React.useCallback(
      (event) => {
        event.stopPropagation();
        event.preventDefault();
        handleClear();
      },
      [handleClear]
    );
    return (
      // @ts-expect-error — conditional spread creates a union that TS cannot narrow to the Combobox discriminated-union props
      /* @__PURE__ */ jsxRuntime.jsxs(
        primitives_Combobox.Combobox,
        {
          name,
          ...effectiveItems && !children ? {
            items: effectiveItems,
            itemToStringLabel: labelForValue,
            ...!isSearchable || isAsync ? { filter: null } : isCreatable ? { filter: creatableFilter } : {}
          } : {},
          value: currentValue,
          onValueChange: handleValueChange,
          ...isCreatable || isAsync ? { onInputValueChange: handleInputValueChange } : {},
          onOpenChange,
          disabled: isDisabled,
          autoHighlight,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              SelectAnchor,
              {
                ref: setAnchorEl,
                isSearchable,
                dataTestId: testIdPrefix,
                className: !isSearchable ? "cursor-pointer" : void 0,
                children: /* @__PURE__ */ jsxRuntime.jsxs(
                  primitives_Combobox.ComboboxChips,
                  {
                    className: utils.cn(
                      sizeConfig.chips,
                      !!error && "border-destructive ring-3 ring-destructive/20 dark:border-destructive/50 dark:ring-destructive/40",
                      inputClassName
                    ),
                    ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-container` } : {},
                    children: [
                      !isSearchable && (currentValue ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "flex-1 truncate", children: renderTrigger(currentValue) }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "flex-1 truncate text-muted-foreground", children: placeholder })),
                      /* @__PURE__ */ jsxRuntime.jsx(
                        primitives_Combobox.ComboboxChipsInput,
                        {
                          ref,
                          id,
                          placeholder: isSearchable && !currentValue ? placeholder : void 0,
                          "aria-invalid": !!error || void 0,
                          "aria-describedby": ariaDescribedBy,
                          "aria-required": required || void 0,
                          className: utils.cn(
                            sizeConfig.input,
                            !isSearchable && "w-0 min-w-0 overflow-hidden p-0 opacity-0"
                          ),
                          disabled: isDisabled,
                          ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-input` } : {}
                        }
                      ),
                      showClearButton && /* @__PURE__ */ jsxRuntime.jsx(
                        "button",
                        {
                          type: "button",
                          tabIndex: -1,
                          "aria-label": "Clear selection",
                          className: "shrink-0 text-muted-foreground hover:text-foreground",
                          onClick: handleClearClick,
                          children: /* @__PURE__ */ jsxRuntime.jsx(x.X, { className: sizeConfig.icon })
                        }
                      ),
                      isSearchable ? /* @__PURE__ */ jsxRuntime.jsx(
                        primitives_Combobox.ComboboxTrigger,
                        {
                          className: utils.cn(
                            "shrink-0 bg-transparent p-0 text-muted-foreground hover:bg-transparent",
                            sizeConfig.icon
                          )
                        }
                      ) : /* @__PURE__ */ jsxRuntime.jsx(
                        chevronDown.ChevronDown,
                        {
                          "aria-hidden": true,
                          className: utils.cn(
                            "pointer-events-none shrink-0 text-muted-foreground",
                            sizeConfig.icon
                          )
                        }
                      )
                    ]
                  }
                )
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxContent, { anchor: anchorEl, ...contentProps, children: /* @__PURE__ */ jsxRuntime.jsx(
              MultiSelectDropdown,
              {
                ...dropdownProps,
                renderOption,
                testIdPrefix,
                children
              }
            ) })
          ]
        }
      )
    );
  }
);
SelectCombobox.displayName = "SelectCombobox";

const MultiSelectCombobox = React.forwardRef(
  ({
    name,
    id,
    effectiveItems,
    labelForValue,
    renderOption,
    isSearchable,
    isAsync,
    isCreatable,
    creatableFilter,
    isControlled,
    valueProp,
    defaultValue,
    selectedValues,
    handleValueChange,
    handleInputValueChange,
    onOpenChange,
    isDisabled,
    autoHighlight,
    required,
    sizeConfig,
    error,
    chipsClassName,
    inputClassName,
    placeholder,
    hideChipRemove,
    ariaDescribedBy,
    testIdPrefix,
    contentProps,
    dropdownProps,
    children
  }, ref) => {
    const [anchorEl, setAnchorEl] = React.useState(null);
    return (
      // @ts-expect-error — conditional spread creates a union that TS cannot narrow to the Combobox discriminated-union props
      /* @__PURE__ */ jsxRuntime.jsxs(
        primitives_Combobox.Combobox,
        {
          multiple: true,
          name,
          ...effectiveItems && !children ? {
            items: effectiveItems,
            itemToStringLabel: labelForValue,
            ...!isSearchable || isAsync ? { filter: null } : isCreatable ? { filter: creatableFilter } : {}
          } : {},
          ...isControlled ? { value: valueProp } : { defaultValue },
          onValueChange: handleValueChange,
          ...isCreatable || isAsync ? { onInputValueChange: handleInputValueChange } : {},
          onOpenChange,
          disabled: isDisabled,
          autoHighlight,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              SelectAnchor,
              {
                ref: setAnchorEl,
                isSearchable,
                className: !isSearchable ? "cursor-pointer" : void 0,
                children: /* @__PURE__ */ jsxRuntime.jsxs(
                  primitives_Combobox.ComboboxChips,
                  {
                    className: utils.cn(
                      sizeConfig.chips,
                      !!error && "border-destructive ring-3 ring-destructive/20 dark:border-destructive/50 dark:ring-destructive/40",
                      chipsClassName,
                      inputClassName
                    ),
                    ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-container` } : {},
                    children: [
                      selectedValues.map((val) => /* @__PURE__ */ jsxRuntime.jsx(
                        primitives_Combobox.ComboboxChip,
                        {
                          className: sizeConfig.chip,
                          showRemove: !hideChipRemove,
                          ...testIdPrefix ? { "data-testid": `${testIdPrefix}-chip` } : {},
                          children: renderOption(val)
                        },
                        val
                      )),
                      /* @__PURE__ */ jsxRuntime.jsx(
                        primitives_Combobox.ComboboxChipsInput,
                        {
                          ref,
                          id,
                          placeholder: isSearchable && selectedValues.length === 0 ? placeholder : void 0,
                          "aria-invalid": !!error || void 0,
                          "aria-describedby": ariaDescribedBy,
                          "aria-required": required || void 0,
                          className: utils.cn(
                            sizeConfig.input,
                            !isSearchable && "w-0 min-w-0 overflow-hidden p-0 opacity-0"
                          ),
                          disabled: isDisabled,
                          ...testIdPrefix ? { "data-testid": `${testIdPrefix}-select-input` } : {}
                        }
                      )
                    ]
                  }
                )
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(primitives_Combobox.ComboboxContent, { anchor: anchorEl, ...contentProps, children: /* @__PURE__ */ jsxRuntime.jsx(
              MultiSelectDropdown,
              {
                ...dropdownProps,
                renderOption,
                testIdPrefix,
                children
              }
            ) })
          ]
        }
      )
    );
  }
);
MultiSelectCombobox.displayName = "MultiSelectCombobox";

const SingleSelectInner = React.forwardRef(
  (props, ref) => {
    const {
      id,
      label,
      error,
      helpText,
      errorId,
      helpTextId,
      isDisabled,
      required,
      testIdPrefix,
      effectiveItems,
      labelForValue,
      renderOption,
      renderTrigger,
      isSearchable,
      isAsync,
      creatableFilter,
      isControlled,
      currentValue,
      handleValueChange,
      handleInputValueChange,
      handleClear,
      autoHighlight,
      showClearButton,
      sizeConfig,
      ariaDescribedBy,
      resolvedOptions,
      flatOptionsMap,
      isGrouped,
      isLoading,
      showCreateOption,
      hasMoreLazy,
      loaderCallbackRef
    } = useSelectState(props);
    return /* @__PURE__ */ jsxRuntime.jsx(
      SelectFieldWrapper.SelectFieldWrapper,
      {
        id,
        label,
        error,
        helpText,
        errorId,
        helpTextId,
        isDisabled,
        required,
        testIdPrefix,
        labelProps: props.labelProps,
        className: props.className,
        children: /* @__PURE__ */ jsxRuntime.jsx(
          SelectCombobox,
          {
            ref,
            name: props.name,
            id,
            effectiveItems,
            labelForValue,
            renderOption,
            renderTrigger,
            isSearchable,
            isAsync,
            isCreatable: props.isCreatable ?? false,
            creatableFilter,
            isControlled,
            valueProp: props.value,
            defaultValue: props.defaultValue,
            currentValue,
            handleValueChange,
            handleInputValueChange,
            handleClear,
            onOpenChange: props.onOpenChange,
            isDisabled,
            autoHighlight,
            required,
            isClearable: props.isClearable ?? false,
            showClearButton,
            sizeConfig,
            error,
            placeholder: props.placeholder ?? "",
            ariaDescribedBy,
            testIdPrefix,
            inputClassName: props.inputClassName,
            contentProps: props.contentProps,
            dropdownProps: {
              resolvedOptions,
              flatOptionsMap,
              isGrouped,
              isLoading,
              loadingMessage: props.loadingMessage ?? "Loading\u2026",
              emptyMessage: props.emptyMessage ?? "No results found.",
              showCreateOption,
              hasMoreLazy,
              loaderCallbackRef
            },
            children: props.children
          }
        )
      }
    );
  }
);
SingleSelectInner.displayName = "SingleSelectInner";
const MultiSelectInner = React.forwardRef(
  (props, ref) => {
    const {
      id,
      label,
      error,
      helpText,
      errorId,
      helpTextId,
      testIdPrefix,
      effectiveItems,
      labelForValue,
      renderOption,
      isAsync,
      creatableFilter,
      isControlled,
      selectedValues,
      handleValueChange,
      handleInputValueChange,
      sizeConfig,
      ariaDescribedBy,
      resolvedOptions,
      flatOptionsMap,
      isGrouped,
      isLoading,
      showCreateOption,
      hasMoreLazy,
      loaderCallbackRef
    } = useMultiSelectState(props);
    const { isDisabled = false, required = false } = props;
    return /* @__PURE__ */ jsxRuntime.jsx(
      SelectFieldWrapper.SelectFieldWrapper,
      {
        id,
        label,
        error,
        helpText,
        errorId,
        helpTextId,
        isDisabled,
        required,
        testIdPrefix,
        labelProps: props.labelProps,
        className: props.className,
        children: /* @__PURE__ */ jsxRuntime.jsx(
          MultiSelectCombobox,
          {
            ref,
            name: props.name,
            id,
            effectiveItems,
            labelForValue,
            renderOption,
            isSearchable: props.isSearchable ?? true,
            isAsync,
            isCreatable: props.isCreatable ?? false,
            creatableFilter,
            isControlled,
            valueProp: props.value,
            defaultValue: props.defaultValue,
            selectedValues,
            handleValueChange,
            handleInputValueChange,
            onOpenChange: props.onOpenChange,
            isDisabled,
            autoHighlight: props.autoHighlight ?? true,
            sizeConfig,
            error,
            chipsClassName: props.chipsClassName,
            inputClassName: props.inputClassName,
            placeholder: props.placeholder ?? "",
            hideChipRemove: props.hideChipRemove ?? false,
            ariaDescribedBy,
            required,
            testIdPrefix,
            contentProps: props.contentProps,
            dropdownProps: {
              resolvedOptions,
              flatOptionsMap,
              isGrouped,
              isLoading,
              loadingMessage: props.loadingMessage ?? "Loading\u2026",
              emptyMessage: props.emptyMessage ?? "No results found.",
              showCreateOption,
              hasMoreLazy,
              loaderCallbackRef
            },
            children: props.children
          }
        )
      }
    );
  }
);
MultiSelectInner.displayName = "MultiSelectInner";
const Select = React.forwardRef((props, ref) => {
  const {
    getOptionValue,
    getOptionLabel,
    options,
    defaultOptions,
    loadOptions,
    ...rest
  } = props;
  const hasAccessors = Boolean(getOptionValue || getOptionLabel);
  const normalizedOptions = React.useMemo(
    () => hasAccessors ? normalizeOptions(options, getOptionValue, getOptionLabel) : options,
    [hasAccessors, options, getOptionValue, getOptionLabel]
  );
  const normalizedDefaultOptions = React.useMemo(() => {
    if (!hasAccessors || !Array.isArray(defaultOptions)) {
      return defaultOptions;
    }
    return defaultOptions.map(
      (o) => normalizeOption(o, getOptionValue, getOptionLabel)
    );
  }, [hasAccessors, defaultOptions, getOptionValue, getOptionLabel]);
  const normalizedLoadOptions = React.useMemo(() => {
    if (!hasAccessors || !loadOptions) return loadOptions;
    return async (input) => {
      const result = await loadOptions(input);
      return result.map(
        (o) => normalizeOption(o, getOptionValue, getOptionLabel)
      );
    };
  }, [hasAccessors, loadOptions, getOptionValue, getOptionLabel]);
  const nextProps = {
    ...rest,
    options: normalizedOptions,
    defaultOptions: normalizedDefaultOptions,
    loadOptions: normalizedLoadOptions
  };
  if (nextProps.isMulti === true) {
    return /* @__PURE__ */ jsxRuntime.jsx(MultiSelectInner, { ...nextProps, ref });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(SingleSelectInner, { ...nextProps, ref });
});
Select.displayName = "Select";

exports.Select = Select;
//# sourceMappingURL=Select-DA4PZAwd.js.map
