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 } from 'react';
import { a as useFloating, b as autoUpdate, f as flip, s as size, o as offset, j as useTypeahead, k as useClick, c as useRole, d as useDismiss, e as useListNavigation, g as useInteractions, h as useMergeRefs, F as FloatingFocusManager, i as FloatingList } from '../floating-ui.react-cWPyyUrN.js';
import cx from 'classnames';
import { l as lodash, 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 CKIcon from '../ck-icon/index.js';
import Portal from '../portal/index.js';
import { Option } from './input.js';
import '../typeof-CgC7Bq6K.js';
import '../index-qSfOyGhk.js';
import 'react-dom';
import 'prop-types';
import '../_commonjsHelpers-_1FafXWI.js';
import '../label/index.js';
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 '../checkbox/index.js';

var _excluded = ["className", "label", "options", "value"];

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_BTN_CLASSES = "inline-flex items-center border transition-colors delay-75 text-sm gap-2 justify-between rounded select-none pl-3 pr-2 outline-none hover:bg-gray-50";

var filterOption = function filterOption(options, value) {
  return options.filter(function (option) {
    return value === null || value === void 0 ? void 0 : value.includes(option.value);
  });
};

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

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

  var _useState3 = useState(filterOption(options, value) || []),
      _useState4 = _slicedToArray(_useState3, 2),
      selected = _useState4[0],
      setSelected = _useState4[1];

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

  var elementsRef = useRef([]);
  var labelsRef = useRef([]); // Reload when value prop changes

  useEffect(function () {
    setSelected(filterOption(options, value) || []);
  }, [options, value]);

  var _useFloating = useFloating({
    placement: "bottom-start",
    open: isOpen,
    onOpenChange: props.disabled ? function () {
      return null;
    } : setIsOpen,
    whileElementsMounted: autoUpdate,
    middleware: [flip(), size(), offset(MENU_OFFSET)]
  }),
      refs = _useFloating.refs,
      floatingStyles = _useFloating.floatingStyles,
      context = _useFloating.context;

  var handleTypeaheadMatch = function handleTypeaheadMatch(index) {
    if (isOpen) {
      setActiveIndex(index);
    }
  };

  var typeahead = useTypeahead(context, {
    listRef: labelsRef,
    activeIndex: activeIndex,
    onMatch: handleTypeaheadMatch
  });
  var click = useClick(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, click, typeahead, listNav]),
      getReferenceProps = _useInteractions.getReferenceProps,
      getFloatingProps = _useInteractions.getFloatingProps,
      getItemProps = _useInteractions.getItemProps;

  var handleSelect = useCallback(function (index) {
    var selections;

    if (selected.find(function (option) {
      return option.value === options[index].value;
    })) {
      selections = selected.filter(function (option) {
        return option.value !== options[index].value;
      });
    } else {
      selections = [].concat(_toConsumableArray(selected), [options[index]]);
    }

    setSelected(selections);

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

    document.body.focus();
  }, [options, selected, props]);
  var selectContext = React__default.useMemo(function () {
    return {
      activeIndex: activeIndex,
      getItemProps: getItemProps,
      handleSelect: handleSelect,
      selected: selected
    };
  }, [activeIndex, getItemProps, handleSelect, selected]);
  var btnProps = lodash.exports.omit(props, ["aria-label", "aria-labelledby", "error", "value"]);
  var btnClassName = cx(DEFAULT_BTN_CLASSES, className, {
    "bg-gray-50": isOpen,
    "border-transparent": !props.error,
    "border-red-500": props.error
  });
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", _extends({
    ref: useMergeRefs([refs.setReference, forwardedRef]),
    tabIndex: 0
  }, getReferenceProps(), btnProps, {
    className: btnClassName,
    "aria-disabled": props.disabled || false,
    "aria-labelledby": props["aria-labelledby"],
    "aria-label": props["aria-label"] || "select multiple options",
    style: {
      paddingBlock: "7px"
    }
  }), /*#__PURE__*/React__default.createElement(Indicator, {
    count: selected.length
  }), /*#__PURE__*/React__default.createElement("span", {
    className: "font-semibold"
  }, label), /*#__PURE__*/React__default.createElement(CKIcon, {
    name: "down",
    className: cx("duration-75 transition-transform 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,
    labelsRef: labelsRef
  }, options.length === 0 && /*#__PURE__*/React__default.createElement(Option, {
    disabled: true,
    className: "text-center text-gray-600"
  }, "No result found"), options.map(function (option) {
    return /*#__PURE__*/React__default.createElement(Option, {
      key: "".concat(option.value, "-").concat(option.label),
      value: option.value
    }, option.label);
  })))))));
});

function Indicator(_ref2) {
  var count = _ref2.count;
  return /*#__PURE__*/React__default.createElement("div", {
    className: cx("text-blue-700", {
      "hidden": count === 0
    }),
    style: {
      fontSize: "28px",
      lineHeight: "22px",
      fontFamily: "sans-serif"
    },
    role: "status",
    "aria-label": "".concat(count, " filter").concat(count !== 1 ? "s" : "", " active")
  }, "\u2022");
}

export { MultiSelectFilter as default };
