import { jsxs, jsx } from 'react/jsx-runtime';
import { useRef, useState, useLayoutEffect, useMemo, useEffect, forwardRef, useId, useCallback } from 'react';
import { w as warnDeprecatedErrorUsage } from './utils-CM48ODEJ.js';
import { u as useToggleSelection, M as MultiSelectOptions } from './useToggleSelection-D_2qS0P1.js';
import { c as cx } from './index-De1g9FRV.js';
import { B as Button } from './Button-Bnt8XUI7.js';
import { C as Chip } from './Chip-CR5i8mQW.js';
import { F as Flex } from './Flex-DOUtHiPi.js';
import { m as mergeRefs, u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.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 { s as styles$1 } from './SelectTriggerBase.module-DKF1FQnc.js';
import { u as useDownshiftEnvironment, a as useCombobox, b as useSelect } from './downshift.esm-xtSnQp44.js';
import { b as useProcessedOptions, c as buildSelectItems, d as useDebouncedCallback, e as OptionsDialog, f as OptionsPopover, a as useSelectOrchestration, g as defaultSyncFilter, t as toSyncFilterFn } from './syncFilterUtils-BLcRXQfd.js';
import { F as FieldMessage } from './FieldMessage-DzxfodaI.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-CB_zHDbW.js';
import { w as warnOnce } from './warnOnce-Y9PRHcU4.js';

import './MultiSelectFieldSync.css';const input = "_input_1ip3q_26";
const error = "_error_1ip3q_55";
const disabled = "_disabled_1ip3q_62";
const chip = "_chip_1ip3q_128";
const prefix = "_prefix_1ip3q_221";
const suffix = "_suffix_1ip3q_222";
const small = "_small_1ip3q_298";
const large = "_large_1ip3q_304";
const styles = {
	"input-wrapper": "_input-wrapper_1ip3q_26",
	input: input,
	error: error,
	disabled: disabled,
	"input-flex": "_input-flex_1ip3q_72",
	"rows-wrapper": "_rows-wrapper_1ip3q_117",
	"chip-wrapper": "_chip-wrapper_1ip3q_128",
	chip: chip,
	"buttons-wrapper": "_buttons-wrapper_1ip3q_140",
	"close-button-wrapper": "_close-button-wrapper_1ip3q_158",
	"close-button": "_close-button_1ip3q_158",
	"toggle-button-wrapper": "_toggle-button-wrapper_1ip3q_182",
	"toggle-button": "_toggle-button_1ip3q_182",
	prefix: prefix,
	suffix: suffix,
	"no-clear-button": "_no-clear-button_1ip3q_290",
	"no-toggle-button": "_no-toggle-button_1ip3q_294",
	small: small,
	large: large};

const hasMultipleRows = (container) => {
  const children = Array.from(container.children);
  if (children.length <= 1) return false;
  const firstTop = children[0].getBoundingClientRect().top;
  return children.some(
    (child) => child.getBoundingClientRect().top !== firstTop
  );
};
function useChipLayout({
  selectedOptionsLength,
  singleRow,
  maxChips
}) {
  const rowsRef = useRef(null);
  const [visibleCount, setVisibleCount] = useState(null);
  const prevSelectedLengthRef = useRef(selectedOptionsLength);
  useLayoutEffect(() => {
    if (prevSelectedLengthRef.current !== selectedOptionsLength) {
      prevSelectedLengthRef.current = selectedOptionsLength;
      setVisibleCount(null);
    }
  }, [selectedOptionsLength]);
  useLayoutEffect(() => {
    if (!singleRow || !rowsRef.current) {
      setVisibleCount(null);
      return;
    }
    if (visibleCount === null) {
      if (hasMultipleRows(rowsRef.current)) {
        const firstRowTop = rowsRef.current.children[0]?.getBoundingClientRect().top;
        const firstRowCount = Array.from(rowsRef.current.children).filter(
          (c) => c.getBoundingClientRect().top === firstRowTop
        ).length;
        setVisibleCount(Math.max(firstRowCount - 1, 0));
      }
      return;
    }
    if (hasMultipleRows(rowsRef.current) && visibleCount > 0) {
      setVisibleCount(visibleCount - 1);
    }
  }, [singleRow, selectedOptionsLength, visibleCount]);
  const maxAllowed = maxChips ?? 10;
  const displayCount = singleRow && visibleCount !== null ? Math.min(visibleCount, maxAllowed) : Math.min(selectedOptionsLength, maxAllowed);
  const hiddenCount = selectedOptionsLength - displayCount;
  return { rowsRef, displayCount, hiddenCount };
}

const MultiSelectFieldInput = ({
  placeholder,
  size,
  disableClearButton,
  disableToggleButton,
  disabled,
  readOnly,
  error,
  onClear,
  id,
  inputWrapperRef,
  htmlInputWrapperProps,
  inputProps,
  toggleButtonProps,
  prefix,
  suffix,
  selectedOptions = [],
  onRemoveOption,
  singleRow,
  maxChips,
  getChipProps,
  onWrapperClick
}) => {
  const inputRef = useRef(null);
  const externalRef = inputProps?.ref;
  const mergedInputRef = mergeRefs([inputRef, externalRef]);
  const { rowsRef, displayCount, hiddenCount } = useChipLayout({
    selectedOptionsLength: selectedOptions.length,
    singleRow,
    maxChips
  });
  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
  });
  const handleInputKeyDown = (e) => {
    if (e.key === "Backspace" && !inputProps?.value && selectedOptions.length > 0 && onRemoveOption && !disabled && !readOnly) {
      onRemoveOption(selectedOptions[selectedOptions.length - 1]);
    }
    if (inputProps?.onKeyDown) {
      inputProps.onKeyDown(e);
    }
  };
  const handleWrapperClick = (e) => {
    const target = e.target;
    if (target.closest("button") || target.tagName === "INPUT") {
      return;
    }
    onWrapperClick?.(e);
    inputRef.current?.focus();
  };
  return (
    // eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events -- Click-to-focus container; Despite the disabled rules, this remains accessible. Keyboard interaction is provided by the input and nested buttons are filtered out in the handler.
    /* @__PURE__ */ jsxs(
      "div",
      {
        ref: inputWrapperRef,
        ...htmlInputWrapperProps,
        className: cx(inputWrapperClassNames, htmlInputWrapperProps?.className),
        onClick: handleWrapperClick,
        children: [
          prefix ? /* @__PURE__ */ jsx("div", { className: styles["prefix"], children: prefix }) : null,
          /* @__PURE__ */ jsxs("div", { className: styles["rows-wrapper"], ref: rowsRef, children: [
            selectedOptions.length > 0 && onRemoveOption ? selectedOptions.slice(0, displayCount).map((option, index) => /* @__PURE__ */ jsx(
              "div",
              {
                className: styles["chip-wrapper"],
                children: /* @__PURE__ */ jsx(
                  Chip,
                  {
                    ...getChipProps?.(option),
                    label: option.label,
                    onClose: disabled || readOnly ? void 0 : () => onRemoveOption(option),
                    className: styles["chip"],
                    title: option.label
                  }
                )
              },
              `selected-item-${option.id}-${index}`
            )) : null,
            hiddenCount > 0 ? /* @__PURE__ */ jsx("div", { className: styles["chip-wrapper"], children: /* @__PURE__ */ jsx(
              Chip,
              {
                label: `+${hiddenCount}`,
                className: styles["chip"],
                title: selectedOptions.slice(displayCount).map((option) => option.label).join(", ")
              }
            ) }) : null,
            /* @__PURE__ */ jsxs(Flex, { className: styles["input-flex"], alignItems: "center", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  id,
                  type: "text",
                  placeholder,
                  disabled,
                  readOnly,
                  ...inputProps,
                  ref: mergedInputRef,
                  onKeyDown: handleInputKeyDown,
                  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
                )
              }
            ) })
          ] })
        ]
      }
    )
  );
};
MultiSelectFieldInput.displayName = "MultiSelectFieldInput";

