import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { createElement as _createElement } from "react";
import { isValidElement, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useTheme, useArrows, useConsolidatedRef, useDirection, useUID, useI18n, useEscape } from '../../hooks';
import ExpandCollapse from '../ExpandCollapse';
import BareButton from '../Button/BareButton';
import Flex from '../Flex';
import Icon, { registerIcon } from '../Icon';
import Text from '../Text';
import Button from '../Button';
import Link from '../Link';
import * as timesIcon from '../Icon/icons/times.icon';
import * as checkIcon from '../Icon/icons/check.icon';
import * as caretLeftIcon from '../Icon/icons/caret-left.icon';
import * as caretRightIcon from '../Icon/icons/caret-right.icon';
import NavigationListItemWrapper from './NavigationListItemWrapper';
import { StyledNavList, StyledNestedNavList, StyledNavItemIconBox, StyledNavListItem, StyledNavListItemExpandCollapse, StyledCaseClose, StyledSingleSelectIconBox, StyledNavListItemVisualContainer } from './AppShell.styles';
import AppShellContext from './AppShellContext';
registerIcon(timesIcon, checkIcon, caretLeftIcon, caretRightIcon);
const NavigationMenu = props => {
    const { navOpen } = useContext(AppShellContext);
    const { visual, primary, secondary, href, onClick, items, onDismiss, actions, forwardedRef, ...restProps } = props;
    const uid = useUID();
    const { navState } = useContext(AppShellContext);
    const [collapsed, setCollapsed] = useState(true);
    const toggleCollapsed = useCallback((e) => {
        e.stopPropagation();
        setCollapsed(state => !state);
    }, [setCollapsed]);
    const itemRef = useConsolidatedRef(forwardedRef);
    const menuRef = useRef(null);
    useArrows(menuRef, { selector: '[role="menuitem"]', cycle: true });
    useEscape(() => {
        setCollapsed(true);
        itemRef.current?.focus();
    }, menuRef);
    const { end } = useDirection();
    return (_createElement(StyledNavListItem, { ...restProps, key: primary, nestedListCollapsed: collapsed, ref: menuRef },
        _jsxs(BareButton, { id: uid, ref: itemRef, "aria-expanded": !collapsed, "aria-controls": `${uid}-menu`, "aria-label": primary, onClick: toggleCollapsed, children: [visual && _jsx(StyledNavItemIconBox, { children: visual }), secondary ? (_jsxs(Flex, { container: { direction: 'column', alignItems: 'start' }, children: [_jsx("span", { children: primary }), _jsx(Text, { variant: 'secondary', children: secondary })] })) : (_jsx("span", { children: primary })), navState === 'open' && _jsx(StyledNavListItemExpandCollapse, { name: `caret-${end}` })] }),
        _jsx(NavigationList, { id: `${uid}-menu`, nestedList: true, items: items, collapsed: !navOpen || collapsed })));
};
export const NavigationListItem = ({ visual, primary, secondary, collapsedItemInfo, href, onClick, items, collapseItems = false, onDismiss, actions, forwardedRef, isMenuItem, count, singleSelect, selected, 'aria-labelledby': ariaLabelledBy, 'aria-current': ariaCurrent, ...restProps }) => {
    const { navOpen, navState } = useContext(AppShellContext);
    const t = useI18n();
    const listItemRef = useConsolidatedRef(forwardedRef);
    const [menuState, setMenuState] = useState('');
    const hasItems = (Array.isArray(items) && items.length > 0) || (Array.isArray(actions) && actions.length > 0);
    const compProps = {
        onClick: (e) => {
            e.stopPropagation();
            onClick?.(e);
        },
        href
    };
    let caseItems;
    if (onDismiss) {
        caseItems = [
            {
                primary: t('go_to_noun', [primary]),
                onClick
            },
            {
                primary: t('dismiss_case'),
                onClick: onDismiss
            }
        ];
    }
    let Component;
    if (href) {
        Component = Link;
    }
    else {
        Component = BareButton;
    }
    useEffect(() => {
        if (!navOpen && actions) {
            const node = document.getElementsByTagName('body')[0];
            const clickEvent = document.createEvent('MouseEvent');
            clickEvent.initEvent('mousedown', true, true);
            node.dispatchEvent(clickEvent);
        }
        if (navOpen && isMenuItem && listItemRef.current?.parentElement?.matches(':first-child'))
            listItemRef.current?.focus();
    }, [navOpen]);
    const { end } = useDirection();
    const primaryId = useUID();
    return (_createElement(StyledNavListItem, { ...restProps, key: primary, singleSelect: singleSelect, nestedListCollapsed: true },
        _jsx(NavigationListItemWrapper, { tooltipLabel: secondary ? `${primary} ${secondary}` : primary, label: primary, childElementRef: listItemRef, items: actions || items || caseItems, onMenuToggle: setMenuState, children: _jsxs(Component, { ...compProps, ref: listItemRef, ...(navOpen && isMenuItem ? { tabIndex: -1, role: 'menuitem' } : {}), "aria-labelledby": `${primaryId} ${count ? `${primary}-count` : ''} ${ariaLabelledBy ?? ''}`, ...(hasItems && { 'aria-haspopup': 'menu', 'aria-expanded': menuState === 'open' }), "aria-current": ariaCurrent, children: [singleSelect && (_jsx(Flex, { container: { justify: 'center', alignItems: 'center' }, as: StyledSingleSelectIconBox, children: selected && _jsx(Icon, { name: 'check' }) })), visual && (_jsxs(Flex, { container: { direction: 'column', gap: 0.5 }, as: StyledNavListItemVisualContainer, isCurrent: ariaCurrent === 'page', children: [_jsx(StyledNavItemIconBox, { children: visual }), !navOpen && collapsedItemInfo && (_jsx(Text, { variant: 'secondary', children: collapsedItemInfo }))] })), secondary ? (_jsxs(Flex, { container: { direction: 'column', alignItems: 'start' }, item: { shrink: 0 }, as: 'span', children: [_jsx("span", { id: primaryId, children: primary }), _jsx(Text, { variant: 'secondary', children: secondary })] })) : (_jsx("span", { id: primaryId, children: primary })), (hasItems || actions) && navState === 'open' && (_jsx(StyledNavListItemExpandCollapse, { name: `caret-${end}` }))] }) }),
        onDismiss && navOpen && (_jsx(Button, { icon: true, variant: 'simple', as: StyledCaseClose, onClick: onDismiss, "aria-label": t('dismiss_case'), children: _jsx(Icon, { name: 'times' }) })),
        hasItems && (
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        _jsx(NavigationList, { nestedList: true, items: actions || items, collapsed: !navOpen || collapseItems }))));
};
const NavigationList = ({ items = [], nestedList, id, collapsed, singleSelect }) => {
    let Component = StyledNavList;
    let ItemComponent;
    const { navOpen } = useContext(AppShellContext);
    let fwdProps = {
        collapsed: !!collapsed
    };
    const { base: { animation } } = useTheme();
    if (nestedList) {
        fwdProps = {
            as: ExpandCollapse,
            forwardedAs: 'ul',
            nullWhenCollapsed: true,
            transitionSpeed: items.length >= 10 ? `calc(2 * ${animation.speed})` : animation.speed,
            ...fwdProps
        };
        Component = StyledNestedNavList;
    }
    return (_jsx(Component, { ...(nestedList ? { role: 'menu', id } : {}), ...fwdProps, children: items.map(item => {
            if (isValidElement(item))
                return item;
            if (item.items && item.items.length > 0 && navOpen) {
                ItemComponent = NavigationMenu;
            }
            else {
                ItemComponent = NavigationListItem;
            }
            return (_jsx(ItemComponent, { isMenuItem: nestedList, singleSelect: singleSelect, "aria-current": item['aria-current'], ...item }, item.id || item.primary));
        }) }));
};
export default NavigationList;
//# sourceMappingURL=NavigationList.js.map