import { _ as _defineProperty } from '../defineProperty-CEd-kZQW.js';
import { _ as _extends } from '../extends-C4cduGrv.js';
import { _ as _toConsumableArray } from '../toConsumableArray-dKQYsfpV.js';
import { _ as _slicedToArray } from '../slicedToArray-BB-AwwkK.js';
import { _ as _objectWithoutProperties } from '../objectWithoutProperties-TXwlfNxG.js';
import React__default, { forwardRef, useState, useRef, useEffect, useCallback, useContext } from 'react';
import { u as useId, a as useFloating, b as autoUpdate, f as flip, s as size, o as offset, c as useRole, d as useDismiss, e as useListNavigation, g as useInteractions, h as useMergeRefs, F as FloatingFocusManager, i as FloatingList, l as useListItem } from '../floating-ui.react-cWPyyUrN.js';
import cx from 'classnames';
import Label from '../label/index.js';
import CKIcon from '../ck-icon/index.js';
import Portal from '../portal/index.js';
import Checkbox from '../checkbox/index.js';
import { b as SelectContext, M as MENU_CLASSES, c as MAX_MENU_HEIGHT, e as MIN_MENU_WIDTH, d as MENU_OFFSET } from '../select-menu-BvA3x4Nf.js';
import '../typeof-CgC7Bq6K.js';
import '../index-qSfOyGhk.js';
import 'react-dom';
import 'prop-types';
import '@reach/visually-hidden';
import '../ck-icon/assets/icon-map/index.js';
import '../icon/index.js';
import '@fortawesome/react-fontawesome';
import '../icon/icons.js';
import '../icon/library.js';
import '@fortawesome/fontawesome-svg-core';
import '@fortawesome/pro-solid-svg-icons';
import '@fortawesome/pro-light-svg-icons';
import '@fortawesome/free-brands-svg-icons';
import '../use-rerender-once/index.js';
import '../use-force-update/index.js';
import '../_commonjsHelpers-_1FafXWI.js';

var _excluded = ["options", "label", "value", "placeholder", "create", "className"],
    _excluded2 = ["children", "label", "disabled", "create", "empty"];

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var DEFAULT_INPUT_CLASSES = "relative inline-flex items-center border transition-colors delay-75 text-sm gap-2 rounded pr-8";

var filteredMatch = function filteredMatch(options, value) {
  return options.findIndex(function (option) {
    return option.label.toLowerCase().includes(value.toLowerCase());
  });
};