const useComboMultiple = ({
  options,
  pinned,
  groupToString,
  groupSorter,
  selectAll,
  selectFiltered,
  selectedOptions,
  onSelectedOptionsChange,
  onInputValueChange,
  onIsOpenChange,
  displayAs = "popover",
  disabled,
  loading = false,
  virtualize = false,
  onScrollToHighlight
}) => {
  const [inputValue, setInputValue] = useState("");
  const { pinnedSections, ungroupedItems, groupSections } = useProcessedOptions(
    {
      options,
      pinned,
      searchValue: inputValue,
      groupToString,
      groupSorter
    }
  );
  const bulkActionItems = useMemo(() => {
    const items2 = [];
    const hasSearchTerm = inputValue.trim().length > 0;
    const hasResults = ungroupedItems.length > 0 || groupSections.some((s) => s.options.length > 0) || pinnedSections.some((s) => s.options.length > 0);
    if (hasSearchTerm && selectFiltered && hasResults && !loading) {
      const config = selectFiltered(inputValue);
      items2.push({
        id: "select-filtered",
        type: "select-filtered",
        original: {
          id: "select-filtered",
          label: config.label ?? `Select items matching "${inputValue}"`
        },
        checkState: config.checkState
      });
    } else if (!hasSearchTerm && selectAll) {
      items2.push({
        id: "select-all",
        type: "select-all",
        original: {
          id: "select-all",
          label: selectAll.label ?? "Select All"
        },
        checkState: selectAll.checkState
      });
    }
    return items2;
  }, [
    inputValue,
    ungroupedItems,
    groupSections,
    pinnedSections,
    selectFiltered,
    selectAll,
    loading
  ]);
  const { items, sectionsMeta } = useMemo(
    () => buildSelectItems({
      prefixItems: bulkActionItems,
      pinnedSections,
      groupSections,
      ungroupedItems
    }),
    [bulkActionItems, pinnedSections, groupSections, ungroupedItems]
  );
  const { ref: wrapperDivRef, environment } = useDownshiftEnvironment();
  const { handleItemClick } = useToggleSelection({
    options,
    pinnedSections,
    selectedOptions,
    onSelectedOptionsChange
  });
  const {
    isOpen,
    highlightedIndex,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getItemProps,
    inputValue: downshiftInputValue,
    closeMenu,
    openMenu,
    toggleMenu
  } = useCombobox({
    isItemDisabled: (item, _index) => {
      if (!item) {
        return false;
      }
      return (disabled || item.disabled) ?? false;
    },
    environment,
    // For multi-select, we don't track a single selected item
    selectedItem: null,
    onSelectedItemChange: ({
      selectedItem: si
    }) => {
      if (si) {
        if (si.type === "select-all") {
          selectAll?.onClick();
        } else if (si.type === "select-filtered") {
          selectFiltered?.(inputValue).onClick();
        } else if (si.type === "option" || si.type === "pinned-option" || si.type === "grouped-option") {
          handleItemClick(si.original);
        }
      }
    },
    onHighlightedIndexChange: ({ type, highlightedIndex: idx }) => {
      if (type !== useCombobox.stateChangeTypes.ItemMouseMove && idx >= 0) {
        onScrollToHighlight?.(idx);
      }
    },
    onInputValueChange: (changes) => {
      setInputValue(changes.inputValue ?? "");
      onInputValueChange?.(changes);
    },
    scrollIntoView: virtualize ? () => {
    } : (node, menuNode) => {
      if (!node || !menuNode) return;
      const firstItem = items[0];
      const hasBulkAction = firstItem?.type === "select-all" || firstItem?.type === "select-filtered";
      if (!hasBulkAction) {
        const nodeRect2 = node.getBoundingClientRect();
        const menuRect2 = menuNode.getBoundingClientRect();
        if (nodeRect2.bottom > menuRect2.bottom || nodeRect2.top < menuRect2.top) {
          node.scrollIntoView({ block: "nearest" });
        }
        return;
      }
      const bulkActionEl = menuNode.querySelector(
        '[data-type="select-all"], [data-type="select-filtered"]'
      );
      if (node === bulkActionEl) {
        menuNode.scrollTop = 0;
        return;
      }
      const stickyHeight = bulkActionEl?.getBoundingClientRect().height ?? 0;
      const nodeRect = node.getBoundingClientRect();
      const menuRect = menuNode.getBoundingClientRect();
      const visibleTop = menuRect.top + stickyHeight;
      if (nodeRect.top < visibleTop) {
        menuNode.scrollTop -= visibleTop - nodeRect.top;
      } else if (nodeRect.bottom > menuRect.bottom) {
        menuNode.scrollTop += nodeRect.bottom - menuRect.bottom;
      }
    },
    onIsOpenChange,
    items,
    itemToString(item) {
      return item?.original.label ?? "";
    },
    stateReducer: (state, actionAndChanges) => stateReducer$1(state, actionAndChanges, displayAs)
  });
  return {
    inputValue: downshiftInputValue,
    wrapperDivRef,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getItemProps,
    highlightedIndex,
    isOpen,
    items,
    sectionsMeta,
    closeMenu,
    openMenu,
    toggleMenu,
    selectedOptions
  };
};
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,
          // Preserve input value for multi-select
          inputValue: state.inputValue
        };
      }
      return {
        ...changes,
        // For multi-select, preserve the input value on blur
        inputValue: state.inputValue
      };
    case useCombobox.stateChangeTypes.InputKeyDownEscape:
    case useCombobox.stateChangeTypes.FunctionCloseMenu:
      return {
        ...changes,
        // Clear input value when menu is closed
        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,
        isOpen: state.isOpen,
        // Keep menu open
        highlightedIndex: state.highlightedIndex,
        // Preserve highlight position
        inputValue: state.inputValue
        // Preserve input value for continued filtering
      };
    case useCombobox.stateChangeTypes.ControlledPropUpdatedSelectedItem:
      return {
        ...changes,
        inputValue: state.inputValue
      };
    default:
      return changes;
  }
}

