import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useMemo, useRef, useCallback, useEffect, forwardRef, useId } from 'react';
import { w as warnDeprecatedErrorUsage } from './utils-CM48ODEJ.js';
import { S as SelectOptions } from './SelectOptions-CDoo4AUu.js';
import { s as styles } from './SelectTriggerBase.module-DKF1FQnc.js';
import { c as cx } from './index-De1g9FRV.js';
import { B as Button } from './Button-Bnt8XUI7.js';
import { S as SvgChevronRight } from './chevron_right-BdpsxX7x.js';
import { S as SvgClose } from './close-DZj38AEh.js';
import { S as SelectFieldLabel } from './SelectFieldLabel-DLT5dKbx.js';
import { u as useDownshiftEnvironment, a as useCombobox, b as useSelect } from './downshift.esm-xtSnQp44.js';
import { b as useProcessedOptions, c as buildSelectItems, h as toSelectItem, d as useDebouncedCallback, e as OptionsDialog, f as OptionsPopover, a as useSelectOrchestration, g as defaultSyncFilter, t as toSyncFilterFn, s as sortByGroup } from './syncFilterUtils-BLcRXQfd.js';
import { F as FieldMessage } from './FieldMessage-DzxfodaI.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-CB_zHDbW.js';

const SelectFieldInput = ({
  placeholder,
  size,
  disableClearButton,
  disableToggleButton,
  disabled,
  readOnly,
  required,
  error,
  onClear,
  id,
  inputWrapperRef,
  htmlInputWrapperProps,
  inputProps,
  toggleButtonProps,
  prefix,
  suffix
}) => {
  const inputWrapperClassNames = cx(styles["input-wrapper"], {
    [styles["small"]]: size === "small",
    [styles["large"]]: size === "large",
    [styles["no-clear-button"]]: disableClearButton,
    [styles["no-toggle-button"]]: disableToggleButton,
    [styles["disabled"]]: disabled || readOnly
  });
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: inputWrapperRef,
      ...htmlInputWrapperProps,
      className: cx(inputWrapperClassNames, htmlInputWrapperProps?.className),
      children: [
        prefix ? /* @__PURE__ */ jsx("div", { className: styles["prefix"], children: prefix }) : null,
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "text",
            id,
            placeholder,
            disabled,
            readOnly,
            required,
            ...inputProps,
            className: cx(styles["input"], inputProps?.className, {
              [styles["error"]]: error
            })
          }
        ),
        suffix ? /* @__PURE__ */ jsx("div", { className: styles["suffix"], children: suffix }) : null,
        /* @__PURE__ */ jsxs("div", { className: styles["buttons-wrapper"], children: [
          disableClearButton ? null : /* @__PURE__ */ jsx("div", { className: styles["close-button-wrapper"], children: /* @__PURE__ */ jsx(
            Button,
            {
              icon: SvgClose,
              "aria-label": "clear selection",
              appearance: "ghost",
              size: "small",
              className: styles["close-button"],
              onClick: () => {
                onClear?.();
              }
            }
          ) }),
          disableToggleButton ? null : /* @__PURE__ */ jsx("div", { className: styles["toggle-button-wrapper"], children: /* @__PURE__ */ jsx(
            Button,
            {
              icon: SvgChevronRight,
              "aria-label": "toggle menu",
              appearance: "ghost",
              size: "small",
              disabled,
              ...toggleButtonProps,
              className: cx(
                styles["toggle-button"],
                toggleButtonProps?.className
              )
            }
          ) })
        ] })
      ]
    }
  );
};
SelectFieldInput.displayName = "SelectFieldInput";

