/* @oracle/oraclejet-preact: undefined */
import { jsxs, jsx, Fragment } from 'preact/jsx-runtime';
import { u as useCurrentKey } from './useCurrentKey-5f865bbd.js';
import { d as getPrevNextKeyUsingRef, k as keyExtractor, c as getItemKeysArray, b as getFirstVisibleKey } from './collectionUtils-5313629f.js';
import { useContext, useCallback, useMemo, useRef, useState, useId, useEffect } from 'preact/hooks';
import { createContext } from 'preact';
import { E as Expander } from './Expander-1347e769.js';
import { F as Flex } from './Flex-03129963.js';
import { m as mergeProps } from './mergeProps-88ea8306.js';
import { u as usePress } from './usePress-051f5adb.js';
import { T as Text } from './Text-834eb35e.js';
import { B as Badge } from './Badge-a458c469.js';
import { S as SvgWarningS } from './WarningS-3e53d87e.js';
import { S as SvgErrorS } from './ErrorS-3a890bf6.js';
import { S as SvgInformationS } from './InformationS-d53c2a91.js';
import { S as SvgSuccessS } from './SuccessS-b5192d40.js';
import { u as useComponentTheme } from './useComponentTheme-d2f9e47f.js';
import { childItemVars } from './PRIVATE_CollapsibleNavigationList/themes/CollapsibleNavigationListItemContract.css.js';
import { NavigationListItemRedwoodTheme } from './PRIVATE_CollapsibleNavigationList/themes/redwood/CollapsibleNavigationListItemTheme.js';
import { u as useInteractionStyle } from './useInteractionStyle-99e32c23.js';
import { u as useUser } from './useUser-06d34d19.js';
import { c as classNames } from './classNames-4e12b00d.js';
import { m as mergeInterpolations } from './mergeInterpolations-30cd9a69.js';
import { f as flexitemInterpolations } from './flexitem-7b7f7920.js';
import { u as useCollectionFocusRing } from './useCollectionFocusRing-23ac7f97.js';
import { navigationListStyles } from './PRIVATE_CollapsibleNavigationList/themes/CollapsibleNavigationListStyles.css.js';
import './keys-49c92dbb.js';
import './clientHints-a42b510c.js';
import './Selector-23bccbe7.js';
import './BaseSelector-7cbc48bc.js';
import './useActive-fb6d4d52.js';
import './useToggle-8b7fcefe.js';
import './useFocus-38c95977.js';
import './useTestId-f24ac480.js';
import './LayerHost-7931b424.js';
import './index-aec1cc7f.js';
import 'preact/compat';
import './UNSAFE_Layer/themes/LayerHostStyles.css.js';
import './LayerHostStyles.styles.css';
import './useHover-85077adb.js';
import './StyledCheckbox-d6c8f557.js';
import './Check-ac39fe00.js';
import './Icon-4983d06e.js';
import './size-af1e638c.js';
import './utils-b1eb54f9.js';
import './themeContract.css-1ffed3bf.js';
import './colorUtils-b3804ee8.js';
import './_curry1-63949a9b.js';
import './useTooltip-94af94d4.js';
import './useTooltipControlled-f2cfa454.js';
import './useId-03dbfdf0.js';
import './useTouch-4828df25.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 './unsafeDomAccess-453eb74e.js';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentTheme.js';
import './hooks/UNSAFE_useTooltip/themes/TooltipContentStyles.css.js';
import './TooltipContentStyles.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentBaseTheme.css.js';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentBaseTheme.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentVariants.css.js';
import './TooltipContentVariants.styles.css';
import './vanilla-extract-recipes-createRuntimeFn.esm-2aaf8c98.js';
import './tooltipUtils-af0abd38.js';
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 './arrayUtils-35a58161.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 './logger-c92f309c.js';
import './UNSAFE_Icon/themes/IconStyle.css.js';
import './IconStyle.styles.css';
import './CheckboxOff-3359a12d.js';
import './CheckboxOn-930b64de.js';
import './CheckboxMixed-c4594250.js';
import './HiddenAccessible-61197e7c.js';
import './HiddenAccessibleStyles.styles.css';
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 './TabbableModeContext-7d8ad946.js';
import './useTabbableMode-090ed4b5.js';
import './StyledCheckbox.styles.css';
import './PRIVATE_BaseSelector/themes/SelectorStyles.css.js';
import './SelectorStyles.styles.css';
import './CollectionInteractionContext-7cf19abc.js';
import './useCollectionInteractionContext-3895c632.js';
import './EmbeddedIconButton-46434710.js';
import './BaseButton-41068c85.js';
import './dimensions-e4fbc23d.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 './usePressClick-945cc43b.js';
import './buttonUtils-55fb1df7.js';
import './id-83adac50.js';
import './ButtonLabelLayout-1631c997.js';
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 './ChevronDown-16a46328.js';
import './ChevronRight-f4ff20cb.js';
import './boxalignment-8980856d.js';
import './boxalignment.styles.css';
import './vanilla-extract-sprinkles-createRuntimeSprinkles.esm-2d655d37.js';
import './flexbox-529f25da.js';
import './flexbox.styles.css';
import './FlexStyles.styles.css';
import './UNSAFE_Text/themes/TextStyles.css.js';
import './TextStyles.styles.css';
import './UNSAFE_Badge/themes/redwood/BadgeTheme.js';
import './UNSAFE_Badge/themes/BadgeStyles.css.js';
import './BadgeStyles.styles.css';
import './UNSAFE_Badge/themes/redwood/BadgeThemeBaseTheme.css.js';
import './UNSAFE_Badge/themes/redwood/BadgeThemeBaseTheme.styles.css';
import './UNSAFE_Badge/themes/redwood/BadgeVariants.css.js';
import './BadgeVariants.styles.css';
import './PRIVATE_CollapsibleNavigationList/themes/NavigationListItemStyles.css.js';
import './NavigationListItemStyles.styles.css';
import './PRIVATE_CollapsibleNavigationList/themes/redwood/CollapsibleNavigationListItemBaseTheme.css.js';
import './PRIVATE_CollapsibleNavigationList/themes/redwood/CollapsibleNavigationListItemBaseTheme.styles.css';
import './PRIVATE_CollapsibleNavigationList/themes/redwood/CollapsibleNavigationListItemVariants.css.js';
import './CollapsibleNavigationListItemVariants.styles.css';
import './mergeDeepWithKey-33e3d1be.js';
import './_curry3-577eb45e.js';
import './_curry2-01c87f61.js';
import './_isObject-1fab0f5b.js';
import './flexitem.styles.css';
import './CollapsibleNavigationListStyles.styles.css';

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * Licensed under The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
/**
 * Context used to pass TabBar information without having to pass it to TabBar children props.
 * We want to communicate information down to any interested TabBar item children.
 */
