/* @oracle/oraclejet-preact: undefined */
import { jsx, Fragment, jsxs } from 'preact/jsx-runtime';
import { useState, useCallback, useRef, useEffect, useId, useMemo } from 'preact/hooks';
import { m as mergeProps } from './mergeProps-88ea8306.js';
import { c as classNames } from './classNames-4e12b00d.js';
import { i as isMobile } from './clientUtils-71f2dbaf.js';
import { u as useId$1 } from './useId-03dbfdf0.js';
import { navigationListStyles } from './UNSAFE_NavigationList/themes/NavigationListStyles.css.js';
import { d as getPrevNextKeyUsingRef, k as keyExtractor, b as getFirstVisibleKey, a as getKey, f as findElementByKey } from './collectionUtils-5313629f.js';
import { u as useCollectionFocusRing } from './useCollectionFocusRing-23ac7f97.js';
import { u as useCurrentKey } from './useCurrentKey-5f865bbd.js';
import { u as useContextMenuGesture } from './useContextMenuGesture-e09f4c69.js';
import { u as useTranslationBundle } from './useTranslationBundle-4822502f.js';
import { g as getDefaultContextMenu, T as TabBarContextMenu } from './TabBarContextMenu-c3326d67.js';
import { forwardRef, useImperativeHandle } from 'preact/compat';
import { u as useTestId } from './useTestId-f24ac480.js';
import { H as HiddenAccessible } from './HiddenAccessible-61197e7c.js';
import { L as LiveRegion } from './LiveRegion-cebac18d.js';
import './UNSAFE_Text/themes/TextStyles.css.js';
import { a as NavigationListContext, B as BaseNavigationListItem } from './NavigationListLinkItem-e28fd846.js';
import './Flex-03129963.js';
import './logger-c92f309c.js';
import './BadgeStyles.styles.css';
import './UNSAFE_Badge/themes/redwood/BadgeThemeBaseTheme.styles.css';
import './UNSAFE_Badge/themes/redwood/BadgeVariants.css.js';
import 'preact';
import './LayerHost-7931b424.js';
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 './UNSAFE_NavigationList/themes/NavigationListItemStyles.css.js';
import './UNSAFE_NavigationList/themes/redwood/NavigationListItemBaseTheme.styles.css';
import './UNSAFE_NavigationList/themes/redwood/NavigationListItemVariants.css.js';
import './BaseButton-41068c85.js';
import './ButtonLabelLayout-1631c997.js';