const useCombo = ({
  options,
  pinned,
  groupToString,
  groupSorter,
  selectedOption,
  onSelectedOptionChange,
  onInputValueChange,
  onIsOpenChange,
  displayAs = "popover",
  disableHighlightOnOpen = false,
  disabled,
  virtualize = false,
  onScrollToHighlight
}) => {
  const [inputValue, setInputValue] = useState(selectedOption?.label ?? "");
  const effectiveSearchValue = selectedOption?.label === inputValue ? "" : inputValue;
  const { pinnedSections, ungroupedItems, groupSections } = useProcessedOptions(
    {
      options,
      pinned,
      searchValue: effectiveSearchValue,
      groupToString,
      groupSorter
    }
  );
  const { items, sectionsMeta } = useMemo(
    () => buildSelectItems({
      pinnedSections,
      groupSections,
      ungroupedItems
    }),
    [pinnedSections, groupSections, ungroupedItems]
  );
  const selectedDownshiftItem = useMemo(() => {
    return selectedOption ? toSelectItem(selectedOption) : null;
  }, [selectedOption]);
  const { ref: wrapperDivRef, environment } = useDownshiftEnvironment();
  const {
    isOpen,
    highlightedIndex,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getItemProps,
    closeMenu,
    openMenu,
    setHighlightedIndex
  } = useCombobox({
    isItemDisabled: (item, _index) => {
      if (!item) {
        return false;
      }
      return (disabled || item.disabled) ?? false;
    },
    environment,
    selectedItem: selectedDownshiftItem,
    inputValue,
    // Controlled input value
    onSelectedItemChange: ({
      selectedItem: si
    }) => {
      if (si && (si.type === "option" || si.type === "pinned-option" || si.type === "grouped-option")) {
        onSelectedOptionChange(si.original);
      } else {
        onSelectedOptionChange(null);
      }
    },
    onInputValueChange: (changes) => {
      setInputValue(changes.inputValue ?? "");
      onInputValueChange?.(changes);
    },
    onHighlightedIndexChange: ({ type, highlightedIndex: idx }) => {
      if (type !== useCombobox.stateChangeTypes.ItemMouseMove && idx >= 0) {
        onScrollToHighlight?.(idx);
      }
    },
    onIsOpenChange: (changes) => {
      onIsOpenChange?.(changes);
      if (changes.isOpen && !disableHighlightOnOpen) {
        const selectedItemIndex = items.findIndex(
          (item) => item.original.id === selectedOption?.id
        );
        setHighlightedIndex(selectedItemIndex);
      }
    },
    items,
    itemToString(item) {
      return item?.original.label ?? "";
    },
    stateReducer: (state, actionAndChanges) => stateReducer$1(state, actionAndChanges, displayAs),
    ...virtualize && { scrollIntoView: () => {
    } }
  });
  return {
    inputValue,
    wrapperDivRef,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getItemProps,
    highlightedIndex,
    isOpen,
    items,
    sectionsMeta,
    closeMenu,
    openMenu
  };
};
function stateReducer$1(state, actionAndChanges, displayAs) {
  const { type, changes } = actionAndChanges;
  switch (type) {
    case useCombobox.stateChangeTypes.InputBlur:
      if (displayAs === "dialog" && state.isOpen) {
        return {
          ...changes,
          isOpen: state.isOpen
        };
      }
      return {
        ...changes,
        inputValue: state.selectedItem?.original.label ?? state.inputValue
      };
    case useCombobox.stateChangeTypes.InputKeyDownEscape:
    case useCombobox.stateChangeTypes.FunctionCloseMenu:
      return {
        ...changes,
        inputValue: state.selectedItem?.original.label ?? state.inputValue
      };
    case useCombobox.stateChangeTypes.InputClick:
      if (displayAs === "dialog" && state.isOpen) {
        return {
          ...changes,
          isOpen: state.isOpen
        };
      }
      return changes;
    case useCombobox.stateChangeTypes.InputKeyDownEnter:
    case useCombobox.stateChangeTypes.ItemClick:
      return changes;
    default:
      return changes;
  }
}

