import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useCallback, memo } from 'react';
import Badge from '../badge';
import Box from '../box';
import Button from '../button';
import { omitThemingProps, vui } from '../core';
import Icon from '../icon';
import Popover from '../popover';
import T from '../t';
import { cs, generateMenuItemId } from '../utils';
import { collapsedWidth, expandedWidth } from './consts';
import useSidemenuItem from './useSidemenuItem';
const SidemenuItemContent = memo(({ icon, iconSize = 'sm', title, isMenuExpanded, badge, badgeLinkUrl }) => {
    // Calculate dynamic margins based on menu state
    const iconBaseMarginLeft = 13 / 8; // 1.625rem (13px)
    const iconMarginRight = isMenuExpanded
        ? 10 / 8 // 1.25rem (10px) when expanded
        : 20 / 8; // 2.5rem (20px) when collapsed
    return (_jsxs(_Fragment, { children: [_jsx(Box, { ml: iconBaseMarginLeft, mr: iconMarginRight, w: "20px", transition: "margin 0.2s ease-in-out", children: icon && _jsx(Icon, { name: icon, size: iconSize }) }), _jsx(T, { isTruncated: true, size: "sm", display: "inline-block", children: title }), badge && typeof badge === 'object' && typeof badge.text === 'string' && badge.text.trim() !== '' && (_jsx(Badge, { ...badge, "data-link": btoa(badgeLinkUrl ?? '#'), variant: badge.variant ?? 'subtleGreen', size: "sm", minW: "32px", fontSize: "12px", lineHeight: "16px", ml: "10px", mr: "10px" }))] }));
});
SidemenuItemContent.displayName = 'SidemenuItemContent';
/** A menu item. */
export const SidemenuItemV2 = vui((props, ref) => {
    const { children, className, disabled = false, icon, isActive = false, isExpanded = true, itemId, level = 0, onBottom = false, onClick, onCollapse, onExpand, title, ...rest } = omitThemingProps(props);
    // Use consistent itemId generation - prioritize provided itemId, then use utility function
    const computedItemId = itemId || generateMenuItemId(title, level) || `item-${Math.random().toString(36).substr(2, 9)}`;
    const { isDark, isMenuExpanded, styles, size, isSubmenuOpen, toggleSubmenu } = useSidemenuItem(computedItemId);
    // Use the isActive prop directly - parent should handle exact path matching
    const isExactlyActive = isActive;
    useEffect(() => {
        // Only call onExpand/onCollapse if the main menu is expanded
        // This prevents child items from expanding the main menu when it's collapsed
        if (isMenuExpanded) {
            if (isSubmenuOpen)
                onExpand?.();
            if (!isSubmenuOpen)
                onCollapse?.();
        }
    }, [isSubmenuOpen, onExpand, onCollapse, isMenuExpanded]);
    // Memoized computed values for better performance
    const computedStates = useMemo(() => {
        const hasChildren = !!children;
        const isSubmenuCollapsed = hasChildren && !isSubmenuOpen;
        // Only allow submenu expansion when main menu is expanded
        const isSubmenuExpanded = hasChildren && isSubmenuOpen && isMenuExpanded;
        const shouldShowExpandButton = hasChildren && isMenuExpanded;
        const buttonSize = level < 1 ? 'lg' : 'md';
        const iconSize = level < 1 ? 'sm' : 'xs';
        const states = {
            hasChildren,
            hasChildrenCollapsed: isSubmenuCollapsed,
            hasChildrenExpanded: isSubmenuExpanded,
            shouldShowExpandButton,
            buttonSize,
            iconSize,
            isDisabled: disabled,
            shouldShowBorder: !hasChildren || isSubmenuOpen,
        };
        return states;
    }, [children, isSubmenuOpen, isMenuExpanded, disabled, size, level]);
    // Memoized theme values to prevent recalculation
    const themeValues = useMemo(() => ({
        activeColor: isDark ? 'digiGreen.main' : 'seaBlue.main',
        buttonVariant: isDark ? 'menuDark' : 'menuLight',
    }), [isDark]);
    // Optimized stable callback
    const handleClick = useCallback((event) => {
        if (!computedStates.isDisabled) {
            const targetTag = event.target;
            if ((targetTag.classList.contains('vui-tagText') || targetTag.classList.contains('vui-tag')) &&
                typeof window !== 'undefined' &&
                (targetTag.parentElement?.dataset.link || targetTag?.dataset.link)) {
                const url = atob(targetTag.parentElement?.dataset.link ?? targetTag?.dataset.link ?? '');
                window.open(url, '_blank', 'noopener,noreferrer');
            }
            else {
                event?.stopPropagation?.();
                onClick?.();
            }
        }
        toggleSubmenu?.();
    }, [onClick, computedStates.isDisabled]);
    // Memoized button styles - Major performance improvement
    const buttonStyles = useMemo(() => ({
        // Get base item styles from theme
        ...(styles && 'item' in styles && styles.item ? styles.item : {}),
        // Dynamic border color based on active state
        borderLeftColor: isExactlyActive ? themeValues.activeColor : 'transparent',
        // Animation properties (enhanced from theme)
        transitionProperty: 'background-color, border-color, color, transform, opacity',
        // Button specific properties
        size: computedStates.buttonSize,
        h: computedStates.buttonSize === 'lg' ? 40 : 36,
        iconSize: computedStates.iconSize,
        variant: themeValues.buttonVariant,
        // Event handlers
        onClick: handleClick,
        disabled: computedStates.isDisabled,
        // Accessibility
        role: 'button',
        tabIndex: computedStates.isDisabled ? -1 : 0,
        'aria-disabled': computedStates.isDisabled,
        'aria-pressed': isExactlyActive,
        // Merge custom props
        ...rest,
    }), [
        // Dependencies grouped logically - simplified since computedStates contains most values
        styles,
        computedStates,
        isExactlyActive,
        themeValues,
        handleClick,
        rest,
    ]);
    // Memoized expand/collapse button properties
    const expandButtonProps = useMemo(() => {
        const isExpanded = isSubmenuOpen;
        const chevronIcon = isExpanded ? 'falChevronUp' : 'falChevronDown';
        const ariaLabel = isExpanded ? 'Collapse' : 'Expand';
        return {
            'aria-label': ariaLabel,
            className: 'vui-sidemenu-item-expand',
            variant: themeValues.buttonVariant,
            icon: chevronIcon,
            size: 'sm',
            pl: '4px',
            pr: '16px',
            ml: 'auto',
            h: '100%',
            border: 'none',
            bg: 'transparent',
            hoverBg: 'transparent',
            activeBg: 'transparent',
            hoverActiveBg: 'transparent',
        };
    }, [isSubmenuOpen, themeValues.buttonVariant]);
    return (_jsxs(Box, { flexDirection: "column", ref: ref, w: "100%", mt: onBottom ? 'auto' : 0, id: computedItemId, children: [!isMenuExpanded && children ? (_jsxs(Popover, { offset: [0, collapsedWidth - expandedWidth - 2], placement: "right-start", trigger: "mouseenter", children: [_jsx(Popover.Trigger, { as: Box, className: cs('vui-sidemenu-item-popover', className), children: _jsx(Box, { ...buttonStyles, borderLeft: `3px solid ${isDark ? 'digiGreen.main' : 'seaBlue.main'}`, children: _jsx(SidemenuItemContent, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded }) }) }), _jsx(Popover.Content, { elevation: "none", children: _jsx(Box, { flexDirection: "column", justifyContent: "start", w: "100%", children: children }) })] })) : (_jsxs(Button, { className: cs('vui-sidemenu-item', isExactlyActive && 'vui-sidemenu-item--active', className), ...buttonStyles, isActive: isExactlyActive, children: [_jsx(SidemenuItemContent, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded, badge: props.badge, badgeLinkUrl: props.badgeLinkUrl }), computedStates.shouldShowExpandButton && _jsx(Button, { ...expandButtonProps }), " "] })), computedStates.hasChildrenExpanded && (_jsx(Box, { flexDirection: "column", justifyContent: "start", w: "100%", children: children }))] }));
});
SidemenuItemV2.displayName = 'SidemenuItemV2';
export default SidemenuItemV2;
//# sourceMappingURL=sidemenuItemV2.js.map