'use strict';

var React = require('react');
var floatingUi_react = require('../floating-ui.react-cjs.js');
var classnames = require('classnames');
var design = require('@jobber/design');
var jobberHooks = require('@jobber/hooks');
var maxHeight = require('../maxHeight-cjs.js');
var Heading = require('../Heading-cjs.js');
var Text = require('../Text-cjs.js');
var Typography = require('../Typography-cjs.js');
var Icon = require('../Icon-cjs.js');
var InputText_index = require('../InputText/index.cjs');
var Glimmer = require('../Glimmer-cjs.js');
var FormField = require('../FormField-cjs.js');
var filterDataAttributes = require('../filterDataAttributes-cjs.js');
var tslib_es6 = require('../tslib.es6-cjs.js');
require('react/jsx-runtime');
require('react-dom');
require('react-hook-form');
require('framer-motion');
require('../Button-cjs.js');
require('react-router-dom');
require('../useFormFieldFocus-cjs.js');
require('../InputValidation-cjs.js');
require('../Spinner-cjs.js');
require('../Content-cjs.js');

var styles$1 = {"list":"_37kZB-nYE08-","loadingList":"ULib3TUQja0-","option":"h5-1Pp0eRyo-","defaultOptionContent":"iBkyj85vd-E-","icon":"I6wAbSJJHNQ-","optionActive":"_4yhnonWAWRY-","actionActive":"oGLMF6n8C74-","action":"LBrwH6TEUYA-","section":"DDOv4DR8bJQ-","emptyStateMessage":"Twgjn26oldE-","stickyTop":"mc1-CEwZtHE-","scrollRegion":"kOR88SFNOn0-","persistentHeader":"_0O-kEf3h9ZI-","persistentFooter":"rQ9ZS7Rb7Z4-","textPersistent":"vxk57ZhP8GU-","spinning":"_0d8hyvaCPAw-"};

function flattenMenu(menu) {
    const optionItems = [];
    const sections = [];
    const persistentsHeaders = [];
    const persistentsFooters = [];
    menu.forEach(item => {
        if (item.type === "header") {
            persistentsHeaders.push(item);
            return;
        }
        if (item.type === "footer") {
            persistentsFooters.push(item);
            return;
        }
        const group = item;
        sections.push(group);
        optionItems.push(...group.options);
    });
    return { optionItems, sections, persistentsHeaders, persistentsFooters };
}
function buildItemsForGroup(group, optionsFilter) {
    var _a;
    const isSection = group.type === "section";
    const filtered = optionsFilter ? optionsFilter(group.options) : group.options;
    const actions = (_a = group.actions) !== null && _a !== void 0 ? _a : [];
    const result = [];
    // Only render a section header when that section has at least one option after filtering
    if (isSection && filtered.length > 0) {
        result.push({
            kind: "section",
            section: group,
        });
    }
    if (filtered.length > 0) {
        result.push(...filtered.map(o => ({
            kind: "option",
            value: o,
        })));
    }
    // Only render actions for a group when that group has at least one option after filtering
    if (actions.length > 0 && filtered.length > 0) {
        result.push(...actions.map(action => ({
            kind: "action",
            action,
            origin: "menu",
        })));
    }
    return result;
}
function buildRenderableList(sections, optionsFilter) {
    const items = [];
    for (const group of sections) {
        items.push(...buildItemsForGroup(group, optionsFilter));
    }
    return items;
}
function getNavigableItemAtIndex(activeIndex, renderable) {
    if (activeIndex == null)
        return null;
    let navigableIndex = -1;
    for (const item of renderable) {
        // Ignore sections
        if (item.kind === "section")
            continue;
        navigableIndex += 1;
        if (navigableIndex === activeIndex)
            return item;
    }
    return null;
}
function findNavigableIndexForValue(renderable, equals, selectedValue) {
    let navigableIndex = -1;
    for (const item of renderable) {
        // Ignore sections
        if (item.kind === "section")
            continue;
        navigableIndex += 1;
        if (item.kind === "option" && equals(item.value, selectedValue)) {
            return navigableIndex;
        }
    }
    return null;
}
function invokeActiveItemOnEnter(event, activeIndex, renderable, onSelect, onAction) {
    const activeItem = getNavigableItemAtIndex(activeIndex, renderable);
    if (!activeItem)
        return;
    event.preventDefault();
    if (activeItem.kind === "option") {
        onSelect(activeItem.value);
    }
    else if (activeItem.kind === "action") {
        onAction({
            run: activeItem.action.onClick,
            closeOnRun: activeItem.action.shouldClose,
        });
    }
}

const MENU_OFFSET = design.tokens["space-small"];
const AUTOCOMPLETE_MAX_HEIGHT$1 = 300;
function useAutocompleteListNav({ navigableCount, shouldResetActiveIndexOnClose, onMenuClose, selectedIndex, readOnly = false, }) {
    const [open, setOpen] = React.useState(false);
    const [activeIndex, setActiveIndex] = React.useState(null);
    const listRef = React.useRef([]);
    const { refs, floatingStyles, context } = floatingUi_react.useFloating({
        placement: "bottom",
        whileElementsMounted: floatingUi_react.autoUpdate,
        open,
        onOpenChange: (isOpen, _event, reason) => {
            setOpen(isOpen);
            if (isOpen === false) {
                if (shouldResetActiveIndexOnClose === null || shouldResetActiveIndexOnClose === void 0 ? void 0 : shouldResetActiveIndexOnClose()) {
                    setActiveIndex(null);
                }
                onMenuClose === null || onMenuClose === void 0 ? void 0 : onMenuClose(String(reason !== null && reason !== void 0 ? reason : ""));
            }
        },
        middleware: [
            floatingUi_react.offset(MENU_OFFSET),
            floatingUi_react.flip({ fallbackPlacements: ["top"] }),
            floatingUi_react.size({
                apply({ availableHeight, elements }) {
                    const maxHeight$1 = maxHeight.calculateMaxHeight(availableHeight, {
                        maxHeight: AUTOCOMPLETE_MAX_HEIGHT$1,
                    });
                    Object.assign(elements.floating.style, {
                        maxHeight: `${maxHeight$1}px`,
                    });
                },
            }),
        ],
    });
    const click = floatingUi_react.useClick(context, {
        enabled: !readOnly,
        toggle: false, // Only open, never close on click
    });
    const listNav = floatingUi_react.useListNavigation(context, {
        listRef,
        activeIndex,
        selectedIndex,
        scrollItemIntoView: {
            behavior: "smooth",
            block: "end",
        },
        loop: true,
        onNavigate: setActiveIndex,
        virtual: true,
        enabled: open,
        openOnArrowKeyDown: false,
        focusItemOnOpen: "auto",
        focusItemOnHover: false,
    });
    const dismiss = floatingUi_react.useDismiss(context, {
        outsidePress: true,
        escapeKey: true,
        outsidePressEvent: "click",
    });
    const { getReferenceProps, getFloatingProps, getItemProps } = floatingUi_react.useInteractions([click, listNav, dismiss]);
    React.useEffect(() => {
        listRef.current.length = navigableCount;
        setActiveIndex(prev => {
            if (navigableCount <= 0)
                return null;
            if (prev == null)
                return null;
            return prev >= navigableCount ? navigableCount - 1 : prev;
        });
    }, [navigableCount, setActiveIndex, listRef]);
    const setReferenceElement = React.useCallback((el) => refs.setReference(el), [refs]);
    return {
        refs,
        floatingStyles,
        context,
        getReferenceProps,
        getFloatingProps,
        getItemProps,
        activeIndex,
        setActiveIndex,
        listRef,
        open,
        setOpen,
        setReferenceElement,
    };
}