const MultiSelectFieldComboboxMode = ({
  labelAiMark,
  id,
  helperUid,
  selectedOptions,
  onSelectedOptionsChange,
  displayAs,
  isDisabledOrReadOnly,
  disabled,
  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,
  selectAll,
  selectFiltered,
  singleRow,
  maxChips,
  getChipProps,
  onSearchChange,
  handleRemoveOption,
  handleClear
}) => {
  const listRef = useRef(null);
  const debouncedOptionLoader = useDebouncedCallback((inputValue2) => {
    loadOptions(inputValue2, { initial: true });
  }, debounceMs);
  const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    wrapperDivRef,
    highlightedIndex,
    getItemProps,
    inputValue,
    items,
    sectionsMeta,
    closeMenu,
    toggleMenu
  } = useComboMultiple({
    displayAs,
    onSelectedOptionsChange,
    disabled: isDisabledOrReadOnly,
    options,
    loading,
    pinned,
    virtualize,
    groupToString,
    groupSorter,
    selectedOptions,
    selectAll,
    selectFiltered,
    async onIsOpenChange(changes) {
      if (initialLoad === "open" && !initialLoadPerformed && changes.isOpen) {
        await loadOptions("", { initial: true });
        setInitialLoadPerformed(true);
      }
    },
    onInputValueChange: ({ inputValue: iv }) => {
      debouncedOptionLoader(iv ?? "");
      onSearchChange?.(iv ?? "");
    },
    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(inputValue);
  };
  if (displayAs === "dialog") {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: className ? `${styles$1["search-field"]} ${className}` : styles$1["search-field"],
        style: { ...layoutStyles, ...style },
        ref: wrapperDivRef,
        children: [
          /* @__PURE__ */ jsx(
            SelectFieldLabel,
            {
              aiMark: labelAiMark,
              label,
              hideLabel,
              getLabelProps,
              required
            }
          ),
          /* @__PURE__ */ jsx(
            MultiSelectFieldInput,
            {
              disabled,
              readOnly,
              disableToggleButton: false,
              placeholder,
              disableClearButton,
              toggleButtonProps: getToggleButtonProps(),
              onClear: handleClear,
              id: `${id}-input`,
              inputProps: getInputProps({
                "aria-describedby": hasHelperText ? helperUid : void 0,
                "aria-invalid": error ? true : void 0
              }),
              size,
              error: !!error,
              prefix,
              suffix,
              selectedOptions,
              onRemoveOption: handleRemoveOption,
              singleRow,
              maxChips,
              getChipProps,
              onWrapperClick: toggleMenu
            }
          ),
          hasHelperText ? /* @__PURE__ */ jsx(
            FieldMessage,
            {
              id: helperUid,
              hint,
              error: errorMessages,
              warning,
              description
            }
          ) : null,
          /* @__PURE__ */ jsx(
            OptionsDialog,
            {
              id: `${id}-dialog`,
              isOpen,
              onClose: closeMenu,
              title: label,
              initialFocusResolver: (elements) => {
                return elements.find((element) => element.tagName === "INPUT") || elements[0];
              },
              field: /* @__PURE__ */ jsx(
                MultiSelectFieldInput,
                {
                  disabled,
                  readOnly,
                  inputProps: getInputProps(),
                  disableToggleButton: true,
                  placeholder,
                  disableClearButton,
                  onClear: handleClear,
                  id: `${id}-dialog-input`,
                  inputWrapperRef,
                  size: "medium",
                  error: !!error,
                  prefix,
                  suffix,
                  selectedOptions,
                  onRemoveOption: handleRemoveOption,
                  singleRow: true,
                  maxChips: 20,
                  getChipProps
                }
              ),
              children: /* @__PURE__ */ jsx(
                MultiSelectOptions,
                {
                  isOpen: true,
                  items,
                  getMenuProps,
                  ref: listRef,
                  getItemProps,
                  highlightedIndex,
                  selectedOptions,
                  hasMore,
                  onLoadMore: handleLoadMore,
                  loading,
                  loadingMore,
                  disabled: isDisabledOrReadOnly,
                  sectionsMeta,
                  virtualize
                }
              )
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: className ? `${styles$1["search-field"]} ${className}` : styles$1["search-field"],
      style: { ...layoutStyles, ...style },
      children: [
        /* @__PURE__ */ jsx(
          SelectFieldLabel,
          {
            aiMark: labelAiMark,
            label,
            hideLabel,
            getLabelProps,
            required
          }
        ),
        /* @__PURE__ */ jsx(
          MultiSelectFieldInput,
          {
            disabled,
            readOnly,
            inputProps: getInputProps({
              popovertarget: `${id}-popover`,
              "aria-describedby": hasHelperText ? helperUid : void 0,
              "aria-invalid": error ? true : void 0
            }),
            toggleButtonProps: getToggleButtonProps(),
            disableToggleButton: false,
            placeholder,
            disableClearButton,
            onClear: handleClear,
            id: `${id}-input`,
            inputWrapperRef,
            size,
            error: !!error,
            prefix,
            suffix,
            selectedOptions,
            onRemoveOption: handleRemoveOption,
            singleRow,
            maxChips,
            getChipProps,
            onWrapperClick: toggleMenu
          }
        ),
        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(
              MultiSelectOptions,
              {
                isOpen,
                items,
                getMenuProps,
                ref: listRef,
                getItemProps,
                highlightedIndex,
                selectedOptions,
                hasMore,
                onLoadMore: handleLoadMore,
                loading,
                loadingMore,
                disabled: isDisabledOrReadOnly,
                sectionsMeta,
                virtualize
              }
            )
          }
        )
      ]
    }
  );
};

