/* @oracle/oraclejet-preact: undefined */
import { jsx, jsxs, Fragment } from 'preact/jsx-runtime';
import { forwardRef } from 'preact/compat';
import { useRef, useState, useImperativeHandle, useCallback, useEffect } from 'preact/hooks';
import { F as Flex } from './Flex-03129963.js';
import { L as Label } from './Label-5d1ae8d7.js';
import { u as useDisplayValue, S as SelectSingleField, a as SelectSingleFieldInput } from './useDisplayValue-65bbc74e.js';
import { S as Separator } from './Separator-93c70737.js';
import './logger-c92f309c.js';
import { T as TabbableModeContext } from './TabbableModeContext-7d8ad946.js';
import './LayerHost-7931b424.js';
import './UserAssistanceStyles.styles.css';
import './UNSAFE_UserAssistance/themes/redwood/UserAssistanceBaseTheme.styles.css';
import './UNSAFE_UserAssistance/themes/redwood/UserAssistanceVariants.css.js';
import { a as InlineUserAssistance } from './InlineUserAssistance-890293dd.js';
import './MessageBannerStyles.styles.css';
import './UNSAFE_MessageBanner/themes/redwood/MessageBannerBaseTheme.styles.css';
import './UNSAFE_MessageBanner/themes/redwood/MessageBannerVariants.css.js';
import 'preact';
import './TooltipContentStyles.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentBaseTheme.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentVariants.css.js';
import './tooltipUtils-af0abd38.js';
import './IconStyle.styles.css';
import './IconButton-7f91481c.js';
import './MessageStyles.styles.css';
import './MessageFormattingUtils-cdb25115.js';
import './TransitionGroup-5fd80dc9.js';
import './MessagesContext-76544845.js';
import './HiddenAccessibleStyles.styles.css';
import './ComponentMessageStyles.styles.css';
import './UNSAFE_ComponentMessage/themes/redwood/ComponentMessageBaseTheme.styles.css';
import './UNSAFE_ComponentMessage/themes/redwood/ComponentMessageVariants.css.js';
import { F as FormFieldContext } from './FormFieldContext-47ca0c20.js';
import './Popup-992b6c27.js';
import './LabelStyles.styles.css';
import './UNSAFE_Label/themes/redwood/LabelBaseTheme.styles.css';
import './UNSAFE_Label/themes/redwood/LabelVariants.css.js';
import './InputGroupContext-20bdbd6e.js';
import './UNSAFE_Popup/themes/redwood/PopupBaseTheme.styles.css';
import './UNSAFE_Popup/themes/redwood/PopupVariants.css.js';
import { V as View } from './View-5bdd9b3c.js';
import './FormContext-55fb8000.js';
import { u as useFormContext } from './useFormContext-bb9dc478.js';
import { u as useLoadingIndicatorTimer } from './useLoadingIndicatorTimer-898d4e3e.js';
import { u as useTextField } from './useTextField-eb9db737.js';
import { u as useTranslationBundle } from './useTranslationBundle-4822502f.js';
import { i as isControlOrFunctionKey, K as KEYS } from './keyboardUtils-986fe923.js';
import { a as allTabbableElements } from './tabbableUtils-c8311ec6.js';
import { U as UNSAFE_DOM_ACCESS } from './unsafeDomAccess-453eb74e.js';
import { h as isBeforeDataFetch, d as useSelectCommon, j as isSearchTextEmptyOrUndefined, f as isPhone, u as useCollectionRenderer, D as DefaultList, b as DropdownList, E as EmptyResults } from './useSelectCommon-a3c69d60.js';
import './useTestId-f24ac480.js';
import './classNames-4e12b00d.js';
import './boxalignment-8980856d.js';
import './size-af1e638c.js';
import './utils-b1eb54f9.js';
import './themeContract.css-1ffed3bf.js';
import './colorUtils-b3804ee8.js';
import './_curry1-63949a9b.js';
import './arrayUtils-35a58161.js';
import './boxalignment.styles.css';
import './vanilla-extract-sprinkles-createRuntimeSprinkles.esm-2d655d37.js';
import './dimensions-e4fbc23d.js';
import './flexbox-529f25da.js';
import './flexbox.styles.css';
import './flexitem-7b7f7920.js';
import './flexitem.styles.css';
import './mergeInterpolations-30cd9a69.js';
import './mergeDeepWithKey-33e3d1be.js';
import './_curry3-577eb45e.js';
import './_curry2-01c87f61.js';
import './_isObject-1fab0f5b.js';
import './FlexStyles.styles.css';
import './useFormFieldContext-daf7a676.js';
import './useComponentTheme-d2f9e47f.js';
import './useTooltip-94af94d4.js';
import './useTooltipControlled-f2cfa454.js';
import './useId-03dbfdf0.js';
import './useHover-85077adb.js';
import './useToggle-8b7fcefe.js';
import './useFocus-38c95977.js';
import './useTouch-4828df25.js';
import './mergeProps-88ea8306.js';
import './useAnimation-fe39685e.js';
import './useThemeInterpolations-e144e8ec.js';
import './useColorScheme-c4f6caab.js';
import './useScale-434ad939.js';
import './theme-63551f30.js';
import './Theme-e6dec6db.js';
import './useDensity-1acb0153.js';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentTheme.js';
import './hooks/UNSAFE_useTooltip/themes/TooltipContentStyles.css.js';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentBaseTheme.css.js';
import './TooltipContentVariants.styles.css';
import './vanilla-extract-recipes-createRuntimeFn.esm-2aaf8c98.js';
import './clientHints-a42b510c.js';
import './UNSAFE_Separator/themes/SeparatorStyles.css.js';
import './SeparatorStyles.styles.css';
import './CompactLabelAssistance-e2fcfcab.js';
import './useTabbableMode-090ed4b5.js';
import './Help-32a9689a.js';
import './Icon-4983d06e.js';
import './UNSAFE_Icon/themes/IconStyle.css.js';
import './useFocusWithin-30b1e2d8.js';
import './UNSAFE_UserAssistance/themes/UserAssistanceStyles.css.js';
import './UNSAFE_Label/themes/redwood/LabelTheme.js';
import './UNSAFE_Label/themes/LabelStyles.css.js';
import './UNSAFE_Label/themes/redwood/LabelBaseTheme.css.js';
import './truncationUtils-e37f95ee.js';
import './UNSAFE_TextField/themes/redwood/TextFieldTheme.js';
import './UNSAFE_TextField/themes/TextFieldStyles.css.js';
import './SkeletonStyles.styles.css';
import './TextFieldLoadingStyles.styles.css';
import './TextFieldStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/TextFieldBaseTheme.css.js';
import './UNSAFE_TextField/themes/redwood/TextFieldBaseTheme.styles.css';
import './UNSAFE_TextField/themes/redwood/TextFieldVariants.css.js';
import './TextFieldVariants.styles.css';
import './NavLeft-9bb41f35.js';
import './StyledTextField-7605d76a.js';
import './useAccessibleContext-5744de8b.js';
import './useTextFieldInputHandlers-8122048f.js';
import './formControlUtils-84e2af0e.js';
import './textAlign-ad252afa.js';
import './text.styles.css';
import './TextFieldUtils-8232bca7.js';
import './UNSAFE_TextField/themes/FormControlUtilsStyles.css.js';
import './FormControlUtilsStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/TextFieldInputTheme.js';
import './UNSAFE_TextField/themes/TextFieldInputStyles.css.js';
import './TextFieldInputStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/TextFieldInputVariants.css.js';
import './TextFieldInputVariants.styles.css';
import './LabelValueLayout-c6b9945a.js';
import './StyledLabelValueLayout-bb05f474.js';
import './LabelValueLayoutStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/FormLayoutTheme.js';
import './UNSAFE_TextField/themes/FormLayoutStyles.css.js';
import './UNSAFE_TextField/themes/redwood/FormLayoutBaseTheme.css.js';
import './UNSAFE_TextField/themes/redwood/FormLayoutBaseTheme.styles.css';
import './formControlUtils-6fc3a497.js';
import './LayoutStyles.css-6b02421a.js';
import './LayoutStyles.styles.css';
import './UNSAFE_Skeleton/themes/redwood/SkeletonTheme.js';
import './UNSAFE_Skeleton/themes/SkeletonStyles.css.js';
import './UNSAFE_Skeleton/themes/redwood/SkeletonBaseTheme.css.js';
import './UNSAFE_Skeleton/themes/redwood/SkeletonBaseTheme.styles.css';
import './UNSAFE_Skeleton/themes/redwood/SkeletonVariants.css.js';
import './useInputGroupContext-1d19411e.js';
import './useUser-06d34d19.js';
import './UNSAFE_TextField/themes/redwood/ReadonlyTextFieldTheme.js';
import './UNSAFE_TextField/themes/ReadonlyTextFieldStyles.css.js';
import './ReadonlyTextFieldStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/ReadonlyTextFieldVariants.css.js';
import './ReadonlyTextFieldVariants.styles.css';
import './ObfuscatedTextFieldInputStyles.styles.css';
import './ReadonlyTextFieldInputStyles.styles.css';
import './UNSAFE_TextField/themes/redwood/ReadonlyTextFieldInputVariants.css.js';
import './TextField-7884fcd7.js';
import './LiveRegionStyles.styles.css';
import './LiveRegion-cebac18d.js';
import './index-aec1cc7f.js';
import './UNSAFE_Layer/themes/LayerHostStyles.css.js';
import './LayerHostStyles.styles.css';
import './ComponentMessageContainer-d16c8b1f.js';
import './MessagesManager-47000438.js';
import './SuccessS-b5192d40.js';
import './ErrorS-3a890bf6.js';
import './InformationS-d53c2a91.js';
import './WarningS-3e53d87e.js';
import './PRIVATE_Message/themes/MessageStyles.css.js';
import './soundUtils-88264cb5.js';
import './useMessagesContext-9e1dbe91.js';
import './Transition-f9501682.js';
import './HiddenAccessible-61197e7c.js';
import './UNSAFE_ComponentMessage/themes/redwood/ComponentMessageTheme.js';
import './UNSAFE_ComponentMessage/themes/ComponentMessageStyles.css.js';
import './UNSAFE_ComponentMessage/themes/redwood/ComponentMessageBaseTheme.css.js';
import './UNSAFE_UserAssistance/themes/redwood/UserAssistanceTheme.js';
import './UNSAFE_UserAssistance/themes/redwood/UserAssistanceBaseTheme.css.js';
import './InlineHelp-9eaac91c.js';
import './MessageBannerVariants.styles.css';
import './EnvironmentProvider-6a0a8212.js';
import './LayerManager-52a26c55.js';
import './Floating-4a82db94.js';
import './useFloating-b9d680f7.js';
import './positionUtils-f26caad9.js';
import './refUtils-76275c69.js';
import './useOutsideClick-b777a43e.js';
import './Layer-535577b5.js';
import './UNSAFE_Layer/themes/LayerStyles.css.js';
import './LayerStyles.styles.css';
import './useModal-953082f2.js';
import './UNSAFE_Floating/themes/redwood/FloatingTheme.js';
import './UNSAFE_Floating/themes/FloatingStyles.css.js';
import './FloatingStyles.styles.css';
import './UNSAFE_Floating/themes/redwood/FloatingBaseTheme.css.js';
import './UNSAFE_Floating/themes/redwood/FloatingBaseTheme.styles.css';
import './UNSAFE_Floating/themes/redwood/FloatingVariants.css.js';
import './vanilla-extract-dynamic.esm-c909758c.js';
import './UNSAFE_Floating/themes/FloatingContract.css.js';
import './useUnsafeDomElementRef-32290273.js';
import './BaseButton-41068c85.js';
import './useActive-fb6d4d52.js';
import './UNSAFE_BaseButton/themes/redwood/BaseButtonTheme.js';
import './UNSAFE_BaseButton/themes/BaseButtonStyles.css.js';
import './BaseButtonStyles.styles.css';
import './UNSAFE_BaseButton/themes/redwood/BaseButtonVariants.css.js';
import './UNSAFE_BaseButton/themes/redwood/BaseButtonBaseTheme.styles.css';
import './BareButton-1e3df7cb.js';
import './useBareButton-ff4bd21e.js';
import './usePress-051f5adb.js';
import './usePressClick-945cc43b.js';
import './buttonUtils-55fb1df7.js';
import './id-83adac50.js';
import './ButtonLabelLayout-1631c997.js';
import './Text-834eb35e.js';
import './UNSAFE_Text/themes/TextStyles.css.js';
import './TextStyles.styles.css';
import './useButtonLabelLayoutTheme-448e671d.js';
import './UNSAFE_ButtonLabelLayout/themes/redwood/ButtonLabelLayoutTheme.js';
import './UNSAFE_ButtonLabelLayout/themes/ButtonLabelLayoutStyles.css.js';
import './ButtonLabelLayoutStyles.styles.css';
import './UNSAFE_ButtonLabelLayout/themes/redwood/ButtonLabelLayoutBaseTheme.css.js';
import './UNSAFE_ButtonLabelLayout/themes/redwood/ButtonLabelLayoutBaseTheme.styles.css';
import './UNSAFE_ButtonLabelLayout/themes/redwood/ButtonLabelLayoutVariants.css.js';
import './ButtonLabelLayoutVariants.styles.css';
import './getLocale-1c41e86a.js';
import './stringUtils-0fe25200.js';
import './FocusTrap-b59d5752.js';
import './FocusTracker-70300f1c.js';
import './PRIVATE_FocusTracker/themes/FocusTrackerStyles.css.js';
import './FocusTrackerStyles.styles.css';
import './Modal-c0f730b8.js';
import './UNSAFE_Modal/themes/ModalStyles.css.js';
import './ModalStyles.styles.css';
import './popupUtils-51366a29.js';
import './WindowOverlay-7264c44a.js';
import './UNSAFE_WindowOverlay/themes/WindowOverlayStyles.css.js';
import './WindowOverlayStyles.styles.css';
import './UNSAFE_WindowOverlay/themes/WindowOverlayContract.css.js';
import './UNSAFE_WindowOverlay/themes/redwood/WindowOverlayTheme.js';
import './UNSAFE_WindowOverlay/themes/redwood/WindowOverlayBaseTheme.css.js';
import './UNSAFE_WindowOverlay/themes/redwood/WindowOverlayBaseTheme.styles.css';
import './UNSAFE_WindowOverlay/themes/redwood/WindowOverlayVariants.css.js';
import './usePopupAnimation-96d2bc83.js';
import './useAnimationStatus-b881f39a.js';
import './popupAnimationUtils-175151d9.js';
import './UNSAFE_Popup/themes/PopupContract.css.js';
import './UNSAFE_Popup/themes/redwood/PopupTheme.js';
import './UNSAFE_Popup/themes/redwood/PopupBaseTheme.css.js';
import './PopupStyles.styles.css';
import './colors-03807160.js';
import './borders-98a63040.js';
import './padding-90265467.js';
import './aria-efa0582c.js';
import './equals-625352e8.js';
import './_isArray-694cc52d.js';
import './_isString-675f1de9.js';
import './useTimer-571e41e7.js';
import './useMessageSeverity-65295e8f.js';
import './useFormFieldContextProps-31bbc12f.js';
import './head-8f89fe66.js';
import './_arity-be492b9e.js';
import './HighlightText-0205faef.js';
import './HighlightTextStyles.styles.css';
import './Grid-9e4b4f19.js';
import './grid-65aa641c.js';
import './GridStyles.styles.css';
import './ListItemLayoutStyles.styles.css';
import './ListItemText-d001751c.js';
import './PRIVATE_SelectCommon/themes/dropdownStyles.css.js';
import './dropdownStyles.styles2.css';
import './List-4636ba9b.js';
import './keys-49c92dbb.js';
import './collectionUtils-5313629f.js';
import './Selector-23bccbe7.js';
import './BaseSelector-7cbc48bc.js';
import './StyledCheckbox-d6c8f557.js';
import './Check-ac39fe00.js';
import './CheckboxOff-3359a12d.js';
import './CheckboxOn-930b64de.js';
import './CheckboxMixed-c4594250.js';
import './UNSAFE_Checkbox/themes/CheckboxIconContract.css.js';
import './UNSAFE_Checkbox/themes/redwood/CheckboxIconTheme.js';
import './UNSAFE_Checkbox/themes/CheckboxIconStyles.css.js';
import './CheckboxIconStyles.styles.css';
import './UNSAFE_Checkbox/themes/redwood/CheckboxIconBaseTheme.css.js';
import './UNSAFE_Checkbox/themes/redwood/CheckboxIconBaseTheme.styles.css';
import './UNSAFE_Checkbox/themes/redwood/CheckboxIconVariants.css.js';
import './CheckboxIconVariants.styles.css';
import './StyledCheckbox.styles.css';
import './PRIVATE_BaseSelector/themes/SelectorStyles.css.js';
import './SelectorStyles.styles.css';
import './CollectionInteractionContext-7cf19abc.js';
import './useCollectionInteractionContext-3895c632.js';
import './LoadMoreCollection-d9f22790.js';
import './Collection-e1ef8b8d.js';
import './useViewportIntersect-6ff65310.js';
import './VirtualizedCollection-0160e675.js';
import './useNavigation-b257c33a.js';
import './useCurrentKey-5f865bbd.js';
import './useReorderableContext-79b1c941.js';
import './ReorderableContext-0daeea89.js';
import './useCollectionFocusRing-23ac7f97.js';
import './useTabbableModeSet-159b0279.js';
import './useInteractionStyle-99e32c23.js';
import './PRIVATE_List/themes/ListStyles.css.js';
import './ImageVars.styles.css';
import './ListStyles.styles.css';
import './Skeleton-d6f0969e.js';
import './ImageVars.css-7b3180c8.js';
import './useTheme-0e7497db.js';
import './useSelection-65134722.js';
import './textSelectionUtils-e87a47ff.js';
import './useAdditiveSelection-3ba8e3e3.js';
import './useItemAction-27b29f5c.js';
import './Inset-8afb9876.js';
import './UNSAFE_Inset/themes/InsetStyles.css.js';
import './InsetStyles.styles.css';
import './PRIVATE_List/themes/redwood/ListBaseTheme.styles.css';
import './CaretDown-4061aefc.js';

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
/**
 * A custom hook for determining prop values for the InlineSelectSingle's child
 * components from its own props.
 * @param param0 options
 * @param ref The ref handle of the component.
 */