/**
 * Handler that prevents default pointer behavior.
 * Used to prevent blur/focus issues when clicking on non-interactive menu elements.
 */
function preventDefaultPointerDown(e) {
    e.preventDefault();
}
/**
 * Creates a handler for pointer down events on interactive menu items (options/actions).
 * Prevents default to avoid blur and sets flag for focus management.
 *
 * @param isHandlingMenuInteractionRef - Ref to track if a menu interaction is in progress
 * @returns A pointer down event handler
 */
function createInteractionPointerDownHandler(isHandlingMenuInteractionRef) {
    return (e) => {
        e.preventDefault();
        // Set flag to prevent blur/focus handlers from interfering
        isHandlingMenuInteractionRef.current = true;
    };
}

// Keeping this hook cohesive improves readability by centralizing related
// interactions and state transitions.
// eslint-disable-next-line max-statements
function useAutocomplete(props) {
    const { menu, emptyActions, getOptionLabel: getOptionLabelProp, isOptionEqualToValue, inputValue, onInputChange, value, onChange, multiple, openOnFocus = true, readOnly = false, debounce: debounceMs = 300, } = props;
    const isHandlingMenuInteractionRef = React.useRef(false);
    // TODO: Clean up the types in these refs by enhancing the type system in useCallbackRef
    const getOptionLabelPropRef = jobberHooks.useCallbackRef((opt) => getOptionLabelProp === null || getOptionLabelProp === void 0 ? void 0 : getOptionLabelProp(opt));
    const getOptionLabel = React.useCallback((opt) => {
        const maybe = getOptionLabelPropRef(opt);
        return maybe !== null && maybe !== void 0 ? maybe : opt.label;
    }, [getOptionLabelPropRef]);
    const isOptionEqualToValueRef = jobberHooks.useCallbackRef((a, b) => isOptionEqualToValue === null || isOptionEqualToValue === void 0 ? void 0 : isOptionEqualToValue(a, b));
    const equals = React.useCallback((a, b) => {
        const custom = isOptionEqualToValueRef(a, b);
        return custom != null ? custom : getOptionLabel(a) === getOptionLabel(b);
    }, [isOptionEqualToValueRef, getOptionLabel]);
    const isOptionSelected = React.useCallback((opt) => {
        var _a;
        if (multiple) {
            const current = (_a = value) !== null && _a !== void 0 ? _a : [];
            return current.some(v => equals(v, opt));
        }
        const current = value;
        return current != null ? equals(current, opt) : false;
    }, [multiple, value, equals]);
    const flatInitial = React.useMemo(() => flattenMenu(menu), [menu]);
    const sections = flatInitial.sections;
    const optionItems = flatInitial.optionItems;
    const persistentsHeaders = flatInitial.persistentsHeaders;
    const persistentsFooters = flatInitial.persistentsFooters;
    // Stable wrappers for function props
    const inputEqualsOptionRef = jobberHooks.useCallbackRef((text, o) => {
        const fn = props.inputEqualsOption;
        return fn ? fn(text, o) : undefined;
    });
    const inputEquals = React.useCallback((text, o) => {
        const custom = inputEqualsOptionRef(text, o);
        return custom != null ? custom : getOptionLabel(o) === text;
    }, [inputEqualsOptionRef, getOptionLabel]);
    // inputValue changes very often, is this worth memoizing?
    const exactLabelMatch = React.useMemo(() => {
        return optionItems.some(o => inputEquals(inputValue, o));
    }, [optionItems, inputEquals, inputValue]);
    const lastInputWasUser = React.useRef(false);
    const [debouncedInputValue, setDebouncedInputValue] = React.useState(inputValue);
    const debouncedSetter = jobberHooks.useDebounce(setDebouncedInputValue, debounceMs);
    React.useEffect(() => {
        // Skip debounce when clearing input for immediate feedback, preventing flickering of last selected item
        if (debounceMs === 0 || inputValue === "") {
            setDebouncedInputValue(inputValue);
            return;
        }
        debouncedSetter(inputValue);
    }, [inputValue, debounceMs, debouncedSetter]);
    const filterOptionsRef = jobberHooks.useCallbackRef((opts, term) => {
        const fn = (typeof props.filterOptions === "function"
            ? props.filterOptions
            : undefined) || undefined;
        return fn ? fn(opts, term) : undefined;
    });
    const applyFilter = React.useCallback((opts, term) => {
        if (props.filterOptions === false)
            return opts;
        const override = filterOptionsRef(opts, term);
        if (override)
            return override;
        const lowered = term.toLowerCase();
        return opts.filter(opt => getOptionLabel(opt).toLowerCase().includes(lowered));
    }, [props.filterOptions, filterOptionsRef, getOptionLabel]);
    const renderable = React.useMemo(() => {
        const filter = (opts) => {
            if (exactLabelMatch && !lastInputWasUser.current)
                return opts;
            return applyFilter(opts, debouncedInputValue);
        };
        const items = buildRenderableList(sections, filter);
        const hasAnyOptions = items.some(i => i.kind === "option");
        if (!hasAnyOptions) {
            if (emptyActions) {
                const derived = typeof emptyActions === "function"
                    ? emptyActions({ inputValue })
                    : emptyActions;
                return derived.map(act => ({
                    kind: "action",
                    action: act,
                    origin: "empty",
                }));
            }
            // No options and no emptyActions: render empty state
            return [];
        }
        return items;
    }, [
        sections,
        applyFilter,
        debouncedInputValue,
        exactLabelMatch,
        emptyActions,
        inputValue,
    ]);
    // This is only options
    const optionCount = renderable.reduce((count, item) => count + (item.kind === "option" ? 1 : 0), 0);
    const hasSelection = React.useMemo(() => {
        var _a;
        if (multiple) {
            const current = (_a = value) !== null && _a !== void 0 ? _a : [];
            return Array.isArray(current) && current.length > 0;
        }
        return value != null;
    }, [multiple, value]);
    const headerInteractivePersistents = persistentsHeaders.filter(p => Boolean(p.onClick));
    const footerInteractivePersistents = persistentsFooters.filter(p => Boolean(p.onClick));
    const mainNavigableCount = renderable.reduce((c, i) => c + (i.kind === "section" ? 0 : 1), 0);
    const totalNavigableCount = headerInteractivePersistents.length +
        mainNavigableCount +
        footerInteractivePersistents.length;
    // Compute the currently selected index in the global navigable list (header -> middle -> footer)
    const selectedIndex = React.useMemo(() => {
        const selectedValue = multiple
            ? value === null || value === void 0 ? void 0 : value[0]
            : value;
        if (!selectedValue)
            return null;
        const middleIndex = findNavigableIndexForValue(renderable, equals, selectedValue);
        if (middleIndex == null)
            return null;
        return headerInteractivePersistents.length + middleIndex;
    }, [
        multiple,
        value,
        renderable,
        equals,
        headerInteractivePersistents.length,
    ]);
    const { refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps, activeIndex, setActiveIndex, listRef, open, setOpen, setReferenceElement, } = useAutocompleteListNav({
        navigableCount: totalNavigableCount,
        shouldResetActiveIndexOnClose: () => !hasSelection,
        selectedIndex,
        readOnly,
        onMenuClose: () => {
            if (props.allowFreeForm !== true) {
                const hasText = inputValue.trim().length > 0;
                if (hasText && !hasSelection) {
                    lastInputWasUser.current = false;
                    onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange("");
                    setActiveIndex(null);
                }
            }
        },
    });
    // Handles activeIndex reset and, in single-select mode only, clearing selection when input is empty
    React.useEffect(() => {
        const hasText = inputValue.trim().length > 0;
        if (hasText)
            return;
        // Always reset highlight when input is empty
        setActiveIndex(null);
        // In multiple mode, clearing the input should NOT clear the selection
        if (multiple)
            return;
        // For single-select, treat clearing input as clearing the selection
        if (hasSelection) {
            onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
        }
    }, [inputValue, multiple, hasSelection, setActiveIndex, onChange, open]);
    function selectOption(option) {
        var _a;
        if (multiple) {
            const current = (_a = value) !== null && _a !== void 0 ? _a : [];
            const exists = current.some(v => equals(v, option));
            const next = exists
                ? current.filter(v => !equals(v, option))
                : [...current, option];
            onChange(next);
        }
        else {
            onChange(option);
            lastInputWasUser.current = false;
            onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(getOptionLabel(option));
        }
    }
    function tryCommitFreeFormOnEnter() {
        if (props.allowFreeForm !== true)
            return false;
        if (open && activeIndex != null)
            return false;
        const inputText = inputValue.trim();
        if (inputText.length === 0)
            return false;
        commitFromInputText(inputText);
        return true;
    }
    // Keep the selected item highlighted when deleting characters from the input
    const prevInputLengthRef = React.useRef(inputValue.length);
    React.useEffect(() => {
        const previousLength = prevInputLengthRef.current;
        prevInputLengthRef.current = inputValue.length;
        if (!open)
            return;
        if (!lastInputWasUser.current)
            return;
        if (previousLength <= inputValue.length)
            return; // only on deletion
        if (!hasSelection)
            return;
        const selectedValue = multiple
            ? value === null || value === void 0 ? void 0 : value[0]
            : value;
        if (!selectedValue)
            return;
        const idx = findNavigableIndexForValue(renderable, equals, selectedValue);
        if (idx != null)
            setActiveIndex(idx);
    }, [
        inputValue,
        renderable,
        equals,
        value,
        open,
        hasSelection,
        multiple,
        setActiveIndex,
    ]);
    React.useEffect(() => {
        if (!open)
            return;
        // When opening the menu, initialize the highlight consistently:
        // - If there is a current selection, highlight that option
        // - Otherwise, leave the highlight unset (null)
        const selectedValue = multiple
            ? value === null || value === void 0 ? void 0 : value[0]
            : value;
        if (selectedValue) {
            const selectedNavigableIndex = findNavigableIndexForValue(renderable, equals, selectedValue);
            if (selectedNavigableIndex != null) {
                setActiveIndex(selectedNavigableIndex);
                return;
            }
        }
        setActiveIndex(null);
    }, [open, multiple, value, renderable, equals, setActiveIndex]);
    const onSelection = React.useCallback((option) => {
        selectOption(option);
        // Might not always want to close on selection. Multi for example.
        setOpen(false);
        if (refs.domReference.current instanceof HTMLElement) {
            refs.domReference.current.focus();
        }
    }, [selectOption, setOpen]);
    const onAction = React.useCallback((action) => {
        action.run();
        setActiveIndex(null);
        if (action.closeOnRun !== false)
            setOpen(false);
        if (refs.domReference.current instanceof HTMLElement) {
            refs.domReference.current.focus();
        }
    }, [setOpen, setActiveIndex]);
    /**
     * Handler for mousedown on interactive menu items (options/actions)
     * Prevents default to avoid blur and sets flag for focus management
     */
    const onInteractionPointerDown = React.useMemo(() => createInteractionPointerDownHandler(isHandlingMenuInteractionRef), []);
    function commitFromInputText(inputText) {
        var _a;
        if (inputText.length === 0)
            return false;
        const match = optionItems.find(o => inputEquals(inputText, o));
        if (match) {
            onSelection(match);
            return true;
        }
        setOpen(false);
        if (props.allowFreeForm !== true)
            return false;
        const freeFormCreated = (_a = props.createFreeFormValue) === null || _a === void 0 ? void 0 : _a.call(props, inputText);
        if (!freeFormCreated)
            return false;
        props.onChange(freeFormCreated);
        return true;
    }
    const tryRestoreInputToSelectedLabel = React.useCallback(() => {
        if (props.allowFreeForm === true)
            return;
        const selectedValue = multiple
            ? value === null || value === void 0 ? void 0 : value[0]
            : value;
        if (!selectedValue)
            return;
        const selectedLabel = getOptionLabel(selectedValue);
        if (inputValue === selectedLabel)
            return;
        lastInputWasUser.current = false;
        onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(selectedLabel);
    }, [
        props.allowFreeForm,
        getOptionLabel,
        inputValue,
        onInputChange,
        multiple,
        value,
    ]);
    const onInputFocus = React.useCallback((event) => {
        var _a;
        if (!readOnly && openOnFocus && !isHandlingMenuInteractionRef.current) {
            setOpen(true);
        }
        // Only call user's onFocus for genuine focus events, not programmatic restorations
        if (!isHandlingMenuInteractionRef.current) {
            (_a = props.onFocus) === null || _a === void 0 ? void 0 : _a.call(props, event);
        }
        isHandlingMenuInteractionRef.current = false;
    }, [props.onFocus, readOnly, openOnFocus, setOpen]);
    const onInputBlur = React.useCallback((event) => {
        var _a, _b;
        if (isHandlingMenuInteractionRef.current) {
            return;
        }
        if (readOnly) {
            (_a = props.onBlur) === null || _a === void 0 ? void 0 : _a.call(props, event);
            return;
        }
        if (props.allowFreeForm === true) {
            const inputText = inputValue.trim();
            if (inputText.length > 0)
                commitFromInputText(inputText);
        }
        else {
            tryRestoreInputToSelectedLabel();
        }
        lastInputWasUser.current = false;
        (_b = props.onBlur) === null || _b === void 0 ? void 0 : _b.call(props, event);
    }, [
        readOnly,
        props.allowFreeForm,
        inputValue,
        props.onBlur,
        tryRestoreInputToSelectedLabel,
        setOpen,
    ]);
    function getRegionByActiveIndex(index) {
        const headerCount = headerInteractivePersistents.length;
        const mainCount = mainNavigableCount;
        if (index < headerCount)
            return { region: "header", regionIndex: index };
        const middleIndex = index - headerCount;
        if (middleIndex < mainCount) {
            return { region: "middle", regionIndex: middleIndex };
        }
        return {
            region: "footer",
            regionIndex: middleIndex - mainCount,
        };
    }
    function computeInitialIndexForArrowUp() {
        // If there are interactive footers, prefer the very last navigable item
        if (footerInteractivePersistents.length > 0) {
            return totalNavigableCount > 0 ? totalNavigableCount - 1 : null;
        }
        // Otherwise, prefer the last OPTION (not action), matching legacy behavior
        let navigable = -1;
        let lastOptionIdx = -1;
        for (const item of renderable) {
            if (item.kind === "section")
                continue;
            navigable += 1;
            if (item.kind === "option")
                lastOptionIdx = navigable;
        }
        if (lastOptionIdx >= 0) {
            return headerInteractivePersistents.length + lastOptionIdx;
        }
        return totalNavigableCount > 0 ? totalNavigableCount - 1 : null;
    }
    function handleArrowNavigation(key, event) {
        if (!open) {
            setOpen(true);
            return;
        }
        if (activeIndex == null) {
            setActiveIndex(key === "ArrowDown" ? 0 : computeInitialIndexForArrowUp());
            event.preventDefault();
        }
    }
    function handleEnterKey(event) {
        if (tryCommitFreeFormOnEnter()) {
            event.preventDefault();
            return;
        }
        if (!open || activeIndex == null)
            return;
        const { region, regionIndex } = getRegionByActiveIndex(activeIndex);
        if (region === "middle") {
            invokeActiveItemOnEnter(event, regionIndex, renderable, onSelection, onAction);
            return;
        }
        const persistent = region === "header"
            ? headerInteractivePersistents[regionIndex]
            : footerInteractivePersistents[regionIndex];
        if (persistent === null || persistent === void 0 ? void 0 : persistent.onClick) {
            onAction({
                run: persistent.onClick,
                closeOnRun: persistent.shouldClose,
            });
        }
    }
    const onInputKeyDown = React.useCallback((event) => {
        const key = event.key;
        if (key !== "ArrowDown" && key !== "ArrowUp" && key !== "Enter")
            return;
        if (key === "ArrowDown" || key === "ArrowUp") {
            handleArrowNavigation(key, event);
            return;
        }
        handleEnterKey(event);
    }, [open, onSelection, onAction]);
    const onInputChangeFromUser = React.useCallback((val) => {
        lastInputWasUser.current = true;
        // Reset highlight (activeIndex) on additions to the search term
        if (val.length > inputValue.length) {
            setActiveIndex(null);
        }
        // Important: update open state before propagating the change so that downstream effects
        // don't see an intermediate state where inputValue changed but open was stale
        if (!readOnly) {
            const hasText = val.trim().length > 0;
            const mustSelectFromOptions = hasText && !props.allowFreeForm;
            const keepOpenOnEmpty = openOnFocus;
            setOpen(mustSelectFromOptions || keepOpenOnEmpty);
        }
        onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(val);
    }, [
        onInputChange,
        inputValue,
        setActiveIndex,
        readOnly,
        props.allowFreeForm,
        openOnFocus,
        setOpen,
    ]);
    return {
        // rendering data
        renderable,
        optionCount,
        persistentsHeaders,
        persistentsFooters,
        headerInteractiveCount: headerInteractivePersistents.length,
        middleNavigableCount: mainNavigableCount,
        getOptionLabel,
        isOptionSelected,
        // floating-ui
        refs,
        floatingStyles,
        context,
        getReferenceProps,
        getFloatingProps,
        getItemProps,
        // state
        open,
        setOpen,
        activeIndex,
        setActiveIndex,
        listRef,
        // actions
        onSelection,
        onAction,
        onInteractionPointerDown,
        // input handlers
        onInputChangeFromUser,
        onInputBlur,
        onInputFocus,
        onInputKeyDown,
        // ref attachment
        setReferenceElement,
    };
}

