import { jsxs, jsx } from 'react/jsx-runtime';
import { useId, useRef, useState, useLayoutEffect, isValidElement } from 'react';
import { c as cx } from './index-SvGbrGuT.js';
import { S as SvgClose } from './close-DZj38AEh.js';
import { S as SvgChevronRight } from './chevron_right-BdpsxX7x.js';
import { B as Button } from './Button-DrNDkO2f.js';
import { C as Chip } from './Chip-Bc7jiIJ1.js';
import { F as Flex } from './Flex-CUtXN-C0.js';
import { F as FieldLabel } from './FieldLabel-DL0D6fvc.js';
import { w as warnDeprecatedErrorUsage } from './utils-pudAMGnO.js';
import { s as styles } from './SelectTriggerBase.module-B0NFRlQP.js';
import { H as Helper } from './Helper-B2UrgJvr.js';

const ADD_NEW = Symbol.for("add-new");
const SELECT_ALL = Symbol.for("select-all");
const defaultItemToString = function(item) {
  return item != null ? String(item) : "";
};
const defaultItemToKey = function(item) {
  return item;
};
function isMultiple(props) {
  return Object.hasOwn(props, "multiple") && props.multiple === true;
}
function getScrollParent(node) {
  if (node == null) {
    return null;
  }
  if (node.scrollHeight > node.clientHeight) {
    return node;
  } else {
    if (node.parentNode instanceof HTMLElement) {
      return getScrollParent(node.parentNode);
    }
    return null;
  }
}