const SelectFieldComboboxMode = ({
  id,
  helperUid,
  selectedOption,
  onSelectedOptionChange,
  displayAs,
  isDisabledOrReadOnly,
  disabled,
  labelAiMark,
  readOnly,
  required,
  placeholder,
  size,
  error,
  hasHelperText,
  disableClearButton,
  prefix,
  suffix,
  label,
  hideLabel,
  hint,
  errorMessages,
  warning,
  description,
  className,
  style,
  layoutStyles,
  pinned,
  groupToString,
  groupSorter,
  virtualize,
  options,
  loading,
  loadingMore,
  hasMore,
  loadOptions,
  loadMore,
  initialLoad,
  initialLoadPerformed,
  setInitialLoadPerformed,
  inputWrapperRef,
  debounceMs
}) => {
  const listRef = useRef(null);
  const debouncedOptionLoader = useDebouncedCallback((inputValue2) => {
    loadOptions(selectedOption?.label === inputValue2 ? "" : inputValue2, {
      initial: true
    });
  }, debounceMs);
  const adjustInputValueForSelectedOption = useCallback(
    (inputValue2) => {
      return selectedOption?.label === inputValue2 ? "" : inputValue2;
    },
    [selectedOption?.label]
  );
  const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    wrapperDivRef,
    highlightedIndex,
    getItemProps,
    inputValue,
    items,
    closeMenu,
    sectionsMeta
  } = useCombo({
    displayAs,
    disabled: isDisabledOrReadOnly,
    options,
    pinned,
    groupToString,
    groupSorter,
    selectedOption,
    virtualize,
    onSelectedOptionChange: (opt) => onSelectedOptionChange(opt),
    async onIsOpenChange(changes) {
      if (initialLoad === "open" && !initialLoadPerformed && changes.isOpen) {
        await loadOptions(adjustInputValueForSelectedOption(inputValue), {
          initial: true
        });
        setInitialLoadPerformed(true);
      }
    },
    onInputValueChange: ({ inputValue: iv }) => {
      debouncedOptionLoader(iv ?? "");
    },
    onScrollToHighlight: (i) => listRef.current?.scrollToIndex(i)
  });
  useEffect(() => {
    const performInitialLoad = async () => {
      if (initialLoad === "immediate" && !initialLoadPerformed) {
        await loadOptions(adjustInputValueForSelectedOption(inputValue), {
          initial: true
        });
        setInitialLoadPerformed(true);
      }
    };
    performInitialLoad();
  }, [
    loadOptions,
    initialLoadPerformed,
    initialLoad,
    inputValue,
    adjustInputValueForSelectedOption,
    setInitialLoadPerformed
  ]);
  const handleLoadMore = async () => {
    await loadMore(adjustInputValueForSelectedOption(inputValue));
  };
  if (displayAs === "dialog") {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: className ? `${styles["search-field"]} ${className}` : styles["search-field"],
        style: { ...layoutStyles, ...style },
        ref: wrapperDivRef,
        children: [
          /* @__PURE__ */ jsx(
            SelectFieldLabel,
            {
              aiMark: labelAiMark,
              label,
              hideLabel,
              getLabelProps,
              required
            }
          ),
          /* @__PURE__ */ jsx(
            SelectFieldInput,
            {
              disabled,
              readOnly,
              required,
              disableToggleButton: false,
              placeholder,
              disableClearButton,
              toggleButtonProps: getToggleButtonProps(),
              onClear: () => onSelectedOptionChange(null),
              id: `${id}-input`,
              inputProps: getInputProps({
                "aria-describedby": hasHelperText ? helperUid : void 0,
                "aria-invalid": error ? true : void 0
              }),
              size,
              error: !!error,
              prefix,
              suffix
            }
          ),
          hasHelperText ? /* @__PURE__ */ jsx(
            FieldMessage,
            {
              id: helperUid,
              hint,
              error: errorMessages,
              warning,
              description
            }
          ) : null,
          /* @__PURE__ */ jsx(
            OptionsDialog,
            {
              id: `${id}-dialog`,
              isOpen,
              onClose: closeMenu,
              title: label,
              field: /* @__PURE__ */ jsx(
                SelectFieldInput,
                {
                  disabled,
                  readOnly,
                  inputProps: getInputProps(),
                  disableToggleButton: true,
                  placeholder,
                  disableClearButton,
                  onClear: () => onSelectedOptionChange(null),
                  id: `${id}-dialog-input`,
                  inputWrapperRef,
                  size: "medium",
                  error: !!error,
                  prefix,
                  suffix
                }
              ),
              initialFocusResolver: (elements) => {
                return elements.find((element) => element.tagName === "INPUT") || elements[0];
              },
              children: /* @__PURE__ */ jsx(
                SelectOptions,
                {
                  ref: listRef,
                  isOpen: true,
                  items,
                  sectionsMeta,
                  getMenuProps,
                  getItemProps,
                  highlightedIndex,
                  selectedOption,
                  hasMore,
                  onLoadMore: handleLoadMore,
                  loading,
                  loadingMore,
                  disabled: isDisabledOrReadOnly,
                  virtualize
                }
              )
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: className ? `${styles["search-field"]} ${className}` : styles["search-field"],
      style: { ...layoutStyles, ...style },
      children: [
        /* @__PURE__ */ jsx(
          SelectFieldLabel,
          {
            aiMark: labelAiMark,
            label,
            hideLabel,
            getLabelProps,
            required
          }
        ),
        /* @__PURE__ */ jsx(
          SelectFieldInput,
          {
            disabled,
            readOnly,
            required,
            inputProps: getInputProps({
              popovertarget: `${id}-popover`,
              "aria-describedby": hasHelperText ? helperUid : void 0,
              "aria-invalid": error ? true : void 0
            }),
            toggleButtonProps: getToggleButtonProps(),
            disableToggleButton: false,
            placeholder,
            disableClearButton,
            onClear: () => onSelectedOptionChange(null),
            id: `${id}-input`,
            inputWrapperRef,
            size,
            error: !!error,
            prefix,
            suffix
          }
        ),
        hasHelperText ? /* @__PURE__ */ jsx(
          FieldMessage,
          {
            id: helperUid,
            hint,
            error: errorMessages,
            warning,
            description
          }
        ) : null,
        /* @__PURE__ */ jsx(
          OptionsPopover,
          {
            id: `${id}-popover`,
            referenceElement: inputWrapperRef,
            open: isOpen && displayAs === "popover",
            onClickOutside: closeMenu,
            width: "reference",
            children: /* @__PURE__ */ jsx(
              SelectOptions,
              {
                ref: listRef,
                isOpen,
                items,
                sectionsMeta,
                getMenuProps,
                getItemProps,
                highlightedIndex,
                selectedOption,
                hasMore,
                onLoadMore: handleLoadMore,
                loading,
                loadingMore,
                disabled: isDisabledOrReadOnly,
                virtualize
              }
            )
          }
        )
      ]
    }
  );
};

const SelectFieldTrigger = ({
  placeholder,
  size,
  disableClearButton,
  disabled,
  readOnly,
  error,
  onClear,
  id,
  inputWrapperRef,
  toggleButtonProps,
  displayValue,
  prefix,
  suffix,
  popoverTarget
}) => {
  const { ref: downshiftRef, ...restToggleButtonProps } = toggleButtonProps ?? {};
  const mergedRef = useMergeRefs([inputWrapperRef, downshiftRef]);
  const inputWrapperClassNames = cx(styles["input-wrapper"], {
    [styles["small"]]: size === "small",
    [styles["large"]]: size === "large",
    [styles["no-clear-button"]]: disableClearButton,
    [styles["disabled"]]: disabled || readOnly
  });
  return /* @__PURE__ */ jsxs("div", { style: { position: "relative" }, children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        ref: mergedRef,
        ...restToggleButtonProps,
        popovertarget: popoverTarget,
        id,
        className: cx(inputWrapperClassNames, restToggleButtonProps?.className),
        children: [
          prefix ? /* @__PURE__ */ jsx("div", { className: styles["prefix"], children: prefix }) : null,
          /* @__PURE__ */ jsx(
            "div",
            {
              className: cx(styles["input"], {
                [styles["error"]]: error
              }),
              children: displayValue ? /* @__PURE__ */ jsx("span", { children: displayValue }) : /* @__PURE__ */ jsx("span", { className: styles["fake-placeholder"], children: placeholder })
            }
          ),
          suffix ? /* @__PURE__ */ jsx("div", { className: styles["suffix"], children: suffix }) : null,
          /* @__PURE__ */ jsx("div", { className: styles["buttons-wrapper"], children: /* @__PURE__ */ jsx("div", { className: styles["toggle-button-wrapper"], children: /* @__PURE__ */ jsx(
            Button,
            {
              icon: SvgChevronRight,
              "aria-label": "toggle menu",
              appearance: "ghost",
              size: "small",
              disabled,
              tabIndex: -1,
              className: styles["toggle-button"]
            }
          ) }) })
        ]
      }
    ),
    disableClearButton ? null : /* @__PURE__ */ jsx(
      "div",
      {
        className: styles["buttons-wrapper"],
        style: { insetInlineEnd: "2rem" },
        children: /* @__PURE__ */ jsx("div", { className: styles["close-button-wrapper"], children: /* @__PURE__ */ jsx(
          Button,
          {
            icon: SvgClose,
            "aria-label": "clear selection",
            appearance: "ghost",
            size: "small",
            className: styles["close-button"],
            onClick: (e) => {
              e.stopPropagation();
              onClear?.();
            }
          }
        ) })
      }
    )
  ] });
};
SelectFieldTrigger.displayName = "SelectFieldTrigger";