const CollapsibleNavigationListContext = createContext(null);

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * Licensed under The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
/**
 * Utility hook for consuming the CollapsibleNavigationListContext
 *
 * @returns The value of CollapsibleNavigationListContext provider
 */
function useCollapsibleNavigationListContext() {
    return useContext(CollapsibleNavigationListContext);
}

const CollapsibleNavigationListItem = ({ item, level }) => {
    const isGroup = Array.isArray(item.children) && item.children.length > 0;
    const itemKey = item.itemKey;
    const label = item.label;
    const { selection, onToggle, onSelect, expandedKeys, showFocusRing, currentKey, navigationListItemPrefix } = useCollapsibleNavigationListContext();
    const isExpanded = isGroup && expandedKeys?.has(item.itemKey);
    const handlePress = useCallback(() => {
        onSelect?.({ value: item.itemKey });
        if (isGroup) {
            onToggle?.({ value: item.itemKey });
        }
    }, [itemKey, onSelect, onToggle, isGroup]);
    const { pressProps } = usePress(handlePress);
    const isCurrent = currentKey === itemKey;
    const isSelected = selection === itemKey;
    const { interactionProps, applyPseudoHoverStyle, applyHoverStyle, applyActiveStyle } = useInteractionStyle();
    const itemHandlers = { ...mergeProps(pressProps, interactionProps) };
    const itemId = navigationListItemPrefix + itemKey;
    const severityRequirement = !(item.severity === 'none' || item.severity === undefined);
    const isComplexItem = item.metadata || severityRequirement || item.badge;
    //Styling
    const flexItemStyleInterpolations = mergeInterpolations([
        ...Object.values(flexitemInterpolations)
    ]);
    const { class: labelContainerFlexItemClasses, ...labelContainerFlexItemStyle } = flexItemStyleInterpolations({
        alignSelf: 'center'
    });
    const { direction } = useUser();
    const isRtl = direction === 'rtl';
    const { classes: listItemClasses, styles: { labelContainerClasses, iconLabelContainer, iconContainer, navigationItemMetadata }, baseTheme } = useComponentTheme(NavigationListItemRedwoodTheme, {
        focusRing: showFocusRing ? 'isFocusRing' : 'notFocusRing',
        current: isCurrent ? 'isCurrent' : 'notCurrent',
        selected: isSelected ? 'isSelected' : 'notSelected',
        direction: isRtl ? 'isRtl' : 'notRtl',
        hybridHover: applyHoverStyle ? 'isHybridHover' : 'notHybridHover',
        pseudoHover: applyPseudoHoverStyle ? 'isPseudoHover' : 'notPseudoHover',
        active: applyActiveStyle ? 'isActive' : 'notActive'
    });
    const labelContainerStyle = labelContainerFlexItemStyle;
    const itemClasses = classNames([listItemClasses]);
    const navigationItemMatadata = classNames([navigationItemMetadata]);
    // const navigationItemLinkClass = classNames([navigationListItemLink]);
    const endIconContainerClasses = classNames([iconLabelContainer, iconContainer]);
    const indentation = calcIndentation(level);
    const IconComponent = (severityValue) => {
        switch (severityValue) {
            case 'error':
                return jsx(SvgErrorS, { color: "danger" });
            case 'warning':
                return jsx(SvgWarningS, { color: "warning" });
            case 'info':
                return jsx(SvgInformationS, { color: "info" });
            case 'confirmation':
                return jsx(SvgSuccessS, { color: "success" });
            default:
                return null;
        }
    };
    const labelRenderer = () => {
        return (jsx("span", { class: labelContainerClasses, style: labelContainerStyle, children: jsx(Text, { size: "inherit", weight: "inherit", variant: "inherit", children: label }) }));
    };
    const complexItemRenderer = () => {
        return (jsxs(Fragment, { children: [label && (jsx("span", { class: labelContainerClasses, style: labelContainerStyle, children: jsx(Text, { size: "inherit", weight: "inherit", variant: "inherit", children: label }) })), (item.metadata || severityRequirement || item.badge) && (jsxs(Flex, { gap: "2x", align: "center", justify: "end", flex: "1 1 auto", children: [' ', item.badge && (jsx("span", { class: endIconContainerClasses, children: jsx(Badge, { size: "md", variant: "neutralSubtle", children: item.badge }) })), item.metadata && (jsx("span", { class: navigationItemMatadata, children: jsx(Text, { children: '( ' + item.metadata + ' )' }) })), item.severityRequirement && (jsx("span", { class: endIconContainerClasses, children: IconComponent(item.severity) }))] }))] }));
    };
    const navlistItemRenderer = () => {
        return (jsx("div", { role: "treeitem", ...itemHandlers, "aria-expanded": isGroup ? isExpanded : undefined, "data-oj-key": itemKey, id: itemId, class: itemClasses, "aria-selected": isSelected, children: jsx("div", { style: { marginInlineStart: indentation, display: 'flex', alignItems: 'center' }, children: jsxs(Flex, { direction: "row", gap: "2x", align: "center", justify: "center", children: [isComplexItem ? complexItemRenderer() : labelRenderer(), isGroup && jsx(Expander, { itemKey: itemKey, expanded: isExpanded, onToggle: onToggle })] }) }) }));
    };
    return (jsxs("div", { class: baseTheme, children: [navlistItemRenderer(), isGroup && isExpanded && (jsx("div", { role: "group", children: item.children.map((child) => (jsx(CollapsibleNavigationListItem, { itemKey: child.itemKey, label: child.label, item: child, expandedKeys: expandedKeys, level: level + 1, onToggle: onToggle }))) }))] }));
};
const calcIndentation = (depth) => {
    return `calc(${Math.max(0, depth)} * ${childItemVars.childItemPadding} )`;
};