var MultiSelectInput = /*#__PURE__*/forwardRef(function (_ref, forwardedRef) {
  var items = _ref.options,
      label = _ref.label,
      value = _ref.value,
      _ref$placeholder = _ref.placeholder,
      placeholder = _ref$placeholder === void 0 ? "Select" : _ref$placeholder,
      create = _ref.create,
      className = _ref.className,
      props = _objectWithoutProperties(_ref, _excluded);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isOpen = _useState2[0],
      setIsOpen = _useState2[1];

  var _useState3 = useState(""),
      _useState4 = _slicedToArray(_useState3, 2),
      inputValue = _useState4[0],
      setInputValue = _useState4[1];

  var _useState5 = useState(items),
      _useState6 = _slicedToArray(_useState5, 2),
      options = _useState6[0],
      setOptions = _useState6[1];

  var _useState7 = useState(options.filter(function (option) {
    return value === null || value === void 0 ? void 0 : value.includes(option.value);
  }) || []),
      _useState8 = _slicedToArray(_useState7, 2),
      selected = _useState8[0],
      setSelected = _useState8[1];

  var _useState9 = useState(null),
      _useState10 = _slicedToArray(_useState9, 2),
      activeIndex = _useState10[0],
      setActiveIndex = _useState10[1];

  var labelId = useId();
  var createPrefix = typeof create === "string" ? create : "Create";
  var createCount = useRef(0);
  var filteredOptions = options.filter(function (option) {
    return option.label.toLowerCase().includes(inputValue.toLowerCase());
  }); // Update selected options when value prop changes

  useEffect(function () {
    setSelected(options.filter(function (option) {
      return value === null || value === void 0 ? void 0 : value.includes(option.value);
    }) || []);
  }, [value, options]);
  useEffect(function () {
    setOptions(items);
  }, [items]);
  var elementsRef = useRef([]);

  var _useFloating = useFloating({
    placement: "bottom-start",
    open: isOpen,
    onOpenChange: setIsOpen,
    whileElementsMounted: autoUpdate,
    middleware: [flip(), size({
      apply: function apply(_ref2) {
        var rects = _ref2.rects,
            elements = _ref2.elements;
        Object.assign(elements.floating.style, {
          width: "".concat(rects.reference.width, "px")
        });
      }
    }), offset(MENU_OFFSET)]
  }),
      refs = _useFloating.refs,
      floatingStyles = _useFloating.floatingStyles,
      context = _useFloating.context;

  var role = useRole(context, {
    role: "listbox"
  });
  var dismiss = useDismiss(context);
  var listNav = useListNavigation(context, {
    listRef: elementsRef,
    activeIndex: activeIndex,
    onNavigate: setActiveIndex,
    virtual: true,
    loop: true
  });

  var _useInteractions = useInteractions([role, dismiss, listNav]),
      getReferenceProps = _useInteractions.getReferenceProps,
      getFloatingProps = _useInteractions.getFloatingProps,
      getItemProps = _useInteractions.getItemProps;

  var handleSelect = useCallback(function (index) {
    if (index === -1) return;
    var selections;
    var newOption = filteredOptions[index] || {
      label: inputValue,
      value: "".concat(inputValue).concat(++createCount.current),
      created: true
    };

    if (selected.find(function (option) {
      return option.value === newOption.value;
    })) {
      selections = selected.filter(function (option) {
        return option.value !== newOption.value;
      });
    } else {
      // Add in the same order as the options
      var selectedOptions = [].concat(_toConsumableArray(selected), [newOption]);

      if (!newOption.created) {
        selections = options.filter(function (option) {
          return selectedOptions.find(function (opt) {
            return opt.value === option.value;
          });
        });
      } else {
        selections = selectedOptions;
        if (!options.find(function (option) {
          return option.value === newOption.value;
        })) setOptions([].concat(_toConsumableArray(options), [{
          label: newOption.label,
          value: newOption.value
        }]));
      }
    }

    setSelected(selections);

    if (props.onChange) {
      props.onChange({
        target: {
          name: props.name,
          value: selections
        }
      });
    }

    setInputValue("");
    var input = refs.reference.current.querySelector("input");
    input.focus();
  }, [options, filteredOptions, refs.reference, selected, props, inputValue]);

  var onLabelClick = function onLabelClick() {
    refs.reference.current.focus();
  };

  var selectContext = React__default.useMemo(function () {
    return {
      activeIndex: activeIndex,
      getItemProps: getItemProps,
      handleSelect: handleSelect,
      selected: selected
    };
  }, [activeIndex, getItemProps, handleSelect, selected]);

  var onChange = function onChange(event) {
    var value = event.target.value;
    setInputValue(value);
    if (!isOpen) setIsOpen(true);
    var filtered = options.filter(function (option) {
      return option.label.toLowerCase().includes(value.toLowerCase());
    });
    var match = filteredMatch(filtered, value);
    var fallback = options.length;
    var indexPosition = match > -1 ? match : fallback;
    setActiveIndex(indexPosition);
  };

  var onKeyDown = useCallback(function (event) {
    if (event.key === "Enter" && activeIndex != null) {
      /*
        We are using a virtual navigation to keep focus on the input (see useListNavigation hook above)
        With a virtual navigation, interactions like Enter will not trigger selection/click/onchange.
        Hence, we need to call handleSelect below to trigger onChange callback during the input keydown event.
      */
      handleSelect(activeIndex);
    } else if (event.key === "Backspace" && !inputValue) {
      if (props.onChange) {
        props.onChange({
          target: {
            name: props.name,
            value: selected.slice(0, -1)
          }
        });
      }

      setSelected(selected.slice(0, -1));
    }
  }, [activeIndex, handleSelect, inputValue, selected, props]);
  var onClick = useCallback(function () {
    if (props.disabled) return;
    var input = refs.reference.current.querySelector("input");
    if (input && !isOpen) input.select();
    setIsOpen(!isOpen);
  }, [isOpen, refs.reference, props.disabled]);
  var inputClassName = cx(DEFAULT_INPUT_CLASSES, className, {
    "text-gray-600": !inputValue,
    "text-gray-900": inputValue,
    "border-blue-500": isOpen && !props.error,
    "border-gray-200 hover:border-gray-300": !isOpen && !props.error,
    "border-red-500": props.error,
    "bg-gray-50": props.disabled
  });

  var removePill = function removePill(pill) {
    if (props.disabled) return;
    var newSelections = selected.filter(function (option) {
      return option.value !== pill.value;
    });

    if (props.onChange) {
      props.onChange({
        target: {
          name: props.name,
          value: newSelections
        }
      });
    }

    setSelected(newSelections);
  };

  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, label && /*#__PURE__*/React__default.createElement(Label, {
    as: "div",
    className: "mb-1 cursor-default",
    id: labelId,
    onClick: onLabelClick
  }, label), /*#__PURE__*/React__default.createElement("div", _extends({
    className: inputClassName,
    style: {
      paddingBlock: 7
    },
    "aria-labelledby": label ? labelId : props["aria-labelledby"],
    "aria-label": !label ? props["aria-label"] : "select multiple options",
    "aria-disabled": props.disabled || false
  }, getReferenceProps({
    ref: useMergeRefs([refs.setReference, forwardedRef]),
    onClick: onClick
  })), /*#__PURE__*/React__default.createElement("div", {
    className: "flex flex-wrap gap-1 items-center pl-2 w-full",
    role: "list"
  }, selected.map(function (pill) {
    var option = options.find(function (option) {
      return option.value === pill.value;
    });
    return /*#__PURE__*/React__default.createElement("div", {
      key: "".concat(option.label, "-").concat(option.value),
      className: cx("inline-flex gap-1 items-center pl-2 pr-1 py-1 bg-gray-100 rounded-full h-6 whitespace-no-wrap max-w-full", {
        "opacity-75": props.disabled
      }),
      role: "listitem"
    }, /*#__PURE__*/React__default.createElement("span", {
      className: "text-gray-800 text-sm leading-relaxed max-w-full truncate"
    }, option.label), /*#__PURE__*/React__default.createElement("button", {
      onClick: function onClick() {
        return removePill(pill);
      },
      "aria-label": "Remove pill",
      className: cx("grid place-content-center border-none bg-gray-200 hover:bg-gray-300 w-4 h-4 rounded-full text-gray-700", {
        "pointer-events-none": props.disabled
      })
    }, /*#__PURE__*/React__default.createElement(CKIcon, {
      name: "close-mini",
      size: "sm",
      "aria-hidden": "true"
    })));
  }), /*#__PURE__*/React__default.createElement("input", {
    className: "border-none h-6 bg-transparent focus:outline-none placeholder-gray-600",
    style: {
      maxWidth: placeholder.length + 2 + "ch"
    },
    placeholder: selected.length ? "" : placeholder,
    value: inputValue,
    onKeyDown: onKeyDown,
    onChange: onChange,
    "aria-autocomplete": "list",
    disabled: props.disabled || false
  })), /*#__PURE__*/React__default.createElement(CKIcon, {
    name: "down",
    className: cx("absolute right-0 mr-2 w-6 duration-75 transition-transform pointer-events-none transform text-gray-800", {
      "rotate-180": isOpen
    }),
    "aria-hidden": "true"
  })), /*#__PURE__*/React__default.createElement(SelectContext.Provider, {
    value: selectContext
  }, isOpen && /*#__PURE__*/React__default.createElement(FloatingFocusManager, {
    context: context,
    initialFocus: -1,
    modal: false
  }, /*#__PURE__*/React__default.createElement(Portal, null, /*#__PURE__*/React__default.createElement("div", _extends({
    ref: refs.setFloating,
    style: _objectSpread(_objectSpread({}, floatingStyles), {}, {
      maxHeight: MAX_MENU_HEIGHT,
      minWidth: MIN_MENU_WIDTH
    }),
    className: MENU_CLASSES,
    "aria-label": "Options"
  }, getFloatingProps()), /*#__PURE__*/React__default.createElement(FloatingList, {
    elementsRef: elementsRef
  }, filteredOptions.length === 0 && /*#__PURE__*/React__default.createElement(Empty, {
    create: create,
    createPrefix: createPrefix,
    input: inputValue
  }), filteredOptions.map(function (option) {
    return /*#__PURE__*/React__default.createElement(Option, {
      key: "".concat(option.value, "-").concat(option.label),
      value: option.value,
      disabled: option.disabled || false
    }, option.label);
  }), create && inputValue.length > 0 && filteredOptions.length > 0 && !filteredOptions.find(function (opt) {
    return opt.label.toLowerCase() === inputValue.toLowerCase();
  }) && /*#__PURE__*/React__default.createElement(Option, {
    create: true
  }, createPrefix, " \u201C", inputValue, "\u201D")))))));
});
function Option(_ref3) {
  var children = _ref3.children,
      label = _ref3.label,
      disabled = _ref3.disabled,
      create = _ref3.create,
      empty = _ref3.empty,
      props = _objectWithoutProperties(_ref3, _excluded2);

  var _useContext = useContext(SelectContext),
      activeIndex = _useContext.activeIndex,
      getItemProps = _useContext.getItemProps,
      handleSelect = _useContext.handleSelect,
      selected = _useContext.selected;

  var _useListItem = useListItem({
    label: disabled ? null : label || children
  }),
      ref = _useListItem.ref,
      index = _useListItem.index;

  var checked = Boolean(selected.find(function (option) {
    return option.value === props.value;
  }));
  var isActive = activeIndex === index;
  var id = "".concat(props.value, "-").concat(index);

  var handleChange = function handleChange() {
    if (disabled) return;
    handleSelect(index);
  };

  if (create) return /*#__PURE__*/React__default.createElement("button", _extends({
    ref: ref
  }, props, {
    role: "option",
    "aria-selected": checked,
    "aria-disabled": disabled,
    tabIndex: isActive && !disabled ? 0 : -1,
    className: cx("flex gap-2 items-center w-full p-2 text-left text-sm focus:outline-none relative border-t border-gray-200 pt-4 px-4 mt-2", props.className, {
      "text-gray-900": !disabled,
      "text-gray-500 cursor-default": disabled
    }),
    style: {
      left: -8,
      width: "calc(100% + 16px)"
    }
  }, getItemProps(), {
    onClick: handleChange
  }), children);
  return /*#__PURE__*/React__default.createElement("label", _extends({
    ref: ref
  }, props, {
    role: "option",
    "aria-selected": checked,
    "aria-disabled": disabled,
    tabIndex: isActive && !disabled ? 0 : -1,
    htmlFor: id,
    className: cx("flex gap-2 items-center w-full p-2 text-left text-sm focus:outline-none rounded", props.className, {
      "rounded": !create,
      "text-gray-900": !disabled,
      "bg-gray-50": isActive && !disabled,
      "text-gray-500 cursor-default": disabled
    })
  }, getItemProps()), !empty && /*#__PURE__*/React__default.createElement(Checkbox, {
    checked: checked,
    id: id,
    onChange: handleChange,
    className: "flex-shrink-0"
  }), children);
}

function Empty(_ref4) {
  var create = _ref4.create,
      createPrefix = _ref4.createPrefix,
      input = _ref4.input;
  if (!create) return /*#__PURE__*/React__default.createElement(Option, {
    disabled: true,
    empty: true,
    className: "text-center text-gray-600"
  }, "No result found");
  return /*#__PURE__*/React__default.createElement("div", null, /*#__PURE__*/React__default.createElement("div", {
    className: "text-center text-sm text-gray-600 p-2 pointer-events-none"
  }, "No result found"), /*#__PURE__*/React__default.createElement(Option, {
    create: true
  }, createPrefix, " \u201C", input, "\u201D"));
}

export { Option, MultiSelectInput as default };
