<?php
/**
 * Project: 光明组织 (The Light Org) - 多功能扩展混合终端 (全屏状态锁死版)
 * 修复：1. 彻底解决刷新后自动退出全屏的 Bug（全屏状态持久化常驻）
 * 2. 完美修复退出/进入全屏时滚动条丢失、以及刷新后回到顶端的痛点，两端体验全面对齐。
 */

mb_internal_encoding("UTF-8");

$config = [
    "org_name" => "光明组织",
    "founder"  => "不太亮的光",
    "slogan"   => "定义逻辑，自动生成现实。",
    "avatar"   => "https://q1.qlogo.cn/g?b=qq&nk=1799457360&s=640", 
    "github"   => "https://github.com/butailiangdeguang/", 
    "bg"       => "https://api.dujin.org/bing/1920.php"
];

$start_time = microtime(true);

// --- 获取访客真实 IP ---
function get_visitor_ip() {
    $ip = '0.0.0.0';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]);
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$visitor_ip = get_visitor_ip();

/**
 * 递归扫描 /pp/ 目录
 */
function render_pp_tree($current_dir, $current_active_path) {
    if (!is_dir($current_dir)) return "";
    $html = '<ul class="tree-list">';
    $files = scandir($current_dir);
    $dirs_list = []; $files_list = [];
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        if (mb_substr($file, 0, 1) === '_') continue;
        if (is_dir($current_dir . '/' . $file)) $dirs_list[] = $file;
        elseif (pathinfo($file, PATHINFO_EXTENSION) === 'md') $files_list[] = $file;
    }
    foreach ($dirs_list as $sub_dir) {
        $html .= '<li class="tree-folder">';
        $html .= '<div class="folder-title" onclick="toggleFolder(this)">📁 ' . htmlspecialchars($sub_dir) . ' <span class="arrow">▶</span></div>';
        $html .= '<div class="folder-content" style="display:none;">' . render_pp_tree($current_dir . '/' . $sub_dir, $current_active_path) . '</div>';
        $html .= '</li>';
    }
    foreach ($files_list as $file) {
        $filename = pathinfo($file, PATHINFO_FILENAME);
        $route_path = preg_replace('/^pp\//', '', $current_dir . '/' . $filename);
        $icon = (strpos($route_path, 'we/') === 0) ? "👥" : "📜";
        $active_class = ($route_path === $current_active_path && !isset($_GET['g'])) ? 'active' : '';
        
        $html .= '<li class="tree-file" data-search-name="' . mb_strtolower($filename) . '">';
        $html .= '<a href="index.php?w=' . urlencode($route_path) . '" class="menu-item ' . $active_class . '" onclick="clearScrollPos()">';
        $html .= '<span>' . $icon . '</span><span>' . htmlspecialchars($filename) . '</span>';
        $html .= '</a>';
        $html .= '</li>';
    }
    return $html . '</ul>';
}

/**
 * 自动扫描 /gg/ 目录
 */
function render_gg_menu($dir, $active_plugin) {
    if (!is_dir($dir)) return "";
    $html = '<ul class="tree-list">';
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        if (mb_substr($file, 0, 1) === '_') continue;
        if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
            $filename = pathinfo($file, PATHINFO_FILENAME);
            $active_class = ($filename === $active_plugin) ? 'active' : '';
            $html .= '<li class="tree-file" data-search-name="' . mb_strtolower($filename) . '">';
            $html .= '<a href="index.php?g=' . urlencode($filename) . '" class="menu-item ' . $active_class . '" onclick="clearScrollPos()">';
            $html .= '<span>⚡</span><span>' . htmlspecialchars($filename) . '</span>';
            $html .= '</a>';
            $html .= '</li>';
        }
    }
    return $html . '</ul>';
}

// --- 混合路由解析 ---
$content_mode = 'md'; 
$active_route = '';
$active_plugin = '';

