"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 = exports.PopoverHovered = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const box_1 = __importDefault(require("../box"));
const button_1 = __importDefault(require("../button"));
const core_1 = require("../core");
const popover_1 = __importDefault(require("../popover"));
const theme_1 = require("../theme");
const tooltip_1 = __importDefault(require("../tooltip"));
const utils_1 = require("../utils");
const consts_1 = require("./consts");
const SidemenuItemContent_1 = __importDefault(require("./SidemenuItemContent"));
const useSidemenuItem_1 = __importDefault(require("./useSidemenuItem"));
exports.PopoverHovered = core_1.styled.div `
  &:hover .vui-sidemenu-item-popover .vui-button.vui-button {
    background: ${p => core_1.th.color(p.hoverColor)};
  }
  &:hover div:last-child .tippy-content .vui-sidemenu-item-content > .vui-box > .vui-button.vui-button {
    background: ${p => core_1.th.color(p.hoverColor)};
  }
`;
// SidemenuPopover component extracted from inline Popover logic
const SidemenuPopover = ({ isDark, className, buttonStyles, isExactlyActive, icon, title, isMenuExpanded, children, }) => ((0, jsx_runtime_1.jsx)(popover_1.default, { offset: [0, consts_1.collapsedWidth - consts_1.expandedWidth - 2], placement: "right-start", trigger: "mouseenter", children: ({ isOpen }) => ((0, jsx_runtime_1.jsxs)(exports.PopoverHovered, { hoverColor: isDark ? theme_1.colors.seaBlue.main : theme_1.colors.skyBlue.selected, 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)(button_1.default, Object.assign({}, buttonStyles, { borderLeft: `3px solid ${isDark ? 'digiGreen.main' : 'seaBlue.main'}`, isActive: isExactlyActive, className: (0, utils_1.cs)('focusAsBorder'), children: (0, jsx_runtime_1.jsx)(SidemenuItemContent_1.default, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded }) })) }), (0, jsx_runtime_1.jsx)(popover_1.default.Content, { elevation: "none", className: (0, utils_1.cs)('vui-sidemenu-item-content', className), children: (0, jsx_runtime_1.jsxs)(box_1.default, { flexDirection: "column", justifyContent: "start", w: "100%", children: [(0, jsx_runtime_1.jsx)(button_1.default, Object.assign({}, buttonStyles, { borderLeftColor: 'transparent!important', minW: '240px', isActive: isOpen && isExactlyActive, className: (0, utils_1.cs)('focusAsBorder'), children: (0, jsx_runtime_1.jsx)(SidemenuItemContent_1.default, { title: title, isInPopover: true }) })), children] }) })] })) }));
/** 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',
        };
    }, [isSubmenuOpen, themeValues.buttonVariant]);
    // Helper: Render collapsed popover
    const renderPopover = () => ((0, jsx_runtime_1.jsx)(SidemenuPopover, { isDark: isDark, className: className, buttonStyles: buttonStyles, isExactlyActive: isExactlyActive, icon: icon, title: title, isMenuExpanded: isMenuExpanded, children: children ? children : undefined }));
    // Helper: Render expanded button
    const renderButton = () => {
        if (level === 0 && !isMenuExpanded) {
            return ((0, jsx_runtime_1.jsx)(tooltip_1.default, { text: title, placement: "right", offset: [0, -200], children: (0, jsx_runtime_1.jsxs)(button_1.default, Object.assign({ className: (0, utils_1.cs)('vui-sidemenu-item focusAsBorder', isExactlyActive && 'vui-sidemenu-item--active', className) }, buttonStyles, { isActive: isExactlyActive, children: [(0, jsx_runtime_1.jsx)(SidemenuItemContent_1.default, { icon: icon, iconSize: buttonStyles.iconSize }), isMenuExpanded && computedStates.shouldShowExpandButton && (0, jsx_runtime_1.jsx)(button_1.default, Object.assign({}, expandButtonProps)), ' '] })) }));
        }
        return ((0, jsx_runtime_1.jsxs)(button_1.default, Object.assign({ className: (0, utils_1.cs)('vui-sidemenu-item focusAsBorder', isExactlyActive && 'vui-sidemenu-item--active', className) }, buttonStyles, { isActive: isExactlyActive, title: !isMenuExpanded ? title : undefined, children: [(0, jsx_runtime_1.jsx)(SidemenuItemContent_1.default, { icon: icon, iconSize: buttonStyles.iconSize, title: title, isMenuExpanded: isMenuExpanded, badge: props.badge, badgeLinkUrl: props.badgeLinkUrl }), isMenuExpanded && computedStates.shouldShowExpandButton && (0, jsx_runtime_1.jsx)(button_1.default, Object.assign({}, expandButtonProps)), ' '] })));
        // No leftover return, handled above
    };
    // Helper: Render expanded children
    const renderChildren = () => ((0, jsx_runtime_1.jsx)(box_1.default, { flexDirection: "column", justifyContent: "start", w: "100%", children: children }));
    const shouldShowPopover = Boolean(!isMenuExpanded && level === 0 && !!children);
    const shouldShowChildren = computedStates.hasChildrenExpanded;
    return ((0, jsx_runtime_1.jsxs)(box_1.default, { flexDirection: "column", ref: ref, w: "100%", mt: onBottom ? 'auto' : 0, id: computedItemId, children: [shouldShowPopover && renderPopover(), !shouldShowPopover && renderButton(), shouldShowChildren && renderChildren()] }));
});
exports.SidemenuItemV2.displayName = 'SidemenuItemV2';
exports.default = exports.SidemenuItemV2;
//# sourceMappingURL=sidemenuItemV2.js.map