(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';

        // 添加加载占位符，避免空白闪烁
        this.menuContainer.innerHTML = '<li class="loading-placeholder" style="padding: 10px 20px; color: #b8daf0;">加载中...</li>';

        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 (data && Array.isArray(data) && data.length > 0) {
                        self.renderMenu(data);
                    } else {
                        self.menuContainer.innerHTML = '<li>暂无版块</li>';
                    }
                } catch (e) {
                    self.menuContainer.innerHTML = '<li>数据加载错误</li>';
                }
            } else {
                self.menuContainer.innerHTML = '<li>加载失败，请刷新</li>';
            }
        };
        xhr.onerror = function() {
            self.menuContainer.innerHTML = '<li>网络错误</li>';
        };
        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.innerHTML = 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) {
            // 1. 移除所有三级菜单的 has-submenu 类，让二级菜单不显示箭头且无法展开三级
            var thirdLevelMenus = menuContainer.querySelectorAll('.submenu');
            for (var i = 0; i < thirdLevelMenus.length; i++) {
                var thirdMenu = thirdLevelMenus[i];
                // 找到包含三级菜单的父级 li
                var parentLi = thirdMenu.closest('li');
                if (parentLi) {
                    // 移除 has-submenu 类
                    parentLi.classList.remove('has-submenu');
                    // 移除箭头图标
                    var arrowIcon = parentLi.querySelector('.sub-icon');
                    if (arrowIcon) {
                        arrowIcon.remove();
                    }
                }
            }
            
            // 2. 处理一级菜单的展开/收起（只展开二级，不处理三级）
            var topLevelItems = menuContainer.querySelectorAll('.forum-nav > 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();
    }
})();