"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SidemenuItemV2 = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const badge_1 = __importDefault(require("../badge"));
const box_1 = __importDefault(require("../box"));
const button_1 = __importDefault(require("../button"));
const core_1 = require("../core");
const icon_1 = __importDefault(require("../icon"));
const popover_1 = __importDefault(require("../popover"));
const t_1 = __importDefault(require("../t"));
const utils_1 = require("../utils");
const consts_1 = require("./consts");
const useSidemenuItem_1 = __importDefault(require("./useSidemenuItem"));
const SidemenuItemContent = (0, react_1.memo)(({ icon, iconSize = 'sm', title, isMenuExpanded, badge, badgeLinkUrl }) => {
    var _a;
    // 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 ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(box_1.default, { ml: iconBaseMarginLeft, mr: iconMarginRight, w: "20px", transition: "margin 0.2s ease-in-out", children: icon && (0, jsx_runtime_1.jsx)(icon_1.default, { name: icon, size: iconSize }) }), (0, jsx_runtime_1.jsx)(t_1.default, { isTruncated: true, size: "sm", display: "inline-block", children: title }), badge && typeof badge === 'object' && typeof badge.text === 'string' && badge.text.trim() !== '' && ((0, jsx_runtime_1.jsx)(badge_1.default, Object.assign({}, badge, { "data-link": btoa(badgeLinkUrl !== null && badgeLinkUrl !== void 0 ? badgeLinkUrl : '#'), variant: (_a = badge.variant) !== null && _a !== void 0 ? _a : 'subtleGreen', size: "sm", minW: "32px", fontSize: "12px", lineHeight: "16px", ml: "10px", mr: "10px" })))] }));
});
SidemenuItemContent.displayName = 'SidemenuItemContent';
/** A menu item. */
exports.SidemenuItemV2 = (0, core_1.vui)((props, ref) => {
    const _a = (0, core_1.omitThemingProps)(props), { children, className, disabled = false, icon, isActive = false, isExpanded = true, itemId, level = 0, onBottom = false, onClick, onCollapse, onExpand, title } = _a, rest = __rest(_a, ["children", "className", "disabled", "icon", "isActive", "isExpanded", "itemId", "level", "onBottom", "onClick", "onCollapse", "onExpand", "title"]);
    // Use consistent itemId generation - prioritize provided itemId, then use utility function
    const computedItemId = itemId || (0, utils_1.generateMenuItemId)(title, level) || `item-${Math.random().toString(36).substr(2, 9)}`;
    const { isDark, isMenuExpanded, styles, size, isSubmenuOpen, toggleSubmenu } = (0, useSidemenuItem_1.default)(computedItemId);
    // Use the isActive prop directly - parent should handle exact path matching
    const isExactlyActive = isActive;
    (0, react_1.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 === null || onExpand === void 0 ? void 0 : onExpand();
            if (!isSubmenuOpen)
                onCollapse === null || onCollapse === void 0 ? void 0 : onCollapse();
        }
    }, [isSubmenuOpen, onExpand, onCollapse, isMenuExpanded]);
    // Memoized computed values for better performance
    const computedStates = (0, react_1.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 = (0, react_1.useMemo)(() => ({
        activeColor: isDark ? 'digiGreen.main' : 'seaBlue.main',
        buttonVariant: isDark ? 'menuDark' : 'menuLight',
    }), [isDark]);
    // Optimized stable callback
    const handleClick = (0, react_1.useCallback)((event) => {
        var _a, _b, _c, _d, _e;
        if (!computedStates.isDisabled) {
            const targetTag = event.target;
            if ((targetTag.classList.contains('vui-tagText') || targetTag.classList.contains('vui-tag')) &&
                typeof window !== 'undefined' &&
                (((_a = targetTag.parentElement) === null || _a === void 0 ? void 0 : _a.dataset.link) || (targetTag === null || targetTag === void 0 ? void 0 : targetTag.dataset.link))) {
                const url = atob((_d = (_c = (_b = targetTag.parentElement) === null || _b === void 0 ? void 0 : _b.dataset.link) !== null && _c !== void 0 ? _c : targetTag === null || targetTag === void 0 ? void 0 : targetTag.dataset.link) !== null && _d !== void 0 ? _d : '');
                window.open(url, '_blank', 'noopener,noreferrer');
            }
            else {
                (_e = event === null || event === void 0 ? void 0 : event.stopPropagation) === null || _e === void 0 ? void 0 : _e.call(event);
                onClick === null || onClick === void 0 ? void 0 : onClick();
            }
        }
        toggleSubmenu === null || toggleSubmenu === void 0 ? void 0 : toggleSubmenu();
    }, [onClick, computedStates.isDisabled]);
    // Memoized button styles - Major performance improvement
    const buttonStyles = (0, react_1.useMemo)(() => (Object.assign(Object.assign(Object.assign({}, (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 }), rest)), [
        // Dependencies grouped logically - simplified since computedStates contains most values
        styles,
        computedStates,
        isExactlyActive,
        themeValues,
        handleClick,
        rest,
    ]);
    // Memoized expand/collapse button properties
    const expandButtonProps = (0, react_1.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 ((0, jsx_runtime_1.jsxs)(box_1.default, { flexDirection: "column", ref: ref, w: "100%", mt: onBottom ? 'auto' : 0, id: computedItemId, children: [!isMenuExpanded && children ? ((0, jsx_runtime_1.jsxs)(popover_1.default, { offset: [0, consts_1.collapsedWidth - consts_1.expandedWidth - 2], placement: "right-start", trigger: "mouseenter", children: [(0, jsx_runtime_1.jsx)(popover_1.default.Trigger, { as: box_1.default, className: (0, utils_1.cs)('vui-sidemenu-item-popover', className), children: (0, jsx_runtime_1.jsx)(box_1.default, Object.assign({}, buttonStyles, { borderLeft: `3px solid ${isDark ? 'digiGreen.main' : 'seaBlue.main'}`, children: (0, jsx_runtime_1.jsx)(SidemenuItemContent, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded }) })) }), (0, jsx_runtime_1.jsx)(popover_1.default.Content, { elevation: "none", children: (0, jsx_runtime_1.jsx)(box_1.default, { flexDirection: "column", justifyContent: "start", w: "100%", children: children }) })] })) : ((0, jsx_runtime_1.jsxs)(button_1.default, Object.assign({ className: (0, utils_1.cs)('vui-sidemenu-item', isExactlyActive && 'vui-sidemenu-item--active', className) }, buttonStyles, { isActive: isExactlyActive, children: [(0, jsx_runtime_1.jsx)(SidemenuItemContent, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded, badge: props.badge, badgeLinkUrl: props.badgeLinkUrl }), computedStates.shouldShowExpandButton && (0, jsx_runtime_1.jsx)(button_1.default, Object.assign({}, expandButtonProps)), " "] }))), computedStates.hasChildrenExpanded && ((0, jsx_runtime_1.jsx)(box_1.default, { flexDirection: "column", justifyContent: "start", w: "100%", children: children }))] }));
});
exports.SidemenuItemV2.displayName = 'SidemenuItemV2';
exports.default = exports.SidemenuItemV2;
//# sourceMappingURL=sidemenuItemV2.js.map