const MultiSelectFieldTrigger = ({
  placeholder,
  size,
  disableClearButton,
  disabled,
  readOnly,
  error,
  onClear,
  id,
  inputWrapperRef,
  toggleButtonProps,
  prefix,
  suffix,
  selectedOptions = [],
  onRemoveOption,
  singleRow,
  maxChips,
  getChipProps,
  popoverTarget
}) => {
  const { ref: downshiftRef, ...restToggleButtonProps } = toggleButtonProps ?? {};
  const triggerRef = useRef(null);
  const mergedRef = useMergeRefs([inputWrapperRef, downshiftRef, triggerRef]);
  const { rowsRef, displayCount, hiddenCount } = useChipLayout({
    selectedOptionsLength: selectedOptions.length,
    singleRow,
    maxChips
  });
  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__ */ jsxs("div", { className: styles["rows-wrapper"], ref: rowsRef, children: [
            selectedOptions.length > 0 && onRemoveOption ? selectedOptions.slice(0, displayCount).map((option, index) => /* @__PURE__ */ jsx(
              "div",
              {
                className: styles["chip-wrapper"],
                children: /* @__PURE__ */ jsx(
                  Chip,
                  {
                    ...getChipProps?.(option),
                    label: option.label,
                    onClose: disabled || readOnly ? void 0 : (e) => {
                      e.stopPropagation();
                      onRemoveOption(option);
                      triggerRef.current?.focus();
                    },
                    className: styles["chip"],
                    title: option.label
                  }
                )
              },
              `selected-item-${option.id}-${index}`
            )) : null,
            hiddenCount > 0 ? /* @__PURE__ */ jsx("div", { className: styles["chip-wrapper"], children: /* @__PURE__ */ jsx(
              Chip,
              {
                label: `+${hiddenCount}`,
                className: styles["chip"],
                title: selectedOptions.slice(displayCount).map((option) => option.label).join(", ")
              }
            ) }) : null,
            selectedOptions.length === 0 ? /* @__PURE__ */ jsxs(Flex, { className: styles["input-flex"], alignItems: "center", children: [
              /* @__PURE__ */ jsx(
                "div",
                {
                  className: cx(styles["input"], {
                    [styles["error"]]: error
                  }),
                  children: placeholder
                }
              ),
              suffix ? /* @__PURE__ */ jsx("div", { className: styles["suffix"], children: suffix }) : null
            ] }) : 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?.();
            }
          }
        ) })
      }
    )
  ] });
};
MultiSelectFieldTrigger.displayName = "MultiSelectFieldTrigger";

