import { _ as _extends } from '../extends-C4cduGrv.js';
import { _ as _defineProperty } from '../defineProperty-CEd-kZQW.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 { 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 } from '../floating-ui.react-cWPyyUrN.js';
import cx from 'classnames';
import { l as lodash, b as SelectContext, M as MENU_CLASSES, O as Option, c as MAX_MENU_HEIGHT, d as MENU_OFFSET } from '../select-menu-BvA3x4Nf.js';
import Label from '../label/index.js';
import CKIcon from '../ck-icon/index.js';
import Portal from '../portal/index.js';
import '../typeof-CgC7Bq6K.js';
import '../index-qSfOyGhk.js';
import 'react-dom';
import 'prop-types';
import '../_commonjsHelpers-_1FafXWI.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';

var _excluded = ["async", "value", "options", "className", "label", "placeholder", "filter", "create", "disabled"];

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 h-10";

var DEFAULT_FILTER = function DEFAULT_FILTER(options, inputValue, selectedIndex) {
  var input = inputValue.toLowerCase();
  if (!input) return options;
  if (selectedIndex !== -1) return options;
  return options.filter(function (option) {
    var _option$label, _option$label$props;

    var labelString = typeof option.label === "string" ? option.label : (_option$label = option.label) === null || _option$label === void 0 ? void 0 : (_option$label$props = _option$label.props) === null || _option$label$props === void 0 ? void 0 : _option$label$props.children;
    return labelString.toLowerCase().includes(input);
  });
};

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

  if (async && typeof items !== "function") {
    throw new Error("Async autocomplete requires options to be a function");
  }

  var _useState = useState(async ? [] : items),
      _useState2 = _slicedToArray(_useState, 2),
      options = _useState2[0],
      setOptions = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

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

  var _useState7 = useState(function () {
    var _selectedLabel$props;

    var selectedObject = options.find(function (option) {
      return option.value === value;
    });
    var selectedLabel = (value === null || value === void 0 ? void 0 : value.label) || (selectedObject === null || selectedObject === void 0 ? void 0 : selectedObject.label);
    var valueString = typeof selectedLabel === "string" ? selectedLabel : selectedLabel === null || selectedLabel === void 0 ? void 0 : (_selectedLabel$props = selectedLabel.props) === null || _selectedLabel$props === void 0 ? void 0 : _selectedLabel$props.children;
    return valueString || "";
  }),
      _useState8 = _slicedToArray(_useState7, 2),
      inputValue = _useState8[0],
      setInputValue = _useState8[1];

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

  var selectedIndex = options.findIndex(function (option) {
    return option.label === inputValue;
  });
  var filteredOptions = filter(options, inputValue, selectedIndex);
  var labelId = useId();
  var createPrefix = typeof create === "string" ? create : "Create";
  var createCount = useRef(0);
  var elementsRef = useRef([]);
  var loadOptions = React__default.useMemo(function () {
    return lodash.exports.debounce(function () {
      if (inputValue.length < 2) return;
      var abortController = new AbortController();
      setLoading(true);
      items(inputValue, {
        signal: abortController.signal
      }).then(function (opts) {
        if (opts) setOptions(opts);
      })["catch"](function (error) {
        if (error.code === DOMException.AbortError) {
          // cancelled, ignore
          return;
        }

        throw error;
      })["finally"](function () {
        setLoading(false);
      });
    }, 300);
  }, [items, inputValue]);
  useEffect(function () {
    if (!async) return;
    loadOptions();
  }, [async, loadOptions]);

  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, {
          minWidth: "".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) {
    var _refs$domReference$cu;

    var selectedOption = filteredOptions[index] || {
      label: inputValue,
      value: "".concat(inputValue).concat(++createCount.current),
      created: true
    };

    if (selectedOption.created && !options.find(function (option) {
      return option.label === selectedOption.label;
    })) {
      setOptions([].concat(_toConsumableArray(options), [selectedOption]));
    }

    var labelString = typeof selectedOption.label === "string" ? selectedOption.label : selectedOption.label.props.children;
    setInputValue(labelString);

    if (props.onChange) {
      props.onChange({
        target: _objectSpread(_objectSpread({}, selectedOption), {}, {
          name: props.name
        })
      });
    }

    setIsOpen(false);
    (_refs$domReference$cu = refs.domReference.current) === null || _refs$domReference$cu === void 0 ? void 0 : _refs$domReference$cu.focus();
  }, [filteredOptions, refs.domReference, props, inputValue, options]);

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

  var selectContext = React__default.useMemo(function () {
    return {
      activeIndex: activeIndex,
      selectedIndex: selectedIndex,
      getItemProps: getItemProps,
      handleSelect: handleSelect
    };
  }, [activeIndex, selectedIndex, getItemProps, handleSelect]);
  var onChange = useCallback(function (event) {
    var value = event.target.value;
    setInputValue(value);
    if (!isOpen) setIsOpen(true);

    if (value) {
      setActiveIndex(0);
    }
  }, [isOpen]);
  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);
    }
  }, [activeIndex, handleSelect]);
  var onClick = useCallback(function () {
    if (!isOpen) refs.reference.current.select();
    setIsOpen(!isOpen);
  }, [isOpen, refs.reference]);
  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": disabled
  });
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, label && /*#__PURE__*/React__default.createElement(Label, {
    as: "div",
    className: "cursor-default",
    id: labelId,
    onClick: onLabelClick
  }, label), /*#__PURE__*/React__default.createElement("div", {
    className: inputClassName
  }, /*#__PURE__*/React__default.createElement("input", _extends({}, getReferenceProps({
    ref: useMergeRefs([refs.setReference, forwardedRef]),
    onChange: onChange,
    onClick: onClick,
    onKeyDown: onKeyDown,
    value: inputValue,
    placeholder: placeholder,
    "aria-autocomplete": "list"
  }), {
    "aria-labelledby": label ? labelId : props["aria-labelledby"],
    "aria-label": !label ? props["aria-label"] : null,
    className: "border-none w-full h-full bg-transparent focus:outline-none pl-3 pr-12 placeholder-gray-600",
    style: {
      minWidth: placeholder.length + 2 + "ch"
    },
    disabled: disabled
  })), /*#__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
    }),
    className: MENU_CLASSES,
    "aria-label": "Options"
  }, getFloatingProps()), /*#__PURE__*/React__default.createElement(FloatingList, {
    elementsRef: elementsRef
  }, loading && filteredOptions.length < 1 && /*#__PURE__*/React__default.createElement(Option, {
    disabled: true,
    className: "text-center text-gray-600"
  }, "Loading..."), filteredOptions.length === 0 && !loading && /*#__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)
    }, option.component || option.label);
  }), create && inputValue.length > 1 && filteredOptions.length !== 0 && !filteredOptions.find(function (option) {
    return option.label.toLowerCase() === inputValue.toLowerCase();
  }) && /*#__PURE__*/React__default.createElement(Option, {
    create: true
  }, createPrefix, " \u201C", inputValue, "\u201D")))))));
});

function Empty(_ref3) {
  var create = _ref3.create,
      createPrefix = _ref3.createPrefix,
      input = _ref3.input;
  if (!create) return /*#__PURE__*/React__default.createElement(Option, {
    disabled: 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"), input.length > 0 && /*#__PURE__*/React__default.createElement(Option, {
    create: true
  }, createPrefix, " \u201C", input, "\u201D"));
}

export { AutoComplete as default };
