"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const index = require("../../icons/index.cjs");
;/* empty css                                                                                                                                                                                        */
;/* empty css                                                                                                                                                                                         */
;/* empty css                                                                                                                                                                                                 */
;/* empty css                                                                                                                                                                                            */
;/* empty css                                                                                                                                                                                            */
const helper = require("./helper.cjs");
const useProps = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/MantineProvider/use-props/use-props.cjs");
const MantineThemeProvider = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/MantineProvider/MantineThemeProvider/MantineThemeProvider.cjs");
const useCombobox = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/use-combobox/use-combobox.cjs");
const useUncontrolled = require("../../node_modules/.pnpm/@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-uncontrolled/use-uncontrolled.cjs");
const getParsedComboboxData = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/get-parsed-combobox-data/get-parsed-combobox-data.cjs");
const getOptionsLockup = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/get-options-lockup/get-options-lockup.cjs");
const defaultOptionsFilter = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/OptionsDropdown/default-options-filter.cjs");
const Pill = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Pill/Pill.cjs");
const isOptionsGroup = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/OptionsDropdown/is-options-group.cjs");
const Combobox = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Combobox/Combobox.cjs");
const Group = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Group/Group.cjs");
const Checkbox = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Checkbox/Checkbox.cjs");
const Box = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/Box/Box.cjs");
const Divider = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Divider/Divider.cjs");
const InputBase = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/InputBase/InputBase.cjs");
const Loader = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Loader/Loader.cjs");
const Input = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Input/Input.cjs");
const ScrollArea = require("../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/ScrollArea/ScrollArea.cjs");
const Option = ({ data, withCheckIcon, value, checkIconPosition, unstyled, renderOption }) => {
  if (!isOptionsGroup.isOptionsGroup(data)) {
    const checked = helper.isValueChecked(value, data.value);
    const check = withCheckIcon && /* @__PURE__ */ jsxRuntime.jsx(Checkbox.Checkbox, { size: "xs", checked, "aria-checked": checked, readOnly: true });
    const defaultContent = /* @__PURE__ */ jsxRuntime.jsxs(Group.Group, { children: [
      checkIconPosition === "left" && check,
      /* @__PURE__ */ jsxRuntime.jsx(Box.Box, { sx: { flex: 1 }, children: data.label }),
      checkIconPosition === "right" && check
    ] });
    return /* @__PURE__ */ jsxRuntime.jsx(
      Combobox.Combobox.Option,
      {
        value: data.value,
        disabled: data.disabled,
        "data-reverse": checkIconPosition === "right" || void 0,
        "data-checked": checked || void 0,
        "aria-selected": checked,
        active: checked,
        styles: (theme) => ({
          option: {
            "&:hover": {
              backgroundColor: theme.colors.carbon[3]
            }
          }
        }),
        children: typeof renderOption === "function" ? renderOption({ option: data, checked }) : defaultContent
      }
    );
  }
  const options = data.items.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
    Option,
    {
      data: item,
      value,
      unstyled,
      withCheckIcon,
      checkIconPosition,
      renderOption
    },
    item.value
  ));
  return /* @__PURE__ */ jsxRuntime.jsx(Combobox.Combobox.Group, { label: data.group, children: options });
};
const defaultProps = {
  maxValues: Infinity,
  withCheckIcon: true,
  checkIconPosition: "left",
  hiddenInputValuesDivider: ","
};
const ValuesVisible = ({ moreCount, readOnly, values, disabled, onRemove, optionsLockup }) => {
  const containerRef = React.useRef(null);
  const [valsVisible, setValsVisible] = React.useState(values);
  const [moreVisible, setMoreVisible] = React.useState(moreCount);
  const [isLongFirstOverflow, setIsLongFirstOverflow] = React.useState(false);
  const isCheckOverflowEnd = React.useRef(false);
  React.useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container) {
      return;
    }
    const resizeObserver = new ResizeObserver(() => {
      isCheckOverflowEnd.current = false;
      setValsVisible(values);
      setMoreVisible(moreCount);
    });
    resizeObserver.observe(container);
    return () => resizeObserver.unobserve(container);
  }, [values, moreCount]);
  React.useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container || isCheckOverflowEnd.current) {
      return;
    }
    const isOverflow = container.scrollWidth > container.clientWidth;
    if (isOverflow) {
      if (valsVisible.length === 1) {
        isCheckOverflowEnd.current = true;
        setIsLongFirstOverflow(true);
        return;
      }
      const newValsVisible = valsVisible.slice(0, -1);
      const newMoreVisible = moreVisible + 1;
      setValsVisible(newValsVisible);
      setMoreVisible(newMoreVisible);
    } else if (!isOverflow && isLongFirstOverflow) {
      setIsLongFirstOverflow(false);
    } else {
      isCheckOverflowEnd.current = true;
    }
  }, [valsVisible, moreVisible, isLongFirstOverflow]);
  return /* @__PURE__ */ jsxRuntime.jsxs(
    Pill.Pill.Group,
    {
      mah: 22,
      sx: {
        display: "flex",
        flexWrap: "nowrap",
        overflow: "hidden"
      },
      ref: containerRef,
      children: [
        valsVisible.map((item, index2) => {
          var _a, _b;
          return /* @__PURE__ */ jsxRuntime.jsx(
            Pill.Pill,
            {
              withRemoveButton: !readOnly && !((_a = optionsLockup[item]) == null ? void 0 : _a.disabled),
              onRemove: () => {
                onRemove(item);
              },
              disabled,
              styles: (theme) => ({
                root: {
                  backgroundColor: theme.colors.carbon[3],
                  borderRadius: theme.radius.sm,
                  // if the first item is too long, we need to set flex: 1 and minWidth: 0 to make it shrink
                  flex: isLongFirstOverflow ? "1" : void 0,
                  minWidth: isLongFirstOverflow ? 0 : void 0
                }
              }),
              children: ((_b = optionsLockup[item]) == null ? void 0 : _b.label) || item
            },
            `${item}-${index2}`
          );
        }),
        /* @__PURE__ */ jsxRuntime.jsxs(
          Pill.Pill,
          {
            styles: (theme) => ({
              root: {
                backgroundColor: theme.colors.carbon[3],
                borderRadius: theme.radius.sm,
                display: moreCount > 0 ? "block" : "none",
                opacity: moreVisible > 0 ? 1 : 0,
                flexShrink: 0
              }
            }),
            children: [
              "+",
              moreVisible
            ]
          }
        )
      ]
    }
  );
};
const ProMultiSelect = (_props) => {
  const props = useProps.useProps("MultiSelect", defaultProps, _props);
  const {
    data,
    value,
    defaultValue,
    limit,
    searchable,
    searchValue,
    defaultSearchValue,
    maxValues,
    readOnly,
    disabled,
    size,
    width,
    selectFirstOptionOnChange,
    placeholder,
    clearable,
    label,
    nothingFoundMessage,
    dropdownOpened,
    defaultDropdownOpened,
    loading,
    maxDropdownHeight,
    error,
    allowSelectAll,
    selectAllText,
    onOptionSubmit,
    renderOption,
    filter,
    onChange,
    onSearchChange,
    onRemove,
    onClear
  } = props;
  const theme = MantineThemeProvider.useMantineTheme();
  const combobox = useCombobox.useCombobox({
    opened: dropdownOpened,
    defaultOpened: defaultDropdownOpened,
    onDropdownClose: () => {
      combobox.resetSelectedOption();
      setSearchValue("");
    },
    onDropdownOpen: () => {
      combobox.focusSearchInput();
    }
  });
  const [_value, setValue] = useUncontrolled.useUncontrolled({
    value,
    defaultValue,
    finalValue: [],
    onChange
  });
  const [_searchValue, setSearchValue] = useUncontrolled.useUncontrolled({
    value: searchValue,
    defaultValue: defaultSearchValue,
    finalValue: "",
    onChange: onSearchChange
  });
  const parsedData = getParsedComboboxData.getParsedComboboxData(data);
  const optionsLockup = getOptionsLockup.getOptionsLockup(parsedData);
  const shouldFilter = typeof _searchValue === "string";
  const filteredData = shouldFilter ? (filter || defaultOptionsFilter.defaultOptionsFilter)({
    options: parsedData,
    search: searchable ? _searchValue : "",
    limit: limit ?? Infinity
  }) : parsedData;
  const [targetIndex, setTargetIndex] = React.useState(-1);
  const valuesForCompute = _value.map((item, index2) => {
    var _a, _b;
    return /* @__PURE__ */ jsxRuntime.jsx(
      Pill.Pill,
      {
        withRemoveButton: !readOnly && !((_a = optionsLockup[item]) == null ? void 0 : _a.disabled),
        onRemove: () => {
          setValue(_value.filter((i) => item !== i));
          onRemove == null ? void 0 : onRemove(item);
        },
        disabled,
        styles: (theme2) => ({ root: { backgroundColor: theme2.colors.carbon[3], borderRadius: theme2.radius.sm } }),
        children: ((_b = optionsLockup[item]) == null ? void 0 : _b.label) || item
      },
      `${item}-${index2}`
    );
  });
  const inputRef = React.useRef(null);
  React.useLayoutEffect(() => {
    var _a;
    const child = (_a = inputRef.current) == null ? void 0 : _a.children;
    if (!child || (child == null ? void 0 : child.length) <= 1) {
      return;
    }
    const firstOffsetLeft = child[0].offsetLeft;
    const index2 = Array.from(child).findIndex(
      (child2, idx) => child2.offsetLeft === firstOffsetLeft && idx > 0
    );
    setTargetIndex(index2);
  }, [_value]);
  const options = filteredData == null ? void 0 : filteredData.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
    Option,
    {
      data: item,
      value: _value,
      unstyled: false,
      withCheckIcon: true,
      checkIconPosition: "left",
      renderOption
    },
    isOptionsGroup.isOptionsGroup(item) ? item.group : item.value
  ));
  const allChecked = React.useMemo(() => {
    return parsedData.every((value2) => {
      if (isOptionsGroup.isOptionsGroup(value2)) {
        return value2.items.every((item) => _value.includes(item.value));
      } else {
        return _value.includes(value2.value);
      }
    });
  }, [parsedData, _value]);
  const indeterminate = _value.length > 0 && !allChecked;
  const selectAll = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      Combobox.Combobox.Option,
      {
        value: "_select_all",
        "data-checked": allChecked,
        "aria-selected": allChecked,
        active: allChecked,
        styles: (theme2) => ({
          option: {
            "&:hover": {
              backgroundColor: theme2.colors.carbon[3]
            }
          }
        }),
        children: /* @__PURE__ */ jsxRuntime.jsxs(Group.Group, { children: [
          /* @__PURE__ */ jsxRuntime.jsx(Checkbox.Checkbox, { size: "xs", checked: allChecked, indeterminate, "aria-checked": allChecked, readOnly: true }),
          /* @__PURE__ */ jsxRuntime.jsx(Box.Box, { sx: { flex: 1 }, children: selectAllText || "All" })
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(Divider.Divider, { color: "carbon.3" })
  ] });
  const handleOptionSubmit = (val) => {
    if (val === "_select_all") {
      if (allChecked) {
        setValue([]);
      } else {
        const allValues = parsedData.reduce((acc, value2) => {
          if (isOptionsGroup.isOptionsGroup(value2)) {
            return [...acc, ...value2.items.map((item) => item.value)];
          } else {
            return [...acc, value2.value];
          }
        }, []);
        setValue(allValues);
      }
    } else {
      onOptionSubmit == null ? void 0 : onOptionSubmit(val);
      setSearchValue("");
      combobox.updateSelectedOptionIndex("selected");
      if (_value.includes(optionsLockup[val].value)) {
        setValue(_value.filter((v) => v !== optionsLockup[val].value));
        onRemove == null ? void 0 : onRemove(optionsLockup[val].value);
      } else if (_value.length < maxValues) {
        setValue([..._value, optionsLockup[val].value]);
      }
    }
  };
  const clearButton = /* @__PURE__ */ jsxRuntime.jsx(
    Combobox.Combobox.ClearButton,
    {
      onClear: () => {
        onClear == null ? void 0 : onClear();
        setValue([]);
        setSearchValue("");
      }
    }
  );
  const _clearable = clearable && _value.length > 0 && !disabled && !readOnly;
  const moreCount = targetIndex > 0 ? _value.length - targetIndex : 0;
  return /* @__PURE__ */ jsxRuntime.jsxs(
    Combobox.Combobox,
    {
      store: combobox,
      withinPortal: true,
      size,
      readOnly,
      onOptionSubmit: handleOptionSubmit,
      shadow: "sm",
      styles: {
        search: {
          borderRadius: theme.radius.md
        }
      },
      children: [
        /* @__PURE__ */ jsxRuntime.jsx(Combobox.Combobox.Target, { children: /* @__PURE__ */ jsxRuntime.jsxs(
          InputBase.InputBase,
          {
            error,
            w: width,
            component: "button",
            type: "button",
            pointer: true,
            disabled: disabled || loading,
            rightSection: loading ? /* @__PURE__ */ jsxRuntime.jsx(Loader.Loader, { size: "sm" }) : _clearable ? clearButton : /* @__PURE__ */ jsxRuntime.jsx(Combobox.Combobox.Chevron, {}),
            label,
            styles: {
              label: { color: theme.colors.carbon[8], marginBottom: 6, fontSize: 14, lineHeight: "20px" },
              description: { color: theme.colors.carbon[6] },
              error: { color: theme.colors.red[7] }
            },
            rightSectionPointerEvents: value === null ? "none" : "all",
            onClick: () => combobox.toggleDropdown(),
            children: [
              _value.length === 0 && !!placeholder && /* @__PURE__ */ jsxRuntime.jsx(Input.Input.Placeholder, { children: placeholder }),
              /* @__PURE__ */ jsxRuntime.jsx(
                Pill.Pill.Group,
                {
                  ref: inputRef,
                  mah: 22,
                  sx: {
                    flexWrap: "wrap",
                    overflowY: "clip",
                    maxWidth: "100%",
                    opacity: 0,
                    pointerEvents: "none",
                    height: 0
                  },
                  children: valuesForCompute
                }
              ),
              // _value.length > 0 is required. Because this component need a render cycle to synchronize props to state. So if we remove '_value.length > 0', when we uncheck the last item, the placeholder will show, but at that moment, the state in this ValuesVisible component keeps previous values
              _value.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(
                ValuesVisible,
                {
                  disabled,
                  readOnly,
                  optionsLockup,
                  moreCount,
                  values: _value.slice(0, targetIndex > 0 ? targetIndex : _value.length),
                  onRemove: (item) => {
                    setValue(_value.filter((i) => item !== i));
                    onRemove == null ? void 0 : onRemove(item);
                  }
                }
              )
            ]
          }
        ) }),
        /* @__PURE__ */ jsxRuntime.jsxs(Combobox.Combobox.Dropdown, { children: [
          searchable && /* @__PURE__ */ jsxRuntime.jsx(
            Combobox.Combobox.Search,
            {
              leftSection: /* @__PURE__ */ jsxRuntime.jsx(index.IconSearchLg, { size: 16, c: "gray.9", strokeWidth: 2 }),
              value: _searchValue,
              onChange: (event) => {
                setSearchValue(event.currentTarget.value);
                searchable && combobox.openDropdown();
                selectFirstOptionOnChange && combobox.selectFirstOption();
              },
              placeholder: "Find"
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsxs(ScrollArea.ScrollArea.Autosize, { type: "scroll", mah: maxDropdownHeight ?? 200, children: [
            allowSelectAll && selectAll,
            /* @__PURE__ */ jsxRuntime.jsx(Combobox.Combobox.Options, { children: options.length > 0 ? options : /* @__PURE__ */ jsxRuntime.jsx(Combobox.Combobox.Empty, { children: nothingFoundMessage || "Nothing found" }) })
          ] })
        ] })
      ]
    }
  );
};
exports.ProMultiSelect = ProMultiSelect;