const useSelectMode = ({
  options,
  pinned,
  groupToString,
  groupSorter,
  selectedOption,
  onSelectedOptionChange,
  onIsOpenChange,
  displayAs = "popover",
  disableHighlightOnOpen = false,
  disabled,
  virtualize = false,
  onScrollToHighlight
}) => {
  const { pinnedSections, ungroupedItems, groupSections } = useProcessedOptions(
    {
      options,
      pinned,
      searchValue: "",
      groupToString,
      groupSorter
    }
  );
  const { items, sectionsMeta } = useMemo(
    () => buildSelectItems({
      pinnedSections,
      groupSections,
      ungroupedItems
    }),
    [pinnedSections, groupSections, ungroupedItems]
  );
  const selectedDownshiftItem = useMemo(() => {
    return selectedOption ? toSelectItem(selectedOption) : null;
  }, [selectedOption]);
  const { ref: wrapperDivRef, environment } = useDownshiftEnvironment();
  const {
    isOpen,
    highlightedIndex,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getItemProps,
    closeMenu,
    openMenu,
    setHighlightedIndex
  } = useSelect({
    isItemDisabled: (item) => {
      if (!item) return false;
      return (disabled || item.disabled) ?? false;
    },
    environment,
    selectedItem: selectedDownshiftItem,
    onSelectedItemChange: ({
      selectedItem: si
    }) => {
      if (si && (si.type === "option" || si.type === "pinned-option" || si.type === "grouped-option")) {
        onSelectedOptionChange(si.original);
      } else {
        onSelectedOptionChange(null);
      }
    },
    onHighlightedIndexChange: ({ type, highlightedIndex: idx }) => {
      if (type !== useSelect.stateChangeTypes.ItemMouseMove && idx >= 0) {
        onScrollToHighlight?.(idx);
      }
    },
    onIsOpenChange: (changes) => {
      onIsOpenChange?.(changes);
      if (changes.isOpen && !disableHighlightOnOpen) {
        const selectedItemIndex = items.findIndex(
          (item) => item.original.id === selectedOption?.id
        );
        setHighlightedIndex(selectedItemIndex);
      }
    },
    items,
    itemToString(item) {
      return item?.original.label ?? "";
    },
    stateReducer: (state, actionAndChanges) => stateReducer(state, actionAndChanges, displayAs),
    ...virtualize && { scrollIntoView: () => {
    } }
  });
  return {
    wrapperDivRef,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getItemProps,
    highlightedIndex,
    isOpen,
    items,
    sectionsMeta,
    closeMenu,
    openMenu
  };
};
function stateReducer(state, actionAndChanges, displayAs) {
  const { type, changes } = actionAndChanges;
  switch (type) {
    case useSelect.stateChangeTypes.ToggleButtonBlur:
      if (displayAs === "dialog" && state.isOpen) {
        return { ...changes, isOpen: state.isOpen };
      }
      return changes;
    case useSelect.stateChangeTypes.ToggleButtonKeyDownEscape:
    case useSelect.stateChangeTypes.FunctionCloseMenu:
      return changes;
    case useSelect.stateChangeTypes.ToggleButtonClick:
      if (displayAs === "dialog" && state.isOpen) {
        return { ...changes, isOpen: state.isOpen };
      }
      return changes;
    case useSelect.stateChangeTypes.ToggleButtonKeyDownEnter:
    case useSelect.stateChangeTypes.ItemClick:
      return changes;
    default:
      return changes;
  }
}