function MenuList({ items, activeIndex, indexOffset = 0, getItemProps, listRef, listboxId, customRenderOption, customRenderSection, customRenderAction, getOptionLabel, onSelect, onAction, onInteractionPointerDown, isOptionSelected, slotOverrides, }) {
    let navigableIndex = -1;
    function renderItemNode(item) {
        var _a, _b, _c, _d, _e, _f;
        if (item.kind === "section") {
            return handleSectionRendering({
                section: item.section,
                customRenderSection,
                sectionClassName: (_a = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.section) === null || _a === void 0 ? void 0 : _a.className,
                sectionStyle: (_b = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.section) === null || _b === void 0 ? void 0 : _b.style,
            });
        }
        if (item.kind === "option") {
            const result = handleOptionRendering({
                option: item.value,
                activeIndex,
                navigableIndex,
                getItemProps,
                listRef,
                listboxId,
                isOptionSelected,
                customRenderOption,
                getOptionLabel,
                onSelect,
                onInteractionPointerDown,
                indexOffset,
                optionClassName: (_c = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.option) === null || _c === void 0 ? void 0 : _c.className,
                optionStyle: (_d = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.option) === null || _d === void 0 ? void 0 : _d.style,
            });
            navigableIndex = result.nextNavigableIndex;
            return result.node;
        }
        const result = handleActionRendering({
            action: item.action,
            activeIndex,
            navigableIndex,
            getItemProps,
            listRef,
            listboxId,
            customRenderAction,
            onAction,
            onInteractionPointerDown,
            indexOffset,
            actionClassName: (_e = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.action) === null || _e === void 0 ? void 0 : _e.className,
            actionStyle: (_f = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.action) === null || _f === void 0 ? void 0 : _f.style,
            origin: item.origin,
        });
        navigableIndex = result.nextNavigableIndex;
        return result.node;
    }
    return React.createElement(React.Fragment, null, items.map(renderItemNode));
}
function handleSectionRendering({ customRenderSection, section, sectionClassName, sectionStyle, }) {
    var _a;
    const headerContent = customRenderSection ? (customRenderSection(section)) : (React.createElement(DefaultSectionContent, { section: section }));
    return (React.createElement("div", { key: `section-${String((_a = section.key) !== null && _a !== void 0 ? _a : section.label)}`, role: "presentation", tabIndex: -1, "data-testid": "ATL-AutocompleteRebuilt-Section", className: classnames(styles$1.section, styles$1.stickyTop, sectionClassName), style: sectionStyle, onPointerDown: preventDefaultPointerDown }, headerContent));
}
function DefaultSectionContent({ section, }) {
    return React.createElement(Heading.Heading, { level: 5 }, section.label);
}
function handleOptionRendering({ option, activeIndex, navigableIndex, getItemProps, listRef, listboxId, isOptionSelected, customRenderOption, getOptionLabel, onSelect, onInteractionPointerDown, indexOffset = 0, optionClassName, optionStyle, }) {
    var _a;
    const nextNavigableIndex = navigableIndex + 1;
    const isActive = activeIndex === nextNavigableIndex;
    const isSelected = isOptionSelected(option);
    const optionContent = customRenderOption ? (customRenderOption({ value: option, isActive, isSelected })) : (React.createElement(DefaultOptionContent, { isSelected: isSelected, text: getOptionLabel(option) }));
    return {
        node: (React.createElement("div", Object.assign({ key: `option-${String((_a = option.key) !== null && _a !== void 0 ? _a : getOptionLabel(option))}` }, getItemProps({
            ref(node) {
                const idx = nextNavigableIndex + indexOffset;
                if (node)
                    listRef.current[idx] = node;
            },
            onClick: () => onSelect(option),
            onPointerDown: onInteractionPointerDown,
            className: classnames(styles$1.option, isActive && styles$1.optionActive, optionClassName),
            style: optionStyle,
        }), { role: "option", tabIndex: -1, "aria-selected": isSelected ? true : false, id: `${listboxId}-item-${nextNavigableIndex + indexOffset}`, "data-index": nextNavigableIndex + indexOffset, "data-active": isActive ? true : undefined }), optionContent)),
        nextNavigableIndex,
    };
}
function DefaultOptionContent({ isSelected, text, }) {
    return (React.createElement("div", { className: styles$1.defaultOptionContent },
        React.createElement("div", { className: styles$1.icon }, isSelected && React.createElement(Icon.Icon, { name: "checkmark", size: "small" })),
        React.createElement(Text.Text, null, text)));
}
function handleActionRendering({ action, activeIndex, navigableIndex, getItemProps, listRef, listboxId, customRenderAction, onAction, onInteractionPointerDown, indexOffset = 0, actionClassName, actionStyle, origin, }) {
    var _a;
    const nextNavigableIndex = navigableIndex + 1;
    const isActive = activeIndex === nextNavigableIndex;
    const actionContent = customRenderAction ? (customRenderAction({ value: action, isActive, origin })) : (React.createElement(DefaultActionContent, { textContent: action.label }));
    const computedIndex = nextNavigableIndex + indexOffset;
    const itemProps = getItemProps({
        ref(node) {
            if (node) {
                listRef.current[computedIndex] = node;
            }
        },
        onClick: () => {
            onAction({
                run: action.onClick,
                closeOnRun: action.shouldClose,
            });
        },
        onPointerDown: onInteractionPointerDown,
        className: classnames(styles$1.action, isActive && styles$1.actionActive, actionClassName),
        style: actionStyle,
    });
    return {
        node: (React.createElement("div", Object.assign({ key: `action-${String((origin !== null && origin !== void 0 ? origin : "menu") + "-" + ((_a = action.key) !== null && _a !== void 0 ? _a : action.label))}` }, itemProps, { role: "button", tabIndex: -1, "data-testid": "ATL-AutocompleteRebuilt-Action", id: `${listboxId}-item-${computedIndex}`, "data-index": computedIndex, "data-origin": origin, "data-active": isActive ? true : undefined }), actionContent)),
        nextNavigableIndex,
    };
}
function DefaultActionContent({ textContent, }) {
    return (React.createElement(Typography.Typography, { textColor: "interactive", fontWeight: "semiBold", underline: "solid color-interactive", UNSAFE_style: {
            textStyle: {
                textDecorationThickness: "var(--border-thick)",
                textUnderlineOffset: "var(--space-smallest)",
            },
        } }, textContent));
}