function mergeChipProps(...propSets) {
  const merged = propSets.reduce(
    (acc, props) => ({ ...acc, ...props }),
    {}
  );
  return merged;
}
const SelectTriggerBase = function({
  className,
  label,
  size,
  error,
  hint,
  description,
  prefix,
  suffix,
  maxRows,
  selectedItemProps = (_item, _index) => ({}),
  disabled,
  readOnly,
  /** ======== */
  disableClearSelection,
  itemToString: itemToStringProp,
  selectedItem,
  selectedItems,
  removeSelectedItem,
  inputValue,
  referenceRef,
  /** ======== */
  variant = "select",
  onClearButtonClick,
  labelProps,
  inputWrapperProps = {},
  toggleButtonProps = {},
  inputProps = {},
  chipProps = (_item, _index) => ({}),
  warning,
  placeholder,
  ...rest
}) {
  const itemToString = itemToStringProp ?? defaultItemToString;
  const ComboboxTriggerClassNames = cx(styles["search-field"], {
    [styles["select"]]: variant === "select"
  });
  const noClearButton = disabled || readOnly || disableClearSelection;
  const ComboboxInputWrapperClassNames = cx(
    styles["input-wrapper"],
    className ? {
      [className]: variant === "select"
    } : {},
    {
      [styles["small"]]: size === "small",
      [styles["large"]]: size === "large",
      [styles["no-clear-button"]]: noClearButton
    }
  );
  const ComboboxInputClassNames = cx(
    styles["input"],
    className ? {
      [className]: variant === "combobox"
    } : {},
    {
      [styles["error"]]: error
    }
  );
  const helperUid = "helper" + useId();
  const placeholderUid = "placeholder" + useId();
  const ariaDescribedBy = `${helperUid} ${placeholderUid}`;
  warnDeprecatedErrorUsage("SelectTrigger", error);
  const errorMessages = typeof error === "boolean" || error === void 0 ? void 0 : error;
  const rowsRef = useRef(null);
  const [stillCalculating, setStillCalculating] = useState(false);
  const [collapsedChips, setCollapsedChips] = useState(false);
  const [visibleChipsCount, setVisibleChipsCount] = useState(
    null
  );
  const [forceRenderCount, setForceRenderCount] = useState(0);
  useLayoutEffect(() => {
    if (maxRows === void 0) return;
    if (stillCalculating === false) {
      setStillCalculating(true);
      setCollapsedChips(false);
      setVisibleChipsCount(null);
      setForceRenderCount((x) => x + 1);
    } else if (rowsRef?.current?.children) {
      const children = rowsRef?.current?.children;
      const rowData = Array.from(children).reduce(
        (acc, child) => {
          const top = child.getBoundingClientRect().top;
          if (!acc.length) {
            return [{ count: 1, top }];
          } else if (acc[acc.length - 1].top === top) {
            return [
              ...acc.slice(0, -1),
              { count: acc[acc.length - 1].count + 1, top }
            ];
          } else if (acc[acc.length - 1].top !== top) {
            return [...acc, { count: 1, top }];
          } else {
            return acc;
          }
        },
        []
      );
      if (!rowData[maxRows] || visibleChipsCount === 0 || selectedItems.length === 1) {
        setStillCalculating(false);
      } else {
        setCollapsedChips(true);
        if (visibleChipsCount == null) {
          if (rowData[maxRows]) {
            const quickGuess = Math.max(
              rowData.slice(0, maxRows).reduce((sum, row) => sum + row.count, -1),
              0
            );
            setVisibleChipsCount(quickGuess);
          } else {
            const naiveGuess = Math.max(
              rowData.reduce((sum, row) => sum + row.count, -2),
              0
            );
            setVisibleChipsCount(naiveGuess);
          }
        } else {
          setVisibleChipsCount(visibleChipsCount - 1);
        }
        setForceRenderCount((x) => x + 1);
      }
    }
  }, [selectedItems.length, maxRows, forceRenderCount]);
  const selectedItemsDisplayCount = collapsedChips && maxRows != null && visibleChipsCount !== null ? visibleChipsCount : selectedItems.length;
  return /* @__PURE__ */ jsxs("div", { ...rest, className: ComboboxTriggerClassNames, ref: referenceRef, children: [
    label ? /* @__PURE__ */ jsx(
      FieldLabel,
      {
        ...labelProps,
        className: cx(styles["label"], labelProps?.className),
        children: label
      }
    ) : null,
    /* @__PURE__ */ jsxs(
      "div",
      {
        ...inputWrapperProps,
        className: ComboboxInputWrapperClassNames,
        ...variant === "select" ? {
          "aria-describedby": ariaDescribedBy,
          "aria-labelledby": labelProps?.id
        } : {},
        children: [
          /* @__PURE__ */ jsxs("div", { className: styles["buttons-wrapper"], children: [
            (inputValue || selectedItem || selectedItems.length) && !noClearButton ? /* @__PURE__ */ jsx("div", { className: styles["close-button-wrapper"], children: /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": "clear selection",
                appearance: "ghost",
                size: "small",
                icon: SvgClose,
                className: styles["close-button"],
                onClick: (e) => {
                  e.stopPropagation();
                  onClearButtonClick?.(e);
                },
                tabIndex: -1
              }
            ) }) : null,
            /* @__PURE__ */ jsx("div", { className: styles["toggle-button-wrapper"], children: /* @__PURE__ */ jsx(
              Button,
              {
                ...toggleButtonProps,
                ...variant === "select" ? { tabIndex: -1, inert: "true" } : {},
                className: styles["toggle-button"],
                "aria-label": "toggle menu",
                icon: SvgChevronRight,
                appearance: "ghost",
                size: "small",
                disabled
              }
            ) })
          ] }),
          /* @__PURE__ */ jsx("div", { className: styles["prefix-wrapper"], children: prefix ? /* @__PURE__ */ jsx("div", { className: styles["prefix"], children: prefix }) : null }),
          /* @__PURE__ */ jsxs("div", { className: styles["rows-wrapper"], ref: rowsRef, children: [
            selectedItems.length && removeSelectedItem != null ? selectedItems.slice(0, selectedItemsDisplayCount).map((item, index) => {
              return /* @__PURE__ */ jsx(
                "div",
                {
                  className: styles["chip-wrapper"],
                  children: /* @__PURE__ */ jsx(
                    Chip,
                    {
                      ...mergeChipProps(
                        chipProps(item, index),
                        selectedItemProps(item, index),
                        {
                          label: itemToString(item),
                          onClose: disabled || readOnly ? void 0 : (_e) => {
                            removeSelectedItem(item);
                          },
                          className: styles["chip"],
                          title: itemToString(item)
                        }
                      )
                    }
                  )
                },
                `selected-item-${index}`
              );
            }) : null,
            collapsedChips && maxRows != null ? /* @__PURE__ */ jsx("div", { className: styles["chip-wrapper"], children: /* @__PURE__ */ jsx(
              Chip,
              {
                label: `+${selectedItems.length - selectedItemsDisplayCount}`,
                className: styles["chip"],
                title: selectedItems.slice(selectedItemsDisplayCount).map((item) => itemToString(item)).join(", ")
              }
            ) }) : null,
            /* @__PURE__ */ jsxs(Flex, { className: styles["input-flex"], alignItems: "center", children: [
              variant === "select" ? /* @__PURE__ */ jsx(
                "div",
                {
                  ...inputProps,
                  className: cx(ComboboxInputClassNames, inputProps.className),
                  children: selectedItems.length ? null : selectedItem ? itemToString(selectedItem) : /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: styles["fake-placeholder"],
                      id: placeholderUid,
                      children: placeholder
                    }
                  )
                }
              ) : /* @__PURE__ */ jsx(
                "input",
                {
                  ...inputProps,
                  placeholder,
                  className: cx(ComboboxInputClassNames, inputProps.className),
                  ...inputProps["aria-expanded"] != null && inputProps["aria-controls"] != null ? {
                    role: "combobox"
                  } : {}
                }
              ),
              suffix ? /* @__PURE__ */ jsx("div", { className: styles["suffix"], children: suffix }) : null
            ] })
          ] })
        ]
      }
    ),
    hint || errorMessages || warning || description ? /* @__PURE__ */ jsx(
      Helper,
      {
        id: helperUid,
        error: typeof errorMessages === "string" || Array.isArray(errorMessages) ? errorMessages : void 0,
        warning,
        errorMessage: isValidElement(errorMessages) ? errorMessages : void 0,
        hint,
        description
      }
    ) : null
  ] });
};

export { ADD_NEW as A, SelectTriggerBase as S, defaultItemToKey as a, SELECT_ALL as b, defaultItemToString as d, getScrollParent as g, isMultiple as i };
//# sourceMappingURL=SelectTriggerBase-Cs827tDp.js.map