function useInlineSelectSingle({ 'aria-describedby': ariaDescribedBy, assistiveText, data, hasBackIcon = 'never', hasClearIcon = 'never', helpSourceLink, helpSourceText, isLoading: propIsLoading, itemText, label, onBackIconAction, onCommit: propOnCommit, onFilter, placeholder, textAlign: propTextAlign, valueItem, virtualKeyboard }, ref) {
    const inputRef = useRef(null);
    const { textAlign: formTextAlign } = useFormContext();
    const textAlign = propTextAlign ?? formTextAlign ?? 'start';
    const isDataFetched = data != null && !isBeforeDataFetch(data);
    const isEmptyResults = isDataFetched && data?.totalSize === 0;
    // Refs to keep track of prop changes and sync internal state
    const prevDataRef = useRef(data);
    const prevValueItemRef = useRef(valueItem);
    const isInitialRender = useRef(true);
    // State for holding the selected keys in the list
    const [selectedKeys, setSelectedKeys] = useState(valueItem === undefined ? undefined : new Set([valueItem.key]));
    // The incoming propIsLoading tells us that we are in a loading state, but we don't want to
    // show the loading indicator until after a delay, because showing it immediately could result
    // in unwanted flashing.  The isLoading var below will be set to true by useLoadingIndicatorTimer
    // after the delay, when the timer expires, at which point we should show the loading indicator.
    // If propIsLoading is set to false before the timer expires, then the timer will be cancelled
    // and no loading indicator will be shown.
    // (ListView detects its loading state by checking data === null.  While it would be nice for
    // us to be consistent and check valueItems === null, we need to use a separate isLoading prop.
    // If valueItems === null triggers our loading state, then the selections in the dropdown
    // are cleared for that period of time, which is undesirable.)
    const isLoading = useLoadingIndicatorTimer(propIsLoading ?? false);
    const displayValue = useDisplayValue(itemText, valueItem, 'InlineSelectSingle');
    // add methods to the ref
    useImperativeHandle(ref, () => ({
        focus: () => inputRef.current?.focus(),
        blur: () => inputRef.current?.blur(),
        [UNSAFE_DOM_ACCESS]: inputRef.current
    }), []);
    const { currentRowKeyRef, currentRowOverride, dropdownRef, isFocused, isUserFiltering, onCurrentKeyChange, searchText, setCurrentRowOverride, stopFiltering, updateFiltering, userInput } = useSelectCommon({
        data,
        inputRef,
        // The component can only be in a focused visual state
        isFocused: true,
        onFilter
    });
    const { baseId, formFieldContext, inputProps, labelProps, userAssistanceProps } = useTextField({
        ariaDescribedBy,
        helpSourceLink,
        helpSourceText,
        isFocused,
        isLoading,
        value: valueItem !== undefined ? true : undefined
    });
    const listId = `${baseId}-list`;
    // If we're waiting for the selected values to load, the component should look like it
    // has a value in the meantime.
    // Use the original propIsLoading instead of isLoading because we don't want to delay
    // the inside label position by a timer like we do the progressive loading indicator.
    formFieldContext.hasValue = propIsLoading || formFieldContext.hasValue;
    const translations = useTranslationBundle('@oracle/oraclejet-preact');
    const liveRegionText = isDataFetched
        ? data?.totalSize === 0
            ? translations.select_noMatchesFound()
            : data?.totalSize === 1
                ? translations.select_oneMatchFound()
                : data?.sizePrecision === 'exact'
                    ? translations.select_sizeMatchesFound({ TOTAL_SIZE: `${data?.totalSize}` })
                    : translations.select_sizeOrMoreMatchesFound({ TOTAL_SIZE: `${data?.totalSize}` })
        : '';
    /**
     * Lifecycle updates
     */
    // When the valueItem changes, save the new selectedKeys
    if (prevValueItemRef.current !== valueItem) {
        prevValueItemRef.current = valueItem;
        setSelectedKeys(valueItem === undefined ? undefined : new Set([valueItem.key]));
    }
    // When data changes, highlight the first result
    if (prevDataRef.current !== data) {
        prevDataRef.current = data;
        // when filtering, set the first result of the filtered data set to be the current item
        // (check the data offset so we don't try to highlight again if the user scrolls through
        // the list and more data is fetched)
        if (isUserFiltering && data != null && data.offset === 0 && data.data.length > 0) {
            // if there are results and search text, highlight the first row, otherwise clear
            // an existing highlight
            setCurrentRowOverride({
                rowKey: !isSearchTextEmptyOrUndefined(searchText) ? data.data[0].metadata.key : undefined
            });
        }
    }
    // During the initial render, set the current row override if we have selected values.
    // This way pressing DOWN arrow will start the navigation from the selected row.
    if (isInitialRender.current) {
        isInitialRender.current = false;
        setCurrentRowOverride({ rowKey: [...(selectedKeys ?? [undefined])][0] });
    }
    /**
     * A helper onCommit wrapper that consumes the metadata and calls the
     * propOnCommit with only the necessary information.
     * (Similar to onCommit in useSelectSingle.ts)
     */
    const onCommit = useCallback((value, metadata) => {
        propOnCommit?.({
            value: value,
            previousValue: valueItem !== undefined ? valueItem.key : undefined,
            reason: metadata.reason
        });
    }, [propOnCommit, valueItem]);
    /**
     * A helper function to clear the selectedKeys and commits empty value.
     * (Similar to clearValue in useSelectSingle.ts but without dropdown related logic)
     */
    const clearValue = useCallback((metadata) => {
        setSelectedKeys(new Set());
        // call the onCommit callback so that the consuming code can update the valueItem
        onCommit(undefined, metadata);
    }, [onCommit]);
    /**
     * Determine if we need to clear the value because the user has deleted all the text.
     * (Similar to isClearValueNeeded in useSelectSingle.ts)
     */
    const isClearValueNeeded = useCallback(() => {
        return isUserFiltering && userInput === '' && valueItem !== undefined;
    }, [isUserFiltering, userInput, valueItem]);
    /**
     * Handler for List.onItemAction
     * (Similar to useSelectSingle.ts's onItemAction but without dropdown related logic)
     * This is used for handling:
     * - Commits value when one performs an action on the list
     */
    const handleItemAction = useCallback((detail) => {
        // after selecting a value, the user is no longer actively filtering, so update related
        // state accordingly so that the newly selected value appears in the field
        stopFiltering();
        const newKey = detail.context.key;
        // update the selectedKeys so that the selection visual state of the collection
        // updates immediately while waiting for a new valueItem to be set
        setSelectedKeys(new Set([newKey]));
        // call the onCommit callback so that the consuming code can update the valueItem
        onCommit(newKey, { reason: 'itemAction' });
    }, [onCommit, stopFiltering]);
    /**
     * Handler for SelectSingleFieldInput.onInput
     * This is used for handling:
     * - Typing in text in the field should filter the results (i.e. invoke onFilter with the text)
     */
    const handleFieldInput = useCallback(({ value }) => {
        updateFiltering(value);
        onFilter?.({ searchText: value });
    }, [onFilter, updateFiltering]);
    /**
     * Handler for SelectSingleFieldInput.onKeyDown
     * This is used for handling:
     * - Prevents default browser behavior on UP/DOWN to avoid scrolling
     * - Clears value or selects current row on ENTER
     * - Clears value or selects current row on TAB
     */
    const handleFieldKeyDown = useCallback((event) => {
        // ignore ctrl and fn key events
        if (isControlOrFunctionKey(event))
            return;
        switch (event.code) {
            case KEYS.UP:
            case KEYS.DOWN:
                // prevent the default action, since we do not want the page to scroll
                event.preventDefault();
                break;
            case KEYS.ENTER:
            case KEYS.TAB: {
                // if this is on a mobile device (only phone and not in tablet devices), do not do anything
                if (isPhone())
                    return;
                // Otherwise, proceed
                const commitMetadata = {
                    reason: event.code === KEYS.TAB ? 'tabKey' : 'itemAction'
                };
                // check to see if we need to clear the value
                if (isClearValueNeeded()) {
                    // in this case, clear the value and return.
                    clearValue(commitMetadata);
                    return;
                }
                // if there is no data to select, no need to handle this event
                if (data == null || data.data.length === 0)
                    return;
                // If we will be making a selection, the user is no longer actively filtering,
                // so update related state accordingly so that the newly selected value appears in the field.
                stopFiltering();
                // Current design have this component in a dropdown/modal. So, pressing Tab from
                // the main field without doing any other interaction is still considered a selection
                // unlike SelectSingle (see JET-68215). So, we handle both Enter and Tab similarly.
                // If there is a currentRow in the dropdown (meaning a highlighted item that would
                // have keyboard focus if the dropdown list had physical focus, which may be different
                // from the currently selected item), select it and commit it.
                if (currentRowKeyRef.current !== undefined && data != null && data.data.length > 0) {
                    setSelectedKeys(new Set([currentRowKeyRef.current]));
                    onCommit(currentRowKeyRef.current, commitMetadata);
                    return;
                }
                // Otherwise commit the currently selected value again so that a valueAction event
                // can be fired from the core-pack side.
                onCommit(valueItem?.key ?? undefined, commitMetadata);
                break;
            }
        }
    }, [clearValue, currentRowKeyRef, data, isClearValueNeeded, onCommit, stopFiltering, valueItem]);
    /**
     * Handler for SelectSingleFieldInput.onKeyUp
     * This is used for handling:
     * - Pressing UP/DOWN from the main field should move the focus to the list
     * - If Ctrl or Fn key is pressed, then ignore the event
     */
    const handleFieldKeyUp = useCallback((event) => {
        // ignore ctrl and fn key events
        if (isControlOrFunctionKey(event))
            return;
        switch (event.code) {
            case KEYS.UP:
            case KEYS.DOWN:
                // Transfer physical focus into the dropdown only if the data is present and the dropdown
                // has rendered the data. Otherwise, keep the focus in the field.
                if (data != null && dropdownRef.current) {
                    // get the focusable element from the dropdown.
                    // consider element with tabindex=-1 as well.
                    const firstFocusableElem = allTabbableElements(dropdownRef.current, undefined, true)[0];
                    // focus the first element if it exists
                    firstFocusableElem?.focus();
                    // set the first row as current row if there is no current row at the moment
                    if (currentRowOverride.rowKey === undefined) {
                        setCurrentRowOverride({ rowKey: data.data[0]?.metadata?.key });
                    }
                }
                // prevent the default action, since we are handling it
                event.preventDefault();
                break;
        }
    }, [currentRowOverride, data, dropdownRef, setCurrentRowOverride]);
    /**
     * Handler for DropdownList.onKeyDown
     * This is used for handling:
     * - Pressing Tab when highlighted on a list item should select & commit that item as value
     */
    const handleListKeyDown = useCallback((event) => {
        switch (event.code) {
            case KEYS.TAB:
                // if there is a currentRow in the dropdown, select it and commit it
                if (currentRowKeyRef.current !== undefined && data != null && data.data.length > 0) {
                    setSelectedKeys(new Set([currentRowKeyRef.current]));
                    onCommit(currentRowKeyRef.current, { reason: 'tabKey' });
                }
                break;
        }
    }, [currentRowKeyRef, data, onCommit]);
    /**
     * Handler for ClearButton.onClick
     * This is for handling:
     * - on clicking the clear icon, the value & selection should be cleared.
     */
    const handleClearButtonClick = useCallback(() => {
        // reset the user filter and the value of the component
        stopFiltering();
        // clear the value
        clearValue({ reason: 'itemAction' });
        // set focus to the input
        inputRef.current?.focus();
        // call onFilter with undefined
        onFilter?.({ searchText: undefined });
    }, [clearValue, onFilter, stopFiltering]);
    /**
     * Create collection Renderer context. This will be used by the default
     * collectionRenderer.
     */
    const collectionRendererContext = useCollectionRenderer({
        currentKey: currentRowOverride.rowKey,
        searchText,
        selectedKeys,
        onCurrentKeyChange,
        onItemAction: handleItemAction
    });
    // TODO: JET-73973 - ListView is not respecting TabbableMode
    // Currently List does not respect TabbableMode, so for now explicitly set tabindex="-1".
    // When this bug is fixed, this useEffect can be removed.
    useEffect(() => {
        const list = dropdownRef.current?.querySelector('div[role="listbox"][tabindex="0"]');
        list?.setAttribute('tabindex', '-1');
    });
    return {
        collectionRendererContext,
        formFieldContext,
        hasUserAssistance: Boolean(assistiveText || helpSourceLink),
        isEmptyResults,
        isUserFiltering,
        labelProps: {
            ...labelProps,
            children: label
        },
        listContainerProps: {
            id: listId,
            dropdownListRef: dropdownRef,
            onKeyDown: handleListKeyDown
        },
        selectSingleFieldProps: {
            contentVariant: 'input',
            // InlineSelectSingle currently only supports inside label.
            hasInsideLabel: true,
            isBackButtonShown: hasBackIcon === 'always',
            isClearButtonShown: hasClearIcon === 'conditionally' && valueItem !== undefined,
            onBackButtonClick: onBackIconAction,
            onClearButtonClick: handleClearButtonClick,
            styleVariant: 'embedded'
        },
        selectFieldInputProps: {
            ...inputProps,
            'aria-controls': listId,
            // InlineSelectSingle always have the list open, so it will always be in an expanded state.
            'aria-expanded': true,
            displayValue,
            // InlineSelectSingle currently only supports inside label,
            // so it is expected to always have a label.
            hasEmptyLabel: false,
            // InlineSelectSingle currently only supports inside label.
            hasInsideLabel: true,
            inputRef,
            // InlineSelectSingle currently does not support Add to List.
            isAddToListShown: false,
            // InlineSelectSingle currently does not support Advanced Search.
            isAdvancedSearchShown: false,
            // InlineSelectSingle currently does not support Required.
            isRequired: false,
            isUserFiltering,
            liveRegionText,
            onInput: handleFieldInput,
            onKeyDown: handleFieldKeyDown,
            onKeyUp: handleFieldKeyUp,
            placeholder,
            textAlign,
            userInput,
            variant: 'embedded',
            virtualKeyboard
        },
        userAssistanceProps: {
            ...userAssistanceProps,
            assistiveText,
            fieldLabel: label,
            helpSourceLink,
            helpSourceText
        }
    };
}