function PersistentRegion({ items, position, activeIndex, indexOffset, getItemProps, listRef, customRenderHeader, customRenderFooter, className, style, onAction, onInteractionPointerDown, }) {
    if (!items || items.length === 0)
        return null;
    let navigableIndex = -1;
    return (React.createElement("div", { className: className, style: style, "data-region": position, "data-testid": `ATL-AutocompleteRebuilt-${position}` }, items.map(persistent => {
        const result = handlePersistentRendering({
            persistent,
            position,
            activeIndex,
            indexOffset,
            getItemProps,
            customRenderHeader,
            customRenderFooter,
            listRef,
            onAction,
            onInteractionPointerDown,
            navigableIndex,
        });
        navigableIndex = result.nextNavigableIndex;
        return result.node;
    })));
}
function handlePersistentRendering({ persistent, position, activeIndex, indexOffset, getItemProps, customRenderHeader, customRenderFooter, listRef, onAction, onInteractionPointerDown, navigableIndex, }) {
    const interactive = Boolean(persistent.onClick);
    if (!interactive) {
        const node = handleTextPersistentRendering({
            persistent,
            position,
            customRenderHeader,
            customRenderFooter,
        });
        return { node, nextNavigableIndex: navigableIndex };
    }
    return handleActionPersistentRendering({
        persistent,
        position,
        activeIndex,
        indexOffset,
        getItemProps,
        customRenderHeader,
        customRenderFooter,
        listRef,
        onAction,
        onInteractionPointerDown,
        navigableIndex,
    });
}
function handleTextPersistentRendering({ persistent, position, customRenderHeader, customRenderFooter, }) {
    var _a;
    let content;
    if (position === "header" && customRenderHeader) {
        content = customRenderHeader({ value: persistent });
    }
    else if (position === "footer" && customRenderFooter) {
        content = customRenderFooter({ value: persistent });
    }
    else {
        content = React.createElement(DefaultTextPersistentContent, { persistent: persistent });
    }
    return (React.createElement("div", { key: `persistent-${position}-${String((_a = persistent.key) !== null && _a !== void 0 ? _a : persistent.label)}`, role: "presentation", tabIndex: -1, className: styles$1.textPersistent, onPointerDown: preventDefaultPointerDown }, content));
}
function handleActionPersistentRendering({ persistent, position, activeIndex, indexOffset, getItemProps, customRenderHeader, customRenderFooter, listRef, onAction, onInteractionPointerDown, navigableIndex, }) {
    var _a;
    const nextNavigableIndex = navigableIndex + 1;
    const isActive = activeIndex === indexOffset + nextNavigableIndex;
    let content;
    if (position === "header" && customRenderHeader) {
        content = customRenderHeader({
            value: persistent,
            isActive,
        });
    }
    else if (position === "footer" && customRenderFooter) {
        content = customRenderFooter({
            value: persistent,
            isActive,
        });
    }
    else {
        content = React.createElement(DefaultActionContent, { textContent: persistent.label });
    }
    return {
        node: (React.createElement("div", Object.assign({ key: `persistent-${position}-${String((_a = persistent.key) !== null && _a !== void 0 ? _a : persistent.label)}`, "data-index": indexOffset + nextNavigableIndex, id: `${position}-persistent-${indexOffset + nextNavigableIndex}`, "data-active": isActive ? true : undefined }, getItemProps({
            ref(persistNode) {
                const idx = indexOffset + nextNavigableIndex;
                if (persistNode)
                    listRef.current[idx] = persistNode;
            },
            onClick: () => {
                onAction({
                    run: () => {
                        var _a;
                        (_a = persistent.onClick) === null || _a === void 0 ? void 0 : _a.call(persistent);
                    },
                    closeOnRun: persistent.shouldClose,
                });
            },
            onPointerDown: onInteractionPointerDown,
            className: classnames(styles$1.action, isActive && styles$1.actionActive),
        }), { role: "button", tabIndex: -1 }), content)),
        nextNavigableIndex,
    };
}
function DefaultTextPersistentContent({ persistent, }) {
    return React.createElement("div", { className: styles$1.textPersistent }, persistent.label);
}

