import React, { useState, useEffect, } from "react";
import Icon from "../Icon/Icon";
import IconProp from "../../../Types/Icon/IconProp";
import useComponentOutsideClick from "../../Types/UseComponentOutsideClick";
import Navigation from "../../Utils/Navigation";
import useTranslateValue from "../../Utils/Translation";
import SideMenuItem from "./SideMenuItem";
import SideMenuSection from "./SideMenuSection";
import CountModelSideMenuItem from "./CountModelSideMenuItem";
const SideMenu = (props) => {
    const { translateString } = useTranslateValue();
    const [isMobile, setIsMobile] = useState(false);
    const [isMobileMenuVisible, setIsMobileMenuVisible] = useState(false);
    // Use the existing outside click hook for mobile menu
    const { ref: mobileMenuRef, isComponentVisible: isMobileMenuOpen, setIsComponentVisible: setIsMobileMenuOpen, } = useComponentOutsideClick(false);
    // Sync local state with hook state
    useEffect(() => {
        setIsMobileMenuVisible(isMobileMenuOpen);
    }, [isMobileMenuOpen]);
    // Check if we're on mobile
    useEffect(() => {
        const checkMobile = () => {
            setIsMobile(window.innerWidth < 768); // md breakpoint
        };
        checkMobile();
        window.addEventListener("resize", checkMobile);
        return () => {
            window.removeEventListener("resize", checkMobile);
        };
    }, []);
    // Close mobile menu when clicking on a menu item
    const handleMenuItemClick = () => {
        if (isMobile && isMobileMenuVisible) {
            setIsMobileMenuOpen(false);
        }
    };
    // Function to find the active menu item and section - much simpler now!
    const findActiveMenuItem = () => {
        // Check sections first
        if (props.sections) {
            for (const section of props.sections) {
                for (const item of section.items) {
                    if (Navigation.isOnThisPage(item.link.to)) {
                        const result = {
                            sectionTitle: section.title,
                            itemTitle: item.link.title,
                        };
                        if (item.icon) {
                            result.icon = item.icon;
                        }
                        return result;
                    }
                }
            }
        }
        // Check direct items
        if (props.items) {
            for (const item of props.items) {
                if (Navigation.isOnThisPage(item.link.to)) {
                    const result = {
                        itemTitle: item.link.title,
                    };
                    if (item.icon) {
                        result.icon = item.icon;
                    }
                    return result;
                }
            }
        }
        return {};
    };
    const activeItem = findActiveMenuItem();
    const translatedSectionTitle = translateString(activeItem.sectionTitle);
    const translatedItemTitle = translateString(activeItem.itemTitle);
    const displayText = translatedSectionTitle && translatedItemTitle
        ? `${translatedSectionTitle} / ${translatedItemTitle}`
        : translatedItemTitle || translateString("Navigation") || "Navigation";
    // Re-run active item detection when location changes
    useEffect(() => {
        /*
         * This will trigger a re-render when navigation changes
         * The activeItem will be recalculated
         */
    }, [Navigation.getCurrentPath().toString()]);
    // Render function for the menu content
    const renderMenuContent = () => {
        const content = [];
        // Render sections
        if (props.sections) {
            props.sections.forEach((section, sectionIndex) => {
                // Build section props conditionally to avoid undefined values
                const sectionProps = {
                    key: `section-${sectionIndex}`,
                    title: section.title,
                };
                if (section.icon) {
                    sectionProps.icon = section.icon;
                }
                if (section.defaultCollapsed !== undefined) {
                    sectionProps.defaultCollapsed = section.defaultCollapsed;
                }
                if (section.collapsible !== undefined) {
                    sectionProps.collapsible = section.collapsible;
                }
                content.push(React.createElement(SideMenuSection, Object.assign({}, sectionProps), section.items.map((item, itemIndex) => {
                    // If item has modelType, render CountModelSideMenuItem
                    if (item.modelType && item.countQuery) {
                        return (React.createElement(CountModelSideMenuItem, { key: `section-${sectionIndex}-count-item-${itemIndex}`, link: item.link, badgeType: item.badgeType, modelType: item.modelType, countQuery: item.countQuery, requestOptions: item.requestOptions, icon: item.icon, className: item.className, onCountFetchInit: item.onCountFetchInit }));
                    }
                    // Otherwise render regular SideMenuItem
                    return (React.createElement(SideMenuItem, { key: `section-${sectionIndex}-item-${itemIndex}`, link: item.link, showAlert: item.showAlert, showWarning: item.showWarning, badge: item.badge, badgeType: item.badgeType, icon: item.icon, className: item.className, subItemLink: item.subItemLink, subItemIcon: item.subItemIcon }));
                })));
            });
        }
        // Render direct items
        if (props.items) {
            props.items.forEach((item, itemIndex) => {
                // If item has modelType, render CountModelSideMenuItem
                if (item.modelType && item.countQuery) {
                    content.push(React.createElement(CountModelSideMenuItem, { key: `count-item-${itemIndex}`, link: item.link, badgeType: item.badgeType, modelType: item.modelType, countQuery: item.countQuery, requestOptions: item.requestOptions, icon: item.icon, className: item.className, onCountFetchInit: item.onCountFetchInit }));
                }
                else {
                    // Otherwise render regular SideMenuItem
                    content.push(React.createElement(SideMenuItem, { key: `item-${itemIndex}`, link: item.link, showAlert: item.showAlert, showWarning: item.showWarning, badge: item.badge, badgeType: item.badgeType, icon: item.icon, className: item.className, subItemLink: item.subItemLink, subItemIcon: item.subItemIcon }));
                }
            });
        }
        // Support legacy children prop for backward compatibility
        if (props.children) {
            const children = Array.isArray(props.children)
                ? props.children
                : [props.children];
            children.forEach((child, index) => {
                content.push(React.cloneElement(child, { key: `child-${index}` }));
            });
        }
        return content;
    };
    // Mobile view
    if (isMobile) {
        return (React.createElement("div", { className: "md:hidden mb-6" },
            React.createElement("button", { type: "button", onClick: () => {
                    setIsMobileMenuOpen(!isMobileMenuVisible);
                }, className: `
            w-full flex items-center justify-between
            px-3 py-2.5
            bg-white rounded-xl
            border border-gray-200
            shadow-sm
            transition-all duration-200
            ${isMobileMenuVisible ? "ring-2 ring-indigo-100 border-indigo-200" : "hover:border-gray-300"}
          `, "aria-expanded": isMobileMenuVisible, "aria-label": isMobileMenuVisible
                    ? translateString("Close navigation menu") ||
                        "Close navigation menu"
                    : translateString("Open navigation menu") ||
                        "Open navigation menu", "data-testid": "mobile-sidemenu-toggle" },
                React.createElement("div", { className: "flex items-center gap-2 min-w-0" },
                    activeItem.icon && (React.createElement("div", { className: "flex items-center justify-center w-6 h-6 rounded-md bg-indigo-50 text-indigo-600 flex-shrink-0" },
                        React.createElement(Icon, { icon: activeItem.icon, className: "h-3.5 w-3.5" }))),
                    React.createElement("div", { className: "min-w-0" },
                        React.createElement("p", { className: "text-xs text-gray-400 font-medium" }, translateString("Navigate to")),
                        React.createElement("h3", { className: "text-sm font-semibold text-gray-900 truncate" }, displayText))),
                React.createElement("div", { className: `
              flex items-center justify-center
              w-6 h-6 rounded-md
              transition-all duration-200
              ${isMobileMenuVisible ? "bg-indigo-100 text-indigo-600" : "bg-gray-100 text-gray-500"}
            ` },
                    React.createElement(Icon, { icon: isMobileMenuVisible ? IconProp.Close : IconProp.Bars3, className: "h-3.5 w-3.5" }))),
            isMobileMenuVisible && (React.createElement(React.Fragment, null,
                React.createElement("div", { className: "fixed inset-0 bg-black/20 z-40 animate-in fade-in duration-200", onClick: () => {
                        setIsMobileMenuOpen(false);
                    } }),
                React.createElement("div", { ref: mobileMenuRef, className: `
                relative z-50
                mt-2
                bg-white rounded-xl
                border border-gray-200
                shadow-xl
                overflow-hidden
                animate-in slide-in-from-top-2 fade-in duration-200
              `, role: "navigation", "aria-label": "Main navigation" },
                    props.header && (React.createElement("div", { className: "px-3 py-2 border-b border-gray-100 bg-gray-50/50" }, props.header)),
                    React.createElement("nav", { className: "p-2 max-h-[60vh] overflow-y-auto", onClick: handleMenuItemClick },
                        React.createElement("div", { className: "space-y-0.5" }, renderMenuContent())),
                    props.footer && (React.createElement("div", { className: "px-3 py-2 border-t border-gray-100 bg-gray-50/50" }, props.footer)))))));
    }
    // Desktop view
    return (React.createElement("aside", { className: `hidden md:block w-52 lg:w-60 flex-shrink-0 mb-10 ${props.className || ""}`, role: "navigation", "aria-label": "Main navigation" },
        React.createElement("div", { className: "sticky top-6" },
            React.createElement("div", { className: `
            bg-white rounded-2xl
            border border-gray-200/80
            shadow-sm
            overflow-hidden
          ` },
                props.header && (React.createElement("div", { className: "px-3 py-3 border-b border-gray-100 bg-gradient-to-b from-gray-50 to-white" }, props.header)),
                React.createElement("nav", { className: "p-2" },
                    React.createElement("div", { className: "space-y-0.5" }, renderMenuContent())),
                props.footer && (React.createElement("div", { className: "px-3 py-2 border-t border-gray-100 bg-gray-50/50" }, props.footer))))));
};
export default SideMenu;
//# sourceMappingURL=SideMenu.js.map