const PREVENT_TABBING = { isTabbable: false };
/**
 * A InlineSelectSingle is a text field with an inline list that supports single selection and search filtering.
 * Note: This is only meant to be used by the Spectra Smart Search component. As such, it only has limited features
 * needed for the Smart Search component.
 */
function InlineSelectSingleImpl(props, ref) {
    const { data, itemRenderer, itemText, label, onLoadRange, testId, userAssistancePosition = 'belowList' } = props;
    const { collectionRendererContext, formFieldContext, hasUserAssistance, isEmptyResults, isUserFiltering, labelProps, listContainerProps, selectSingleFieldProps, selectFieldInputProps, userAssistanceProps } = useInlineSelectSingle(props, ref);
    const defaultCollectionRenderer = useCallback(({ onPersistCurrentRowKey, onRowAction, selected, searchText, currentRowKeyOverride }) => (jsx(DefaultList, { "aria-label": label, componentName: "InlineSelectSingle", currentItemVariant: "highlight", currentKey: currentRowKeyOverride, data: data, itemRenderer: itemRenderer, itemText: itemText, onCurrentKeyChange: onPersistCurrentRowKey, onItemAction: onRowAction, onLoadRange: onLoadRange, searchText: isUserFiltering ? searchText : undefined, selectedKeys: selected, selectionMode: "single" })), [data, isUserFiltering, itemRenderer, itemText, label, onLoadRange]);
    const userAssistance = (jsx(View, { minWidth: "100%", padding: "2x", children: jsx(InlineUserAssistance, { testId: testId && `${testId}_userAssistance`, ...userAssistanceProps }) }));
    return (jsx(Flex, { direction: "column", gap: "2x", maxHeight: "100%", width: "100%", children: jsxs(FormFieldContext.Provider, { value: formFieldContext, children: [jsxs(View, { flex: 0, children: [jsx(SelectSingleField, { ...selectSingleFieldProps, label: jsx(Label, { ...labelProps }), testId: testId && `${testId}_selectSingleField`, children: jsx(SelectSingleFieldInput, { ...selectFieldInputProps }) }), userAssistancePosition === 'aboveList' && jsx(Separator, {}), userAssistancePosition === 'aboveList' && hasUserAssistance && (jsxs(Fragment, { children: [userAssistance, jsx(Separator, {})] }))] }), userAssistancePosition !== 'aboveList' && jsx(Separator, {}), jsx(DropdownList, { ...listContainerProps, 
                    // Add bottom gap only when we are configured to show UA above the list
                    hasBottomGap: userAssistancePosition === 'aboveList', hasTopGap: false, children: jsx(TabbableModeContext.Provider, { value: PREVENT_TABBING, children: isEmptyResults ? (jsx(EmptyResults, {})) : (defaultCollectionRenderer(collectionRendererContext)) }) }), userAssistancePosition === 'belowList' && hasUserAssistance && (jsxs("div", { children: [jsx(Separator, {}), userAssistance] }))] }) }));
}
const InlineSelectSingle = forwardRef(InlineSelectSingleImpl); // forwardRef will remove generics, so we cast it explicitly to preserve generics.;

export { InlineSelectSingle };
//# sourceMappingURL=UNSAFE_InlineSelectSingle.js.map