const AutocompleteRebuilt = React.forwardRef(AutocompleteRebuiltInternal);
// eslint-disable-next-line max-statements
function AutocompleteRebuiltInternal(props, forwardedRef) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
    const { inputValue, placeholder, disabled, error, invalid, description, size: sizeProp, loading = false, } = props;
    const { renderable, optionCount, persistentsHeaders, persistentsFooters, headerInteractiveCount, middleNavigableCount, getOptionLabel, isOptionSelected, refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps, activeIndex, open, listRef, onSelection, onAction, onInteractionPointerDown, onInputChangeFromUser, onInputBlur, onInputFocus, onInputKeyDown, setReferenceElement, } = useAutocomplete(props);
    const listboxId = React.useId();
    // Provides mount/unmount-aware transition styles for the floating element
    const { isMounted, styles: transitionStyles } = floatingUi_react.useTransitionStyles(context, {
        initial: { opacity: 0 },
        open: { opacity: 1 },
        close: { opacity: 0 },
        duration: { open: design.tokens["timing-base"], close: design.tokens["timing-base"] },
    });
    const [menuWidth, setMenuWidth] = React.useState(undefined);
    const [positionRefEl, setPositionRefEl] = React.useState(null);
    const composedReferenceProps = getReferenceProps({
        onKeyDown: onInputKeyDown,
        onFocus: onInputFocus,
        onBlur: onInputBlur,
    });
    const dataAttrs = filterDataAttributes.filterDataAttributes(props);
    const inputProps = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ version: 2, value: inputValue, onChange: props.readOnly ? undefined : onInputChangeFromUser }, (props.readOnly ? { onFocus: onInputFocus, onBlur: onInputBlur } : {})), { placeholder,
        disabled, readOnly: props.readOnly, error: error !== null && error !== void 0 ? error : undefined, name: props.name, invalid, autoComplete: "off", autoFocus: props.autoFocus, description, size: sizeProp ? sizeProp : undefined, prefix: props.prefix, suffix: props.suffix }), (props.readOnly ? {} : composedReferenceProps)), { role: "combobox", "aria-autocomplete": "list", "aria-expanded": open ? true : false, "aria-controls": listboxId, "aria-activedescendant": open && activeIndex != null
            ? `${listboxId}-item-${activeIndex}`
            : undefined }), dataAttrs);
    const referenceInputRef = React.useCallback((node) => {
        setReferenceElement(node);
        // Workaround to get the width of the visual InputText element, which is not the same as
        // the literal input reference element when props like suffix/prefix/clearable are present.
        const visualInputTextElement = node === null || node === void 0 ? void 0 : node.closest("[data-testid='Form-Field-Wrapper']");
        if (visualInputTextElement) {
            setMenuWidth(visualInputTextElement.clientWidth);
            setPositionRefEl(visualInputTextElement);
        }
    }, [setReferenceElement]);
    const mergedInputRef = React.useMemo(() => FormField.mergeRefs([
        referenceInputRef,
        forwardedRef,
    ]), [referenceInputRef, forwardedRef]);
    React.useEffect(() => {
        if (!positionRefEl)
            return;
        // Set the reference element to the visual InputText element so the menu aligns with the input.
        refs.setPositionReference(positionRefEl);
    }, [positionRefEl, refs]);
    const menuClassName = classnames(styles$1.list, (_a = props.UNSAFE_className) === null || _a === void 0 ? void 0 : _a.menu);
    const showEmptyStateMessage = optionCount === 0 && props.emptyStateMessage !== false;
    const activeIndexForMiddle = activeIndex != null ? activeIndex - headerInteractiveCount : null;
    return (React.createElement("div", { "data-testid": "ATL-AutocompleteRebuilt" },
        props.customRenderInput ? (props.customRenderInput({ inputRef: mergedInputRef, inputProps })) : (React.createElement(InputText_index.InputText, Object.assign({ ref: mergedInputRef }, inputProps))),
        isMounted && !props.readOnly && (React.createElement(floatingUi_react.FloatingPortal, null,
            React.createElement(floatingUi_react.FloatingFocusManager, { context: context, modal: false, initialFocus: -1, closeOnFocusOut: true, returnFocus: false },
                React.createElement("div", Object.assign({}, getFloatingProps({
                    ref(node) {
                        if (node)
                            refs.setFloating(node);
                    },
                    id: listboxId,
                    role: "listbox",
                    className: menuClassName,
                    style: Object.assign(Object.assign(Object.assign(Object.assign({}, floatingStyles), transitionStyles), (_b = props.UNSAFE_styles) === null || _b === void 0 ? void 0 : _b.menu), (menuWidth
                        ? { width: menuWidth, maxWidth: menuWidth }
                        : {})),
                })),
                    React.createElement(PersistentRegion, { items: persistentsHeaders, position: "header", activeIndex: activeIndex, indexOffset: 0, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderHeader: props.customRenderHeader, customRenderFooter: props.customRenderFooter, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, className: classnames(styles$1.persistentHeader, (_c = props.UNSAFE_className) === null || _c === void 0 ? void 0 : _c.header), style: (_d = props.UNSAFE_styles) === null || _d === void 0 ? void 0 : _d.header }),
                    React.createElement("div", { className: styles$1.scrollRegion }, loading ? ((_e = props.customRenderLoading) !== null && _e !== void 0 ? _e : React.createElement(LoadingContent, null)) : (React.createElement(React.Fragment, null,
                        showEmptyStateMessage && (React.createElement(EmptyStateMessage, { emptyState: props.emptyStateMessage })),
                        renderable.length > 0 && (React.createElement(MenuList, { items: renderable, activeIndex: activeIndexForMiddle, indexOffset: headerInteractiveCount, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderOption: props.customRenderOption, customRenderSection: props.customRenderSection, customRenderAction: props.customRenderAction, getOptionLabel: getOptionLabel, onSelect: onSelection, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, isOptionSelected: isOptionSelected, slotOverrides: {
                                option: {
                                    className: (_f = props.UNSAFE_className) === null || _f === void 0 ? void 0 : _f.option,
                                    style: (_g = props.UNSAFE_styles) === null || _g === void 0 ? void 0 : _g.option,
                                },
                                action: {
                                    className: (_h = props.UNSAFE_className) === null || _h === void 0 ? void 0 : _h.action,
                                    style: (_j = props.UNSAFE_styles) === null || _j === void 0 ? void 0 : _j.action,
                                },
                                section: {
                                    className: (_k = props.UNSAFE_className) === null || _k === void 0 ? void 0 : _k.section,
                                    style: (_l = props.UNSAFE_styles) === null || _l === void 0 ? void 0 : _l.section,
                                },
                            } }))))),
                    React.createElement(PersistentRegion, { items: persistentsFooters, position: "footer", activeIndex: activeIndex, indexOffset: headerInteractiveCount + middleNavigableCount, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderHeader: props.customRenderHeader, customRenderFooter: props.customRenderFooter, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, className: classnames(styles$1.persistentFooter, (_m = props.UNSAFE_className) === null || _m === void 0 ? void 0 : _m.footer), style: (_o = props.UNSAFE_styles) === null || _o === void 0 ? void 0 : _o.footer })))))));
}
function LoadingContent() {
    return (React.createElement("div", { className: styles$1.loadingList, onPointerDown: preventDefaultPointerDown },
        React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" }),
        React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" }),
        React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" })));
}
function EmptyStateMessage({ emptyState, }) {
    const emptyStateDefault = "No options";
    const emptyStateContent = emptyState !== null && emptyState !== void 0 ? emptyState : emptyStateDefault;
    return (React.createElement("div", { className: styles$1.emptyStateMessage, onPointerDown: preventDefaultPointerDown }, emptyStateContent));
}

var styles = {"autocomplete":"_7mObJiwfPh4-","options":"dL5JShAJlKM-","heading":"PWZL-94hH7k-","visible":"_2RzcnTdaPyc-","option":"y9zhi8Wr8QA-","active":"_3Xg49dtL1Q8-","separator":"LIeh390F3W8-","icon":"K2phy6IC3TY-","text":"a6-LbUm5WnY-","label":"tQNbuxcE9nU-","details":"qacStG9-XbE-","spinning":"P9cQDL4MZ-s-"};

const AUTOCOMPLETE_MAX_HEIGHT = 300;

function useRepositionMenu(attachTo, visible, cssManagedVisibility) {
    const { refs, floatingStyles, update } = floatingUi_react.useFloating(Object.assign({ placement: "bottom", middleware: [
            floatingUi_react.offset(8),
            floatingUi_react.flip({ fallbackPlacements: ["top"] }),
            floatingUi_react.size({
                apply({ availableHeight, elements }) {
                    const maxHeight$1 = maxHeight.calculateMaxHeight(availableHeight, {
                        maxHeight: AUTOCOMPLETE_MAX_HEIGHT,
                    });
                    Object.assign(elements.floating.style, {
                        maxHeight: `${maxHeight$1}px`,
                    });
                },
            }),
        ], elements: {
            reference: attachTo,
        } }, (!cssManagedVisibility
        ? {
            whileElementsMounted: floatingUi_react.autoUpdate,
        }
        : {})));
    // While DefaultMenu leverages conditional rendering, CustomMenu is hidden with CSS
    // We need to apply the correct update method to each case
    jobberHooks.useSafeLayoutEffect(() => {
        if (cssManagedVisibility && visible && attachTo && refs.floating.current) {
            const cleanup = floatingUi_react.autoUpdate(attachTo, refs.floating.current, update);
            return cleanup;
        }
        return undefined;
    }, [
        cssManagedVisibility,
        visible,
        attachTo,
        refs.floating.current,
        update,
        floatingUi_react.autoUpdate,
    ]);
    const targetWidth = attachTo === null || attachTo === void 0 ? void 0 : attachTo.clientWidth;
    return {
        menuRef: refs.floating.current,
        setMenuRef: refs.setFloating,
        targetWidth,
        styles: {
            float: floatingStyles,
        },
    };
}

function BaseAutocompleteMenuWrapperInternal({ setMenuRef, floatStyles, targetWidth, visible, children, }) {
    return (React.createElement("div", { className: classnames(styles.options, { [styles.visible]: visible }), ref: setMenuRef, style: Object.assign(Object.assign({}, floatStyles.float), { width: targetWidth }), "data-elevation": "elevated" }, children));
}
/**
 * Provides a wrapper for the Autocomplete menu that handles positioning and visibility.
 * @param attachTo - The element that the menu should be attached to.
 */
function useAutocompleteMenu({ attachTo, }) {
    const [menuRef, setMenuRef] = React.useState(null);
    const AutocompleteMenuWrapper = React.useCallback(({ children, visible, }) => {
        const menuFloatProps = useRepositionMenu(attachTo, visible, true);
        React.useEffect(() => {
            setMenuRef(menuFloatProps.menuRef);
        }, [menuFloatProps.menuRef]);
        return (React.createElement(BaseAutocompleteMenuWrapper, { floatStyles: menuFloatProps.styles, setMenuRef: menuFloatProps.setMenuRef, targetWidth: menuFloatProps.targetWidth, visible: visible }, children));
    }, [attachTo]);
    return { MenuWrapper: AutocompleteMenuWrapper, menuRef };
}
function BaseAutocompleteMenuWrapper(props) {
    const mounted = jobberHooks.useIsMounted();
    const menu = React.createElement(BaseAutocompleteMenuWrapperInternal, Object.assign({}, props));
    return mounted.current ? React.createElement(floatingUi_react.FloatingPortal, null, menu) : menu;
}

function isOptionSelected(selectedOption, option) {
    return Boolean(selectedOption && selectedOption.value === option.value);
}
/**
 * Helper function to determine if the option is a group. This is used to
 * determine if the option contains a list of options for rendering Section
 * Labels in the Autocomplete component.
 */
function isOptionGroup(option) {
    return "options" in option;
}

/**
 * The rendering of the default MenuOption
 */
function MenuOption({ isHighlighted, option, onOptionSelect, isSelected, addSeparators, UNSAFE_className = {}, UNSAFE_style = {}, }) {
    if (isOptionGroup(option)) {
        return (React.createElement(MenuGroupOptions, { UNSAFE_className: UNSAFE_className.groupOption, option: option, UNSAFE_style: UNSAFE_style.groupOption }));
    }
    return (React.createElement(BaseMenuOption, { UNSAFE_className: UNSAFE_className.option, UNSAFE_style: UNSAFE_style.option, option: option, isHighlighted: isHighlighted, onOptionSelect: onOptionSelect, addSeparators: addSeparators },
        React.createElement(MenuOptionContent, { option: option, isSelected: isSelected, UNSAFE_className: UNSAFE_className.content, UNSAFE_style: UNSAFE_style.content })));
}
function MenuOptionContent({ option, isSelected, UNSAFE_className = {}, UNSAFE_style = {}, }) {
    const iconClassName = classnames(styles.icon, UNSAFE_className.icon);
    const textClassName = classnames(styles.text, UNSAFE_className.text);
    const labelClassName = classnames(styles.label, UNSAFE_className.label);
    const detailsClassName = classnames(styles.details, UNSAFE_className.details);
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: iconClassName, style: UNSAFE_style.icon }, isSelected && React.createElement(Icon.Icon, { name: "checkmark", size: "small" })),
        React.createElement("div", { className: textClassName, style: UNSAFE_style.text },
            React.createElement("div", { className: labelClassName, style: UNSAFE_style.label },
                React.createElement(Text.Text, null, option.label),
                option.description !== undefined && (React.createElement(Text.Text, { variation: "subdued" }, option.description))),
            option.details !== undefined && (React.createElement("div", { className: detailsClassName, style: UNSAFE_style.details },
                React.createElement(Text.Text, null, option.details))))));
}
/**
 * The rendering of the default MenuGroupOption
 */
