import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment, useCallback, useContext, useMemo } from 'react';
import MetaList from '../MetaList';
import SummaryItem from '../SummaryItem';
import Flex from '../Flex';
import Icon, { registerIcon } from '../Icon';
import * as caretLeftIcon from '../Icon/icons/caret-left.icon';
import * as caretRightIcon from '../Icon/icons/caret-right.icon';
import * as checkIcon from '../Icon/icons/check.icon';
import Text from '../Text';
import { Count } from '../Badges';
import BareButton from '../Button/BareButton';
import { replaceMatchWithElement, withTestIds } from '../../utils';
import { useElement, useI18n, useDirection, useTestIds } from '../../hooks';
import Tooltip from '../Tooltip';
import Mark from '../Mark';
import Button from '../Button';
import menuHelpers from './helpers';
import MenuContext from './Menu.context';
import { StyledAncestors, StyledCheckMarkIcon, StyledMenuItem } from './Menu.styles';
import { getMenuItemTestIds } from './Menu.test-ids';
registerIcon(caretLeftIcon, caretRightIcon, checkIcon);
const DrillDown = ({ expandHandler }) => {
    const { end } = useDirection();
    const icon = _jsx(Icon, { name: `caret-${end}` });
    return expandHandler ? (_jsx(Button, { as: 'span', icon: true, variant: 'simple', "aria-hidden": true, onClick: expandHandler, children: icon })) : (icon);
};
const AncestorPath = ({ ancestors = [] }) => {
    const truncatedPath = ancestors.length > 2;
    const pathParts = truncatedPath ? [ancestors[0], ancestors[ancestors.length - 1]] : ancestors;
    const { end } = useDirection();
    return (_jsx(Flex, { container: { gap: 0.5, alignItems: 'center' }, as: StyledAncestors, title: ancestors.map(a => (menuHelpers.isItem(a) ? a.primary : a.label)).join(' > '), children: pathParts.map((ancestor, i, arr) => {
            const label = menuHelpers.isItem(ancestor) ? ancestor.primary : ancestor.label;
            return (_jsxs(Fragment, { children: [_jsx(Text, { variant: 'secondary', children: label }), i < arr.length - 1 && (_jsxs(_Fragment, { children: [_jsx(Text, { variant: 'secondary', children: _jsx(Icon, { name: `caret-${end}` }) }), truncatedPath && (_jsxs(_Fragment, { children: [_jsx(Text, { variant: 'secondary', children: "\u2026" }), _jsx(Text, { variant: 'secondary', children: _jsx(Icon, { name: `caret-${end}` }) })] }))] }))] }, ancestor.id));
        }) }));
};
const MenuItem = ({ testId, id, primary, secondary, ancestors, visual, count, items, selected, partial, href, tooltip, onClick, onExpand, disabled, role = 'menuitem', ...restProps }) => {
    const t = useI18n();
    const { mode, onItemClick, itemLayout, accent, variant: menuVariant, setFocusDescendant, getScopedItemId, arrowNavigationUnsupported } = useContext(MenuContext);
    const testIds = useTestIds(testId, getMenuItemTestIds);
    const selectionMode = mode === 'single-select' || mode === 'multi-select';
    const selectableParent = items && typeof selected === 'boolean';
    const itemId = useMemo(() => getScopedItemId(id), [id, getScopedItemId]);
    const itemCountId = `${id}-count`;
    const secondaryId = `${id}-secondary`;
    const clickHandler = useCallback((e) => {
        const mouseClick = e.detail > 0;
        if (mouseClick) {
            const target = e.target;
            const focusAtEl = target.getAttribute('role') === role ? target : target.closest(`li[role="${role}"]`);
            if (focusAtEl)
                setFocusDescendant(focusAtEl);
        }
        onClick?.(id, e);
        onItemClick?.(id, e);
    }, [onClick, onItemClick, id]);
    const expandHandler = useCallback((e) => {
        onExpand?.(id, e);
        e.stopPropagation();
    }, [onExpand, id]);
    let accentedPrimary;
    if (accent && !items) {
        const accentRegex = typeof accent === 'function' ? accent(primary) : accent;
        accentedPrimary = replaceMatchWithElement(primary, accentRegex, str => {
            return _jsx(Mark, { children: str });
        });
    }
    const secondaryContent = ancestors ? (_jsx(AncestorPath, { ancestors: ancestors })) : (secondary && _jsx(MetaList, { items: secondary, id: secondaryId }));
    const [summaryItemRef, setSummaryItemRef] = useElement();
    const summaryItem = (_jsxs(_Fragment, { children: [_jsx(SummaryItem, { ref: setSummaryItemRef, primary: accentedPrimary || (!items ? _jsx(Text, { children: primary }) : primary), secondary: secondaryContent, layout: itemLayout, visual: visual, actions: items || count ? (_jsxs(Flex, { container: { gap: 1, alignItems: 'center', justify: 'center' }, children: [count !== undefined && (_jsx(Count, { id: itemCountId, "aria-label": t('menu_item_count', [count]), children: count })), items && _jsx(DrillDown, { expandHandler: selectableParent ? expandHandler : undefined })] })) : undefined, container: {
                    colGap: 1
                } }), tooltip && (_jsx(Tooltip, { target: summaryItemRef, hideDelay: 'none', showDelay: 'short', children: tooltip }))] }));
    const itemLabel = useMemo(() => {
        const collapsedLabel = t('menu_collapsed', [primary]);
        if (items) {
            return arrowNavigationUnsupported
                ? t('menu_item_shift_space_expand_collapse', [collapsedLabel])
                : t('menu_item_expand_arrow', [collapsedLabel]);
        }
        return primary;
    }, [selected, primary, items]);
    const ariaDescribedBy = useMemo(() => {
        const hasSecondary = !!secondary;
        let idString;
        if (hasSecondary) {
            idString = secondaryId;
            if (count !== undefined && count >= 0) {
                idString = `${idString} ${itemCountId}`;
            }
        }
        else if (count !== undefined && count >= 0) {
            idString = itemCountId;
        }
        else
            idString = '';
        return idString;
    }, [items, secondary, itemCountId, secondaryId]);
    return (_jsxs(Flex, { "data-testid": testIds.root, ...restProps, container: { alignItems: 'center', justify: 'between', gap: 1 }, id: itemId, as: StyledMenuItem, "aria-label": itemLabel, "aria-describedby": ariaDescribedBy, role: role, "aria-disabled": disabled, "data-expand": !!items, itemLayout: itemLayout, tabIndex: -1, disabled: disabled, onMouseDown: (e) => {
            e.preventDefault();
        }, onClick: (e) => {
            if (disabled) {
                return;
            }
            return items && typeof selected !== 'boolean' ? expandHandler(e) : clickHandler(e);
        }, onMouseEnter: menuVariant === 'flyout' ? expandHandler : undefined, href: href, mode: mode, isParentItem: !!items, "aria-selected": !!selected, selectableParent: selectableParent, children: [selectionMode && (!items || selectableParent) && _jsx(StyledCheckMarkIcon, { name: 'check' }), href && !selectionMode ? (_jsx(BareButton, { href: href, tabIndex: '-1', children: summaryItem })) : (summaryItem)] }));
};
export default withTestIds(MenuItem, getMenuItemTestIds);
//# sourceMappingURL=MenuItem.js.map