<?php
if (!function_exists('admin_nav_items')) {
    function admin_nav_items()
    {
        $items = array(
            'dashboard' => array('href' => '/admin/dashboard/index.php', 'icon' => '🏠', 'title' => '仪表盘', 'desc' => '总览与监控', 'group' => 'overview'),
            'ai_models' => array('href' => '/admin/ai-model/list.php', 'icon' => '🤖', 'title' => 'AI模型', 'desc' => '配置与测试', 'group' => 'site'),
            'domains' => array('href' => '/admin/domain/list.php', 'icon' => '🌐', 'title' => '域名管理', 'desc' => '站点与分组', 'group' => 'site'),
            'menus' => array('href' => '/admin/menu/list.php', 'icon' => '📋', 'title' => '菜单管理', 'desc' => '导航与栏目', 'group' => 'site'),
            'site_build' => array('href' => '/admin/site-build/index.php', 'icon' => '🚀', 'title' => '站点发布', 'desc' => '首页与文章任务', 'group' => 'site'),
            'content' => array('href' => '/admin/content/list.php', 'icon' => '📄', 'title' => '内容管理', 'desc' => '页面与发布', 'group' => 'site'),
            'ads' => array('href' => '/admin/ad/list.php', 'icon' => '📣', 'title' => '广告管理', 'desc' => '文章页广告位', 'group' => 'site'),
            'template_packs' => array('href' => '/admin/template-pack/list.php', 'icon' => '🎨', 'title' => '模板与模块', 'desc' => '套件管理与组件模块', 'group' => 'site'),
            'market' => array('href' => '/admin/template-pack/market.php', 'icon' => '☁️', 'title' => '模板市场', 'desc' => '云端模板下载', 'group' => 'site'),
            'spider_stats' => array('href' => '/admin/spider-stats/index.php', 'icon' => '🕷️', 'title' => '蜘蛛统计', 'desc' => '搜索引擎蜘蛛监控', 'group' => 'site'),
            'plugins' => array('href' => '/admin/plugin/list.php', 'icon' => '🔌', 'title' => '插件管理', 'desc' => '扩展功能与应用', 'group' => 'system'),
            'plugin_market' => array('href' => '/admin/plugin/market.php', 'icon' => '☁️', 'title' => '插件市场', 'desc' => '云端插件下载', 'parent' => 'plugins'),
            'system_update' => array('href' => '/admin/system-update/index.php', 'icon' => '🔄', 'title' => '系统升级', 'desc' => '在线检查与升级', 'group' => 'system'),
            'settings' => array('href' => '/admin/settings/index.php', 'icon' => '⚙️', 'title' => '系统设置', 'desc' => '安全与调度', 'group' => 'system'),
            'help' => array('href' => '/admin/help/index.php', 'icon' => '❓', 'title' => '使用帮助', 'desc' => '指引与排错', 'group' => 'system'),
            'admins' => array('href' => '/admin/user/list.php', 'icon' => '👤', 'title' => '账户管理', 'desc' => '管理员与日志', 'group' => 'system')
        );
        // 允许插件注册后台菜单
        if (function_exists('hook_filter')) {
            $items = hook_filter('admin_nav_items', $items);
        }
        return $items;
    }
}

if (!function_exists('admin_nav_groups')) {
    function admin_nav_groups()
    {
        return array(
            'overview' => '总览',
            'site' => '站点',
            'system' => '系统'
        );
    }
}