function MenuGroupOptions({ option, UNSAFE_className = {}, UNSAFE_style = {}, }) {
    return (React.createElement(BaseMenuGroupOption, { UNSAFE_className: UNSAFE_className.heading, UNSAFE_style: UNSAFE_style.heading },
        React.createElement(Heading.Heading, { level: 5 }, option.label)));
}
function BaseMenuGroupOption({ children, UNSAFE_className = "", UNSAFE_style = {}, }) {
    const headingClassName = classnames(styles.heading, UNSAFE_className);
    return (React.createElement("div", { className: headingClassName, style: UNSAFE_style }, children));
}
/**
 * Renders the base option component. The component takes children and renders them inside a button.
 */
function BaseMenuOption({ option, isHighlighted, onOptionSelect, addSeparators, children, UNSAFE_className = "", UNSAFE_style = {}, }) {
    const optionClass = classnames(styles.option, {
        [styles.active]: isHighlighted,
        [styles.separator]: addSeparators,
    }, UNSAFE_className);
    return (React.createElement("button", { role: "option", type: "button", className: optionClass, onMouseDown: onOptionSelect === null || onOptionSelect === void 0 ? void 0 : onOptionSelect.bind(undefined, option), style: UNSAFE_style }, children));
}

exports.KeyboardAction = void 0;
(function (KeyboardAction) {
    KeyboardAction[KeyboardAction["Previous"] = -1] = "Previous";
    KeyboardAction[KeyboardAction["Next"] = 1] = "Next";
    KeyboardAction[KeyboardAction["Select"] = 0] = "Select";
})(exports.KeyboardAction || (exports.KeyboardAction = {}));
/**
 * Hook to handle custom keyboard navigation for the Autocomplete component.
 * Use this hook if you are using components in the menu that aren't MenuOption or BaseMenuOption.
 */
