import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import React__default, { useState, useRef, useMemo, useEffect, useCallback } from "react";
import ReactSelect from "react-select";
import { Alert } from "../Alert/index.js";
import { CustomGroupHeading } from "./customGroupHeading.js";
import Dropdown from "./dropdown.js";
import { useClickOutside } from "./hooks/useClickOutside.js";
import { MenuList } from "./menuList.js";
import { Option } from "./optionList.js";
import SearchFilter from "./SearchFilter.js";
import { SelectedOptionsTags } from "./selected-option-tags.js";
import { Checkbox } from "../Checkbox/index.js";
import { flattenOptions, handleSelectAllWhenCompLoads, handleDropdownClose, getPlaceholder, handleSearch, onKeyDown, handleDropdownOpen } from "./utils.js";
import { HelperText } from "../common/HelperText/index.js";
import { Tooltip } from "../Tooltip/index.js";
/* empty css                   */
const selectStyles = {
  menu: () => ({})
};
const countTotalSelectedOptions = (selectedOptions) => {
  if (!selectedOptions) return 0;
  if (Array.isArray(selectedOptions)) return selectedOptions.length;
  return selectedOptions.value !== void 0 ? 1 : 0;
};
const Select = React__default.memo(function Select2(props) {
  var _a, _b, _c, _d;
  const {
    isOpen,
    setIsOpen,
    label,
    isRequired,
    name,
    placeholder,
    searchPlaceholder = "Search here...",
    labelOrientation = "top",
    isMulti = false,
    isDisabled,
    isLoading,
    isWithIcon,
    isError,
    isWithSearch,
    isClearable,
    isWithSelectedOptionTags,
    toggleSelectAll,
    isSelectAll,
    icon,
    withPortal,
    dropDownPortalClassName,
    initialOptions,
    currentOptions,
    setCurrentOptions,
    selectedOptions = [],
    setSelectedOptions,
    portalContainer,
    isAgGridCellRenderer,
    onMenuScrollToBottom,
    setIsSelectAll,
    isWithSelectAll,
    isCloseWhenClickOutside = true,
    handleChange: externalOnChange,
    onSelectAll: externalOnSelectAll,
    onClearAll: externalOnClearAll,
    onSearch: externalOnSearch,
    onDropdownClose: externalOnDropdownClose,
    onDropdownOpen: externalOnDropdownOpen,
    minWidth,
    width,
    menuShouldBlockScroll = false,
    onBlur,
    isGrouped,
    selectId,
    column,
    customPlaceholderAfterSelect,
    isMultiInSubmenu = false,
    customBadgeLabel,
    customBadgeColor = "success",
    helperText,
    dropdownPosition,
    maxSelectableOptions,
    noOptionMessage = "No options available"
  } = props;
  const [submenuOptions, setSubmenuOptions] = useState(null);
  const [submenuParent, setSubmenuParent] = useState(null);
  const flattenInitialOptions = flattenOptions(initialOptions);
  const searchBarRef = useRef(null);
  const containerRef = useRef(null);
  const focusedIndex = useRef(0);
  const dropdownButtonRef = useRef(null);
  const textSpanRef = useRef(null);
  const [isTextTruncated, setIsTextTruncated] = useState(false);
  const memoizedOptions = useMemo(() => currentOptions, [currentOptions]);
  const submenuTimeoutRef = useRef(null);
  const [submenuPosition, setSubmenuPosition] = useState({ top: 0, left: 0, width: 0 });
  const dropdownMenuRef = useRef(null);
  const menuRef = useRef(null);
  const [isSubmenuHovered, setIsSubmenuHovered] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [columnWidth, setColumnWidth] = useState(
    column ? ((_a = column.getActualWidth) == null ? void 0 : _a.call(column)) ?? ((_b = column.getWidth) == null ? void 0 : _b.call(column)) : void 0
  );
  useEffect(() => {
    if (textSpanRef.current) {
      const isTruncated = textSpanRef.current.scrollWidth > textSpanRef.current.clientWidth;
      setIsTextTruncated(isTruncated);
    }
  }, [columnWidth, currentOptions, selectedOptions, placeholder]);
  useEffect(() => {
    var _a2;
    if (isAgGridCellRenderer && column) {
      const handleColumnResized = () => {
        var _a3, _b2;
        const newWidth = ((_a3 = column.getActualWidth) == null ? void 0 : _a3.call(column)) ?? ((_b2 = column.getWidth) == null ? void 0 : _b2.call(column));
        if (newWidth !== void 0) setColumnWidth(newWidth - 12);
      };
      (_a2 = column.addEventListener) == null ? void 0 : _a2.call(column, "widthChanged", handleColumnResized);
      return () => {
        var _a3;
        (_a3 = column.removeEventListener) == null ? void 0 : _a3.call(column, "widthChanged", handleColumnResized);
      };
    }
    return void 0;
  }, [isAgGridCellRenderer, column, columnWidth]);
  useClickOutside({
    isOpen,
    containerRef,
    menuRef,
    isCloseWhenClickOutside,
    onClose: (event) => {
      handleDropdownClose({
        externalOnDropdownClose,
        setCurrentOptions,
        initialOptions: isGrouped ? flattenInitialOptions : initialOptions,
        currentOptions,
        setIsOpen,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onBlur,
        event
      });
    }
  });
  useEffect(() => {
    if (isWithSelectAll) {
      handleSelectAllWhenCompLoads({
        currentOptions,
        selectedOptions: Array.isArray(selectedOptions) ? selectedOptions : [],
        setSelectedOptions: (opts) => {
          setSelectedOptions(opts);
        }
      });
    }
  }, [isWithSelectAll]);
  const syncParentChildSelection = useCallback(
    (selectedArr2) => {
      if (!selectedArr2 || selectedArr2.length === 0) {
        setSelectedOptions([]);
        setIsSelectAll == null ? void 0 : setIsSelectAll(false);
        return;
      }
      let updated = [...selectedArr2];
      (initialOptions || []).forEach((parent) => {
        if (parent.children && parent.children.length > 0) {
          const allChildrenSelected = parent.children.every(
            (child) => updated.some((sel) => sel.value === child.value)
          );
          const parentSelected = updated.some((sel) => sel.value === parent.value);
          if (allChildrenSelected && !parentSelected) {
            updated.push(parent);
          } else if (!allChildrenSelected && parentSelected) {
            updated = updated.filter((sel) => sel.value !== parent.value);
          }
        }
      });
      setSelectedOptions(updated);
      setIsSelectAll == null ? void 0 : setIsSelectAll(
        updated.length === (initialOptions.length > 0 ? initialOptions.length : currentOptions.length)
      );
    },
    [initialOptions, currentOptions, setSelectedOptions, setIsSelectAll]
  );
  const handleSelect = useCallback(
    (selectedValues, event, index) => {
      if ((event == null ? void 0 : event.action) === "clear") {
        if (externalOnChange) {
          externalOnChange([], event, index);
        }
        return;
      }
      if (isMulti) {
        let newSelectedOptions = Array.isArray(selectedOptions) ? [...selectedOptions] : [];
        const option = (event == null ? void 0 : event.option) || selectedValues;
        const isParent = !!(option.children && option.children.length > 0);
        const valuesSet = new Set(newSelectedOptions.map((o) => o.value));
        const isSelected = Array.isArray(option) ? option.some((opt) => valuesSet.has(opt.value)) : option ? valuesSet.has(option.value) : false;
        const currentCount = maxSelectableOptions !== void 0 ? countTotalSelectedOptions(selectedOptions) : 0;
        if (isParent) {
          if (!isSelected) {
            if (maxSelectableOptions !== void 0 && currentCount >= maxSelectableOptions) {
              return;
            }
            newSelectedOptions.push({ ...option, children: option.children });
          } else {
            newSelectedOptions = newSelectedOptions.filter((sel) => sel.value !== option.value);
          }
        } else {
          const parentOption = (initialOptions || []).find(
            (parent) => parent.children && parent.children.some((child) => child.value === option.value)
          );
          if (parentOption) {
            const parentIndex = newSelectedOptions.findIndex(
              (sel) => sel.value === parentOption.value
            );
            if (isSelected) {
              if (parentIndex !== -1) {
                const parent = { ...newSelectedOptions[parentIndex] };
                parent.children = (parent.children ?? []).filter(
                  (child) => child.value !== option.value
                );
                if (parent.children.length === 0) {
                  newSelectedOptions = newSelectedOptions.filter(
                    (sel) => sel.value !== parentOption.value
                  );
                } else {
                  newSelectedOptions[parentIndex] = parent;
                }
              }
            } else {
              if (parentIndex !== -1) {
                const parent = { ...newSelectedOptions[parentIndex] };
                if (!(parent.children ?? []).some((child) => child.value === option.value)) {
                  parent.children = [...parent.children ?? [], option];
                }
                newSelectedOptions[parentIndex] = parent;
              } else {
                if (maxSelectableOptions !== void 0 && currentCount >= maxSelectableOptions) {
                  return;
                }
                newSelectedOptions.push({ ...parentOption, children: [option] });
              }
            }
          } else {
            if (isSelected) {
              const optionValues = Array.isArray(option) ? option.map((o) => o.value) : [option.value];
              newSelectedOptions = newSelectedOptions.filter(
                (sel) => !optionValues.includes(sel.value)
              );
            } else {
              if (maxSelectableOptions !== void 0 && currentCount >= maxSelectableOptions) {
                return;
              }
              newSelectedOptions.push(option);
            }
          }
        }
        setSelectedOptions(newSelectedOptions);
        setIsSelectAll == null ? void 0 : setIsSelectAll(newSelectedOptions.length === initialOptions.length);
        if (externalOnChange) {
          externalOnChange(newSelectedOptions, event, index);
        }
        return;
      }
      if (isGrouped && isMulti) {
        const flattenSelectedValues = flattenOptions(selectedValues);
        setSelectedOptions(flattenSelectedValues);
        setIsSelectAll == null ? void 0 : setIsSelectAll(flattenSelectedValues.length === flattenInitialOptions.length);
        if (externalOnChange) {
          externalOnChange(flattenSelectedValues, event, index);
        }
      } else {
        setSelectedOptions(selectedValues);
        if (externalOnChange) {
          externalOnChange(selectedValues, event, index);
        }
      }
      if (isMulti && !isGrouped) {
        if (initialOptions.length > 0)
          setIsSelectAll == null ? void 0 : setIsSelectAll(
            Array.isArray(selectedValues) && selectedValues.length === initialOptions.length
          );
        else
          setIsSelectAll == null ? void 0 : setIsSelectAll(
            Array.isArray(selectedValues) && selectedValues.length === currentOptions.length
          );
      }
      if (!isMulti) {
        handleDropdownClose({
          externalOnDropdownClose,
          setCurrentOptions,
          initialOptions,
          currentOptions,
          setIsOpen,
          event: void 0
        });
      }
    },
    [
      isMulti,
      setIsSelectAll,
      setIsOpen,
      externalOnChange,
      initialOptions,
      selectedOptions,
      setSelectedOptions,
      flattenInitialOptions,
      isGrouped,
      currentOptions,
      maxSelectableOptions,
      externalOnDropdownClose,
      setCurrentOptions
    ]
  );
  const isMaxLimitReached = useMemo(() => {
    const total = countTotalSelectedOptions(selectedOptions);
    return maxSelectableOptions !== void 0 && total >= maxSelectableOptions;
  }, [maxSelectableOptions, selectedOptions]);
  const handleOptionHover = useCallback(
    (option, _index, event) => {
      var _a2;
      if (submenuTimeoutRef.current) {
        clearTimeout(submenuTimeoutRef.current);
      }
      if (option.children && option.children.length > 0) {
        const optionNode = event.currentTarget;
        const dropdownRect = (_a2 = dropdownMenuRef.current) == null ? void 0 : _a2.getBoundingClientRect();
        const optionRect = optionNode.getBoundingClientRect();
        if (dropdownRect && optionRect) {
          setSubmenuPosition({
            top: optionRect.top - dropdownRect.top,
            left: dropdownRect.width + 12,
            width: dropdownRect.width
          });
        }
        setSubmenuOptions(option.children);
        setSubmenuParent(option);
        setIsSubmenuHovered(true);
      } else {
        setIsSubmenuHovered(false);
        setSubmenuOptions(null);
        setSubmenuParent(null);
      }
    },
    []
  );
  useEffect(() => {
    return () => {
      if (submenuTimeoutRef.current) {
        clearTimeout(submenuTimeoutRef.current);
      }
    };
  }, []);
  function handleSelectAllWrapper(event) {
    if (externalOnSelectAll) {
      externalOnSelectAll(event);
    } else {
      if (event && event.target.checked) {
        setIsSelectAll == null ? void 0 : setIsSelectAll(true);
        const currentSelected = Array.isArray(selectedOptions) ? selectedOptions : [];
        const restCurrentOptions = currentOptions.filter(
          (option) => !currentSelected.find((sel) => sel.label === option.label && option.value === sel.value)
        );
        const merged = [...currentSelected, ...restCurrentOptions];
        setSelectedOptions(merged);
        if (externalOnChange) externalOnChange(merged);
      } else {
        setIsSelectAll == null ? void 0 : setIsSelectAll(false);
        setSelectedOptions([]);
        if (externalOnChange) externalOnChange([]);
      }
    }
  }
  function handleClearAllWrapper() {
    if (externalOnClearAll) {
      externalOnClearAll();
      setSelectedOptions([]);
      setIsSelectAll == null ? void 0 : setIsSelectAll(false);
    } else {
      handleSelect([], { action: "clear" });
      setSelectedOptions([]);
      setIsSelectAll == null ? void 0 : setIsSelectAll(false);
    }
    syncParentChildSelection([]);
  }
  const portalContainerResolved = typeof document !== "undefined" ? portalContainer ?? document.body : null;
  if (isMulti && !setIsSelectAll) {
    return /* @__PURE__ */ jsx(
      Alert,
      {
        description: "isMulti cannot be used without isSelectAll & setIsSelectAll",
        severity: "error",
        title: "Select Error"
      }
    );
  }
  const selectedArr = Array.isArray(selectedOptions) ? selectedOptions : [];
  const placeholderText = getPlaceholder(
    isMulti,
    selectedOptions,
    placeholder,
    customPlaceholderAfterSelect
  );
  const isPlaceholder = placeholderText === placeholder;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: `ia-select-main-container-v3 ${labelOrientation === "top" ? "top-orientation" : ""} ${isAgGridCellRenderer ? "isAgGridCellRenderer" : ""}`,
      children: [
        label && /* @__PURE__ */ jsxs("div", { className: "ia-select-label-v3", children: [
          label,
          " ",
          isRequired && /* @__PURE__ */ jsx("span", { style: { color: "red" }, children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          "div",
          {
            ref: containerRef,
            style: {
              width: isAgGridCellRenderer ? "100%" : minWidth ?? width ?? "auto",
              minWidth: isAgGridCellRenderer ? "0" : minWidth ?? width ?? "auto",
              maxWidth: isAgGridCellRenderer ? columnWidth != null ? columnWidth : "100%" : "none"
            },
            children: /* @__PURE__ */ jsxs(
              Dropdown,
              {
                containerRef,
                disabled: isDisabled,
                dropdownButtonRef,
                dropDownPortalClassName,
                dropdownPosition,
                isOpen,
                menuRef,
                portalContainer: portalContainerResolved,
                target: /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsxs(
                    "button",
                    {
                      ref: dropdownButtonRef,
                      className: `ia-select-styled-dropdown-main-button ${isError ? "impact-select-error" : ""} ${isDisabled ? "impact-select-disabled" : ""} ${isClearable ? "is-with-clearable" : ""}`,
                      disabled: isDisabled,
                      id: selectId,
                      name,
                      style: {
                        minWidth: isAgGridCellRenderer ? "0" : minWidth ?? "240px",
                        width: isAgGridCellRenderer ? "100%" : width ?? minWidth ?? "240px",
                        maxWidth: isAgGridCellRenderer ? columnWidth != null ? columnWidth : "100%" : "300px",
                        flex: isAgGridCellRenderer ? "1 1 auto" : "none"
                      },
                      type: "button",
                      onBlur: (e) => {
                        if (!isMulti) {
                          e.preventDefault();
                          e.stopPropagation();
                          if (onBlur) onBlur(e);
                        }
                      },
                      onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        isOpen ? handleDropdownClose({
                          externalOnDropdownClose,
                          setCurrentOptions,
                          initialOptions,
                          currentOptions,
                          setIsOpen,
                          // eslint-disable-next-line @typescript-eslint/no-explicit-any
                          onBlur,
                          event: e
                        }) : handleDropdownOpen({
                          externalOnDropdownOpen,
                          isOpen,
                          setIsOpen
                        });
                      },
                      onKeyDown: !isWithSearch ? (e) => {
                        onKeyDown({ e, focusedIndex, currentOptions });
                      } : void 0,
                      children: [
                        /* @__PURE__ */ jsxs(
                          "div",
                          {
                            className: `ia-select-button-text ${isPlaceholder ? "placeholder" : ""} ${!(isClearable && selectedOptions || isMulti && selectedArr.length > 0 && isClearable) ? "ia-select-button-text-full-width" : ""} ${isAgGridCellRenderer ? "impact-select-table" : ""}`,
                            children: [
                              isWithIcon && icon,
                              isTextTruncated ? /* @__PURE__ */ jsx(
                                Tooltip,
                                {
                                  orientation: "top",
                                  title: getPlaceholder(isMulti, selectedOptions, placeholder),
                                  variant: "tertiary",
                                  children: /* @__PURE__ */ jsx("span", { ref: textSpanRef, className: "ia-select-button-text-span", children: isMultiInSubmenu && !isMulti && selectedOptions && !Array.isArray(selectedOptions) && selectedOptions.children && (selectedOptions.children.length ?? 0) > 0 ? selectedOptions.children.length === 1 ? (_c = selectedOptions.children[0]) == null ? void 0 : _c.label : `Selected (${selectedOptions.children.length})` : placeholderText })
                                }
                              ) : /* @__PURE__ */ jsx("span", { ref: textSpanRef, className: "ia-select-button-text-span", children: !isMulti && selectedOptions && !Array.isArray(selectedOptions) && selectedOptions.children && (selectedOptions.children.length ?? 0) > 0 ? selectedOptions.children.length === 1 ? (_d = selectedOptions.children[0]) == null ? void 0 : _d.label : `Selected (${selectedOptions.children.length})` : placeholderText })
                            ]
                          }
                        ),
                        isMulti && selectedArr.length > 0 && isClearable && /* @__PURE__ */ jsx(
                          "div",
                          {
                            className: "ia-select-button-clear-icon",
                            role: "button",
                            onClick: (event) => {
                              event.stopPropagation();
                              if (externalOnClearAll) {
                                externalOnClearAll();
                              } else {
                                setSelectedOptions([]);
                                setIsSelectAll == null ? void 0 : setIsSelectAll(false);
                                syncParentChildSelection([]);
                              }
                            }
                          }
                        ),
                        !isMulti && isClearable && selectedOptions && !Array.isArray(selectedOptions) && Object.keys(selectedOptions).length > 0 && /* @__PURE__ */ jsx(
                          "div",
                          {
                            className: "ia-select-button-clear-icon",
                            role: "button",
                            onClick: (event) => {
                              event.stopPropagation();
                              if (externalOnClearAll) {
                                externalOnClearAll();
                              } else {
                                setSelectedOptions([]);
                                setIsSelectAll == null ? void 0 : setIsSelectAll(false);
                                syncParentChildSelection([]);
                              }
                            }
                          }
                        ),
                        /* @__PURE__ */ jsx(
                          "div",
                          {
                            className: `ia-select-chevron-icon ${isOpen ? "open" : ""} ${isDisabled ? "disabled" : ""}`
                          }
                        )
                      ]
                    }
                  ),
                  helperText && /* @__PURE__ */ jsx(
                    HelperText,
                    {
                      error: isError,
                      helper: isError ? helperText : "",
                      minWidth: typeof minWidth === "number" ? `${minWidth}px` : minWidth
                    }
                  ),
                  isMulti && isWithSelectedOptionTags && /* @__PURE__ */ jsx(
                    SelectedOptionsTags,
                    {
                      selectedOptions: selectedArr,
                      onChange: (opts) => {
                        handleSelect(opts);
                      }
                    }
                  )
                ] }),
                withPortal,
                onClose: () => {
                  handleDropdownClose({
                    externalOnDropdownClose,
                    setCurrentOptions,
                    initialOptions,
                    currentOptions,
                    setIsOpen,
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    onBlur
                  });
                },
                children: [
                  /* @__PURE__ */ jsx(
                    SearchFilter,
                    {
                      ref: searchBarRef,
                      externalOnSearch,
                      isClearable,
                      isLoading,
                      isMulti,
                      isSelectAll,
                      isWithSearch,
                      searchPlaceholder,
                      searchTerm,
                      selectedOptions,
                      setSearchTerm,
                      toggleSelectAll,
                      onClearAll: handleClearAllWrapper,
                      onKeyDown: (e) => {
                        onKeyDown({ e, focusedIndex, currentOptions });
                      },
                      onSearch: (event) => {
                        handleSearch({
                          event,
                          externalOnSearch,
                          initialOptions,
                          setCurrentOptions,
                          setSearchTerm
                        });
                      },
                      onSelectAll: handleSelectAllWrapper
                    }
                  ),
                  /* @__PURE__ */ jsxs("div", { ref: dropdownMenuRef, className: "ia-select-dropdown-container", children: [
                    /* @__PURE__ */ jsx(
                      ReactSelect,
                      {
                        autoFocus: true,
                        menuIsOpen: true,
                        backspaceRemovesValue: false,
                        className: "ia-select-dropdown-v3",
                        classNames: {
                          option: () => "ia-select-option"
                        },
                        components: {
                          IndicatorSeparator: null,
                          Option: (optionProps) => {
                            var _a2, _b2, _c2, _d2;
                            const data = optionProps.data;
                            const optionIndex = memoizedOptions.findIndex(
                              (opt) => opt.value === data.value
                            );
                            const parentOption = (initialOptions || []).find(
                              (parent) => parent.children && parent.children.some((child) => child.value === data.value)
                            );
                            let isSelected;
                            if (!isMulti) {
                              if (isMultiInSubmenu) {
                                if (parentOption) {
                                  isSelected = !!(selectedOptions && !Array.isArray(selectedOptions) && ((_a2 = selectedOptions.children) == null ? void 0 : _a2.some(
                                    (child) => child.value === data.value
                                  )));
                                } else if (data.children) {
                                  isSelected = !!(selectedOptions && !Array.isArray(selectedOptions) && ((_b2 = selectedOptions.children) == null ? void 0 : _b2.length) && selectedOptions.value === data.value);
                                } else {
                                  isSelected = !!(selectedOptions && !Array.isArray(selectedOptions) && selectedOptions.value === data.value);
                                }
                              } else {
                                if (parentOption) {
                                  isSelected = !!(selectedOptions && !Array.isArray(selectedOptions) && ((_c2 = selectedOptions.children) == null ? void 0 : _c2.some(
                                    (child) => child.value === data.value
                                  )));
                                } else {
                                  isSelected = !!(selectedOptions && !Array.isArray(selectedOptions) && selectedOptions.value === data.value);
                                }
                              }
                            } else {
                              if (parentOption) {
                                const selectedParent = Array.isArray(selectedOptions) ? selectedOptions.find((sel) => sel.value === parentOption.value) : null;
                                isSelected = !!(selectedParent && ((_d2 = selectedParent.children) == null ? void 0 : _d2.some((child) => child.value === data.value)));
                              } else {
                                isSelected = Array.isArray(selectedOptions) ? selectedOptions.some((sel) => sel.value === data.value) : false;
                              }
                            }
                            const shouldDisableOption = isMaxLimitReached && !isSelected && isMulti;
                            return /* @__PURE__ */ jsx(
                              Option,
                              {
                                ...optionProps,
                                isSelected,
                                selectedOptions,
                                initialOptions,
                                isDisabled: shouldDisableOption || !!(data == null ? void 0 : data.disabled) || !!(data == null ? void 0 : data.isDisabled),
                                customOptionProps: {
                                  onMouseEnter: (e) => {
                                    handleOptionHover(data, optionIndex, e);
                                  }
                                }
                              }
                            );
                          },
                          ...!isGrouped && { MenuList },
                          ...isGrouped && {
                            GroupHeading: (groupProps) => /* @__PURE__ */ jsx(
                              CustomGroupHeading,
                              {
                                ...groupProps,
                                customBadgeLabel,
                                customBadgeColor
                              }
                            )
                          }
                        },
                        controlShouldRenderValue: true,
                        hideSelectedOptions: false,
                        isClearable,
                        isLoading,
                        isMulti,
                        menuShouldBlockScroll,
                        options: memoizedOptions,
                        placeholder: "Search...",
                        styles: selectStyles,
                        tabSelectsValue: false,
                        value: selectedOptions,
                        onChange: (selectedValues, actionMeta) => {
                          const option = actionMeta == null ? void 0 : actionMeta.option;
                          const idx = memoizedOptions.findIndex(
                            (opt) => opt.value === ((option == null ? void 0 : option.value) ?? (selectedValues == null ? void 0 : selectedValues.value))
                          );
                          if (!isMulti) {
                            actionMeta.option = selectedValues;
                          }
                          handleSelect(
                            selectedValues,
                            actionMeta,
                            idx
                          );
                        },
                        onMenuScrollToBottom,
                        captureMenuScroll: false,
                        ...{ noOptionMessage, maxSelectableOptions }
                      }
                    ),
                    submenuOptions && submenuParent && /* @__PURE__ */ jsx(
                      "div",
                      {
                        className: "ia-select-submenu",
                        style: {
                          position: "absolute",
                          top: submenuPosition.top,
                          left: submenuPosition.left,
                          width: submenuPosition.width
                        },
                        onMouseEnter: () => {
                          setIsSubmenuHovered(true);
                          if (submenuTimeoutRef.current) {
                            clearTimeout(submenuTimeoutRef.current);
                          }
                        },
                        onMouseLeave: () => {
                          setIsSubmenuHovered(false);
                          submenuTimeoutRef.current = setTimeout(() => {
                            if (!isSubmenuHovered) {
                              setSubmenuOptions(null);
                              setSubmenuParent(null);
                            }
                          }, 100);
                        },
                        children: /* @__PURE__ */ jsx("div", { className: "ia-select-submenu-content", children: submenuOptions.map((option) => {
                          var _a2;
                          const isChildSelected = !isMulti ? !!(selectedOptions && !Array.isArray(selectedOptions) && ((_a2 = selectedOptions.children) == null ? void 0 : _a2.some((child) => child.value === option.value))) : (() => {
                            const selectedOptionsArray = Array.isArray(selectedOptions) ? selectedOptions : [];
                            const parentOpt = selectedOptionsArray.find(
                              (sel) => sel.value === submenuParent.value
                            );
                            return parentOpt ? (parentOpt.children ?? []).some(
                              (child) => child.value === option.value
                            ) : false;
                          })();
                          return /* @__PURE__ */ jsx(
                            "div",
                            {
                              className: `select-option-content${isChildSelected ? " selected" : ""}`,
                              onClick: () => {
                                if (!isMulti) {
                                  if (isMultiInSubmenu) {
                                    if (isChildSelected) {
                                      const single = selectedOptions;
                                      if (single.children) {
                                        const updatedChildren = single.children.filter(
                                          (child) => child.value !== option.value
                                        );
                                        if (updatedChildren.length === 0) {
                                          setSelectedOptions(null);
                                          if (externalOnChange)
                                            externalOnChange(null, { option }, void 0);
                                        } else {
                                          const newSelected = { ...single, children: updatedChildren };
                                          setSelectedOptions(newSelected);
                                          if (externalOnChange)
                                            externalOnChange(newSelected, { option }, void 0);
                                        }
                                      }
                                    } else {
                                      if (!selectedOptions) {
                                        const newSelected = { ...submenuParent, children: [option] };
                                        setSelectedOptions(newSelected);
                                        if (externalOnChange)
                                          externalOnChange(newSelected, { option }, void 0);
                                      } else if (selectedOptions.value === submenuParent.value) {
                                        const single = selectedOptions;
                                        const newSelected = {
                                          ...single,
                                          children: [...single.children ?? [], option]
                                        };
                                        setSelectedOptions(newSelected);
                                        if (externalOnChange)
                                          externalOnChange(newSelected, { option }, void 0);
                                      } else {
                                        const newSelected = { ...submenuParent, children: [option] };
                                        setSelectedOptions(newSelected);
                                        if (externalOnChange)
                                          externalOnChange(newSelected, { option }, void 0);
                                      }
                                    }
                                  } else {
                                    const newSelected = { ...submenuParent, children: [option] };
                                    setSelectedOptions(newSelected);
                                    if (externalOnChange)
                                      externalOnChange(newSelected, { option }, void 0);
                                    handleDropdownClose({
                                      externalOnDropdownClose,
                                      setCurrentOptions,
                                      initialOptions,
                                      currentOptions,
                                      setIsOpen,
                                      // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                      onBlur
                                    });
                                  }
                                } else {
                                  const newSelectedOptions = Array.isArray(selectedOptions) ? [...selectedOptions] : [];
                                  const parentIndex = newSelectedOptions.findIndex(
                                    (sel) => sel.value === submenuParent.value
                                  );
                                  if (isChildSelected) {
                                    if (parentIndex !== -1) {
                                      const parent = { ...newSelectedOptions[parentIndex] };
                                      parent.children = (parent.children ?? []).filter(
                                        (child) => child.value !== option.value
                                      );
                                      if (parent.children.length === 0) {
                                        newSelectedOptions.splice(parentIndex, 1);
                                      } else {
                                        newSelectedOptions[parentIndex] = parent;
                                      }
                                    }
                                  } else {
                                    if (parentIndex !== -1) {
                                      const parent = { ...newSelectedOptions[parentIndex] };
                                      if (!(parent.children ?? []).some(
                                        (child) => child.value === option.value
                                      )) {
                                        parent.children = [...parent.children ?? [], option];
                                      }
                                      newSelectedOptions[parentIndex] = parent;
                                    } else {
                                      newSelectedOptions.push({
                                        ...submenuParent,
                                        children: [option]
                                      });
                                    }
                                  }
                                  setSelectedOptions(newSelectedOptions);
                                  if (externalOnChange)
                                    externalOnChange(newSelectedOptions, { option }, void 0);
                                }
                              },
                              children: isMulti || isMultiInSubmenu ? /* @__PURE__ */ jsx(
                                Checkbox,
                                {
                                  checked: isChildSelected,
                                  label: /* @__PURE__ */ jsx("div", { className: "select-label-with-icon", children: option.label }),
                                  withoutFormLabel: true,
                                  onChange: () => null
                                }
                              ) : /* @__PURE__ */ jsx("div", { className: "select-label-with-icon", children: option.label })
                            },
                            option.value
                          );
                        }) })
                      }
                    )
                  ] })
                ]
              }
            )
          }
        )
      ]
    }
  );
});
Select.displayName = "Select";
export {
  Select
};
