"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var AutoComplete_exports = {};
__export(AutoComplete_exports, {
  default: () => AutoComplete_default
});
module.exports = __toCommonJS(AutoComplete_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = __toESM(require("react"));
var import_downshift = __toESM(require("downshift"));
var import_prop_types = require("prop-types");
var import_styled_components = __toESM(require("styled-components"));
var import_yoga_icons = require("@gympass/yoga-icons");
var import_Input = __toESM(require("../../Input/web/Input"));
const escapeRegExp = (str) => str.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
const Wrapper = import_styled_components.default.div`
  position: relative;

  ${({ full }) => `width: ${full ? "100%" : "auto"}`}

  ${({
  isOpen,
  theme: {
    yoga: {
      components: { input }
    }
  }
}) => isOpen ? `

      ${import_Input.default} {
        border-color: ${input.border.color.typed};
        border-bottom-width: 0;
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
      }

      fieldset {
        border-color: ${input.border.color.typed};
        border-bottom-width: 0;
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
      }

      label {
        color: ${input.label.color.focus};
        font-weight: ${input.label.font.weight};
      }

      legend {
        font-weight: ${input.label.font.weight};
      }
      ` : ""}
`;
const List = import_styled_components.default.ul`
  position: absolute;
  margin: 0;

  padding: 0;

  z-index: 999;

  ${({
  full,
  error,
  theme: {
    yoga: {
      colors,
      components: { autocomplete }
    }
  }
}) => import_styled_components.css`
    top: ${autocomplete.height}px;

    width: ${full ? "100%" : `${autocomplete.width}px`};
    max-height: ${autocomplete.height * 6}px;
    overflow-y: auto;
    box-sizing: border-box;

    background-color: ${autocomplete.field.backgroundColor};

    border-width: ${autocomplete.border.width}px;
    border-style: solid;
    border-color: ${autocomplete.border.color.typed};

    border-color: ${error ? colors.feedback.attention[1] : autocomplete.border.color.typed};

    border-top-width: 0;
    border-bottom-left-radius: ${autocomplete.border.radius}px;
    border-bottom-right-radius: ${autocomplete.border.radius}px;
  `}
`;
const Item = import_styled_components.default.li`
  box-sizing: border-box;

  list-style: none;

  cursor: pointer;

  ${({
  selected,
  theme: {
    yoga: {
      components: { autocomplete }
    }
  }
}) => `
    padding:
      ${autocomplete.list.padding.top}px
      ${autocomplete.list.padding.right}px
      ${autocomplete.list.padding.bottom}px
      ${autocomplete.list.padding.left}px;

    background-color: ${autocomplete.list.backgroundColor.default};
    outline: none;

    font-size: ${autocomplete.list.font.size}px;
    font-weight: ${autocomplete.list.font.weight.default};
    line-height: ${autocomplete.list.font.lineHeight}px;

    &:hover {
      background-color: ${autocomplete.list.backgroundColor.hover};
    }

    ${selected ? `background-color: ${autocomplete.list.backgroundColor.hover};` : ""}
  `}
`;
const Match = import_styled_components.default.mark`
  background: transparent;
  color: inherit;

  ${({
  theme: {
    yoga: {
      components: { autocomplete }
    }
  }
}) => `
    font-weight: ${autocomplete.list.font.weight.matched};
  `}
`;
const noop = () => {
};
const emptyArr = [];
const AutoComplete = import_react.default.forwardRef(
  (_a, ref) => {
    var _b = _a, {
      className,
      style,
      full = false,
      options = emptyArr,
      onChange = noop,
      onClean = noop,
      onSelect = noop,
      value,
      error,
      openSuggestionsAriaLabel = "Open suggestions",
      closeSuggestionsAriaLabel = "Close suggestions",
      highlightFirst = false,
      shouldFilterOptions = true
    } = _b, props = __objRest(_b, [
      "className",
      "style",
      "full",
      "options",
      "onChange",
      "onClean",
      "onSelect",
      "value",
      "error",
      "openSuggestionsAriaLabel",
      "closeSuggestionsAriaLabel",
      "highlightFirst",
      "shouldFilterOptions"
    ]);
    const [userValue, setUserValue] = (0, import_react.useState)(value);
    const [isSuggestionsOpen, setIsSuggestionsOpen] = (0, import_react.useState)(false);
    const inputRef = (0, import_react.useRef)();
    const handleOpenSuggestions = (0, import_react.useCallback)(() => {
      var _a2;
      (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
      setIsSuggestionsOpen(true);
    }, []);
    const handleCloseSuggestions = (0, import_react.useCallback)(() => {
      setIsSuggestionsOpen(false);
    }, []);
    (0, import_react.useEffect)(() => {
      const handleKeyUp = ({ key }) => {
        return key === "Escape" && handleCloseSuggestions();
      };
      window.addEventListener("keyup", handleKeyUp);
      return () => window.removeEventListener("keyup", handleKeyUp);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_downshift.default,
      {
        selectedItem: userValue,
        defaultHighlightedIndex: highlightFirst ? 0 : null,
        onStateChange: (changes) => {
          const { selectedItem, inputValue } = changes;
          if (selectedItem) {
            setUserValue(selectedItem);
            onSelect(selectedItem);
            onChange(selectedItem);
            handleCloseSuggestions();
          } else if (Object.prototype.hasOwnProperty.call(changes, "inputValue")) {
            setUserValue(inputValue);
            onChange(inputValue);
          }
        },
        children: ({
          getInputProps,
          getItemProps,
          clearSelection,
          getMenuProps,
          getRootProps,
          highlightedIndex,
          isOpen,
          openMenu,
          inputValue
        }) => {
          const reg = new RegExp(
            `(${escapeRegExp(inputValue || "").trim()})`,
            "gi"
          );
          const suggestionList = shouldFilterOptions ? options.filter((option) => option.match(reg)).sort(
            (first, second) => first.toLowerCase().indexOf(inputValue) < second.toLowerCase().indexOf(inputValue) ? -1 : 1
          ) : options;
          if (!!inputValue && isOpen) {
            setIsSuggestionsOpen(true);
          }
          return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
            Wrapper,
            __spreadProps(__spreadValues({
              className,
              style,
              full,
              isOpen: isSuggestionsOpen
            }, getRootProps()), {
              ref,
              onBlur: handleCloseSuggestions,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                  import_Input.default,
                  __spreadProps(__spreadValues(__spreadProps(__spreadValues({}, props), {
                    error,
                    full,
                    onClean: (cleanable) => {
                      onClean(cleanable);
                      clearSelection();
                      handleCloseSuggestions();
                    }
                  }), getInputProps({
                    onFocus: () => inputValue.length ? openMenu() : null
                  })), {
                    rightIcon: isSuggestionsOpen ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                      import_yoga_icons.ChevronUp,
                      {
                        onClick: handleCloseSuggestions,
                        "aria-label": closeSuggestionsAriaLabel
                      }
                    ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                      import_yoga_icons.ChevronDown,
                      {
                        onClick: handleOpenSuggestions,
                        "aria-label": openSuggestionsAriaLabel
                      }
                    ),
                    ref: inputRef,
                    includeAriaAttributes: false
                  })
                ),
                isSuggestionsOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(List, __spreadProps(__spreadValues({}, getMenuProps()), { full, error: !!error, children: suggestionList.map((option, optionIndex) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                  Item,
                  __spreadProps(__spreadValues({}, getItemProps({
                    key: `${option}${optionIndex}`,
                    index: optionIndex,
                    item: option,
                    selected: highlightedIndex === optionIndex
                  })), {
                    children: option.split(reg).map(
                      (part, index) => !!inputValue && part.match(reg) ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Match, { children: part }, index) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.default.Fragment, { children: part }, `unmatch-${index}`)
                    )
                  })
                )) }))
              ]
            })
          );
        }
      }
    );
  }
);
AutoComplete.propTypes = {
  className: import_prop_types.string,
  full: import_prop_types.bool,
  options: (0, import_prop_types.arrayOf)(import_prop_types.string),
  style: (0, import_prop_types.shape)({}),
  /** callback to know when a user selects a suggestion */
  onSelect: import_prop_types.func,
  /** called when user type or clean the field and when selects a suggestion */
  onChange: import_prop_types.func,
  /** a callback to know when the user cleaned the field */
  onClean: import_prop_types.func,
  value: import_prop_types.string,
  error: import_prop_types.string,
  /** an aria label for the open suggestions icon */
  openSuggestionsAriaLabel: import_prop_types.string,
  /** an aria label for the close suggestions icon */
  closeSuggestionsAriaLabel: import_prop_types.string,
  /** flag to enable options filtering */
  shouldFilterOptions: import_prop_types.bool,
  /** first highlighted option for whenever Autocomplete is restarted */
  highlightFirst: import_prop_types.bool
};
var AutoComplete_default = AutoComplete;
