const rootMenusElement = document.getElementById("menusPopup");
const rootMenus = ReactDOM.createRoot(rootMenusElement); 

//alert(_token_encode);
const MenusComponent=()=>{
    return(
        
        <BrowserRouter>
            <CMSMenus/>
        </BrowserRouter> 
    )  
}

rootMenus.render(<MenusComponent  />, rootMenusElement);
///////////////////////////////////////////////////

const CMSMenus =(props)=>{
    const {userLogin} = props
    const [groupFeatures, setGroupFeatures] =useState([])
    const [loading, setLoading] = useState(false)
    let config = null
    try {
        config = { token: _token_encode }
    }catch (e) {
        config = { token: '' }
    }
  
    useEffect(()=>{
        fetchMenus()
    },[])

    const fetchMenus= async () => {      
        try {
            setLoading(true)
            const data ={
               active:true,
            }
            const result =  await commonApi.APIPOSTByURL('/api/get-menus', data,config) 
            
            if (result.status==200){      
                                       
                setGroupFeatures (result.data);               
            }else{
                setGroupFeatures ([]);
            }
        } catch (e) {
            // Handle error 
            setGroupFeatures([])           
            //console.log("ERROR" )
        } finally {
            setLoading(false)
        }     
    };
    function removeEmptyParentNodes(groupFeatures) {
        
        // First, organize the features into a hierarchical structure for easier processing.
        const featureMap = new Map();
        const rootNodes = [];

        groupFeatures.forEach(feature => {
            featureMap.set(feature.id, { ...feature,
            children: []
            });
        });

        featureMap.forEach(feature => {
            if (feature.parent_id) {
            const parent = featureMap.get(feature.parent_id);
            if (parent) {
                parent.children.push(feature);
            }
            } else {
            rootNodes.push(feature);
            }
        });

        // Recursively filter out invisible children and empty parent nodes.
        function filterNodes(nodes) {
            return nodes.filter(node => {
            if (node.is_parent) {
                // If it's a parent, recursively filter its children.
                node.children = filterNodes(node.children);
                // Keep the parent only if it has visible children remaining.
                return node.children.length > 0;
            } else {
                // If it's a child, keep it only if it's visible.
                return node.visible;
            }
            });
        }

        // Start the filtering process from the root nodes.
        const filteredTree = filterNodes(rootNodes);

        // Flatten the filtered tree back into a list (optional, depending on your needs)
        const flattenedResult = [];

        function flatten(nodes) {
            nodes.forEach(node => {
            // Create a shallow copy to avoid modifying the original 'children' property
            // if you intend to reuse the `filteredTree` for other purposes.
            const {
                children,
                ...rest
            } = node;
            flattenedResult.push(rest);
            if (children.length > 0) {
                flatten(children);
            }
            });
        }

        flatten(filteredTree);

        return flattenedResult;
    }
    const group  =removeEmptyParentNodes(groupFeatures)
    
    return(
        <> 
            {groupFeatures?.length>0 ?
                    <CMSMenuTreeGroupFeature group={group}/>
                    :
                    <>None</>
            }              
        </>
    )
}