const useSelectModeMultiple = ({
  options,
  pinned,
  groupToString,
  groupSorter,
  selectAll,
  selectedOptions,
  onSelectedOptionsChange,
  onIsOpenChange,
  displayAs = "popover",
  disabled,
  virtualize = false,
  onScrollToHighlight
}) => {
  const { pinnedSections, ungroupedItems, groupSections } = useProcessedOptions(
    {
      options,
      pinned,
      searchValue: "",
      groupToString,
      groupSorter
    }
  );
  const bulkActionItems = useMemo(() => {
    const items2 = [];
    if (selectAll) {
      items2.push({
        id: "select-all",
        type: "select-all",
        original: {
          id: "select-all",
          label: selectAll.label ?? "Select All"
        },
        checkState: selectAll.checkState
      });
    }
    return items2;
  }, [selectAll]);
  const { items, sectionsMeta } = useMemo(
    () => buildSelectItems({
      prefixItems: bulkActionItems,
      pinnedSections,
      groupSections,
      ungroupedItems
    }),
    [bulkActionItems, pinnedSections, groupSections, ungroupedItems]
  );
  const { ref: wrapperDivRef, environment } = useDownshiftEnvironment();
  const { handleItemClick } = useToggleSelection({
    options,
    pinnedSections,
    selectedOptions,
    onSelectedOptionsChange
  });
  const {
    isOpen,
    highlightedIndex,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getItemProps,
    closeMenu,
    openMenu
  } = useSelect({
    isItemDisabled: (item) => {
      if (!item) return false;
      return (disabled || item.disabled) ?? false;
    },
    environment,
    selectedItem: null,
    onSelectedItemChange: ({
      selectedItem: si
    }) => {
      if (si) {
        if (si.type === "select-all") {
          selectAll?.onClick();
        } else if (si.type === "option" || si.type === "pinned-option" || si.type === "grouped-option") {
          handleItemClick(si.original);
        }
      }
    },
    onHighlightedIndexChange: ({ type, highlightedIndex: idx }) => {
      if (type !== useSelect.stateChangeTypes.ItemMouseMove && idx >= 0) {
        onScrollToHighlight?.(idx);
      }
    },
    onIsOpenChange,
    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,
    toggleMenu: () => isOpen ? closeMenu() : openMenu(),
    selectedOptions
  };
};
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, selectedItem: null };
      }
      return { ...changes, selectedItem: null };
    case useSelect.stateChangeTypes.ToggleButtonKeyDownEnter:
    case useSelect.stateChangeTypes.ToggleButtonKeyDownSpaceButton:
    case useSelect.stateChangeTypes.ItemClick:
      return {
        ...changes,
        isOpen: state.isOpen,
        highlightedIndex: state.highlightedIndex
      };
    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;
    default:
      return changes;
  }
}

