"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.SidemenuV2 = exports.useSidemenuContext = exports.SidemenuStateProvider = void 0;
const react_1 = require("react");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_2 = require("react");
const box_1 = __importDefault(require("../box"));
const button_1 = __importDefault(require("../button"));
const core_1 = require("../core");
const icon_1 = __importDefault(require("../icon"));
const utils_1 = require("../utils");
const consts_1 = require("./consts");
const context_1 = require("./context");
Object.defineProperty(exports, "SidemenuStateProvider", { enumerable: true, get: function () { return context_1.SidemenuStateProvider; } });
Object.defineProperty(exports, "useSidemenuContext", { enumerable: true, get: function () { return context_1.useSidemenuContext; } });
const sidemenuItemV2_1 = __importDefault(require("./sidemenuItemV2"));
const sidemenuTopV2_1 = __importDefault(require("./sidemenuTopV2"));
/** A collapsible side menu for navigation. */
exports.SidemenuV2 = (0, core_1.vui)((props, ref) => {
    const { isExpandedInitial = true, // Uncontrolled: only affects initial state
    onExpandedChange, // Extract this to prevent it from being passed to DOM
    size, variant = 'light', children, className, items, shouldExpand, isSticky, width, top, onNavigate } = props, restProps = __rest(props, ["isExpandedInitial", "onExpandedChange", "size", "variant", "children", "className", "items", "shouldExpand", "isSticky", "width", "top", "onNavigate"]) // Only DOM-safe props remain
    ;
    return ((0, jsx_runtime_1.jsx)(context_1.SidemenuStateProvider, { isExpandedInitial: isExpandedInitial, onExpandedChange: onExpandedChange, variant: variant, size: size, isDark: variant === 'dark', children: (0, jsx_runtime_1.jsx)(SidemenuInner, Object.assign({ ref: ref, 
            // Only pass DOM-safe props, not onExpandedChange
            children: children, className: className, items: items, shouldExpand: shouldExpand, isSticky: isSticky, size: size, variant: variant, width: width, top: top, onNavigate: onNavigate }, restProps)) }));
});
// Inner component that uses context
const SidemenuInner = (0, core_1.vui)((props, ref) => {
    const { children, className, items, shouldExpand, // Callback: fine-grained control over expansion
    isSticky = false, size, variant = 'light', width = consts_1.expandedWidth, top, onNavigate } = props, rest = __rest(props
    // Get state from context
    , ["children", "className", "items", "shouldExpand", "isSticky", "size", "variant", "width", "top", "onNavigate"]);
    // Get state from context
    const context = (0, context_1.useSidemenuContext)();
    const { isMenuExpanded = false, setIsExpanded } = context || {};
    // Get styles configuration early
    const styles = (0, core_1.useStyleConfig)('SidemenuV2', props);
    // Memoized boolean conditions
    const conditions = (0, react_2.useMemo)(() => ({
        isDark: variant === 'dark',
        hasItems: !!items,
        shouldShowItems: !!items && items.length > 0,
        isMenuSticky: isSticky,
        isMenuExpanded: isMenuExpanded,
    }), [variant, items, isSticky, isMenuExpanded]);
    // Memoized computed values for styling and behavior
    const computedValues = (0, react_2.useMemo)(() => {
        var _a, _b;
        // Get toggle button config from theme
        const toggleButtonTheme = styles.toggleButton || {};
        const currentSize = size || 'md'; // Ensure we have a valid size
        const sizeStyles = ((_a = styles.sizes) === null || _a === void 0 ? void 0 : _a[currentSize]) || {};
        const toggleButtonSizeTheme = sizeStyles.toggleButton || {};
        // Merge base theme with size-specific overrides
        const toggleConfig = {
            baseHeight: toggleButtonSizeTheme.baseHeight || toggleButtonTheme.baseHeight || 52,
            basePadding: toggleButtonSizeTheme.basePadding || toggleButtonTheme.basePadding || 2,
            expandedPaddingMultiplier: toggleButtonTheme.expandedPaddingMultiplier || 5,
            expandedWidth: toggleButtonTheme.expandedWidth || '52px',
            collapsedWidth: toggleButtonTheme.collapsedWidth || '100%',
        };
        // Helper function for consistent top position formatting
        const getMenuTopPosition = (isSticky, topValue) => {
            if (!isSticky)
                return 'auto';
            if (typeof topValue === 'string')
                return topValue;
            if (typeof topValue === 'number')
                return `${topValue}px`;
            return '0px'; // fallback for undefined/null/complex types
        };
        return {
            menuWidth: conditions.isMenuExpanded ? width : consts_1.collapsedWidth,
            toggleArrowDirection: conditions.isMenuExpanded ? 'Left' : 'Right',
            toggleButtonJustification: conditions.isMenuExpanded ? 'flex-end' : 'center',
            toggleButtonVariant: ((_b = styles.toggleButton) === null || _b === void 0 ? void 0 : _b.variant) || (conditions.isDark ? 'tertiaryLight' : 'tertiaryDark'),
            toggleAriaLabel: conditions.isMenuExpanded ? 'Collapse menu' : 'Expand menu',
            toggleButtonPadding: toggleConfig.basePadding,
            toggleButtonVerticalPadding: conditions.isMenuExpanded
                ? toggleConfig.basePadding * toggleConfig.expandedPaddingMultiplier
                : toggleConfig.basePadding,
            toggleButtonHeight: toggleConfig.baseHeight,
            toggleButtonWidth: conditions.isMenuExpanded ? toggleConfig.expandedWidth : toggleConfig.collapsedWidth,
            menuPosition: conditions.isMenuSticky ? 'sticky' : 'static',
            menuTopPosition: getMenuTopPosition(conditions.isMenuSticky, top),
        };
    }, [conditions, width, top, styles, size]);
    // Memoized icon name
    const toggleIcon = (0, react_2.useMemo)(() => `falArrow${computedValues.toggleArrowDirection}`, [computedValues.toggleArrowDirection]);
    // Stable callback for toggle (simplified)
    const handleToggle = (0, react_2.useCallback)(() => {
        const newExpandedState = !conditions.isMenuExpanded;
        // Check if expansion should be allowed via callback
        if (shouldExpand && !shouldExpand('toggle', conditions.isMenuExpanded)) {
            return; // Block the toggle
        }
        // Update state via context
        setIsExpanded === null || setIsExpanded === void 0 ? void 0 : setIsExpanded(newExpandedState);
    }, [conditions.isMenuExpanded, shouldExpand, setIsExpanded]);
    // Stable callback for item click - with expansion control
    const handleItemClick = (0, react_2.useCallback)((item) => {
        var _a;
        // Early return for clarity
        if (shouldExpand && (item === null || item === void 0 ? void 0 : item.path)) {
            const shouldExpandOnNav = shouldExpand('navigation', conditions.isMenuExpanded);
            if (typeof shouldExpandOnNav === 'boolean' && shouldExpandOnNav !== conditions.isMenuExpanded) {
                setIsExpanded === null || setIsExpanded === void 0 ? void 0 : setIsExpanded(shouldExpandOnNav);
            }
        }
        // Call item click handler
        (_a = item === null || item === void 0 ? void 0 : item.onClick) === null || _a === void 0 ? void 0 : _a.call(item);
        // Navigate if path exists
        if (item === null || item === void 0 ? void 0 : item.path)
            onNavigate === null || onNavigate === void 0 ? void 0 : onNavigate(item.path);
    }, [onNavigate, shouldExpand, conditions.isMenuExpanded, setIsExpanded]);
    // Create stable item click handlers
    const itemClickHandlers = (0, react_2.useMemo)(() => {
        return (items !== null && items !== void 0 ? items : []).reduce((handlers, item, index) => {
            const itemId = item.itemId || item.path || (0, utils_1.generateMenuItemId)(item.title, item.level || 0) || `item-${index}`;
            handlers[itemId] = () => handleItemClick(item);
            return handlers;
        }, {});
    }, [items, handleItemClick]);
    // Memoized items rendering
    const renderedItems = (0, react_2.useMemo)(() => {
        var _a;
        if (!conditions.shouldShowItems)
            return children;
        return (_a = items === null || items === void 0 ? void 0 : items.map) === null || _a === void 0 ? void 0 : _a.call(items, (item, index) => {
            // Use consistent itemId generation that matches the component's logic
            const itemId = item.itemId || item.path || (0, utils_1.generateMenuItemId)(item.title, item.level || 0) || `item-${index}`;
            // Use explicit isActive prop if provided, otherwise calculate from path
            const calculatedIsActive = item.isActive !== undefined ? item.isActive : (0, utils_1.isActivePath)((item === null || item === void 0 ? void 0 : item.path) || '');
            return ((0, jsx_runtime_1.jsx)(sidemenuItemV2_1.default, Object.assign({ isActive: calculatedIsActive, onBottom: item.onBottom, itemId: itemId, level: item.level || 0 }, item, { onClick: itemClickHandlers[itemId] }), itemId));
        });
    }, [conditions.shouldShowItems, conditions.isMenuExpanded, items, children, itemClickHandlers]);
    // Memoized CSS class names
    const cssClasses = (0, react_2.useMemo)(() => (0, utils_1.cs)('vui-sidemenu', `vui-sidemenu--${variant}`, conditions.isMenuExpanded && 'vui-sidemenu--expanded', !conditions.isMenuExpanded && 'vui-sidemenu--collapsed', conditions.isDark && 'vui-sidemenu--dark', conditions.isMenuSticky && 'vui-sidemenu--sticky', className), [variant, conditions, className]);
    // Memoized container props
    const containerProps = (0, react_2.useMemo)(() => (Object.assign(Object.assign({ className: cssClasses, flexDirection: 'column', overflowX: 'hidden', position: computedValues.menuPosition, ref, top: computedValues.menuTopPosition, transitionDuration: 'normal', transitionProperty: 'width', w: computedValues.menuWidth }, styles.container), rest)), [
        cssClasses,
        computedValues.menuPosition,
        computedValues.menuTopPosition,
        computedValues.menuWidth,
        ref,
        styles.container,
        rest,
    ]);
    // Memoized toggle button props with complete dependencies
    const toggleButtonProps = (0, react_2.useMemo)(() => {
        var _a;
        return ({
            'aria-expanded': conditions.isMenuExpanded,
            'aria-label': computedValues.toggleAriaLabel,
            border: 0,
            borderRadius: 0,
            justifyContent: computedValues.toggleButtonJustification,
            minHeight: `${computedValues.toggleButtonHeight}px`,
            minWidth: 0,
            onClick: handleToggle,
            px: computedValues.toggleButtonPadding,
            py: `${computedValues.toggleButtonVerticalPadding}px`,
            size: 'lg',
            variant: computedValues.toggleButtonVariant,
            w: computedValues.toggleButtonWidth,
            flexShrink: 0,
            transition: ((_a = styles.toggleButton) === null || _a === void 0 ? void 0 : _a.transition) || 'padding 0.2s ease-in-out, width 0.2s ease-in-out',
        });
    }, [
        computedValues.toggleAriaLabel,
        computedValues.toggleButtonJustification,
        computedValues.toggleButtonVariant,
        computedValues.toggleButtonPadding,
        computedValues.toggleButtonVerticalPadding,
        computedValues.toggleButtonHeight,
        computedValues.toggleButtonWidth,
        conditions.isMenuExpanded,
        handleToggle,
        styles.toggleButton,
    ]);
    return ((0, jsx_runtime_1.jsxs)(box_1.default, Object.assign({ elevation: "1" }, containerProps, { children: [(0, jsx_runtime_1.jsx)(box_1.default, { className: "vui-sidemenu-content", flexDirection: "column", flexGrow: 1, justifyContent: "flex-start", minW: consts_1.expandedWidth, overflowX: "hidden", overflowY: "auto", w: "100%", role: "navigation", "aria-label": "Main navigation", children: renderedItems }), (0, jsx_runtime_1.jsx)(box_1.default, { className: "vui-sidemenu-bottom", justifyContent: conditions.isMenuExpanded ? 'flex-end' : 'flex-start', borderTop: "1px solid sandstone.main", children: (0, react_1.createElement)(button_1.default, Object.assign({}, toggleButtonProps, { key: 'sidemenu-toggle-button' }),
                    (0, jsx_runtime_1.jsx)(icon_1.default, { name: toggleIcon, size: "sm", "aria-hidden": "true" })) })] })));
});
exports.SidemenuV2.Item = sidemenuItemV2_1.default;
exports.SidemenuV2.Top = sidemenuTopV2_1.default;
exports.SidemenuV2.displayName = 'SidemenuV2';
exports.default = exports.SidemenuV2;
//# sourceMappingURL=sidemenuV2.js.map