const CMSMenuTreeGroupFeature = ({ group }) => {
    const { Accordion } = ReactBootstrap;
    const [searchQuery, setSearchQuery] = React.useState('');

    // Dynamic import of Outfit and Inter fonts for premium typography
    React.useEffect(() => {
        if (!document.getElementById('mimi-fonts-pre')) {
            const link = document.createElement('link');
            link.id = 'mimi-fonts-pre';
            link.href = 'https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Inter:wght@300;400;500;600;700&display=swap';
            link.rel = 'stylesheet';
            document.head.appendChild(link);
        }
    }, []);

    const isVi = (typeof commonFunc !== 'undefined' && commonFunc.getCookies('user_lang') === 'en') ? false : true;

    const [expandedKeys, setExpandedKeys] = React.useState(() => {
        if (Array.isArray(group) && group.length > 0) {
            const firstParent = group.find(g => 
                g.parent_id === null && group.some(child => child.parent_id === g.id)
            );
            return firstParent ? [firstParent.id.toString()] : [];
        }
        return [];
    });

    // Handle search filtering with null name check and keep matching items and their ancestors
    const filteredGroup = React.useMemo(() => {
        if (!searchQuery.trim()) return group;
        const query = searchQuery.toLowerCase().trim();
        
        const matchingItems = group.filter(item => 
            (item.name && item.name.toLowerCase().includes(query)) || 
            (item.path && item.path.toLowerCase().includes(query))
        );
        
        const keepIds = new Set();
        matchingItems.forEach(item => {
            keepIds.add(item.id);
            let parentId = item.parent_id;
            while (parentId) {
                const parent = group.find(g => g.id === parentId);
                if (parent) {
                    keepIds.add(parent.id);
                    parentId = parent.parent_id;
                } else {
                    break;
                }
            }
        });
        
        return group.filter(item => keepIds.has(item.id));
    }, [group, searchQuery]);

    // Automatically expand nodes containing search results, utilizing cycle-prevention sets and name checks
    React.useEffect(() => {
        if (searchQuery.trim() && group.length > 0) {
            const query = searchQuery.toLowerCase().trim();
            const keysToExpand = group
                .filter(g => g.is_parent || group.some(child => child.parent_id === g.id))
                .filter(g => {
                    const hasMatchingDescendant = (parentId, visited = new Set()) => {
                        if (visited.has(parentId)) return false;
                        visited.add(parentId);
                        const children = group.filter(c => c.parent_id === parentId);
                        return children.some(c => 
                            (c.name && c.name.toLowerCase().includes(query)) || 
                            hasMatchingDescendant(c.id, visited)
                        );
                    };
                    return hasMatchingDescendant(g.id);
                })
                .map(g => g.id.toString());
            setExpandedKeys(keysToExpand);
        }
    }, [searchQuery, group]);

    const handleAccordionSelect = (eventKey) => {
        if (!eventKey) return;
        const selectedKeys = Array.isArray(eventKey) ? eventKey : [eventKey.toString()];
        setExpandedKeys(selectedKeys);
    };

    const handleExpandAll = () => {
        const parentKeys = group
            .filter(g => group.some(child => child.parent_id === g.id))
            .map(g => g.id.toString());
        setExpandedKeys(parentKeys);
    };

    const handleCollapseAll = () => {
        setExpandedKeys([]);
    };

    const gotoLink = (path) => { if (path) window.location.href = path; };

    const renderIcon = (iconSource, isRoot) => {
        const isBase64 = iconSource && (iconSource.startsWith('data:image') || iconSource.length > 50);

        if (isBase64) {
            return (
                <img 
                    src={iconSource} 
                    alt="icon" 
                    style={{ 
                        width: isRoot ? '22px' : '16px', 
                        height: isRoot ? '22px' : '16px', 
                        marginRight: '12px', 
                        objectFit: 'contain',
                        borderRadius: '4px'
                    }} 
                />
            );
        }
        
        const defaultClass = isRoot ? "fa fa-th-large" : "fa fa-cube";
        return (
            <i 
                className={iconSource || defaultClass} 
                style={{ 
                    width: isRoot ? '22px' : '16px', 
                    marginRight: '12px', 
                    textAlign: 'center', 
                    fontSize: isRoot ? '16px' : '13px', 
                    color: isRoot ? '#c084fc' : '#94a3b8',
                    display: 'inline-flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transition: 'color 0.2s ease'
                }}
            ></i>
        );
    };

    const renderTree = (parentId, isRoot = false) => {
        if (!Array.isArray(filteredGroup)) return null;
        const children = filteredGroup.filter(g => g.parent_id === parentId);

        return children.map(g => {
            const hasChildren = filteredGroup.some(item => item.parent_id === g.id);
            const gIdStr = g.id.toString();
            const isExpanded = Array.isArray(expandedKeys) && expandedKeys.includes(gIdStr);

            if (!hasChildren) {
                return (
                    <div 
                        key={g.id} 
                        className={`cms-clickable ${isRoot ? 'cms-menu-item-root' : 'cms-menu-leaf'}`}
                        onClick={() => gotoLink(g.path)}
                    >
                        {renderIcon(g.icon, isRoot)}
                        <span style={{ flexGrow: 1 }}>{g.name}</span>
                        {isRoot && <i className="fa fa-angle-right" style={{ opacity: 0.5 }}></i>}
                    </div>
                );
            } else {
                return (
                    <Accordion.Item eventKey={gIdStr} key={g.id} className="border-0 bg-transparent mb-0">
                        <Accordion.Header className="w-100 p-0 border-0 bg-transparent">
                            <div className={`cms-menu-item-root ${isExpanded ? 'active-parent' : ''}`}>
                                {renderIcon(g.icon, true)}
                                <span style={{ flexGrow: 1 }}>{g.name}</span>
                                <i className={`fa ${isExpanded ? 'fa-angle-down' : 'fa-angle-right'}`} style={{ fontSize: '15px', opacity: 0.8 }}></i>
                            </div>
                        </Accordion.Header>
                        <Accordion.Body className="p-0 border-0 bg-transparent">
                            <div className="tree-branch-container">
                                {renderTree(g.id, false)}
                            </div>
                        </Accordion.Body>
                    </Accordion.Item>
                );
            }
        });
    };

    const styles = {
        container: { 
            background: 'linear-gradient(135deg, #070410 0%, #100a20 100%)', 
            padding: '24px 16px 40px 16px', 
            color: '#f8fafc', 
            width: '100%', 
            fontFamily: '"Outfit", "Inter", -apple-system, sans-serif'
        }
    };

    return (
        <div className="cms-menu-full-wrapper" style={styles.container}>
            <style>{`
                /* Bootstrap overrides */
                .accordion-button { padding: 0 !important; background: none !important; box-shadow: none !important; width: 100% !important; }
                .accordion-button::after { display: none !important; }
                .accordion-item { border: none !important; background-color: transparent !important; margin-bottom: 0 !important; }
                
                /* Micro-interactions & animations */
                .cms-clickable:active { opacity: 0.7; transform: scale(0.98); }
                
                .search-input-glow:focus {
                    background: rgba(30, 27, 75, 0.5) !important;
                    border-color: #a78bfa !important;
                    box-shadow: 0 0 12px rgba(139, 92, 246, 0.25) !important;
                }
                .btn-action-pill {
                    background: rgba(30, 27, 75, 0.3) !important;
                    border: 1px solid rgba(99, 102, 241, 0.2) !important;
                    color: #a78bfa !important;
                    border-radius: 12px !important;
                    width: 42px !important;
                    height: 42px !important;
                    display: flex !important;
                    align-items: center !important;
                    justify-content: center !important;
                    transition: all 0.3s ease !important;
                }
                .btn-action-pill:hover {
                    background: rgba(99, 102, 241, 0.15) !important;
                    border-color: #a78bfa !important;
                    color: #ffffff !important;
                    transform: translateY(-1px);
                }
                .menu-avatar-glow {
                    width: 32px;
                    height: 32px;
                    background: rgba(124, 58, 237, 0.2);
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .text-purple-glow {
                    color: #c084fc;
                    text-shadow: 0 0 8px rgba(192, 132, 252, 0.5);
                }
                
                /* Tree node connector lines */
                .tree-branch-container {
                    position: relative;
                    padding-left: 16px;
                    margin-left: 16px;
                    border-left: 1px dashed rgba(99, 102, 241, 0.15);
                }
                
                .cms-menu-item-root {
                    display: flex;
                    align-items: center;
                    padding: 10px 16px;
                    margin-bottom: 6px;
                    border-radius: 10px;
                    background: rgba(30, 27, 75, 0.3);
                    border: 1px solid rgba(99, 102, 241, 0.1);
                    color: #f1f5f9;
                    font-weight: 500;
                    font-size: 14px;
                    cursor: pointer;
                    width: 100%;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                }
                
                .cms-menu-item-root:hover {
                    background: rgba(30, 27, 75, 0.5);
                    border-color: rgba(139, 92, 246, 0.4);
                    box-shadow: 0 4px 15px rgba(124, 58, 237, 0.1);
                    transform: translateY(-1px);
                    color: #c084fc !important;
                }
                .cms-menu-item-root:hover i {
                    color: #c084fc !important;
                }
                
                .cms-menu-item-root.active-parent {
                    background: linear-gradient(135deg, #6d28d9 0%, #a855f7 100%) !important;
                    border-color: #a855f7 !important;
                    box-shadow: 0 4px 15px rgba(109, 40, 217, 0.3) !important;
                    font-weight: 600;
                }
                .cms-menu-item-root.active-parent i {
                    color: #ffffff !important;
                }
                
                .cms-menu-leaf {
                    display: flex;
                    align-items: center;
                    padding: 7px 12px;
                    margin-bottom: 3px;
                    border-radius: 6px;
                    color: #94a3b8;
                    font-size: 13px;
                    cursor: pointer;
                    transition: all 0.2s ease;
                    position: relative;
                }
                
                .cms-menu-leaf::before {
                    content: '';
                    position: absolute;
                    left: -16px;
                    top: 50%;
                    width: 10px;
                    border-top: 1px dashed rgba(99, 102, 241, 0.15);
                }
                
                .cms-menu-leaf:hover {
                    color: #c084fc !important;
                    background: rgba(139, 92, 246, 0.08);
                    transform: translateX(3px);
                    padding-left: 14px;
                }
                .cms-menu-leaf:hover i {
                    color: #c084fc !important;
                }
                
                .cms-menu-leaf.active-leaf {
                    color: #ffffff !important;
                    background: rgba(139, 92, 246, 0.15) !important;
                    font-weight: 600;
                    border-left: 3px solid #c084fc;
                }
                
                .btn-logout-menu {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                    color: #f43f5e !important;
                    font-weight: 600;
                    text-decoration: none !important;
                    padding: 12px 20px;
                    border-radius: 12px;
                    background: rgba(244, 63, 94, 0.08);
                    border: 1px solid rgba(244, 63, 94, 0.15);
                    transition: all 0.3s ease;
                    font-size: 14px;
                    width: 100%;
                    cursor: pointer;
                    margin-top: 10px;
                }
                .btn-logout-menu:hover {
                    background: rgba(244, 63, 94, 0.18) !important;
                    border-color: #f43f5e !important;
                    box-shadow: 0 4px 15px rgba(244, 63, 94, 0.2);
                    transform: translateY(-1px);
                    color: #ffffff !important;
                }
                .btn-logout-menu:active {
                    transform: translateY(0) scale(0.98);
                }
                
                @media (max-width: 768px) {
                    .cms-menu-full-wrapper { padding: 10px 0 !important; width: 100vw !important; margin: 0 !important; }
                    .accordion-item, .cms-clickable { border-radius: 0 !important; width: 100% !important; margin: 0 !important; }
                    div[style*="borderRadius: 12px"], div[style*="border-radius: 12px"] { border-radius: 0 !important; border-left: none !important; border-right: none !important; }
                    .tree-branch-container { margin-left: 12px; padding-left: 12px; }
                    .cms-menu-leaf::before { left: -12px; width: 8px; }
                }
            `}</style> 

            {/* Header section */}
            <div className="menu-header mb-2 text-center text-md-start px-2">
                
                {/* Search & Action Controls */}
                <div className="d-flex gap-2 align-items-center mb-3">
                    <div className="position-relative flex-grow-1">
                        <i className="fa fa-search position-absolute top-50 start-0 translate-middle-y ms-3 text-muted"></i>
                        <input 
                            type="text" 
                            className="form-control search-input-glow" 
                            placeholder={isVi ? "Tìm kiếm chức năng..." : "Search menu items..."}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            style={{
                                paddingLeft: '40px',
                                background: 'rgba(30, 27, 75, 0.3)',
                                border: '1px solid rgba(99, 102, 241, 0.2)',
                                borderRadius: '12px',
                                color: '#ffffff',
                                height: '42px',
                                fontSize: '14px',
                                transition: 'all 0.3s ease'
                            }}
                        />
                        {searchQuery && (
                            <i className="fa fa-times position-absolute top-50 end-0 translate-middle-y me-3 text-muted cursor-pointer" 
                               onClick={() => setSearchQuery('')}
                               style={{ cursor: 'pointer' }}></i>
                        )}
                    </div>
                    <div className="d-flex gap-1">
                        <button className="btn btn-action-pill" title={isVi ? "Mở rộng tất cả" : "Expand All"} onClick={handleExpandAll}>
                            <i className="fa fa-expand"></i>
                        </button>
                        <button className="btn btn-action-pill" title={isVi ? "Thu gọn tất cả" : "Collapse All"} onClick={handleCollapseAll}>
                            <i className="fa fa-compress"></i>
                        </button>
                    </div>
                </div>
            </div>

            <Accordion activeKey={expandedKeys} onSelect={handleAccordionSelect} alwaysOpen>
                {renderTree(null, true)}
            </Accordion>

            {/* Premium Logout Button at the bottom of the menu tree */}
            <div className="mt-4 pt-3 border-top border-secondary border-opacity-20 d-flex justify-content-center">
                <a 
                    href={`/logout?next=${encodeURIComponent(window.location.pathname)}`}
                    className="btn-logout-menu"
                >
                    <i className="fa fa-sign-out"></i>
                    <span>{isVi ? "Đăng xuất" : "Logout"}</span>
                </a>
            </div>
        </div>
    );
};