const ITEM_SELECTOR = '[role="tab"]';
const REMOVE_ICON_SELECTOR = '[data-oj-navigationlist-item-remove-icon]';
const TOUCH_OFFSET_VALUE = 40;
const menuPropGestureStates = {
    mouse: {
        initialFocus: 'menu',
        placement: 'bottom-start',
        offsetValue: 0
    },
    keyboard: {
        initialFocus: 'firstItem',
        placement: 'bottom-start',
        offsetValue: 0
    },
    touch: {
        initialFocus: 'menu',
        placement: 'end',
        offsetValue: TOUCH_OFFSET_VALUE
    }
};
const initialMenuProps = {
    isOpen: false,
    initialFocus: 'menu',
    placement: 'bottom-start',
    offsetValue: 0,
    anchorRef: { current: null }
};
/*TODO: JET-58534. Create a hook to share some logic between navlist and tabbar. Hook will be used inside this one. */
function useNavigationList({ containerRef, selection, onRemove, onSelectionChange, children, contextMenuConfig }) {
    const translations = useTranslationBundle('@oracle/oraclejet-preact');
    const [currentKey, setCurrentKey] = useState(selection);
    const onCurrentKeyChange = useCallback((detail) => {
        setCurrentKey(detail.value);
    }, []);
    const { currentKeyProps } = useCurrentKey((element) => onRemove
        ? extractOnlyItemKey(element, ITEM_SELECTOR, REMOVE_ICON_SELECTOR)
        : keyExtractor(element, ITEM_SELECTOR), false, false, getPrevNextKeyUsingRef(containerRef, currentKey, true, ITEM_SELECTOR), getPrevNextKeyUsingRef(containerRef, currentKey, false, ITEM_SELECTOR), undefined, undefined, currentKey, onCurrentKeyChange);
    const [showFocusRing, focusRingProps] = useCollectionFocusRing(containerRef, [
        'Home',
        'End',
        'ArrowUp',
        'ArrowDown'
    ]);
    const onFocus = useCallback(() => {
        if (containerRef.current && currentKey === undefined) {
            const key = getFirstVisibleKey(containerRef.current, ITEM_SELECTOR);
            if (key) {
                setCurrentKey(key);
            }
        }
    }, [currentKey, containerRef]);
    const onFocusProps = { onFocus };
    const prevNavItems = useRef();
    useEffect(() => {
        if (containerRef.current) {
            const navListItemKeys = Array.from(containerRef.current.querySelectorAll(ITEM_SELECTOR), (elem) => getKey(elem));
            if (currentKey != null && navListItemKeys.indexOf(currentKey) !== -1) {
                const navListItem = findElementByKey(containerRef.current, currentKey, ITEM_SELECTOR);
                if (navListItem.scrollIntoViewIfNeeded) {
                    // for some browsers, we'll need the non-standard scrollIntoViewIfNeeded
                    navListItem.scrollIntoViewIfNeeded();
                }
                else {
                    navListItem.scrollIntoView({ block: 'nearest' });
                }
            }
            else {
                if (currentKey && navListItemKeys.indexOf(currentKey) === -1) {
                    prevNavItems.current
                        ? setCurrentKey(findNextCurrentKey(currentKey, navListItemKeys, prevNavItems.current))
                        : setCurrentKey(navListItemKeys[0]);
                }
                prevNavItems.current = navListItemKeys;
            }
        }
    }, [children, currentKey, containerRef]);
    const onKeyDown = useCallback((event) => {
        if ((event.key === 'Home' || event.key === 'End') && containerRef.current && currentKey) {
            const navListItemKey = Array.from(containerRef.current.querySelectorAll(ITEM_SELECTOR), (elem) => getKey(elem));
            onCurrentKeyChange?.({
                value: navListItemKey[event.key === 'Home' ? 0 : navListItemKey.length - 1]
            });
        }
        if (currentKey && (event.key === 'Enter' || event.key === ' ')) {
            // Prevent default to avoid page scrolling on Space (and native actions on Enter)
            event.preventDefault();
            onSelectionChange?.({
                value: currentKey,
                reason: 'keyboard'
            });
        }
        if (currentKey && event.key === 'Delete') {
            onRemove?.({ value: currentKey });
        }
    }, [currentKey, onSelectionChange, onRemove, onCurrentKeyChange, containerRef]);
    const [contextMenuContext, setContextMenuContext] = useState();
    const [menuProps, setMenuProps] = useState(initialMenuProps);
    const [accStatusInfo, setAccStatusInfo] = useState();
    const { triggerProps } = useContextMenuGesture(({ gesture, anchor, target }) => {
        let anchorBasedOnGesture = anchor;
        let itemKey = currentKey;
        if (gesture === 'keyboard') {
            //We find the element where the position of the menu is going to be based of
            const elem = findElementByKey(containerRef.current, currentKey, ITEM_SELECTOR);
            //We set the correct anchor
            anchorBasedOnGesture = elem ? elem : anchor;
        }
        else {
            //We search for the key using the target of the event
            const key = keyExtractor(target, ITEM_SELECTOR);
            //On touch devices, the keyExtractor returns null because target of touch event is the entire tabbar. Hence we make use of currentkey since the context menu is always launched from selected item and its key is currentKey
            itemKey = key != null ? key : currentKey;
        }
        let isRemovable = false;
        if (containerRef.current) {
            isRemovable = getItemAttribute(itemKey, containerRef.current, REMOVE_ICON_SELECTOR) != null;
        }
        const defaultContext = getDefaultContextMenu({
            // For default menu items the existence of REMOVE_ICON_SELECTOR is the indicator that it is removable because we render the default menu in touch devices not the application.
            // Furthermore in corepack due to delegations onRemove is always defined as it is a even handler hence not a good check for isRemovable.
            isRemovable: isRemovable,
            handleRemove: onRemove,
            handleReorder: undefined,
            itemKey: itemKey,
            tabKeys: undefined,
            // As direction is only needed for reorder to switch the labels
            direction: undefined,
            itemLabels: {
                labelRemove: isRemovable ? translations.tabbar_labelRemove() : undefined
            },
            handleAccStatus: (detail) => {
                const removeItemLabel = getItemLabel(detail.removedKey, containerRef.current);
                const removeStatus = isRemovable && detail.removedKey ? ` Removed ${removeItemLabel}` : '';
                setAccStatusInfo(removeStatus);
            }
        });
        setContextMenuContext(defaultContext);
        setMenuProps({
            ...menuPropGestureStates[gesture],
            anchorRef: { current: anchorBasedOnGesture },
            // This is set so that when no contextMenuConfig and when items is not removable we need not open it.
            isOpen: contextMenuConfig != null
        });
    }, {
        isDisabled: !contextMenuConfig //If there is no a context menu renderer we disable the hook
    });
    const handleCloseContextMenu = useCallback((detail) => {
        //Focus has to be set on the current target that was obtained
        //during context menu gesture when menu is dismissed or item is "selected"
        if (detail.reason === 'dismissed' || detail.reason === 'itemAction') {
            setCurrentKey(contextMenuContext?.itemKey);
            containerRef.current?.focus();
        }
        // We close the menu.The only prop that matters here is isOpen
        setMenuProps({ ...initialMenuProps });
    }, [containerRef, contextMenuContext?.itemKey]);
    const contextMenuDescriptionId = 'contextMenu_' + useId();
    const contextMenuDescription = translations.tabbar_labelContextMenu();
    return {
        showFocusRing,
        currentKey,
        onCurrentKeyChange,
        onKeyDown,
        menuProps: { ...menuProps, onClose: handleCloseContextMenu },
        contextMenuContext,
        contextMenuDescription,
        contextMenuDescriptionId,
        accStatusInfo,
        containerHandlers: mergeProps(focusRingProps, currentKeyProps, onFocusProps, triggerProps)
    };
}
// Utility that returns the value for a attribute related to the role="tab" item.
const getItemAttribute = (itemKey, root, attribute) => {
    const navItem = findElementByKey(root, itemKey, ITEM_SELECTOR);
    if (navItem) {
        const tabBarItemAttribute = navItem.querySelector(attribute);
        return tabBarItemAttribute;
    }
    return;
};
// Utility that returns the visible inner text inside the role="tab" item.
const getItemLabel = (itemKey, root) => {
    const tabBarItem = findElementByKey(root, itemKey, ITEM_SELECTOR);
    if (tabBarItem) {
        return tabBarItem.innerText;
    }
    return;
};
const extractOnlyItemKey = (element, itemSelector, itemEliminator) => {
    const navigationListItem = element.closest(itemSelector);
    const removeButton = element.closest(itemEliminator);
    return navigationListItem?.contains(removeButton) ? null : keyExtractor(element, itemSelector);
};
const findNextCurrentKey = (currentKey, currNavs, prevNavs) => {
    const index = prevNavs.indexOf(currentKey);
    if (index > 0) {
        const nextIndex = index === prevNavs.length - 1 ? index - 1 : index + 1;
        const nextKey = prevNavs[nextIndex];
        if (currNavs.indexOf(nextKey) !== -1) {
            return nextKey;
        }
    }
    // update current key to be the first one if we can't find a suitable next key
    return currNavs[0];
};

