"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const cmdk = require('cmdk');
const LucideIcons = require('lucide-react');
const React = require('react');
const badge = require('./badge.cjs');
const command = require('./command.cjs');
const utils = require('../lib/utils.cjs');
const useDebounce = require('../hooks/use-debounce.cjs');

function _interopNamespaceCompat(e) {
  if (e && typeof e === 'object' && 'default' in e) return e;
  const n = Object.create(null);
  if (e) {
    for (const k in e) {
      n[k] = e[k];
    }
  }
  n.default = e;
  return n;
}

const React__namespace = /*#__PURE__*/_interopNamespaceCompat(React);

const EMPTY_ARRAY = [];
function transToGroupOption(options, groupBy) {
  if (options.length === 0) {
    return {};
  }
  if (!groupBy) {
    return {
      "": options
    };
  }
  const groupOption = {};
  options.forEach((option) => {
    const key = option[groupBy] || "";
    if (!groupOption[key]) {
      groupOption[key] = [];
    }
    groupOption[key].push(option);
  });
  return groupOption;
}
function removePickedOption(groupOption, picked) {
  const cloneOption = JSON.parse(JSON.stringify(groupOption));
  for (const [key, value] of Object.entries(cloneOption)) {
    cloneOption[key] = value.filter(
      (val) => !picked.find((p) => p.value === val.value)
    );
  }
  return cloneOption;
}
function isOptionsExist(groupOption, targetOption) {
  for (const [, value] of Object.entries(groupOption)) {
    if (value.some((option) => targetOption.find((p) => p.value === option.value))) {
      return true;
    }
  }
  return false;
}
const CommandEmpty = React.forwardRef(({ className, ...props }, forwardedRef) => {
  const render = cmdk.useCommandState((state) => state.filtered.count === 0);
  if (!render) return null;
  return /* @__PURE__ */ jsxRuntime.jsx(
    "div",
    {
      ref: forwardedRef,
      className: utils.cn("py-6 text-center text-sm", className),
      "cmdk-empty": "",
      role: "presentation",
      ...props
    }
  );
});
CommandEmpty.displayName = "CommandEmpty";
const MultipleSelector = React__namespace.forwardRef(
  ({
    value,
    onChange,
    placeholder,
    defaultOptions: arrayDefaultOptions = EMPTY_ARRAY,
    options: arrayOptions,
    delay,
    onSearch,
    onSearchSync,
    loadingIndicator,
    emptyIndicator,
    maxSelected = Number.MAX_SAFE_INTEGER,
    onMaxSelected,
    hidePlaceholderWhenSelected,
    disabled,
    groupBy,
    className,
    badgeClassName,
    selectFirstItem = true,
    creatable = false,
    triggerSearchOnFocus = false,
    commandProps,
    inputProps,
    hideClearAllButton = false
  }, ref) => {
    const inputRef = React__namespace.useRef(null);
    const [open, setOpen] = React__namespace.useState(false);
    const [onScrollbar, setOnScrollbar] = React__namespace.useState(false);
    const [isLoading, setIsLoading] = React__namespace.useState(false);
    const dropdownRef = React__namespace.useRef(null);
    const [selected, setSelected] = React__namespace.useState(
      value || EMPTY_ARRAY
    );
    const [options, setOptions] = React__namespace.useState(
      transToGroupOption(arrayDefaultOptions, groupBy)
    );
    const [inputValue, setInputValue] = React__namespace.useState("");
    const debouncedSearchTerm = useDebounce.useDebounce(inputValue, delay || 500);
    const selectedValue = React.useMemo(() => {
      return {
        selectedValue: [...selected],
        input: inputRef.current,
        focus: () => inputRef?.current?.focus(),
        reset: () => setSelected([])
      };
    }, [selected]);
    React__namespace.useImperativeHandle(ref, () => selectedValue, [selectedValue]);
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target) && inputRef.current && !inputRef.current.contains(event.target)) {
        setOpen(false);
        inputRef.current.blur();
      }
    };
    const handleUnselect = React__namespace.useCallback(
      (option) => {
        const newOptions = selected.filter((s) => s.value !== option.value);
        setSelected(newOptions);
        onChange?.(newOptions);
      },
      [onChange, selected]
    );
    const handleKeyDown = React__namespace.useCallback(
      (e) => {
        const input = inputRef.current;
        if (input) {
          if (e.key === "Delete" || e.key === "Backspace") {
            if (input.value === "" && selected.length > 0) {
              const lastSelectOption = selected[selected.length - 1];
              if (lastSelectOption && !lastSelectOption.fixed) {
                handleUnselect(lastSelectOption);
              }
            }
          }
          if (e.key === "Escape") {
            input.blur();
          }
        }
      },
      [handleUnselect, selected]
    );
    React.useEffect(() => {
      if (open) {
        document.addEventListener("mousedown", handleClickOutside);
        document.addEventListener("touchend", handleClickOutside);
      } else {
        document.removeEventListener("mousedown", handleClickOutside);
        document.removeEventListener("touchend", handleClickOutside);
      }
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
        document.removeEventListener("touchend", handleClickOutside);
      };
    }, [open]);
    React.useEffect(() => {
      if (value) {
        setSelected(value);
      }
    }, [value]);
    React.useEffect(() => {
      if (!arrayOptions || onSearch) {
        return;
      }
      const newOption = transToGroupOption(
        arrayOptions || EMPTY_ARRAY,
        groupBy
      );
      if (JSON.stringify(newOption) !== JSON.stringify(options)) {
        setOptions(newOption);
      }
    }, [arrayDefaultOptions, arrayOptions, groupBy, onSearch, options]);
    React.useEffect(() => {
      const doSearchSync = () => {
        const res = onSearchSync?.(debouncedSearchTerm);
        setOptions(transToGroupOption(res || [], groupBy));
      };
      const exec = async () => {
        if (!onSearchSync || !open) return;
        if (triggerSearchOnFocus) {
          doSearchSync();
        }
        if (debouncedSearchTerm) {
          doSearchSync();
        }
      };
      void exec();
    }, [debouncedSearchTerm, groupBy, open, triggerSearchOnFocus]);
    React.useEffect(() => {
      const doSearch = async () => {
        setIsLoading(true);
        const res = await onSearch?.(debouncedSearchTerm);
        setOptions(transToGroupOption(res || [], groupBy));
        setIsLoading(false);
      };
      const exec = async () => {
        if (!onSearch || !open) return;
        if (triggerSearchOnFocus) {
          await doSearch();
        }
        if (debouncedSearchTerm) {
          await doSearch();
        }
      };
      void exec();
    }, [debouncedSearchTerm, groupBy, open, triggerSearchOnFocus]);
    const handleCommandKeyDown = React.useCallback(
      (e) => {
        handleKeyDown(e);
        commandProps?.onKeyDown?.(e);
      },
      [handleKeyDown, commandProps]
    );
    const handleBadgeGroupClick = React.useCallback(() => {
      if (disabled) return;
      inputRef?.current?.focus();
    }, [disabled]);
    const targetOption = React.useMemo(() => {
      return [{ value: inputValue, label: inputValue }];
    }, [inputValue]);
    const handleCommandItemMouseDown = React.useCallback(
      (e) => {
        e.preventDefault();
        e.stopPropagation();
      },
      []
    );
    const handleCommandItemSelect = React.useCallback(
      (value2) => {
        if (selected.length >= maxSelected) {
          onMaxSelected?.(selected.length);
          return;
        }
        setInputValue("");
        const newOptions = [...selected, { value: value2, label: value2 }];
        setSelected(newOptions);
        onChange?.(newOptions);
      },
      [maxSelected, onMaxSelected, selected, onChange]
    );
    const CreatableItem = () => {
      if (!creatable) return void 0;
      if (isOptionsExist(options, targetOption) || selected.find((s) => s.value === inputValue)) {
        return void 0;
      }
      const Item = /* @__PURE__ */ jsxRuntime.jsx(
        command.CommandItem,
        {
          value: inputValue,
          className: "cursor-pointer",
          onMouseDown: handleCommandItemMouseDown,
          onSelect: handleCommandItemSelect,
          children: `Create "${inputValue}"`
        }
      );
      if (!onSearch && inputValue.length > 0) {
        return Item;
      }
      if (onSearch && debouncedSearchTerm.length > 0 && !isLoading) {
        return Item;
      }
      return void 0;
    };
    const EmptyItem = React__namespace.useCallback(() => {
      if (!emptyIndicator) return void 0;
      if (onSearch && !creatable && Object.keys(options).length === 0) {
        return /* @__PURE__ */ jsxRuntime.jsx(command.CommandItem, { value: "-", disabled: true, children: emptyIndicator });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(CommandEmpty, { children: emptyIndicator });
    }, [creatable, emptyIndicator, onSearch, options]);
    const selectables = React__namespace.useMemo(
      () => removePickedOption(options, selected),
      [options, selected]
    );
    const commandFilter = React__namespace.useCallback(() => {
      if (commandProps?.filter) {
        return commandProps.filter;
      }
      if (creatable) {
        return (value2, search) => {
          return value2.toLowerCase().includes(search.toLowerCase()) ? 1 : -1;
        };
      }
      return void 0;
    }, [creatable, commandProps?.filter]);
    const handlePrimitiveInputValueChange = React.useCallback(
      (value2) => {
        setInputValue(value2);
        inputProps?.onValueChange?.(value2);
      },
      [inputProps]
    );
    const handlePrimitiveInputBlur = React.useCallback(
      (event) => {
        if (!onScrollbar) {
          setOpen(false);
        }
        inputProps?.onBlur?.(event);
      },
      [onScrollbar, inputProps]
    );
    const handlePrimitiveInputFocus = React.useCallback(
      (event) => {
        setOpen(true);
        if (triggerSearchOnFocus) {
          onSearch?.(debouncedSearchTerm);
        }
        inputProps?.onFocus?.(event);
      },
      [triggerSearchOnFocus, debouncedSearchTerm, inputProps, onSearch]
    );
    const handleClearAllButtonClick = React.useCallback(() => {
      setSelected(selected.filter((s) => s.fixed));
      onChange?.(selected.filter((s) => s.fixed));
    }, [selected, onChange]);
    const handleCommandListMouseLeave = React.useCallback(() => {
      setOnScrollbar(false);
    }, []);
    const handleCommandListMouseEnter = React.useCallback(() => {
      setOnScrollbar(true);
    }, []);
    const handleCommandListMouseUp = React.useCallback(() => {
      inputRef?.current?.focus();
    }, []);
    const handleCommandGroupItemMouseDown = React.useCallback(
      (e) => {
        e.preventDefault();
        e.stopPropagation();
      },
      []
    );
    const handleCommandGroupItemSelect = React.useCallback(
      (option) => {
        if (selected.length >= maxSelected) {
          onMaxSelected?.(selected.length);
          return;
        }
        setInputValue("");
        const newOptions = [...selected, option];
        setSelected(newOptions);
        onChange?.(newOptions);
      },
      [maxSelected, onMaxSelected, selected, onChange]
    );
    return /* @__PURE__ */ jsxRuntime.jsxs(
      command.Command,
      {
        ref: dropdownRef,
        ...commandProps,
        onKeyDown: handleCommandKeyDown,
        className: utils.cn(
          "h-auto overflow-visible bg-transparent",
          commandProps?.className
        ),
        shouldFilter: commandProps?.shouldFilter !== void 0 ? commandProps.shouldFilter : !onSearch,
        filter: commandFilter(),
        children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            "div",
            {
              className: utils.cn(
                "min-h-10 rounded-md border border-input text-sm ring-offset-background focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
                {
                  "px-3 py-2": selected.length !== 0,
                  "cursor-text": !disabled && selected.length !== 0
                },
                className
              ),
              onClick: handleBadgeGroupClick,
              children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex flex-wrap gap-1", children: [
                selected.map((option) => {
                  return /* @__PURE__ */ jsxRuntime.jsx(
                    OptionBadge,
                    {
                      option,
                      onUnselect: handleUnselect,
                      badgeClassName,
                      disabled
                    },
                    option.value
                  );
                }),
                /* @__PURE__ */ jsxRuntime.jsx(
                  cmdk.Command.Input,
                  {
                    ...inputProps,
                    ref: inputRef,
                    value: inputValue,
                    disabled,
                    onValueChange: handlePrimitiveInputValueChange,
                    onBlur: handlePrimitiveInputBlur,
                    onFocus: handlePrimitiveInputFocus,
                    placeholder: hidePlaceholderWhenSelected && selected.length !== 0 ? "" : placeholder,
                    className: utils.cn(
                      "flex-1 bg-transparent outline-none placeholder:text-muted-foreground",
                      {
                        "w-full": hidePlaceholderWhenSelected,
                        "px-3 py-2": selected.length === 0,
                        "ml-1": selected.length !== 0
                      },
                      inputProps?.className
                    )
                  }
                ),
                /* @__PURE__ */ jsxRuntime.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleClearAllButtonClick,
                    className: utils.cn(
                      "absolute right-0 h-6 w-6 p-0",
                      (hideClearAllButton || disabled || selected.length < 1 || selected.filter((s) => s.fixed).length === selected.length) && "hidden"
                    ),
                    children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, {})
                  }
                )
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "relative", children: open && /* @__PURE__ */ jsxRuntime.jsx(
            command.CommandList,
            {
              className: "absolute top-1 z-10 w-full rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in",
              onMouseLeave: handleCommandListMouseLeave,
              onMouseEnter: handleCommandListMouseEnter,
              onMouseUp: handleCommandListMouseUp,
              children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: loadingIndicator }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
                EmptyItem(),
                CreatableItem(),
                !selectFirstItem && /* @__PURE__ */ jsxRuntime.jsx(command.CommandItem, { value: "-", className: "hidden" }),
                Object.entries(selectables).map(([key, dropdowns]) => /* @__PURE__ */ jsxRuntime.jsx(
                  command.CommandGroup,
                  {
                    heading: key,
                    className: "h-full overflow-auto",
                    children: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: dropdowns.map((option) => {
                      return /* @__PURE__ */ jsxRuntime.jsx(
                        CommandGroupItem,
                        {
                          option,
                          onSelect: handleCommandGroupItemSelect,
                          onMouseDown: handleCommandGroupItemMouseDown
                        },
                        option.value
                      );
                    }) })
                  },
                  key
                ))
              ] })
            }
          ) })
        ]
      }
    );
  }
);
MultipleSelector.displayName = "MultipleSelector";
const OptionBadge = ({
  option,
  onUnselect,
  badgeClassName,
  disabled
}) => {
  const handleUnselect = React.useCallback(() => {
    onUnselect(option);
  }, [onUnselect, option]);
  const handleKeyDown = React.useCallback(
    (e) => {
      if (e.key === "Enter") {
        onUnselect(option);
      }
    },
    [onUnselect, option]
  );
  const handleMouseDown = React.useCallback(
    (e) => {
      e.preventDefault();
      e.stopPropagation();
    },
    []
  );
  return /* @__PURE__ */ jsxRuntime.jsxs(
    badge.Badge,
    {
      className: utils.cn(
        "data-disabled:bg-muted-foreground data-disabled:text-muted data-disabled:hover:bg-muted-foreground",
        "data-fixed:bg-muted-foreground data-fixed:text-muted data-fixed:hover:bg-muted-foreground",
        badgeClassName
      ),
      "data-fixed": option.fixed,
      "data-disabled": disabled || void 0,
      children: [
        option.label,
        /* @__PURE__ */ jsxRuntime.jsx(
          "button",
          {
            className: utils.cn(
              "ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",
              (disabled || option.fixed) && "hidden"
            ),
            onKeyDown: handleKeyDown,
            onMouseDown: handleMouseDown,
            onClick: handleUnselect,
            children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, { className: "h-3 w-3 text-muted-foreground hover:text-foreground" })
          }
        )
      ]
    },
    option.value
  );
};
const CommandGroupItem = ({
  option,
  onSelect,
  onMouseDown
}) => {
  const handleSelect = React.useCallback(() => {
    onSelect(option);
  }, [onSelect, option]);
  return /* @__PURE__ */ jsxRuntime.jsx(
    command.CommandItem,
    {
      value: option.value,
      disabled: option.disable,
      onMouseDown,
      onSelect: handleSelect,
      className: utils.cn(
        "cursor-pointer",
        option.disable && "cursor-default text-muted-foreground"
      ),
      children: option.label
    },
    option.value
  );
};

module.exports = MultipleSelector;
