(function() {
    'use strict';
    
    function ForumMenu() {
        this.menuContainer = document.getElementById('forumNav');
        if (!this.menuContainer) return;
        this.init();
    }

    ForumMenu.prototype.init = function() {
        this.loadData();
    };

    ForumMenu.prototype.loadData = function() {
        var self = this;
        var apiUrl = window.themePath + '/forum_menu_data.php';
        
        // 移除之前所有非静态的动态 li
        var children = this.menuContainer.children;
        for (var i = children.length - 1; i >= 0; i--) {
            var li = children[i];
            if (!li.classList || !li.classList.contains('static-home')) {
                this.menuContainer.removeChild(li);
            }
        }
        
        // 显示加载占位符
        var placeholderLi = document.createElement('li');
        placeholderLi.className = 'loading-placeholder';
        placeholderLi.style.padding = '10px 20px';
        placeholderLi.style.color = '#b8daf0';
        placeholderLi.textContent = '加载中...';
        this.menuContainer.appendChild(placeholderLi);
        
        var xhr = new XMLHttpRequest();
        xhr.open('GET', apiUrl, true);
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    // 移除占位符
                    if (placeholderLi.parentNode) placeholderLi.parentNode.removeChild(placeholderLi);
                    if (data && Array.isArray(data) && data.length > 0) {
                        self.renderMenu(data);
                    } else {
                        var emptyLi = document.createElement('li');
                        emptyLi.textContent = '暂无版块';
                        self.menuContainer.appendChild(emptyLi);
                    }
                } catch (e) {
                    if (placeholderLi.parentNode) placeholderLi.parentNode.removeChild(placeholderLi);
                    var errorLi = document.createElement('li');
                    errorLi.textContent = '数据加载错误';
                    self.menuContainer.appendChild(errorLi);
                }
            } else {
                if (placeholderLi.parentNode) placeholderLi.parentNode.removeChild(placeholderLi);
                var errorLi = document.createElement('li');
                errorLi.textContent = '加载失败，请刷新';
                self.menuContainer.appendChild(errorLi);
            }
        };
        xhr.onerror = function() {
            if (placeholderLi.parentNode) placeholderLi.parentNode.removeChild(placeholderLi);
            var errorLi = document.createElement('li');
            errorLi.textContent = '网络错误';
            self.menuContainer.appendChild(errorLi);
        };
        xhr.send();
    };

    ForumMenu.prototype.renderMenu = function(forums) {
        var html = '';
        for (var i = 0; i < forums.length; i++) {
            html += this.renderMenuItem(forums[i], 1);
        }
        this.menuContainer.insertAdjacentHTML('beforeend', html);
        this.bindEvents();
        this.highlightActive();
    };

    ForumMenu.prototype.renderMenuItem = function(forum, level) {
        if (!forum || typeof forum.id === 'undefined') return '';
        
        var hasChildren = forum.children && Array.isArray(forum.children) && forum.children.length > 0;
        var childrenHtml = '';
        if (hasChildren) {
            var subItems = '';
            for (var i = 0; i < forum.children.length; i++) {
                subItems += this.renderMenuItem(forum.children[i], level + 1);
            }
            var ulClass = (level === 1) ? 'dropdown-menu' : 'submenu';
            childrenHtml = '<ul class="' + ulClass + '">' + subItems + '</ul>';
        }
        
        var iconHtml = hasChildren ? '<i class="fa fa-angle-right sub-icon"></i>' : '';
        var titleHtml = (level === 1)
            ? '<a href="./viewforum.php?f=' + forum.id + '" class="level1-title">' + forum.name + iconHtml + '</a>'
            : '<a href="./viewforum.php?f=' + forum.id + '" class="sub-link"><span class="sub-title-text">' + forum.name + '</span>' + iconHtml + '</a>';
        
        var statsHtml = '';
        if ((level === 2 || level === 3) && forum.type === 1) {
            var stats = [];
            if (forum.topics_count > 0) stats.push('<span class="stat-item"><i class="fa fa-sticky-note-o"></i> ' + forum.topics_count + '</span>');
            if (forum.posts_count > 0) stats.push('<span class="stat-item"><i class="fa fa-comments-o"></i> ' + forum.posts_count + '</span>');
            statsHtml = stats.length ? '<div class="forum-stats">' + stats.join('') + '</div>' : '';
        }
        
        return '<li class="' + (hasChildren ? 'has-submenu' : '') + '">' + titleHtml + statsHtml + childrenHtml + '</li>';
    };

    ForumMenu.prototype.bindEvents = function() {
        var self = this;
        var menuContainer = this.menuContainer;
        
        var toggleBtn = document.querySelector('.mobile-menu-toggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var isShowing = menuContainer.classList.contains('show');
                menuContainer.classList.toggle('show');
                if (isShowing) {
                    self.closeAllSubmenus();
                }
            });
        }
        
        if (window.innerWidth <= 768) {
            // 移除三级菜单的展开功能
            var thirdLevelMenus = menuContainer.querySelectorAll('.submenu');
            for (var i = 0; i < thirdLevelMenus.length; i++) {
                var parentLi = thirdLevelMenus[i].closest('li');
                if (parentLi) {
                    parentLi.classList.remove('has-submenu');
                    var arrowIcon = parentLi.querySelector('.sub-icon');
                    if (arrowIcon) arrowIcon.remove();
                }
            }
            
            // 处理一级菜单的展开/收起 (只展开二级)
            var topLevelItems = menuContainer.querySelectorAll('li.has-submenu');  // 修正选择器
            for (var j = 0; j < topLevelItems.length; j++) {
                (function(item) {
                    var titleLink = item.querySelector('.level1-title');
                    if (!titleLink) return;
                    var submenu = item.querySelector('.dropdown-menu');
                    if (!submenu) return;
                    submenu.style.display = 'none';
                    titleLink.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var isOpen = item.classList.contains('open');
                        for (var k = 0; k < topLevelItems.length; k++) {
                            var otherItem = topLevelItems[k];
                            if (otherItem !== item && otherItem.classList.contains('open')) {
                                otherItem.classList.remove('open');
                                var otherSub = otherItem.querySelector('.dropdown-menu');
                                if (otherSub) otherSub.style.display = 'none';
                            }
                        }
                        if (isOpen) {
                            item.classList.remove('open');
                            submenu.style.display = 'none';
                        } else {
                            item.classList.add('open');
                            submenu.style.display = 'block';
                        }
                    };
                })(topLevelItems[j]);
            }
        }
    };
    
    ForumMenu.prototype.closeAllSubmenus = function() {
        var items = this.menuContainer.querySelectorAll('.has-submenu.open');
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove('open');
            var ul = items[i].querySelector('.dropdown-menu');
            if (ul) ul.style.display = 'none';
        }
    };
    
    ForumMenu.prototype.highlightActive = function() {
        var f = new URLSearchParams(window.location.search).get('f');
        if (!f) return;
        var links = this.menuContainer.querySelectorAll('a[href*="f=' + f + '"]');
        for (var i = 0; i < links.length; i++) {
            links[i].classList.add('active');
        }
    };
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() { new ForumMenu(); });
    } else {
        new ForumMenu();
    }
})();