"use strict";
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const dedent = require("dedent");
const parseHighlights = require("autosuggest-highlight/parse/index.js");
const styles_lib_components_Box_Box_cjs = require("../Box/Box.cjs");
const styles_lib_components_Accordion_AccordionItem_cjs = require("../Accordion/AccordionItem.cjs");
const styles_lib_components_Strong_Strong_cjs = require("../Strong/Strong.cjs");
const styles_lib_components_HiddenVisually_HiddenVisually_cjs = require("../HiddenVisually/HiddenVisually.cjs");
const styles_lib_components_private_Announcement_Announcement_cjs = require("../private/Announcement/Announcement.cjs");
const styles_lib_components_private_Field_Field_cjs = require("../private/Field/Field.cjs");
const styles_lib_components_ButtonIcon_ButtonIcon_cjs = require("../ButtonIcon/ButtonIcon.cjs");
const styles_lib_css_typography_cjs = require("../../css/typography.cjs");
const styles_lib_css_typography_css_cjs = require("../../css/typography.css.cjs");
const sideEffects_lib_components_BraidProvider_BraidProvider_cjs = require("../../../../side-effects/lib/components/BraidProvider/BraidProvider.cjs");
const styles_lib_css_breakpoints_cjs = require("../../css/breakpoints.cjs");
const reactRemoveScroll = require("react-remove-scroll");
const styles_lib_components_Autosuggest_Autosuggest_css_cjs = require("./Autosuggest.css.cjs");
const _interopDefaultCompat = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const dedent__default = /* @__PURE__ */ _interopDefaultCompat(dedent);
const parseHighlights__default = /* @__PURE__ */ _interopDefaultCompat(parseHighlights);
function resolveResponsiveObject(breakpointName, value) {
  let resolvedValue = null;
  for (const currentBreakpointName of styles_lib_css_breakpoints_cjs.breakpointNames) {
    const valueForBreakpoint = value[currentBreakpointName];
    if (valueForBreakpoint !== void 0) {
      resolvedValue = valueForBreakpoint;
    }
    if (breakpointName === currentBreakpointName) {
      return resolvedValue;
    }
  }
  return resolvedValue;
}
const useResponsiveValue = () => {
  const breakpointName = React.useContext(sideEffects_lib_components_BraidProvider_BraidProvider_cjs.breakpointContext);
  return function responsiveValue(value) {
    return breakpointName ? resolveResponsiveObject(breakpointName, value) : null;
  };
};
function getNextIndex(moveAmount, current, total) {
  const maxIndex = total - 1;
  if (current === null) {
    return moveAmount > 0 ? 0 : maxIndex;
  }
  const nextIndex = moveAmount + current;
  if (nextIndex > maxIndex) {
    return 0;
  }
  if (nextIndex < 0) {
    return maxIndex;
  }
  return nextIndex;
}
function normalizeKey({ key, keyCode }) {
  if (keyCode >= 37 && keyCode <= 40 && key.indexOf("Arrow") !== 0) {
    return `Arrow${key}`;
  }
  if (keyCode === 27) {
    return "Escape";
  }
  return key;
}
const FieldButtonIcon = React.forwardRef(
  ({ label, onClick, onMouseDown, ...restProps }, forwardedRef) => {
    const handleMouseDown = React.useCallback(
      (event) => {
        if (typeof onMouseDown !== "function") {
          return;
        }
        if (!onClick) {
          event.preventDefault();
        }
        onMouseDown(event);
      },
      [onClick, onMouseDown]
    );
    return /* @__PURE__ */ jsxRuntime.jsx(
      styles_lib_components_ButtonIcon_ButtonIcon_cjs.ButtonIcon,
      {
        ref: forwardedRef,
        label,
        tone: "secondary",
        variant: "transparent",
        onClick,
        onMouseDown: handleMouseDown,
        tabIndex: -1,
        ...restProps
      }
    );
  }
);
const ClearField = ({
  hide = false,
  onClear,
  label = "Clear",
  id,
  inputRef
}) => {
  const clearHandler = React.useCallback(
    (event) => {
      if (typeof onClear !== "function" || event.button !== 0) {
        return;
      }
      onClear();
      if (inputRef && typeof inputRef === "object" && inputRef.current) {
        inputRef.current.focus();
      }
    },
    [onClear, inputRef]
  );
  return /* @__PURE__ */ jsxRuntime.jsx(
    styles_lib_components_Box_Box_cjs.Box,
    {
      component: "span",
      height: "touchable",
      width: "touchable",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      transition: "fast",
      pointerEvents: hide ? "none" : void 0,
      opacity: hide ? 0 : void 0,
      children: /* @__PURE__ */ jsxRuntime.jsx(
        FieldButtonIcon,
        {
          id: `${id}-clear`,
          label,
          icon: /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.IconClear, {}),
          onMouseDown: clearHandler
        }
      )
    }
  );
};
const easeModifier = (t) => t > 0.5 ? 4 * Math.pow(t - 1, 3) + 1 : 4 * Math.pow(t, 3);
const getExpectedTime = (distance, duration, speed, minDuration) => {
  const calculatedDuration = distance / speed;
  const normalizedDuration = minDuration > calculatedDuration ? minDuration : calculatedDuration;
  return duration !== null ? duration : normalizedDuration;
};
const getScrollPosition = (scrollContainer, direction) => scrollContainer[direction === "horizontal" ? "scrollLeft" : "scrollTop"];
const getScrollOffset = (scrollContainer, targetElement, direction) => {
  if (scrollContainer === window.document.documentElement) {
    const scrollPosition = getScrollPosition(scrollContainer, direction);
    const positionOnScreen = targetElement.getBoundingClientRect()[direction === "horizontal" ? "left" : "top"];
    return positionOnScreen + scrollPosition;
  }
  let totalOffset = 0;
  let currentElement = targetElement;
  const offsetKey = direction === "horizontal" ? "offsetLeft" : "offsetTop";
  while (scrollContainer.contains(currentElement) || currentElement === scrollContainer) {
    totalOffset += currentElement[offsetKey];
    const { offsetParent } = currentElement;
    if (!(offsetParent instanceof HTMLElement)) {
      break;
    }
    currentElement = offsetParent;
  }
  return totalOffset;
};
const scrollTo = (scrollContainer, direction, to) => {
  scrollContainer[direction === "horizontal" ? "scrollLeft" : "scrollTop"] = to;
};
const getPossibleScroll = (scrollContainer, direction) => scrollContainer[direction === "horizontal" ? "scrollWidth" : "scrollHeight"] - (scrollContainer === window.document.documentElement ? 0 : scrollContainer[direction === "horizontal" ? "offsetWidth" : "offsetHeight"]);
const limitNumberToRange = (number, min, max) => {
  if (number < min) {
    return min;
  }
  if (number > max) {
    return max;
  }
  return number;
};
const scroll = (scrollContainer, direction, to, { duration = null, speed = 2, minDuration = 0 }, callback) => {
  const startTime = Date.now();
  const initial = getScrollPosition(scrollContainer, direction);
  const possibleScroll = getPossibleScroll(scrollContainer, direction);
  const targetScrollPosition = limitNumberToRange(to, 0, possibleScroll);
  const total = Math.abs(targetScrollPosition - initial);
  const expectedTime = getExpectedTime(total, duration, speed, minDuration);
  const scrollForwards = targetScrollPosition > initial;
  const step = () => {
    requestAnimationFrame(() => {
      const timePassed = Date.now() - startTime;
      const progress = timePassed / expectedTime;
      const distance = easeModifier(progress) * total;
      const newPosition = Math.floor(
        scrollForwards ? initial + distance : initial - distance
      );
      const isComplete = scrollForwards ? newPosition >= targetScrollPosition : newPosition <= targetScrollPosition;
      if (isComplete) {
        scrollTo(scrollContainer, direction, targetScrollPosition);
        if (callback) {
          callback();
        }
      } else {
        scrollTo(scrollContainer, direction, newPosition);
        step();
      }
    });
  };
  if (targetScrollPosition !== initial) {
    step();
  } else if (callback) {
    callback();
  }
};
const smoothScroll = (element, {
  scrollContainer = window.document.documentElement,
  direction = "vertical",
  offset = 0,
  position = "start",
  ...scrollOptions
} = {}) => new Promise((resolve) => {
  const scrollOffset = getScrollOffset(scrollContainer, element, direction);
  const scrollPosition = position === "end" ? scrollOffset - scrollContainer.offsetWidth + element.offsetWidth + offset : scrollOffset - offset;
  scroll(scrollContainer, direction, scrollPosition, scrollOptions, resolve);
});
const smoothScrollIntoView = (element, options) => {
  const {
    scrollContainer = window.document.documentElement,
    direction = "vertical",
    offset = 0
  } = options;
  const containerWidth = scrollContainer.offsetWidth;
  const scrollOffset = getScrollOffset(scrollContainer, element, direction);
  const positionOnScreen = scrollOffset - getScrollPosition(scrollContainer, direction);
  if (positionOnScreen < offset) {
    smoothScroll(element, { ...options, position: "start" });
  } else if (positionOnScreen > containerWidth - element.offsetWidth - offset) {
    smoothScroll(element, { ...options, position: "end" });
  }
};
function useScrollIntoView(element, scrollContainer) {
  React.useEffect(() => {
    if (scrollContainer && element) {
      const itemOffsetRelativeToContainer = element.offsetParent === scrollContainer ? element.offsetTop : element.offsetTop - scrollContainer.offsetTop;
      let { scrollTop } = scrollContainer;
      if (itemOffsetRelativeToContainer < scrollTop) {
        scrollTop = itemOffsetRelativeToContainer;
      } else if (itemOffsetRelativeToContainer + element.offsetHeight > scrollTop + scrollContainer.offsetHeight) {
        scrollTop = itemOffsetRelativeToContainer + element.offsetHeight - scrollContainer.offsetHeight;
      }
      if (scrollTop !== scrollContainer.scrollTop) {
        scrollContainer.scrollTop = scrollTop;
      }
    }
  }, [scrollContainer, element]);
}
const getItemId = (id, index) => `${id}-item-${index}`;
const createAccessbilityProps = ({
  id,
  highlightedIndex,
  isOpen
}) => {
  const menuId = `${id}-menu`;
  const assistiveDescriptionId = `${id}-aria-description`;
  return {
    inputProps: {
      id,
      role: "combobox",
      "aria-haspopup": "listbox",
      "aria-owns": isOpen ? menuId : void 0,
      // backwards compatibility for screenreaders implementing ARIA 1.0
      "aria-controls": menuId,
      "aria-expanded": isOpen,
      "aria-autocomplete": "list",
      "aria-activedescendant": typeof highlightedIndex === "number" ? getItemId(id, highlightedIndex) : void 0,
      "aria-describedby": assistiveDescriptionId,
      autoComplete: "off",
      // https://stackoverflow.com/questions/47775041/disable-autofill-in-chrome-63/47822599
      spellCheck: false
    },
    assistiveDescriptionProps: {
      id: assistiveDescriptionId
    },
    menuProps: {
      id: menuId,
      role: "listbox"
    },
    getItemProps: ({
      index,
      label,
      description,
      groupHeading
    }) => ({
      id: getItemId(id, index),
      role: "option",
      "aria-selected": index === highlightedIndex,
      "aria-label": `${label}${description ? ` - ${description}` : ""}${groupHeading ? ` (${groupHeading})` : ""}`
    })
  };
};
const autosuggest = {
  assistiveDescription: "Suggestions will appear below the field as you type",
  suggestionInstructions: "Use up and down arrow keys to navigate. Press enter to select",
  suggestionsAvailableAnnouncement: (suggestionCount) => `${suggestionCount} suggestion${suggestionCount === 1 ? "" : "s"} available`,
  noSuggestionsAvailableAnnouncement: "No suggestions available",
  suggestionAutoSelectedAnnouncement: (suggestion) => `Suggestion ${suggestion} is automatically selected`
};
const INPUT_FOCUS = 0;
const INPUT_BLUR = 1;
const INPUT_CHANGE = 2;
const INPUT_ARROW_UP = 3;
const INPUT_ARROW_DOWN = 4;
const INPUT_ESCAPE = 5;
const INPUT_ENTER = 6;
const SUGGESTION_MOUSE_CLICK = 7;
const SUGGESTION_MOUSE_ENTER = 8;
const HAS_SUGGESTIONS_CHANGED = 9;
function SuggestionItem({
  suggestion,
  highlighted,
  selected,
  onHover,
  id,
  ...restProps
}) {
  const { highlights = [], onClear, clearLabel } = suggestion;
  const label = suggestion.label ?? suggestion.text;
  const suggestionParts = parseHighlights__default.default(
    label,
    highlights.map(({ start, end }) => [start, end])
  );
  return /* @__PURE__ */ jsxRuntime.jsx(
    styles_lib_components_Box_Box_cjs.Box,
    {
      component: "li",
      cursor: "pointer",
      onMouseDown: (event) => {
        event.preventDefault();
      },
      onMouseMove: onHover,
      onTouchStart: onHover,
      id,
      ...restProps,
      children: /* @__PURE__ */ jsxRuntime.jsxs(
        styles_lib_components_Box_Box_cjs.Box,
        {
          component: "span",
          display: "flex",
          justifyContent: "spaceBetween",
          background: highlighted ? "formAccentSoft" : void 0,
          paddingX: "small",
          paddingRight: onClear ? "none" : void 0,
          children: [
            /* @__PURE__ */ jsxRuntime.jsxs(styles_lib_components_Box_Box_cjs.Box, { className: styles_lib_css_typography_css_cjs.touchableText.standard, children: [
              /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.Text, { baseline: false, children: suggestionParts.map(
                ({ highlight, text }, index) => selected || highlight ? /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Strong_Strong_cjs.Strong, { children: text }, index) : /* @__PURE__ */ jsxRuntime.jsx(React.Fragment, { children: text }, index)
              ) }),
              suggestion.description ? /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.Text, { size: "small", tone: "secondary", baseline: false, children: suggestion.description }) : null
            ] }),
            typeof onClear === "function" ? /* @__PURE__ */ jsxRuntime.jsx(
              styles_lib_components_Box_Box_cjs.Box,
              {
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                width: "touchable",
                height: "touchable",
                children: /* @__PURE__ */ jsxRuntime.jsx(
                  styles_lib_components_ButtonIcon_ButtonIcon_cjs.ButtonIcon,
                  {
                    id: `${id}-clear`,
                    icon: /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.IconClear, {}),
                    tone: "secondary",
                    tabIndex: -1,
                    label: clearLabel || "Clear suggestion",
                    onClick: (event) => {
                      event.preventDefault();
                      event.stopPropagation();
                      onClear(valueFromSuggestion(suggestion));
                    }
                  }
                )
              }
            ) : null
          ]
        }
      )
    }
  );
}
function GroupHeading({ children }) {
  return /* @__PURE__ */ jsxRuntime.jsx(
    styles_lib_components_Box_Box_cjs.Box,
    {
      paddingX: "small",
      className: [
        styles_lib_components_Autosuggest_Autosuggest_css_cjs.groupHeading,
        styles_lib_css_typography_css_cjs.touchableText.xsmall,
        styles_lib_css_typography_cjs.textStyles({
          size: "xsmall",
          baseline: false,
          weight: "strong",
          tone: "formAccent"
        })
      ],
      "data-testid": process.env.NODE_ENV !== "production" ? `group-heading-${children}` : void 0,
      children
    }
  );
}
function normaliseSuggestions(suggestions) {
  let index = 0;
  const normalisedSuggestions = [];
  const groupHeadingIndexes = /* @__PURE__ */ new Map();
  const groupHeadingForSuggestion = /* @__PURE__ */ new Map();
  for (const item of suggestions) {
    if ("suggestions" in item) {
      groupHeadingIndexes.set(index, item.label);
      item.suggestions.forEach((suggestion) => {
        groupHeadingForSuggestion.set(suggestion, item.label);
      });
      index = normalisedSuggestions.push(...item.suggestions);
    } else {
      index = normalisedSuggestions.push(item);
    }
  }
  return {
    normalisedSuggestions,
    groupHeadingIndexes,
    groupHeadingForSuggestion
  };
}
function valueFromSuggestion(suggestion) {
  return "value" in suggestion ? {
    text: suggestion.text,
    value: suggestion.value
  } : { text: suggestion.text };
}
const noop = () => {
};
const fallbackValue = { text: "" };
const fallbackSuggestions = [];
function normaliseNoSuggestionMessage(noSuggestionsMessage, suggestionProp) {
  if (noSuggestionsMessage) {
    return typeof noSuggestionsMessage === "string" ? { description: noSuggestionsMessage } : noSuggestionsMessage;
  }
  if ("message" in suggestionProp) {
    const message = suggestionProp.message;
    if (process.env.NODE_ENV !== "production") {
      console.warn(
        dedent__default.default`
          Passing \`message\` to \`suggestions\` is deprecated and will be removed in a future version. Use "noSuggestionsMessage" instead. See the documentation for usage: https://seek-oss.github.io/braid-design-system/components/Autosuggest#messaging-when-no-suggestions-are-available
             <Autosuggest
            %c-   suggestions={{ message: '${message}' }}
            %c+   noSuggestionsMessage="${message}"
             %c/>
        `,
        "color: red",
        "color: green",
        "color: inherit"
      );
    }
    return { description: message };
  }
}
const Autosuggest = React.forwardRef(function({
  id,
  value = fallbackValue,
  suggestions: suggestionsProp = fallbackSuggestions,
  noSuggestionsMessage: noSuggestionsMessageProp,
  onChange = noop,
  automaticSelection = false,
  showMobileBackdrop = false,
  scrollToTopOnMobile = true,
  hideSuggestionsOnSelection = true,
  onFocus = noop,
  onBlur = noop,
  placeholder,
  type = "text",
  clearLabel,
  onClear,
  translations = autosuggest,
  ...restProps
}, forwardedRef) {
  const suggestionsPropValue = typeof suggestionsProp === "function" ? suggestionsProp(value) : suggestionsProp;
  const suggestions = Array.isArray(suggestionsPropValue) ? suggestionsPropValue : [];
  const noSuggestionsMessage = normaliseNoSuggestionMessage(
    noSuggestionsMessageProp,
    suggestionsPropValue
  );
  const hasItems = suggestions.length > 0 || Boolean(noSuggestionsMessage);
  const defaultRef = React.useRef(null);
  const inputRef = forwardedRef || defaultRef;
  const fireChange = React.useCallback(
    (suggestion) => onChange(valueFromSuggestion(suggestion)),
    [onChange]
  );
  const rootRef = React.useRef(null);
  const menuRef = React.useRef(null);
  const justPressedArrowRef = React.useRef(false);
  const {
    normalisedSuggestions,
    groupHeadingIndexes,
    groupHeadingForSuggestion
  } = normaliseSuggestions(suggestions);
  const suggestionCount = normalisedSuggestions.length;
  const hasSuggestions = suggestionCount > 0;
  const reducer = (state, action) => {
    switch (action.type) {
      case INPUT_ARROW_DOWN: {
        if (hasSuggestions) {
          const nextIndex = getNextIndex(
            1,
            state.highlightedIndex,
            suggestionCount
          );
          return {
            ...state,
            showSuggestionsIfAvailable: true,
            previewValue: normalisedSuggestions[nextIndex],
            highlightedIndex: nextIndex
          };
        }
      }
      case INPUT_ARROW_UP: {
        if (hasSuggestions) {
          const nextIndex = getNextIndex(
            -1,
            state.highlightedIndex,
            suggestionCount
          );
          return {
            ...state,
            showSuggestionsIfAvailable: true,
            previewValue: normalisedSuggestions[nextIndex],
            highlightedIndex: nextIndex
          };
        }
      }
      case INPUT_CHANGE: {
        return {
          ...state,
          showSuggestionsIfAvailable: true,
          inputChangedSinceFocus: true,
          previewValue: null,
          highlightedIndex: hasSuggestions && automaticSelection && value.text.length > 0 ? 0 : null
        };
      }
      case INPUT_FOCUS: {
        return {
          ...state,
          showSuggestionsIfAvailable: true,
          inputChangedSinceFocus: false,
          isFocused: true
        };
      }
      case INPUT_BLUR: {
        return {
          ...state,
          showSuggestionsIfAvailable: false,
          previewValue: null,
          highlightedIndex: null,
          isFocused: false
        };
      }
      case INPUT_ESCAPE: {
        if (value.text) {
          return {
            ...state,
            showSuggestionsIfAvailable: false,
            previewValue: null,
            highlightedIndex: null
          };
        } else if (hasItems) {
          return {
            ...state,
            showSuggestionsIfAvailable: !state.showSuggestionsIfAvailable,
            previewValue: null
          };
        }
        return state;
      }
      case INPUT_ENTER:
      case SUGGESTION_MOUSE_CLICK: {
        return {
          ...state,
          showSuggestionsIfAvailable: !hideSuggestionsOnSelection,
          previewValue: null,
          highlightedIndex: null
        };
      }
      case SUGGESTION_MOUSE_ENTER: {
        return {
          ...state,
          highlightedIndex: action.value
        };
      }
      case HAS_SUGGESTIONS_CHANGED: {
        return automaticSelection ? {
          ...state,
          highlightedIndex: hasSuggestions && value.text.length > 0 ? 0 : null
        } : state;
      }
      default: {
        console.error(new Error(`Invalid Autosuggest action: ${action}`));
        return state;
      }
    }
  };
  const [
    {
      showSuggestionsIfAvailable,
      inputChangedSinceFocus,
      previewValue,
      highlightedIndex,
      isFocused
    },
    dispatch
  ] = React.useReducer(reducer, {
    showSuggestionsIfAvailable: false,
    inputChangedSinceFocus: false,
    previewValue: null,
    highlightedIndex: null,
    isFocused: false
  });
  const isOpen = showSuggestionsIfAvailable && hasItems;
  const highlightedItem = typeof highlightedIndex === "number" ? document.getElementById(getItemId(id, highlightedIndex)) : null;
  useScrollIntoView(highlightedItem, menuRef.current);
  React.useEffect(() => {
    dispatch({
      type: HAS_SUGGESTIONS_CHANGED
    });
  }, [hasSuggestions]);
  const isMobile = useResponsiveValue()({
    mobile: true,
    tablet: false
  });
  React.useEffect(() => {
    if (menuRef.current && isOpen && !isMobile) {
      const { bottom: menuBottom } = menuRef.current.getBoundingClientRect();
      const viewportHeight = document.documentElement.clientHeight;
      if (menuBottom > viewportHeight) {
        menuRef.current.scrollIntoView(false);
      }
    }
  }, [isOpen, isMobile, suggestionCount]);
  const inputProps = {
    value: previewValue ? previewValue.text : value.text,
    type: type === "search" ? type : "text",
    placeholder: !restProps.disabled ? placeholder : void 0,
    onChange: (e) => {
      const inputValue = e.target.value;
      dispatch({ type: INPUT_CHANGE });
      fireChange({ text: inputValue });
    },
    onFocus: () => {
      if (rootRef.current && scrollToTopOnMobile && isMobile) {
        smoothScroll(rootRef.current);
      }
      dispatch({ type: INPUT_FOCUS });
      onFocus();
    },
    onBlur: () => {
      if (justPressedArrowRef.current === true) {
        return;
      }
      if (previewValue) {
        fireChange(previewValue);
      } else if (isOpen && automaticSelection && inputChangedSinceFocus && value.text.length > 0 && suggestionCount > 0) {
        fireChange(normalisedSuggestions[0]);
      }
      dispatch({ type: INPUT_BLUR });
      onBlur();
    },
    onKeyDown: (event) => {
      const targetKey = normalizeKey(event);
      if (/^Arrow(Up|Down$)/.test(targetKey)) {
        justPressedArrowRef.current = true;
        setTimeout(() => {
          justPressedArrowRef.current = false;
        }, 150);
      }
      switch (targetKey) {
        case "ArrowDown": {
          event.preventDefault();
          dispatch({ type: INPUT_ARROW_DOWN });
          return;
        }
        case "ArrowUp": {
          event.preventDefault();
          dispatch({ type: INPUT_ARROW_UP });
          return;
        }
        case "Escape": {
          event.preventDefault();
          if (previewValue === null && value.text) {
            fireChange({ text: "" });
          }
          dispatch({ type: INPUT_ESCAPE });
          return;
        }
        case "Enter": {
          if (typeof highlightedIndex === "number") {
            event.preventDefault();
            fireChange(normalisedSuggestions[highlightedIndex]);
          }
          dispatch({ type: INPUT_ENTER });
          return;
        }
        default: {
          return;
        }
      }
    }
  };
  const a11y = createAccessbilityProps({
    id,
    isOpen,
    highlightedIndex
  });
  const clearable = Boolean(
    typeof onClear !== "undefined" && !restProps.disabled && typeof value !== "undefined" && value.text.length > 0
  );
  const announcements = [];
  const hasAutomaticSelection = automaticSelection && previewValue === null && highlightedIndex === 0;
  if (isFocused && isOpen && (highlightedIndex === null || hasAutomaticSelection)) {
    if (hasSuggestions) {
      announcements.push(
        translations.suggestionsAvailableAnnouncement(suggestionCount)
      );
      if (hasAutomaticSelection) {
        announcements.push(
          translations.suggestionAutoSelectedAnnouncement(
            normalisedSuggestions[0].text
          )
        );
      }
      announcements.push(translations.suggestionInstructions);
    } else if (noSuggestionsMessage) {
      if (noSuggestionsMessage.title) {
        announcements.push(noSuggestionsMessage.title);
      }
      announcements.push(noSuggestionsMessage.description);
    } else {
      announcements.push(translations.noSuggestionsAvailableAnnouncement);
    }
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(React.Fragment, { children: [
    showMobileBackdrop ? /* @__PURE__ */ jsxRuntime.jsx(
      styles_lib_components_Box_Box_cjs.Box,
      {
        position: "fixed",
        zIndex: "dropdownBackdrop",
        transition: "fast",
        display: ["block", "none"],
        pointerEvents: isOpen ? void 0 : "none",
        top: 0,
        left: 0,
        opacity: !isOpen ? 0 : void 0,
        className: [
          styles_lib_components_Autosuggest_Autosuggest_css_cjs.backdrop,
          isOpen ? styles_lib_components_Autosuggest_Autosuggest_css_cjs.backdropVisible : void 0
        ]
      }
    ) : null,
    /* @__PURE__ */ jsxRuntime.jsxs(
      styles_lib_components_Box_Box_cjs.Box,
      {
        ...showMobileBackdrop && isOpen ? {
          position: "relative",
          zIndex: "dropdown"
        } : null,
        children: [
          /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Box_Box_cjs.Box, { position: "relative", ref: rootRef, children: /* @__PURE__ */ jsxRuntime.jsx(
            styles_lib_components_private_Field_Field_cjs.Field,
            {
              ...restProps,
              id,
              value: value.text,
              prefix: void 0,
              secondaryIcon: onClear ? /* @__PURE__ */ jsxRuntime.jsx(
                ClearField,
                {
                  id: `${id}-clearfield`,
                  hide: !clearable,
                  onClear,
                  label: clearLabel,
                  inputRef
                }
              ) : null,
              children: (overlays, fieldProps, icon, secondaryIcon) => /* @__PURE__ */ jsxRuntime.jsxs(styles_lib_components_Box_Box_cjs.Box, { width: "full", children: [
                /* @__PURE__ */ jsxRuntime.jsx(
                  styles_lib_components_Box_Box_cjs.Box,
                  {
                    component: "input",
                    ...fieldProps,
                    ...a11y.inputProps,
                    ...inputProps,
                    position: "relative",
                    ref: inputRef
                  }
                ),
                icon,
                /* @__PURE__ */ jsxRuntime.jsx(reactRemoveScroll.RemoveScroll, { ref: menuRef, enabled: isOpen, forwardProps: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
                  styles_lib_components_Box_Box_cjs.Box,
                  {
                    component: "ul",
                    display: isOpen ? "block" : "none",
                    position: "absolute",
                    zIndex: "dropdown",
                    background: !hasSuggestions && noSuggestionsMessage ? { lightMode: "neutralSoft", darkMode: "neutral" } : "surface",
                    borderRadius: "standard",
                    boxShadow: "medium",
                    width: "full",
                    marginTop: "xxsmall",
                    paddingY: "xxsmall",
                    className: styles_lib_components_Autosuggest_Autosuggest_css_cjs.menu,
                    ...a11y.menuProps,
                    children: [
                      isOpen && !hasSuggestions && noSuggestionsMessage ? /* @__PURE__ */ jsxRuntime.jsxs(
                        styles_lib_components_Box_Box_cjs.Box,
                        {
                          component: "li",
                          paddingX: "small",
                          className: styles_lib_css_typography_css_cjs.touchableText.standard,
                          children: [
                            noSuggestionsMessage.title ? /* @__PURE__ */ jsxRuntime.jsx(
                              styles_lib_components_Accordion_AccordionItem_cjs.Text,
                              {
                                tone: "secondary",
                                weight: "medium",
                                baseline: false,
                                children: noSuggestionsMessage.title
                              }
                            ) : null,
                            /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.Text, { tone: "secondary", baseline: false, children: noSuggestionsMessage.description })
                          ]
                        }
                      ) : null,
                      isOpen && hasSuggestions ? normalisedSuggestions.map((suggestion, index) => {
                        const { text } = suggestion;
                        const groupHeading = groupHeadingIndexes.get(index);
                        return /* @__PURE__ */ jsxRuntime.jsxs(React.Fragment, { children: [
                          groupHeading ? /* @__PURE__ */ jsxRuntime.jsx(GroupHeading, { children: groupHeading }) : null,
                          /* @__PURE__ */ jsxRuntime.jsx(
                            SuggestionItem,
                            {
                              suggestion,
                              highlighted: highlightedIndex === index,
                              selected: value === suggestion,
                              onClick: () => {
                                fireChange(suggestion);
                                dispatch({ type: SUGGESTION_MOUSE_CLICK });
                              },
                              onHover: () => {
                                dispatch({
                                  type: SUGGESTION_MOUSE_ENTER,
                                  value: index
                                });
                              },
                              ...a11y.getItemProps({
                                index,
                                label: suggestion.label ?? suggestion.text,
                                description: suggestion.description,
                                groupHeading: groupHeadingForSuggestion.get(suggestion)
                              })
                            }
                          )
                        ] }, index + text);
                      }) : null
                    ]
                  }
                ) }),
                overlays,
                secondaryIcon
              ] })
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_HiddenVisually_HiddenVisually_cjs.HiddenVisually, { ...a11y.assistiveDescriptionProps, children: translations.assistiveDescription }),
          /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_private_Announcement_Announcement_cjs.Announcement, { children: announcements.join(". ") })
        ]
      }
    )
  ] });
});
Autosuggest.displayName = "Autosuggest";
exports.Autosuggest = Autosuggest;
exports.ClearField = ClearField;
exports.FieldButtonIcon = FieldButtonIcon;
exports.getNextIndex = getNextIndex;
exports.normalizeKey = normalizeKey;
exports.smoothScroll = smoothScroll;
exports.smoothScrollIntoView = smoothScrollIntoView;
exports.useResponsiveValue = useResponsiveValue;