const SelectFieldSelectMode = ({
  labelAiMark,
  id,
  helperUid,
  selectedOption,
  onSelectedOptionChange,
  displayAs,
  isDisabledOrReadOnly,
  disabled,
  readOnly,
  placeholder,
  size,
  error,
  hasHelperText,
  disableClearButton,
  prefix,
  suffix,
  label,
  hideLabel,
  hint,
  errorMessages,
  warning,
  description,
  className,
  style,
  layoutStyles,
  pinned,
  groupToString,
  groupSorter,
  virtualize,
  options,
  loading,
  loadingMore,
  hasMore,
  loadOptions,
  loadMore,
  initialLoad,
  initialLoadPerformed,
  setInitialLoadPerformed,
  inputWrapperRef,
  required
}) => {
  const listRef = useRef(null);
  const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    wrapperDivRef,
    highlightedIndex,
    getItemProps,
    items,
    closeMenu,
    sectionsMeta
  } = useSelectMode({
    displayAs,
    disabled: isDisabledOrReadOnly,
    options,
    pinned,
    groupToString,
    groupSorter,
    selectedOption,
    virtualize,
    onSelectedOptionChange: (opt) => onSelectedOptionChange(opt),
    async onIsOpenChange(changes) {
      if (initialLoad === "open" && !initialLoadPerformed && changes.isOpen) {
        await loadOptions("", { initial: true });
        setInitialLoadPerformed(true);
      }
    },
    onScrollToHighlight: (i) => listRef.current?.scrollToIndex(i)
  });
  useEffect(() => {
    const performInitialLoad = async () => {
      if (initialLoad === "immediate" && !initialLoadPerformed) {
        await loadOptions("", { initial: true });
        setInitialLoadPerformed(true);
      }
    };
    performInitialLoad();
  }, [loadOptions, initialLoadPerformed, initialLoad, setInitialLoadPerformed]);
  const handleLoadMore = async () => {
    await loadMore("");
  };
  const toggleButtonProps = getToggleButtonProps({
    disabled: !!disabled,
    "aria-required": required ? true : void 0,
    "aria-describedby": hasHelperText ? helperUid : void 0,
    "aria-invalid": error ? true : void 0
  });
  if (displayAs === "dialog") {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: className ? `${styles["search-field"]} ${className}` : styles["search-field"],
        style: { ...layoutStyles, ...style },
        ref: wrapperDivRef,
        children: [
          /* @__PURE__ */ jsx(
            SelectFieldLabel,
            {
              aiMark: labelAiMark,
              label,
              hideLabel,
              getLabelProps,
              required
            }
          ),
          /* @__PURE__ */ jsx(
            SelectFieldTrigger,
            {
              disabled,
              readOnly,
              placeholder,
              disableClearButton,
              toggleButtonProps,
              onClear: () => onSelectedOptionChange(null),
              id: `${id}-trigger`,
              inputWrapperRef,
              displayValue: selectedOption?.label,
              size,
              error: !!error,
              prefix,
              suffix
            }
          ),
          hasHelperText ? /* @__PURE__ */ jsx(
            FieldMessage,
            {
              id: helperUid,
              hint,
              error: errorMessages,
              warning,
              description
            }
          ) : null,
          /* @__PURE__ */ jsx(
            OptionsDialog,
            {
              id: `${id}-dialog`,
              isOpen,
              onClose: closeMenu,
              title: label,
              children: /* @__PURE__ */ jsx(
                SelectOptions,
                {
                  ref: listRef,
                  isOpen: true,
                  items,
                  sectionsMeta,
                  getMenuProps: (opts) => getMenuProps({
                    ...opts,
                    style: { ...opts?.style, outline: "none" },
                    onKeyDown: toggleButtonProps.onKeyDown,
                    tabIndex: 0,
                    "aria-activedescendant": toggleButtonProps["aria-activedescendant"]
                  }),
                  getItemProps,
                  highlightedIndex,
                  selectedOption,
                  hasMore,
                  onLoadMore: handleLoadMore,
                  loading,
                  loadingMore,
                  disabled: isDisabledOrReadOnly,
                  virtualize
                }
              )
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: className ? `${styles["search-field"]} ${className}` : styles["search-field"],
      style: { ...layoutStyles, ...style },
      children: [
        /* @__PURE__ */ jsx(
          SelectFieldLabel,
          {
            aiMark: labelAiMark,
            label,
            hideLabel,
            getLabelProps,
            required
          }
        ),
        /* @__PURE__ */ jsx(
          SelectFieldTrigger,
          {
            disabled,
            readOnly,
            placeholder,
            disableClearButton,
            toggleButtonProps,
            onClear: () => onSelectedOptionChange(null),
            id: `${id}-trigger`,
            popoverTarget: `${id}-popover`,
            inputWrapperRef,
            displayValue: selectedOption?.label,
            size,
            error: !!error,
            prefix,
            suffix
          }
        ),
        hasHelperText ? /* @__PURE__ */ jsx(
          FieldMessage,
          {
            id: helperUid,
            hint,
            error: errorMessages,
            warning,
            description
          }
        ) : null,
        /* @__PURE__ */ jsx(
          OptionsPopover,
          {
            id: `${id}-popover`,
            referenceElement: inputWrapperRef,
            open: isOpen && displayAs === "popover",
            onClickOutside: closeMenu,
            width: "reference",
            children: /* @__PURE__ */ jsx(
              SelectOptions,
              {
                ref: listRef,
                isOpen,
                items,
                sectionsMeta,
                getMenuProps,
                getItemProps,
                highlightedIndex,
                selectedOption,
                hasMore,
                onLoadMore: handleLoadMore,
                loading,
                loadingMore,
                disabled: isDisabledOrReadOnly,
                virtualize
              }
            )
          }
        )
      ]
    }
  );
};

const SelectField = forwardRef(
  (propsWithLayout, ref) => {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(propsWithLayout);
    const inputWrapperRef = useRef(null);
    const {
      id: idProp,
      value: selectedOption,
      initialLoad: initialLoadProp,
      displayMenuAs: displayMenuAsProp,
      lazy,
      loadOptions: loadOptionsProp,
      label,
      labelAiMark,
      hideLabel,
      placeholder,
      disableClearButton: disableClearButtonProp = false,
      debounceMs = 200,
      onSelectedOptionChange,
      cache,
      size,
      error,
      hint,
      description,
      errorAriaLive: _errorAriaLive,
      required,
      disabled,
      readOnly,
      prefix,
      suffix,
      warning,
      className,
      style,
      pinned,
      virtualize,
      disableSearch
    } = componentProps;
    const groupToString = "groupToString" in componentProps ? componentProps.groupToString : void 0;
    const groupSorter = "groupSorter" in componentProps ? componentProps.groupSorter : void 0;
    const autoId = useId();
    const id = idProp ?? autoId;
    const helperUid = useId();
    warnDeprecatedErrorUsage("SelectField", error);
    const errorMessages = typeof error === "boolean" || error === void 0 ? void 0 : error;
    const hasHelperText = !!(hint || errorMessages || warning || description);
    const isDisabledOrReadOnly = (disabled || readOnly) ?? false;
    const {
      displayAs,
      initialLoad,
      initialLoadPerformed,
      setInitialLoadPerformed,
      options,
      loading,
      loadingMore,
      hasMore,
      loadOptions,
      loadMore
    } = useSelectOrchestration({
      lazy,
      loadOptions: loadOptionsProp,
      cache,
      lazyOptions: "lazyOptions" in componentProps ? componentProps.lazyOptions : void 0,
      initialLoad: initialLoadProp,
      displayMenuAs: displayMenuAsProp,
      ref
    });
    const disableClearButton = disableClearButtonProp || !selectedOption || isDisabledOrReadOnly;
    const baseProps = {
      id,
      helperUid,
      selectedOption,
      onSelectedOptionChange,
      displayAs,
      isDisabledOrReadOnly,
      disabled,
      readOnly,
      required,
      placeholder,
      size,
      error,
      hasHelperText,
      disableClearButton,
      prefix,
      suffix,
      label,
      labelAiMark,
      hideLabel,
      hint,
      errorMessages,
      warning,
      description,
      className,
      style,
      layoutStyles,
      pinned,
      groupToString,
      groupSorter,
      virtualize,
      options,
      loading,
      loadingMore,
      hasMore,
      loadOptions,
      loadMore,
      initialLoad,
      initialLoadPerformed,
      setInitialLoadPerformed,
      inputWrapperRef
    };
    if (disableSearch) {
      return /* @__PURE__ */ jsx(SelectFieldSelectMode, { ...baseProps });
    }
    const comboboxProps = {
      ...baseProps,
      debounceMs
    };
    return /* @__PURE__ */ jsx(SelectFieldComboboxMode, { ...comboboxProps });
  }
);
SelectField.displayName = "SelectField";

const SelectFieldSync = (props) => {
  const {
    options,
    filter: filterProp = defaultSyncFilter,
    groupSorter,
    ...rest
  } = props;
  const filter = useMemo(() => toSyncFilterFn(filterProp), [filterProp]);
  const loadOptions = (searchValue) => {
    const filtered = filter(options, searchValue);
    return groupSorter ? sortByGroup(filtered, groupSorter) : filtered;
  };
  const fieldRef = useRef(null);
  const prevOptionsRef = useRef(options);
  useEffect(() => {
    if (prevOptionsRef.current !== options) {
      prevOptionsRef.current = options;
      fieldRef.current?.invalidate();
    }
  }, [options]);
  return /* @__PURE__ */ jsx(
    SelectField,
    {
      ref: fieldRef,
      lazy: false,
      loadOptions,
      debounceMs: 0,
      ...rest
    }
  );
};

export { SelectField as S, SelectFieldSync as a };
//# sourceMappingURL=SelectFieldSync-C44hPeeS.js.map