function useCustomKeyboardNavigation({ onRequestHighlightChange, }) {
    jobberHooks.useOnKeyDown((event) => {
        onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Next);
    }, "ArrowDown");
    jobberHooks.useOnKeyDown((event) => {
        onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Previous);
    }, "ArrowUp");
    jobberHooks.useOnKeyDown((event) => {
        onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Select);
    }, "Enter");
}
/**
 * Hook to handle keyboard navigation for the Menu in the Autocomplete component.
 * If using components in the menu that aren't MenuOption or BaseMenuOption, you should use the `useCustomKeyboardNavigation` hook.
 */
function useKeyboardNavigation({ options, onOptionSelect, menuRef, visible, }) {
    const [highlightedIndex, setHighlightedIndex] = React.useState(0);
    const initialHighlight = options.some(isOptionGroup) ? 1 : 0;
    React.useEffect(() => setHighlightedIndex(initialHighlight), [options]);
    React.useEffect(() => {
        var _a, _b;
        (_b = (_a = menuRef === null || menuRef === void 0 ? void 0 : menuRef.children[highlightedIndex]) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, {
            behavior: "smooth",
            block: "nearest",
            inline: "start",
        });
    }, [highlightedIndex]);
    const onRequestHighlightChange = React.useCallback((event, direction) => {
        if (!visible)
            return;
        const indexChange = getRequestedIndexChange({
            event,
            options,
            direction,
            highlightedIndex,
        });
        switch (direction) {
            case exports.KeyboardAction.Previous:
                setHighlightedIndex(prev => Math.max(0, prev + indexChange));
                break;
            case exports.KeyboardAction.Next:
                setHighlightedIndex(prev => Math.min(options.length - 1, prev + indexChange));
                break;
            case exports.KeyboardAction.Select:
                if (isOptionGroup(options[highlightedIndex]))
                    return;
                onOptionSelect(options[highlightedIndex]);
                break;
        }
    }, [highlightedIndex, options, onOptionSelect, visible]);
    useCustomKeyboardNavigation({ onRequestHighlightChange });
    return { highlightedIndex };
}
/**
 * Function to get the requested index change based on the current highlighted index and the direction of the keyboard action.
 * Accounts for groups in the options array.
 */
