import { _ as _defineProperty } from '../defineProperty-18999f8e.js';
import { _ as _extends } from '../extends-e61fd370.js';
import { _ as _toConsumableArray } from '../toConsumableArray-f2f53597.js';
import { _ as _slicedToArray } from '../slicedToArray-5b664d46.js';
import { _ as _objectWithoutProperties } from '../objectWithoutProperties-72d23964.js';
import React__default, { forwardRef, useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { b as useId, c as useFloating, d as autoUpdate, f as flip, s as size, o as offset, j as useRole, i as useDismiss, e as useListNavigation, k as useInteractions, l as useMergeRefs, I as Icon, F as FloatingFocusManager, m as FloatingList } from '../index-99927619.js';
import cx from 'classnames';
import { l as lodash, O as Option, a as SelectContext, M as MENU_CLASSES, b as MAX_MENU_HEIGHT, c as MENU_OFFSET } from '../select-74202a5d.js';
import Label from '../label/index.js';
import Portal from '../portal/index.js';
import { jsxTextContent } from './util.js';
import '../typeof-6c6d8d7a.js';
import '../index-81a9bdac.js';
import 'react-dom';
import 'prop-types';
import '../icon/assets/icon-map/index.js';
import '../social-icon/index.js';
import '@fortawesome/react-fontawesome';
import '../social-icon/icons.js';
import '../social-icon/library.js';
import '@fortawesome/fontawesome-svg-core';
import '@fortawesome/free-solid-svg-icons';
import '@fortawesome/free-brands-svg-icons';
import '../tooltip/index.js';
import '../auto-id.esm-2b54f757.js';
import '../utils.esm-514fad91.js';
import '../warning-ed2bf294.js';
import '../portal.esm-613949dc.js';
import '@reach/visually-hidden';
import '../use-rerender-once/index.js';
import '../use-force-update/index.js';
import '../button/button-group.js';
import '../inject-css-ccd0a386.js';
import '../_commonjsHelpers-57e89916.js';

var _excluded = ["async", "value", "options", "onChange"],
    _excluded2 = ["children", "className", "label", "searchValue", "placeholder", "filter", "create", "state", "disabled", "onFilter"];

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;
  var result = options.filter(function (option) {
    var labelString = jsxTextContent(option.label);
    if (!labelString) return false;
    return labelString.toLowerCase().includes(input);
  });
  return result;
};