const MultiSelectFieldSelectMode = ({
  labelAiMark,
  id,
  helperUid,
  selectedOptions,
  onSelectedOptionsChange,
  displayAs,
  isDisabledOrReadOnly,
  disabled,
  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,
  selectAll,
  singleRow,
  maxChips,
  getChipProps,
  handleRemoveOption,
  handleClear
}) => {
  const listRef = useRef(null);
  const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    wrapperDivRef,
    highlightedIndex,
    getItemProps,
    items,
    sectionsMeta,
    closeMenu
  } = useSelectModeMultiple({
    displayAs,
    onSelectedOptionsChange,
    disabled: isDisabledOrReadOnly,
    options,
    pinned,
    virtualize,
    groupToString,
    groupSorter,
    selectedOptions,
    selectAll,
    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$1["search-field"]} ${className}` : styles$1["search-field"],
        style: { ...layoutStyles, ...style },
        ref: wrapperDivRef,
        children: [
          /* @__PURE__ */ jsx(
            SelectFieldLabel,
            {
              aiMark: labelAiMark,
              label,
              hideLabel,
              getLabelProps,
              required
            }
          ),
          /* @__PURE__ */ jsx(
            MultiSelectFieldTrigger,
            {
              disabled,
              readOnly,
              placeholder,
              disableClearButton,
              toggleButtonProps,
              onClear: handleClear,
              id: `${id}-trigger`,
              inputWrapperRef,
              size,
              error: !!error,
              prefix,
              suffix,
              selectedOptions,
              onRemoveOption: handleRemoveOption,
              singleRow,
              maxChips,
              getChipProps
            }
          ),
          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(
                MultiSelectOptions,
                {
                  ref: listRef,
                  isOpen: true,
                  items,
                  getMenuProps: (opts) => getMenuProps({
                    ...opts,
                    style: { ...opts?.style, outline: "none" },
                    onKeyDown: toggleButtonProps.onKeyDown,
                    tabIndex: 0,
                    "aria-activedescendant": toggleButtonProps["aria-activedescendant"]
                  }),
                  getItemProps,
                  highlightedIndex,
                  selectedOptions,
                  hasMore,
                  onLoadMore: handleLoadMore,
                  loading,
                  loadingMore,
                  disabled: isDisabledOrReadOnly,
                  sectionsMeta,
                  virtualize
                }
              )
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: className ? `${styles$1["search-field"]} ${className}` : styles$1["search-field"],
      style: { ...layoutStyles, ...style },
      children: [
        /* @__PURE__ */ jsx(
          SelectFieldLabel,
          {
            aiMark: labelAiMark,
            label,
            hideLabel,
            getLabelProps,
            required
          }
        ),
        /* @__PURE__ */ jsx(
          MultiSelectFieldTrigger,
          {
            disabled,
            readOnly,
            placeholder,
            disableClearButton,
            toggleButtonProps,
            onClear: handleClear,
            id: `${id}-trigger`,
            popoverTarget: `${id}-popover`,
            inputWrapperRef,
            size,
            error: !!error,
            prefix,
            suffix,
            selectedOptions,
            onRemoveOption: handleRemoveOption,
            singleRow,
            maxChips,
            getChipProps
          }
        ),
        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(
              MultiSelectOptions,
              {
                ref: listRef,
                isOpen,
                items,
                getMenuProps,
                getItemProps,
                highlightedIndex,
                selectedOptions,
                hasMore,
                onLoadMore: handleLoadMore,
                loading,
                loadingMore,
                disabled: isDisabledOrReadOnly,
                sectionsMeta,
                virtualize
              }
            )
          }
        )
      ]
    }
  );
};

const MultiSelectField = forwardRef((propsWithLayout, ref) => {
  const { layoutStyles, componentProps } = useLayoutPropsUtil(propsWithLayout);
  const inputWrapperRef = useRef(null);
  const {
    id: idProp,
    value: selectedOptions,
    initialLoad: initialLoadProp,
    displayMenuAs: displayMenuAsProp,
    lazy,
    loadOptions: loadOptionsProp,
    label,
    hideLabel,
    placeholder,
    debounceMs = 200,
    onSelectedOptionsChange,
    cache,
    size,
    error,
    hint,
    description,
    required,
    labelAiMark,
    disabled,
    readOnly,
    prefix,
    suffix,
    selectAll: selectAllProp,
    selectFiltered: selectFilteredProp,
    singleRow,
    maxChips,
    warning,
    pinned,
    onSearchChange,
    className,
    style,
    virtualize,
    disableSearch,
    getChipProps
  } = 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("MultiSelectField", error);
  if (disableSearch && selectFilteredProp) {
    warnOnce(
      "MultiSelectField: `selectFiltered` has no effect when `disableSearch` is true because there is no search input to produce filtered results."
    );
  }
  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 handleRemoveOption = useCallback(
    (option) => {
      onSelectedOptionsChange(
        selectedOptions.filter((opt) => opt.id !== option.id)
      );
    },
    [selectedOptions, onSelectedOptionsChange]
  );
  const handleClear = useCallback(() => {
    onSelectedOptionsChange([]);
  }, [onSelectedOptionsChange]);
  const disableClearButton = selectedOptions.length === 0 || isDisabledOrReadOnly;
  const selectAll = selectAllProp ? {
    label: selectAllProp.label ?? "Select All",
    onClick: selectAllProp.onClick,
    checkState: selectAllProp.checkState === true ? "checked" : selectAllProp.checkState === false ? "unchecked" : selectAllProp.checkState ?? "indeterminate"
  } : void 0;
  const selectFiltered = selectFilteredProp ? (searchValue) => {
    const config = selectFilteredProp(searchValue);
    return {
      label: config.label,
      onClick: config.onClick,
      checkState: config.checkState === true ? "checked" : config.checkState === false ? "unchecked" : config.checkState ?? "indeterminate"
    };
  } : void 0;
  const baseProps = {
    id,
    helperUid,
    selectedOptions,
    onSelectedOptionsChange,
    displayAs,
    isDisabledOrReadOnly,
    disabled,
    readOnly,
    required,
    placeholder,
    size,
    error,
    hasHelperText,
    disableClearButton,
    prefix,
    suffix,
    label,
    hideLabel,
    hint,
    labelAiMark,
    errorMessages,
    warning,
    description,
    className,
    style,
    layoutStyles,
    pinned,
    groupToString,
    groupSorter,
    virtualize,
    options,
    loading,
    loadingMore,
    hasMore,
    loadOptions,
    loadMore,
    initialLoad,
    initialLoadPerformed,
    setInitialLoadPerformed,
    inputWrapperRef,
    selectAll,
    singleRow,
    maxChips,
    getChipProps,
    handleRemoveOption,
    handleClear
  };
  if (disableSearch) {
    return /* @__PURE__ */ jsx(MultiSelectFieldSelectMode, { ...baseProps });
  }
  const comboboxProps = {
    ...baseProps,
    debounceMs,
    selectFiltered,
    onSearchChange
  };
  return /* @__PURE__ */ jsx(MultiSelectFieldComboboxMode, { ...comboboxProps });
});
MultiSelectField.displayName = "MultiSelectField";

const MultiSelectFieldSync = (props) => {
  const {
    options,
    filter: filterProp = defaultSyncFilter,
    selectAll: selectAllProp,
    selectFiltered: selectFilteredProp,
    value,
    onSelectedOptionsChange,
    ...rest
  } = props;
  const filter = useMemo(() => toSyncFilterFn(filterProp), [filterProp]);
  const selectAllConfig = useMemo(() => {
    if (!selectAllProp) return void 0;
    const enabledOptions = options.filter((opt) => !opt.disabled);
    const enabledIds = new Set(enabledOptions.map((opt) => opt.id));
    const selectedCount = value.filter((v) => enabledIds.has(v.id)).length;
    const allSelected = selectedCount === enabledOptions.length;
    const labelProp = typeof selectAllProp === "object" ? selectAllProp.label : void 0;
    const label = typeof labelProp === "function" ? labelProp(allSelected) : labelProp;
    const checkState = allSelected ? "checked" : selectedCount > 0 ? "indeterminate" : "unchecked";
    const handleClick = () => {
      if (allSelected) {
        onSelectedOptionsChange([]);
      } else {
        onSelectedOptionsChange(enabledOptions);
      }
    };
    return {
      label,
      onClick: handleClick,
      checkState
    };
  }, [selectAllProp, options, value, onSelectedOptionsChange]);
  const selectFilteredConfig = useMemo(() => {
    if (!selectFilteredProp) return void 0;
    return (searchValue) => {
      const filteredOptions = filter(options, searchValue);
      const enabledFilteredOptions = filteredOptions.filter(
        (opt) => !opt.disabled
      );
      const selectedIds = new Set(value.map((v) => v.id));
      const allFilteredSelected = enabledFilteredOptions.length > 0 && enabledFilteredOptions.every((opt) => selectedIds.has(opt.id));
      const someFilteredSelected = enabledFilteredOptions.some(
        (opt) => selectedIds.has(opt.id)
      );
      const label = typeof selectFilteredProp === "function" ? selectFilteredProp(searchValue).label : void 0;
      const checkState = allFilteredSelected ? "checked" : someFilteredSelected ? "indeterminate" : "unchecked";
      const handleClick = () => {
        if (allFilteredSelected) {
          const filteredIds = new Set(enabledFilteredOptions.map((o) => o.id));
          onSelectedOptionsChange(value.filter((v) => !filteredIds.has(v.id)));
        } else {
          const currentIds = new Set(value.map((v) => v.id));
          const newSelections = enabledFilteredOptions.filter(
            (opt) => !currentIds.has(opt.id)
          );
          onSelectedOptionsChange([...value, ...newSelections]);
        }
      };
      return {
        label,
        onClick: handleClick,
        checkState
      };
    };
  }, [selectFilteredProp, options, value, onSelectedOptionsChange, filter]);
  const fieldRef = useRef(null);
  const prevOptionsRef = useRef(options);
  useEffect(() => {
    if (prevOptionsRef.current !== options) {
      prevOptionsRef.current = options;
      fieldRef.current?.invalidate();
    }
  }, [options]);
  return /* @__PURE__ */ jsx(
    MultiSelectField,
    {
      ref: fieldRef,
      lazy: false,
      loadOptions: (searchValue) => filter(options, searchValue),
      debounceMs: 0,
      value,
      onSelectedOptionsChange,
      selectAll: selectAllConfig,
      selectFiltered: selectFilteredConfig,
      ...rest
    }
  );
};

export { MultiSelectField as M, MultiSelectFieldSync as a };
//# sourceMappingURL=MultiSelectFieldSync-DZ3tm7zt.js.map