const NavigationList = forwardRef(({ children, selection, edge = 'start', onSelectionChange, onRemove, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelLedBy, testId, display = 'standard' }, ref) => {
    const containerRef = useRef(null);
    const isMobileDevice = isMobile();
    const defaultContextMenuConfig = useMemo(() => {
        return isMobileDevice
            ? {
                itemsRenderer: (context) => {
                    //Only if context is available, it is a mobile device and it is removable item, we will return remove context menu item
                    if (context) {
                        const isRemovableItem = getItemAttribute(context.itemKey, containerRef.current, REMOVE_ICON_SELECTOR) !=
                            null;
                        if (isRemovableItem) {
                            const defaultItems = context.defaultMenuItems;
                            return jsx(Fragment, { children: defaultItems });
                        }
                    }
                    return null;
                }
            }
            : undefined;
    }, [isMobileDevice]);
    const { showFocusRing, currentKey, onCurrentKeyChange, containerHandlers, onKeyDown, contextMenuContext, menuProps, contextMenuDescription, contextMenuDescriptionId, accStatusInfo } = useNavigationList({
        containerRef: containerRef,
        selection,
        onRemove,
        onSelectionChange,
        children,
        contextMenuConfig: defaultContextMenuConfig
    });
    const eventProps = { onKeyDown };
    const navigationListClass = classNames([navigationListStyles.uListStyle]);
    const navigationListItemPrefix = useId$1() + '_';
    const testIdProps = useTestId(testId);
    //Allows to call focus on rootRef without having to expose it
    useImperativeHandle(ref, () => ({
        focus: () => {
            if (containerRef.current) {
                containerRef.current.focus();
            }
        },
        blur: () => {
            if (containerRef.current) {
                containerRef.current.focus();
            }
        }
    }));
    return (jsxs(Fragment, { children: [jsx("div", { "aria-label": ariaLabel, "aria-labelledby": ariaLabelLedBy, role: "tablist", ref: containerRef, "aria-orientation": 'vertical', tabIndex: 0, "aria-activedescendant": currentKey ? navigationListItemPrefix + currentKey : '', ...mergeProps(eventProps, containerHandlers), ...testIdProps, class: navigationListClass, children: jsx(NavigationListContext.Provider, { value: {
                        selection,
                        display,
                        onSelectionChange,
                        onCurrentKeyChange,
                        currentKey,
                        showFocusRing,
                        navigationListItemPrefix,
                        onRemove,
                        edge
                    }, children: children }) }), defaultContextMenuConfig && contextMenuDescriptionId && contextMenuDescription && (jsx("span", { id: contextMenuDescriptionId, children: jsx(HiddenAccessible, { children: contextMenuDescription }) })), defaultContextMenuConfig && accStatusInfo && jsx(LiveRegion, { children: accStatusInfo }), defaultContextMenuConfig && (jsx(TabBarContextMenu, { ...menuProps, contextMenuConfig: defaultContextMenuConfig, contextMenuContext: contextMenuContext }))] }));
});

function NavigationListItem({ itemKey, label, badge, metadata, severity, icon }) {
    return (jsx(BaseNavigationListItem, { itemKey: itemKey, label: label, badge: badge, metadata: metadata, severity: severity, icon: icon }));
}

export { NavigationList as N, NavigationListItem as a };
//# sourceMappingURL=NavigationListItem-340ab770.js.map