if (!function_exists('render_admin_sidebar')) {
    function render_admin_sidebar($activeKey, $adminName, $adminUsername, $avatarText)
    {
        $items = admin_nav_items();
        $groups = admin_nav_groups();
        $licenseLocked = function_exists('license_is_expired') && license_is_expired();
        // 后台异步刷新版本缓存（TTL 6小时），读取是否有新版本
        $hasNewVersion = false;
        try {
            update_refresh_version_cache(21600);
            $hasNewVersion = update_has_cached_new_version();
        } catch (Exception $e) {}

        // 收集子菜单：有 parent 属性的归入对应父菜单
        $children = array();
        $childActive = array(); // 记录哪个父菜单下有激活的子菜单
        foreach ($items as $key => $item) {
            if (!empty($item['parent'])) {
                $parentKey = $item['parent'];
                if (!isset($children[$parentKey])) { $children[$parentKey] = array(); }
                $children[$parentKey][$key] = $item;
                if ($activeKey === $key) { $childActive[$parentKey] = true; }
            }
        }
        ?>
        <aside class="sidebar-float">
            <div class="sidebar-panel">
                <div class="brand-admin">
                    <div class="brand-mark"><img src="/admin-bee.png" alt="蜜蜂AI" style="width:100%; height:100%; object-fit:contain; border-radius:inherit;"></div>
                    <div class="brand-copy">
                        <strong><?php echo e(APP_NAME); ?></strong>
                        <span>后台管理系统</span>
                    </div>
                </div>
                <div class="user-card">
                    <div class="user-avatar"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></div>
                    <div class="user-meta">
                        <strong><?php echo e($adminName); ?></strong>
                        <span><?php echo e($adminUsername); ?></span>
                    </div>
                </div>
                <div class="sidebar-nav-scroll">
                    <?php if ($licenseLocked): ?>
                        <div style="margin:0 0 12px;padding:10px 12px;border-radius:10px;background:#fef2f2;border:1px solid #fecaca;color:#991b1b;font-size:12px;line-height:1.6;">
                            当前授权已过期，菜单已锁定。请前往"系统设置 - 授权管理"重新验证或重新激活。
                        </div>
                    <?php endif; ?>
                    <?php foreach ($groups as $groupKey => $groupTitle): ?>
                        <div class="sidebar-nav-group<?php echo $groupKey === 'overview' ? ' is-first' : ''; ?>">
                            <nav class="nav-list">
                                <?php foreach ($items as $key => $item): ?>
                                    <?php if (!empty($item['parent'])) { continue; } ?>
                                    <?php if ((isset($item['group']) ? $item['group'] : '') !== $groupKey) { continue; } ?>
                                    <?php if ($key === 'admins' && !is_super_admin()) { continue; } ?>
                                    <?php if ($key === 'system_update' && !is_super_admin()) { continue; } ?>
                                    <?php
                                        $lockedItem = $licenseLocked && $key !== 'settings';
                                        $href = ($key === 'settings' && $licenseLocked) ? '/admin/settings/index.php?tab=license' : $item['href'];
                                        $hasChildren = !empty($children[$key]);
                                        $isExpanded = $hasChildren && (!empty($childActive[$key]) || $activeKey === $key);
                                    ?>
                                    <?php if ($lockedItem): ?>
                                        <span class="nav-link" style="opacity:.45;cursor:not-allowed;pointer-events:none;"><span class="nav-icon nav-icon--<?php echo e(str_replace('_', '-', $key)); ?>"></span><span class="nav-text"><strong><?php echo e($item['title']); ?></strong><span>授权过期后已锁定</span></span></span>
                                    <?php elseif ($hasChildren): ?>
                                        <a class="nav-link nav-link--parent<?php echo $isExpanded ? ' expanded' : ''; ?><?php echo $activeKey === $key ? ' active' : ''; ?>" href="<?php echo e($href); ?>" data-toggle-children="<?php echo e($key); ?>"><span class="nav-icon nav-icon--<?php echo e(str_replace('_', '-', $key)); ?>"></span><span class="nav-text"><strong><?php echo e($item['title']); ?></strong><span><?php echo e($item['desc']); ?></span></span><span class="nav-arrow"><?php echo $isExpanded ? '▾' : '▸'; ?></span></a>
                                        <div class="nav-children<?php echo $isExpanded ? ' show' : ''; ?>" id="nav-children-<?php echo e($key); ?>">
                                            <?php foreach ($children[$key] as $childKey => $child): ?>
                                                <a class="nav-link nav-link--child<?php echo $activeKey === $childKey ? ' active' : ''; ?>" href="<?php echo e($child['href']); ?>"><span class="nav-child-icon"><?php echo isset($child['icon']) ? $child['icon'] : '•'; ?></span><span class="nav-text"><strong><?php echo e($child['title']); ?></strong></span></a>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <a class="nav-link<?php echo $activeKey === $key ? ' active' : ''; ?>" href="<?php echo e($href); ?>"><span class="nav-icon nav-icon--<?php echo e(str_replace('_', '-', $key)); ?>"></span><span class="nav-text"><strong><?php echo e($item['title']); ?><?php if ($key === 'system_update' && $hasNewVersion): ?><span class="nav-update-badge">有新版本</span><?php endif; ?></strong><span><?php echo e($key === 'settings' && $licenseLocked ? '前往授权管理' : $item['desc']); ?></span></span></a>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </nav>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="sidebar-foot">
                    <a class="sidebar-logout" href="/logout.php" title="退出登录" onclick="return confirm('确定退出当前登录吗？');">
                        <span class="sidebar-logout-icon">⎋</span>
                        <span>退出登录</span>
                    </a>
                    <span class="sidebar-version">BeeAI v<?php echo e(APP_VERSION); ?></span>
                </div>
            </div>
        </aside>
        <script>
        (function(){
            // 点击有子菜单的父项时切换展开/收起；按住 Ctrl/Cmd 或中键点击则正常跳转
            document.querySelectorAll('.nav-link--parent[data-toggle-children]').forEach(function(parent){
                parent.addEventListener('click', function(e){
                    if (e.ctrlKey || e.metaKey || e.button === 1) return;
                    e.preventDefault();
                    var key = parent.getAttribute('data-toggle-children');
                    var panel = document.getElementById('nav-children-' + key);
                    if (!panel) return;
                    var willShow = !panel.classList.contains('show');
                    panel.classList.toggle('show', willShow);
                    parent.classList.toggle('expanded', willShow);
                    var arrow = parent.querySelector('.nav-arrow');
                    if (arrow) arrow.textContent = willShow ? '▾' : '▸';
                });
            });
        })();
        </script>
        <?php
    }
}