var AutoComplete = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var async = _ref.async,
      value = _ref.value,
      items = _ref.options,
      onChange = _ref.onChange,
      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(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 || "";
  }),
      _useState6 = _slicedToArray(_useState5, 2),
      inputValue = _useState6[0],
      setInputValue = _useState6[1];

  var handleFilter = function handleFilter(filterString) {
    setInputValue(filterString);
  };

  var handleChange = function handleChange(event) {
    if (event.target.created) setOptions([].concat(_toConsumableArray(options), [event.target]));
    if (onChange) onChange(event);
  };

  var loadOptions = useCallback(function (input) {
    if (input.length < 2) return;
    var abortController = new AbortController();
    setLoading(true);
    items(input, {
      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);
    });
  }, [items]);
  var debouncedLoadOptions = useMemo(function () {
    return lodash.exports.debounce(loadOptions, 300);
  }, [loadOptions]);
  useEffect(function () {
    if (!async) return;
    debouncedLoadOptions(inputValue);
  }, [async, debouncedLoadOptions, inputValue]);
  return /*#__PURE__*/React__default.createElement(ComposableAutocomplete, _extends({}, props, {
    ref: ref,
    searchValue: inputValue,
    state: {
      loading: loading
    },
    onFilter: handleFilter,
    onChange: handleChange
  }), options.map(function (option) {
    return /*#__PURE__*/React__default.createElement(Option, {
      key: "".concat(option.value, "-").concat(option.label),
      value: option.value,
      label: option.label
    }, option.component || option.label);
  }));
});
var ComposableAutocomplete = /*#__PURE__*/forwardRef(function (_ref2, forwardedRef) {
  var children = _ref2.children,
      className = _ref2.className,
      label = _ref2.label,
      searchValue = _ref2.searchValue,
      _ref2$placeholder = _ref2.placeholder,
      placeholder = _ref2$placeholder === void 0 ? "Select" : _ref2$placeholder,
      _ref2$filter = _ref2.filter,
      filter = _ref2$filter === void 0 ? DEFAULT_FILTER : _ref2$filter,
      create = _ref2.create,
      _ref2$state = _ref2.state,
      state = _ref2$state === void 0 ? {} : _ref2$state,
      disabled = _ref2.disabled,
      onFilter = _ref2.onFilter,
      props = _objectWithoutProperties(_ref2, _excluded2);

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

  var childNodes = useMemo(function () {
    return React__default.Children.toArray(children);
  }, [children]);

  var _useState9 = useState(function () {
    var index = childNodes.findIndex(function (child) {
      return child.props.selected;
    });
    if (index < 0) return searchValue || "";
    var selectedLabel = childNodes[index].props.label || childNodes[index].props.children;
    return searchValue || selectedLabel || "";
  }),
      _useState10 = _slicedToArray(_useState9, 2),
      inputValue = _useState10[0],
      setInputValue = _useState10[1];

  var selectedIndex = childNodes.findIndex(function (child) {
    var labelString = jsxTextContent(child.props.label || child.props.children);
    return labelString === inputValue;
  });

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

  var createPrefix = typeof create === "string" ? create : "Create"; // Allows to set the input value from the outside

  useEffect(function () {
    if (searchValue) {
      setInputValue(searchValue);
    }
  }, [searchValue]);
  var filteredOptions = filter(childNodes.map(function (child, index) {
    return {
      label: child.props.label || child.props.children,
      value: child.props.value,
      position: index
    };
  }), inputValue, selectedIndex);
  var labelId = useId();
  var elementsRef = useRef([]);

  var _useFloating = useFloating({
    placement: "bottom-start",
    open: isOpen,
    onOpenChange: setIsOpen,
    whileElementsMounted: autoUpdate,
    middleware: [flip(), size({
      apply: function apply(_ref3) {
        var rects = _ref3.rects,
            elements = _ref3.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 createdOption = {
      label: inputValue,
      value: inputValue,
      position: childNodes.length,
      created: true
    };
    var selectedOption = filteredOptions[index] || createdOption;
    if (!selectedOption) return;
    var labelString = jsxTextContent(selectedOption.label);
    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, childNodes]);

  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);
    var newFilteredOptions = filter(childNodes.map(function (child, index) {
      return {
        label: child.props.label || child.props.children,
        value: child.props.value,
        position: index
      };
    }), value, selectedIndex);

    if (value) {
      setActiveIndex(0);
    }

    if (onFilter) {
      onFilter(value, newFilteredOptions);
    }
  }, [isOpen, onFilter, childNodes, filter, selectedIndex]);
  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(Icon, {
    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
  }, filteredOptions.length === 0 && !state.loading && /*#__PURE__*/React__default.createElement(Option, {
    disabled: true,
    className: "text-center text-gray-600"
  }, "No result found"), filteredOptions.length === 0 && state.loading && /*#__PURE__*/React__default.createElement(Option, {
    disabled: true,
    className: "text-center text-gray-600"
  }, "Loading..."), filteredOptions.length > 0 && React__default.Children.map(children, function (child, index) {
    var isFilteredOut = !filteredOptions.find(function (option) {
      return option.position === index;
    });
    return isFilteredOut ? null : child;
  }), create && inputValue.length > 1 && !filteredOptions.find(function (option) {
    return option.label.toLowerCase() === inputValue.toLowerCase();
  }) && /*#__PURE__*/React__default.createElement(Option, {
    create: true
  }, createPrefix, " \u201C", inputValue, "\u201D")))))));
});

export { AutoComplete, ComposableAutocomplete };