if (isset($_GET['g'])) {
    $content_mode = 'php';
    $active_plugin = str_replace(['..', '\\'], '', $_GET['g']);
    $current_file = "gg/" . $active_plugin . ".php";
    $current_title = $active_plugin;
} else {
    $content_mode = 'md';
    $active_route = isset($_GET['w']) ? str_replace(['..', '\\'], '', $_GET['w']) : '';
    if (empty($active_route) && file_exists("pp/pages/manifesto.md")) {
        $active_route = "pages/manifesto";
    }
    $current_file = "pp/" . $active_route . ".md";
    $current_title = !empty($active_route) ? pathinfo($active_route, PATHINFO_BASENAME) : "未定义";
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $config['org_name']; ?> | <?php echo $current_title; ?></title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/styles/github-dark.min.css">
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/lib/highlight.min.js"></script>
    <style>
        :root { --light-cyan: #00ffcc; --gold: #ffcc00; --bg-glass: rgba(0, 0, 0, 0.75); }
        * { box-sizing: border-box; }
        body { 
            margin: 0; padding: 0; min-height: 100vh; 
            background: #000 url('<?php echo $config['bg']; ?>') no-repeat center center fixed; 
            background-size: cover; color: #fff;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            display: flex; justify-content: center; align-items: center;
            transition: 0.3s ease;
        }
        .container { display: flex; width: 95vw; max-width: 1200px; height: 90vh; gap: 20px; transition: 0.4s cubic-bezier(0.2, 1, 0.2, 1); }
        
        /* 🗺️ 侧边栏 */
        .sidebar { width: 280px; flex-shrink: 0; background: var(--bg-glass); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(0, 255, 204, 0.2); border-radius: 20px; padding: 25px 10px; display: flex; flex-direction: column; align-items: center; transition: 0.3s ease; }
        .avatar { width: 85px; height: 85px; border-radius: 50%; border: 2px solid var(--light-cyan); margin-bottom: 12px; flex-shrink: 0; }
        .org-name { font-size: 1.3rem; font-weight: bold; margin: 0; letter-spacing: 2px; }
        .founder { font-size: 0.8rem; color: var(--gold); margin: 5px 0 15px 0; opacity: 0.8; }
        
        .search-wrapper { width: 100%; padding: 0 10px 10px 10px; flex-shrink: 0; }
        .search-input { width: 100%; background: rgba(0,0,0,0.4); border: 1px solid rgba(0,255,204,0.15); border-radius: 8px; padding: 8px 12px; color: var(--light-cyan); font-size: 0.8rem; outline: none; font-family: monospace; transition: 0.2s; }
        .search-input:focus { border-color: var(--light-cyan); box-shadow: 0 0 8px rgba(0,255,204,0.2); }

        .menu-container { width: 100%; overflow-y: auto; flex-grow: 1; padding-right: 5px; }
        .menu-section-title { font-size: 0.75rem; color: #555; text-transform: uppercase; letter-spacing: 1px; margin: 15px 0 8px 5px; font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 3px;}
        
        ul.tree-list { list-style: none; padding-left: 12px; margin: 0; }
        ul.tree-list:first-child { padding-left: 0; }
        li { margin: 4px 0; }
        .folder-title { padding: 8px 10px; border-radius: 8px; font-size: 0.85rem; color: #aaa; cursor: pointer; display: flex; justify-content: space-between; align-items: center; font-weight: bold; }
        .folder-title:hover { background: rgba(255,255,255,0.05); color: #fff; }
        .folder-title .arrow { font-size: 0.6rem; color: #444; transition: transform 0.2s; }
        .folder-title.open { color: var(--light-cyan); }
        .folder-title.open .arrow { transform: rotate(90deg); }
        .folder-content { border-left: 1px dashed rgba(0, 255, 204, 0.15); margin-left: 8px; }

        .menu-item { display: flex; align-items: center; gap: 10px; padding: 8px 12px; background: rgba(255,255,255,0.01); border-radius: 8px; text-decoration: none; color: #bbb; font-size: 0.85rem; border: 1px solid transparent; transition: 0.2s ease; }
        .menu-item:hover, .menu-item.active { background: rgba(0, 255, 204, 0.08); border-color: var(--light-cyan); color: var(--light-cyan); transform: translateX(4px); }
        .menu-item.active { font-weight: bold; background: rgba(0, 255, 204, 0.12); }

        /* 🖥️ 右侧内容主舱 */
        .content-box { flex-grow: 1; background: var(--bg-glass); backdrop-filter: blur(15px); border-radius: 20px; padding: 40px; border: 1px solid rgba(255,255,255,0.1); display: flex; flex-direction: column; position: relative; transition: 0.4s cubic-bezier(0.2, 1, 0.2, 1); }
        
        .top-meta-container { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; margin-bottom: 30px; flex-shrink: 0; }
        .slogan-bar { border-left: 4px solid var(--light-cyan); padding: 5px 15px; font-style: italic; font-size: 0.9rem; color: #ccc; margin: 0; }
        
        .panel-controls { display: flex; align-items: center; gap: 12px; z-index: 100; flex-shrink: 0; }
        .control-btn { background: rgba(0,255,204,0.05); border: 1px solid rgba(0,255,204,0.3); border-radius: 8px; color: var(--light-cyan); padding: 8px 12px; font-size: 0.8rem; font-family: monospace; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 6px; white-space: nowrap; }
        .control-btn:hover { background: var(--light-cyan); color: #000; box-shadow: 0 0 10px rgba(0,255,204,0.4); }
        
        .settings-dropdown { display: none; position: absolute; top: 40px; right: 0; background: #0c0c0c; border: 1px solid var(--light-cyan); border-radius: 12px; padding: 15px; width: 220px; box-shadow: 0 10px 25px rgba(0,0,0,0.5); z-index: 200; }
        .settings-title { font-size: 0.75rem; color: #666; font-family: monospace; font-weight: bold; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 1px; }
        .speed-slider-label { font-size: 0.8rem; display: flex; justify-content: space-between; margin-bottom: 6px; color: #ccc; font-family: monospace; }
        .speed-slider { width: 100%; accent-color: var(--light-cyan); background: #222; outline: none; cursor: pointer; }

        /* 全屏激活动态类 */
        .fullscreen-active .sidebar { 
            width: 0 !important; padding: 0 !important; margin: 0 !important;
            overflow: hidden !important; border: none !important; opacity: 0 !important; 
            pointer-events: none !important; flex-shrink: 1 !important;
        }
        .fullscreen-active .container { max-width: 100vw !important; width: 100vw !important; height: 100vh !important; gap: 0 !important; }
        .fullscreen-active .content-box { border-radius: 0 !important; border: none !important; width: 100% !important; height: 100% !important; padding: 40px !important; }

        #main-display { flex-grow: 1; overflow-y: auto; padding-bottom: 20px; }
        #render h1, #render h2, #render h3 { color: var(--light-cyan); margin-top: 1.2em; }
        #render code { color: var(--gold); background: rgba(0,0,0,0.4); padding: 2px 5px; border-radius: 4px; font-family: monospace; }
        #render pre { background: rgba(0,0,0,0.3); padding: 15px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); overflow-x: auto; }

        .terminal-footer { border-top: 1px solid rgba(255, 255, 255, 0.1); padding-top: 15px; margin-top: 10px; font-size: 0.78rem; color: #666; font-family: monospace; display: flex; justify-content: space-between; flex-shrink: 0; user-select: none; }
        .dashboard-item { margin-right: 15px; color: #888; }
        .dashboard-item span { color: var(--gold); }
        .ip-highlight { color: var(--light-cyan); font-weight: bold; }

        .lock-container { text-align: center; padding: 60px 20px; }
        .lock-input { background: rgba(0,0,0,0.5); border: 1px solid var(--light-cyan); padding: 10px 15px; border-radius: 8px; color: #fff; text-align: center; font-size: 1rem; letter-spacing: 2px; outline: none; margin-top: 15px; width: 200px; }
        .lock-btn { background: var(--light-cyan); color: #000; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; margin-left: 10px; transition: 0.2s; }
        .lock-btn:hover { background: #00ccff; box-shadow: 0 0 10px rgba(0,255,204,0.5); }

        /* 📱 移动端媒体查询响应拦截断点 */
        @media (max-width: 900px) { 
            body { height: auto; overflow-y: auto; display: block; padding: 15px 0; }
            .container { flex-direction: column; height: auto; width: 95vw; margin: 0 auto; gap: 15px; } 
            .sidebar { width: 100%; height: auto; padding: 20px 15px; } 
            .content-box { height: auto; min-height: 65vh; padding: 25px 20px; border-radius: 20px; } 
            
            .top-meta-container { flex-direction: column; align-items: flex-start; gap: 15px; margin-bottom: 20px; }
            .panel-controls { width: 100%; justify-content: flex-start; gap: 10px; }
            .control-btn { padding: 6px 10px; font-size: 0.75rem; }
            .settings-dropdown { left: 0; right: auto; top: 35px; }
            
            .terminal-footer { flex-direction: column; gap: 8px; align-items: flex-start; }

            .fullscreen-active { height: 100vh !important; overflow: hidden !important; }
            .fullscreen-active .container { width: 100vw !important; height: 100vh !important; margin: 0 !important; }
            .fullscreen-active .content-box { position: fixed !important; top: 0 !important; left: 0 !important; right: 0 !important; bottom: 0 !important; z-index: 9999 !important; overflow-y: auto !important; padding: 30px 20px !important; }
        }
    </style>
</head>
<body>
<div class="container" id="terminal-wrapper">
    <div class="sidebar">
        <img src="<?php echo $config['avatar']; ?>" class="avatar" onerror="this.src='https://via.placeholder.com/100/00ffcc/000000?text=Org'">
        <p class="org-name"><?php echo $config['org_name']; ?></p>
        <p class="founder">By <?php echo $config['founder']; ?></p>
        
        <div class="search-wrapper">
            <input type="text" id="treeSearchInput" class="search-input" placeholder="[ 🔍 搜索全站数据节点... ]" oninput="executeTreeSearch()">
        </div>
        
        <div class="menu-container">
            <div class="menu-section-title">📜 知识库集群 (/pp/)</div>
            <?php echo render_pp_tree("pp", $active_route); ?>
            
            <div class="menu-section-title">⚡ 极客功能舱 (/gg/)</div>
            <?php echo render_gg_menu("gg", $active_plugin); ?>
            
            <div class="menu-section-title">📡 外部链接</div>
            <ul class="tree-list">
                <li><a href="<?php echo $config['github']; ?>" target="_blank" class="menu-item"><span>🐙</span><span>Github</span></a></li>
            </ul>
        </div>
    </div>
    
    <div class="content-box" id="mobile-fullscreen-scroll-node">
        <div class="top-meta-container">
            <div class="slogan-bar"><?php echo $config['slogan']; ?></div>
            
            <div class="panel-controls">
                <button class="control-btn" onclick="toggleFullscreenMode()" id="fsBtn">⚡ FULLSCREEN</button>
                <div style="position: relative;">
                    <button class="control-btn" onclick="toggleSettingsDropdown(event)">⚙️ SETTINGS</button>
                    <div class="settings-dropdown" id="settingsBox" onclick="event.stopPropagation()">
                        <div class="settings-title">🔮 TERMINAL CONTROLS</div>
                        <div class="speed-slider-label">
                            <span>打字模拟速率:</span>
                            <span id="sliderValDisplay">30ms</span>
                        </div>
                        <input type="range" min="0" max="100" value="30" class="speed-slider" id="typerSpeedSlider" oninput="updateTyperSpeed(this.value)">
                    </div>
                </div>
            </div>
        </div>
        
        <div id="main-display">
            <?php if ($content_mode === 'php'): ?>
                <?php 
                if (file_exists($current_file)) {
                    include $current_file; 
                } else {
                    echo "<h3>⚠️ 模块丢失</h3>文件 `{$current_file}` 未被定义。";
                }
                ?>
            <?php else: ?>
                <div id="render"></div>
            <?php endif; ?>
        </div>
        
        <div class="terminal-footer">
            <div class="dashboard-left">
                <span class="dashboard-item">⚙️ MODE: <span><?php echo strtoupper($content_mode); ?></span></span>
                <span class="dashboard-item">⏱️ LOAD: <span><?php echo round((microtime(true) - $start_time) * 1000, 2); ?>ms</span></span>
                <span class="dashboard-item">📝 STATS: <span id="word-count"><?php echo ($content_mode === 'php' ? 'DYNAMIC_APP' : '0'); ?></span></span>
            </div>
            <div class="dashboard-right">
                <span>您的IP：<span class="ip-highlight"><?php echo $visitor_ip; ?></span></span>
            </div>
        </div>
    </div>
</div>

<script>
    function toggleFolder(element) {
        element.classList.toggle('open');
        const content = element.nextElementSibling;
        content.style.display = (content.style.display === 'none') ? 'block' : 'none';
    }

    // --- 📺 核心重构：全屏形态双向数据记忆与同步锁 ---
    function toggleFullscreenMode() {
        const body = document.body;
        body.classList.toggle('fullscreen-active');
        const isFS = body.classList.contains('fullscreen-active');
        
        // 同步存入 sessionStorage 中锁死状态
        sessionStorage.setItem('terminal_fullscreen_state', isFS ? 'active' : 'normal');
        updateFullscreenButtonUI(isFS);
    }

    function updateFullscreenButtonUI(isFS) {
        const btn = document.getElementById('fsBtn');
        if(isFS) {
            btn.innerHTML = "📺 EXIT_FOCUS";
            btn.style.borderColor = "var(--gold)";
            btn.style.color = "var(--gold)";
        } else {
            btn.innerHTML = "⚡ FULLSCREEN";
            btn.style.borderColor = "rgba(0,255,204,0.3)";
            btn.style.color = "var(--light-cyan)";
        }
    }

    function toggleSettingsDropdown(e) {
        e.stopPropagation();
        const box = document.getElementById('settingsBox');
        box.style.display = (box.style.display === 'block') ? 'none' : 'block';
    }
    document.addEventListener('click', () => {
        document.getElementById('settingsBox').style.display = 'none';
    });

    let currentTyperSpeed = localStorage.getItem('terminal_typer_speed') !== null ? parseInt(localStorage.getItem('terminal_typer_speed')) : 30;
    document.getElementById('typerSpeedSlider').value = currentTyperSpeed;
    document.getElementById('sliderValDisplay').innerText = currentTyperSpeed === 0 ? "OFF (瞬间加载)" : currentTyperSpeed + "ms";

    function updateTyperSpeed(val) {
        currentTyperSpeed = parseInt(val);
        localStorage.setItem('terminal_typer_speed', currentTyperSpeed);
        document.getElementById('sliderValDisplay').innerText = currentTyperSpeed === 0 ? "OFF (瞬间加载)" : currentTyperSpeed + "ms";
    }

    // --- 🛡️ 终极自适应：多端多姿态滚动高度捕获器 ---
    const pcScrollContainer = document.getElementById('main-display');
    const mobileFullScrollContainer = document.getElementById('mobile-fullscreen-scroll-node');

    function saveScrollPosition() {
        let currentTop = 0;
        // 判定当前是处于手机端的全屏固定定位状态，还是普通多级排版状态
        if (document.body.classList.contains('fullscreen-active') && window.innerWidth <= 900) {
            currentTop = mobileFullScrollContainer.scrollTop;
        } else {
            currentTop = pcScrollContainer.scrollTop;
        }
        sessionStorage.setItem('terminal_scroll_pos', currentTop);
    }
    pcScrollContainer.addEventListener('scroll', saveScrollPosition);
    mobileFullScrollContainer.addEventListener('scroll', saveScrollPosition);

    function restoreScrollPosition() {
        const savedPos = sessionStorage.getItem('terminal_scroll_pos');
        if (savedPos !== null) {
            const targetTop = parseInt(savedPos);
            if (document.body.classList.contains('fullscreen-active') && window.innerWidth <= 900) {
                mobileFullScrollContainer.scrollTop = targetTop;
            } else {
                pcScrollContainer.scrollTop = targetTop;
            }
        }
    }

    function clearScrollPos() {
        sessionStorage.removeItem('terminal_scroll_pos');
    }

    // 搜索
    function executeTreeSearch() {
        const query = document.getElementById('treeSearchInput').value.trim().toLowerCase();
        const files = document.querySelectorAll('.tree-file');
        const folders = document.querySelectorAll('.tree-folder');
        
        if (!query) {
            files.forEach(f => f.style.display = 'block');
            folders.forEach(f => {
                f.style.display = 'block';
                f.querySelector('.folder-content').style.display = 'none';
                f.querySelector('.folder-title').classList.remove('open');
            });
            reExpandActiveNode();
            return;
        }

        folders.forEach(folder => {
            folder.style.display = 'none';
            folder.querySelector('.folder-content').style.display = 'none';
        });

        files.forEach(file => {
            const searchName = file.getAttribute('data-search-name') || '';
            if (searchName.includes(query)) {
                file.style.display = 'block';
                let parentFolder = file.closest('.tree-folder');
                while (parentFolder) {
                    parentFolder.style.display = 'block';
                    parentFolder.querySelector('.folder-content').style.display = 'block';
                    parentFolder.querySelector('.folder-title').classList.add('open');
                    parentFolder = parentFolder.parentElement.closest('.tree-folder');
                }
            } else {
                file.style.display = 'none';
            }
        });
    }

    function reExpandActiveNode() {
        const activeLink = document.querySelector('.menu-item.active');
        if (activeLink) {
            let parentFolder = activeLink.closest('.folder-content');
            while (parentFolder) {
                parentFolder.style.display = 'block';
                parentFolder.previousElementSibling.classList.add('open');
                parentFolder = parentFolder.parentElement.closest('.folder-content');
            }
        }
    }

    // --- 🔮 核心拦截：DOM 载入完毕时立刻抢先恢复全屏状态与滚动条 ---
    document.addEventListener('DOMContentLoaded', () => {
        const savedFS = sessionStorage.getItem('terminal_fullscreen_state');
        if (savedFS === 'active') {
            document.body.classList.add('fullscreen-active');
            updateFullscreenButtonUI(true);
        }
        reExpandActiveNode();
    });

    <?php if ($content_mode === 'md'): ?>
    const rawContent = <?php echo json_encode(file_exists($current_file) ? file_get_contents($current_file) : ''); ?>;
    let typerTimer = null;

    function processAndRender(contentData) {
        if (!contentData) return;
        const lockMatch = contentData.match(/<密文>(.*?)<\/密文>/);
        if (lockMatch) {
            const correctPassword = lockMatch[1];
            document.getElementById('render').innerHTML = `
                <div class="lock-container">
                    <h3>🔒 核心敏感数据已加密</h3>
                    <p style="color:#aaa; font-size:0.85rem;">该档案受 光明组织 安全协议保护，请输入凭证解密</p>
                    <input type="password" id="passInput" class="lock-input" placeholder="输入访问密钥..." onkeydown="if(event.keyCode==13) verifyLock()">
                    <button class="lock-btn" onclick="verifyLock()">解密</button>
                    <div id="lockError" style="color:#ff4d4d; margin-top:10px; font-size:0.85rem;"></div>
                </div>
            `;
            document.getElementById('word-count').innerText = "LOCKED";
            
            window.verifyLock = function() {
                if (document.getElementById('passInput').value === correctPassword) {
                    executeRender(contentData.replace(/<密文>.*?<\/密文>/g, ''));
                } else {
                    document.getElementById('lockError').innerText = "❌ 凭证错误，访问已被拒绝。";
                }
            }
        } else {
            executeRender(contentData);
        }
    }

    function executeRender(markdownText) {
        let txt = markdownText;
        const colorMap = { '红色': '#ff4d4d', '青色': '#00ffcc', '金色': '#ffcc00', '灰色': '#888888', '橙色': '#ff9900' };
        Object.keys(colorMap).forEach(key => {
            txt = txt.replace(new RegExp(`<${key}>(.*?)</${key}>`, 'g'), `<span style="color:${colorMap[key]};font-weight:bold;">$1</span>`);
        });
        
        marked.setOptions({ sanitize: false, breaks: true });
        const finalHtml = marked.parse(txt);
        
        if (currentTyperSpeed === 0) {
            document.getElementById('render').innerHTML = finalHtml;
            hljs.highlightAll();
            document.getElementById('word-count').innerText = document.getElementById('render').innerText.replace(/\s+/g, '').length;
            setTimeout(restoreScrollPosition, 20); // 确保容器全屏DOM响应就绪后还原高度
        } else {
            if(typerTimer) clearInterval(typerTimer);
            const targetContainer = document.getElementById('render');
            targetContainer.innerHTML = ""; 
            
            const virtualDiv = document.createElement('div');
            virtualDiv.innerHTML = finalHtml;
            const fullTextStr = virtualDiv.innerText.replace(/\s+/g, '');
            
            let currentLength = 0;
            typerTimer = setInterval(() => {
                if (currentLength >= finalHtml.length) {
                    clearInterval(typerTimer);
                    targetContainer.innerHTML = finalHtml; 
                    hljs.highlightAll();
                    document.getElementById('word-count').innerText = fullTextStr.length;
                    setTimeout(restoreScrollPosition, 20);
                    return;
                }
                
                if (finalHtml[currentLength] === '<') {
                    const tagEndIndex = finalHtml.indexOf('>', currentLength);
                    if (tagEndIndex !== -1) {
                        currentLength = tagEndIndex + 1;
                    } else {
                        currentLength++;
                    }
                } else {
                    currentLength++;
                }
                
                targetContainer.innerHTML = finalHtml.substring(0, currentLength);
                document.getElementById('word-count').innerText = Math.min(Math.floor((currentLength / finalHtml.length) * fullTextStr.length), fullTextStr.length);
            }, currentTyperSpeed);
        }
    }
    
    document.addEventListener('DOMContentLoaded', () => {
        processAndRender(rawContent);
    });
    <?php else: ?>
    // PHP功能舱组件加载完毕后，立刻瞬间重置回原本的高度
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(restoreScrollPosition, 60);
    });
    <?php endif; ?>
</script>
</body>
</html>