function getRequestedIndexChange({ event, options, direction, highlightedIndex, }) {
    event.preventDefault();
    const requestedIndex = options[highlightedIndex + direction];
    return requestedIndex && isOptionGroup(requestedIndex)
        ? direction + direction
        : direction;
}

/**
 * Renders the default Menu for the Autocomplete component.
 */
function DefaultMenu({ options, selectedOption, onOptionSelect, attachTo, visible, }) {
    const { menuRef, setMenuRef, styles: floatStyles, targetWidth, } = useRepositionMenu(attachTo, visible, false);
    const detectSeparatorCondition = (option) => option.description || option.details;
    const addSeparators = options.some(detectSeparatorCondition);
    const { highlightedIndex } = useKeyboardNavigation({
        onOptionSelect,
        options,
        visible,
        menuRef,
    });
    return (React.createElement(BaseAutocompleteMenuWrapper, { setMenuRef, floatStyles, targetWidth, visible }, options === null || options === void 0 ? void 0 : options.map((option, index) => {
        return (React.createElement(MenuOption, { key: index, option: option, isHighlighted: index === highlightedIndex, onOptionSelect: onOptionSelect, isSelected: isOptionSelected(selectedOption, option), addSeparators: addSeparators }));
    })));
}

function Menu({ options, selectedOption, onOptionSelect, inputFocused, attachTo, inputRef, customRenderMenu, }) {
    if (customRenderMenu) {
        return (React.createElement(CustomMenu, { attachTo: attachTo, inputFocused: inputFocused, inputRef: inputRef, customRenderMenu: customRenderMenu, options: options, onOptionSelect: onOptionSelect, selectedOption: selectedOption }));
    }
    if (!inputFocused || !options.length)
        return null;
    return (React.createElement(DefaultMenu, { attachTo: attachTo, options: options, onOptionSelect: onOptionSelect, selectedOption: selectedOption, visible: inputFocused }));
}
/**
 * Renders the custom Menu for the Autocomplete component.
 * Provides the menuRef and MenuWrapper to the customRenderMenu function.
 */
function CustomMenu({ options, selectedOption, onOptionSelect, customRenderMenu, attachTo, inputFocused, inputRef, }) {
    const { MenuWrapper, menuRef } = useAutocompleteMenu({ attachTo });
    const menuContent = customRenderMenu({
        options,
        menuRef,
        onOptionSelect,
        selectedOption,
        inputFocused,
        MenuWrapper,
        inputRef,
    });
    return menuContent;
}

// Max statements increased to make room for the debounce functions
// eslint-disable-next-line max-statements
function AutocompleteInternal(_a, ref) {
    var _b;
    var { initialOptions = [], value, allowFreeForm = true, size = undefined, debounce: debounceRate = 300, onChange, getOptions, placeholder, onBlur, onFocus, validations, customRenderMenu } = _a, inputProps = tslib_es6.__rest(_a, ["initialOptions", "value", "allowFreeForm", "size", "debounce", "onChange", "getOptions", "placeholder", "onBlur", "onFocus", "validations", "customRenderMenu"]);
    const initialOptionsMemo = React.useMemo(() => mapToOptions(initialOptions), [initialOptions]);
    const [options, setOptions] = React.useState(initialOptionsMemo);
    const [inputFocused, setInputFocused] = React.useState(false);
    const [inputText, setInputText] = React.useState((_b = value === null || value === void 0 ? void 0 : value.label) !== null && _b !== void 0 ? _b : "");
    const [autocompleteRef, setAutocompleteRef] = React.useState(null);
    const delayedSearch = jobberHooks.useDebounce(updateSearch, debounceRate);
    const inputRef = React.useRef(null);
    React.useEffect(() => {
        delayedSearch();
    }, [inputText]);
    React.useEffect(() => {
        var _a;
        updateInput((_a = value === null || value === void 0 ? void 0 : value.label) !== null && _a !== void 0 ? _a : "");
    }, [value]);
    return (React.createElement("div", { className: styles.autocomplete, ref: setAutocompleteRef },
        React.createElement(InputText_index.InputText, Object.assign({ ref: FormField.mergeRefs([ref, inputRef]), autocomplete: false, size: size, value: inputText, onChange: handleInputChange, placeholder: placeholder, onFocus: handleInputFocus, onBlur: handleInputBlur, validations: validations }, inputProps)),
        React.createElement(Menu, { attachTo: autocompleteRef, inputRef: inputRef, inputFocused: inputFocused, options: options, customRenderMenu: customRenderMenu, selectedOption: value, onOptionSelect: handleMenuChange })));
    function updateInput(newText) {
        setInputText(newText);
        if (newText === "") {
            setOptions(mapToOptions(initialOptions));
        }
    }
    function updateSearch() {
        return tslib_es6.__awaiter(this, void 0, void 0, function* () {
            const updatedOptions = yield getOptions(inputText);
            const filteredOptions = updatedOptions.filter(option => isOptionGroup(option) ? option.options.length > 0 : true);
            setOptions(mapToOptions(filteredOptions));
        });
    }
    function handleMenuChange(chosenOption) {
        var _a;
        onChange(chosenOption);
        updateInput((_a = chosenOption === null || chosenOption === void 0 ? void 0 : chosenOption.label) !== null && _a !== void 0 ? _a : "");
        setInputFocused(false);
    }
    function handleInputChange(newText) {
        updateInput(newText);
        if (allowFreeForm) {
            onChange({ label: newText });
        }
    }
    function handleInputBlur() {
        setInputFocused(false);
        if (value == undefined || value.label !== inputText) {
            setInputText("");
            onChange(undefined);
        }
        onBlur && onBlur();
    }
    function handleInputFocus() {
        setInputFocused(true);
        if (onFocus) {
            onFocus();
        }
    }
}
function mapToOptions(items) {
    const retVal = items.reduce((result, item) => {
        result.push(item);
        if (isOptionGroup(item) && item.options) {
            result = result.concat(item.options);
        }
        return result;
    }, []);
    return retVal;
}
// Casts the Generics to the forward ref so autocomplete works as expected for consumers
const Autocomplete$1 = React.forwardRef(AutocompleteInternal);

// Convenience builder helpers (optional usage)
// Helper to improve inference from inline menu literals
function defineMenu(menu) {
    return menu;
}

function isNewAutocompleteProps(props) {
    return props.version === 2;
}
function AutocompleteShim(props, ref) {
    if (isNewAutocompleteProps(props)) {
        return (React.createElement(AutocompleteRebuilt, Object.assign({}, props, { ref: ref })));
    }
    return React.createElement(Autocomplete$1, Object.assign({}, props, { ref: ref }));
}
const AutocompleteForwarded = React.forwardRef(AutocompleteShim);
AutocompleteForwarded.displayName = "Autocomplete";
const Autocomplete = AutocompleteForwarded;

exports.Autocomplete = Autocomplete;
exports.BaseAutocompleteMenuWrapper = BaseAutocompleteMenuWrapper;
exports.BaseMenuGroupOption = BaseMenuGroupOption;
exports.BaseMenuOption = BaseMenuOption;
exports.MenuOption = MenuOption;
exports.defineMenu = defineMenu;
exports.getRequestedIndexChange = getRequestedIndexChange;
exports.isOptionGroup = isOptionGroup;
exports.isOptionSelected = isOptionSelected;
exports.useAutocompleteMenu = useAutocompleteMenu;
exports.useCustomKeyboardNavigation = useCustomKeyboardNavigation;
exports.useKeyboardNavigation = useKeyboardNavigation;
exports.useRepositionMenu = useRepositionMenu;