const CollapsibleNavigationList = ({ items, selection, expandedKeys, edge, onToggle, onSelect }) => {
    const groupKeys = useMemo(() => getGroupKeys(items), [items]);
    const rootRef = useRef(null);
    const [showFocusRing, focusRingProps] = useCollectionFocusRing(rootRef, [
        'ArrowUp',
        'ArrowDown',
        'Home',
        'End'
    ]);
    const onFocus = () => {
        if (rootRef.current && currentKey === undefined) {
            const key = getFirstVisibleKey(rootRef.current, ITEM_SELECTOR);
            if (key != null) {
                setCurrentKey(key);
            }
        }
    };
    const onKeyDown = (event) => {
        if (rootRef.current && currentKey != null) {
            if (event.key === 'Home' || event.key === 'End') {
                const tabBarItemKey = getItemKeysArray(rootRef.current, ITEM_SELECTOR);
                event.preventDefault();
                setCurrentKey?.(tabBarItemKey[event.key === 'Home' ? 0 : tabBarItemKey.length - 1]);
            }
            //Enter or space expands a collapsed node, collapses an expanded node and also triggers onSelect
            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                onSelect?.({ value: currentKey });
                if (groupKeys.has(currentKey)) {
                    onToggle?.({ value: currentKey });
                }
            }
            //ArrowRight only expands, if detected on a previously expanded node it remains expanded
            if (event.key === 'ArrowRight') {
                if (groupKeys.has(currentKey) &&
                    !(expandedKeys && expandedKeys.has(currentKey))) {
                    onToggle?.({ value: currentKey });
                }
            }
            //ArrowLeft only collapses, if detected on a previously collapsed node it remains collapsed
            if (event.key === 'ArrowLeft') {
                if (groupKeys.has(currentKey) && expandedKeys && expandedKeys.has(currentKey)) {
                    onToggle?.({ value: currentKey });
                }
            }
        }
    };
    const [currentKey, setCurrentKey] = useState(selection);
    const ITEM_SELECTOR = '[role="treeitem"]';
    const { currentKeyProps } = useCurrentKey((element) => {
        const key = keyExtractor(element, ITEM_SELECTOR);
        return key;
    }, false, false, getPrevNextKeyUsingRef(rootRef, currentKey, true, ITEM_SELECTOR), getPrevNextKeyUsingRef(rootRef, currentKey, false, ITEM_SELECTOR), undefined, undefined, currentKey, (detail) => {
        const key = detail.value;
        setCurrentKey(key);
    });
    const navListId = useId();
    const navigationListItemPrefix = navListId + '_';
    const collapsibleNavigationListContext = {
        selection: selection,
        onSelect: onSelect,
        onToggle: onToggle,
        expandedKeys,
        edge,
        showFocusRing,
        currentKey: currentKey,
        navigationListItemPrefix
    };
    useEffect(() => {
        if (rootRef.current) {
            const itemKeys = getItemKeysArray(rootRef.current, ITEM_SELECTOR);
            if (currentKey == null && itemKeys) {
                if (selection != null && itemKeys.includes(selection)) {
                    setCurrentKey(selection);
                }
                else if (itemKeys.length > 0) {
                    setCurrentKey(itemKeys[0]);
                }
            }
        }
    }, [items, currentKey, rootRef, selection]);
    const eventProps = { onKeyDown, onFocus };
    //Styling
    const navigationListClass = classNames([navigationListStyles.uListStyle]);
    return (jsx(CollapsibleNavigationListContext.Provider, { value: collapsibleNavigationListContext, children: jsx("div", { role: "tree", class: navigationListClass, ref: rootRef, ...mergeProps(currentKeyProps, focusRingProps, eventProps), tabindex: 0, "aria-activedescendant": currentKey ? navigationListItemPrefix : '', children: items.map((item) => (jsx(CollapsibleNavigationListItem, { itemKey: item.itemKey, item: item, expandedKeys: expandedKeys, level: 0, label: item.label, onToggle: onToggle }))) }) }));
};
// Helper to extract all group item keys from items tree
const getGroupKeys = (items) => {
    const groupKeys = new Set();
    const visited = new Set();
    const keysArray = [...items];
    while (keysArray.length) {
        const item = keysArray.pop();
        if (visited.has(item?.itemKey))
            continue;
        visited.add(item?.itemKey);
        if (Array.isArray(item?.children) && item?.children.length > 0) {
            groupKeys.add(item.itemKey);
            keysArray.push(...item.children);
        }
    }
    return groupKeys;
};

export { CollapsibleNavigationList };
//# sourceMappingURL=PRIVATE_CollapsibleNavigationList.js.map
