/**
 * 闯关卡网页生成器 v2
 * 布局：左上(任务目标+过关方式+快速开始) | 右上(通关提示+隐藏玩法)
 *       中间(展示环节+小知识) | 底部(流程提醒)
 */

const fs = require('fs');
const path = require('path');

const CARDS_DIR = __dirname;
const OUTPUT_FILE = path.join(CARDS_DIR, 'index.html');

function mdToHtml(md) {
    if (!md) return '';
    let html = md
        .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
        .replace(/\*([^*]+)\*/g, '<em>$1</em>')
        .replace(/^#### (.+)$/gm, '<h4>$1</h4>')
        .replace(/^### (.+)$/gm, '<h3>$1</h3>')
        .replace(/^---$/gm, '<hr>')
        .replace(/\n\n+/g, '</p><p>')
        .replace(/(<li>.*?<\/li>)+/g, m => '<ul>' + m + '</ul>')
        .replace(/^(?!<[hupret]|<li|<ul|<ol|<pre)(.+)$/gm, '<p>$1</p>')
        .replace(/<p><\/p>/g, '');
    return html;
}

function splitByHeader(content) {
    const blocks = {};
    const parts = content.split(/(?=^## )/m);
    for (const part of parts) {
        const match = part.match(/^## (.+)\n([\s\S]*)$/);
        if (match) blocks[match[1].trim()] = match[2].trim();
    }
    return blocks;
}

function parseLevels(content) {
    const levels = { green: '', blue: '', red: '' };
    // 先按 --- 分段，再去掉每段的 ### 标题行
    const parts = content.split(/\n---\n/);
    const cleanParts = parts.map(p => p.replace(/^### [🟢🔵🔴⭐\s].*$/gm, '').trim());
    if (cleanParts[0]) levels.green = mdToHtml(cleanParts[0]);
    if (cleanParts[1]) levels.blue = mdToHtml(cleanParts[1]);
    if (cleanParts[2]) levels.red = mdToHtml(cleanParts[2]);
    return levels;
}

function extractTitle(content) {
    const m = content.match(/^# (.+)$/m);
    return m ? m[1] : '闯关卡';
}

function extractNavName(filename) {
    return filename
        .replace(/^智能体入门_\d{4}-\d{2}-\d{2}_/, '')
        .replace(/_v\d+$/, '')
        .replace(/.md$/, '');
}

// 从 README.md 读取序号，映射 filename -> order
function getOrderMap() {
    const readme = fs.readFileSync(path.join(CARDS_DIR, 'README.md'), 'utf-8');
    const map = {};
    const rows = readme.split('\n');
    for (const row of rows) {
        const m = row.match(/^\|\s*(\d+)\s*\|/);
        if (m) {
            // 找到同一行的文件名
            const fileMatch = row.match('`([^`]+)`');
            if (fileMatch) {
                map[fileMatch[1]] = parseInt(m[1]);
            }
        }
    }
    return map;
}

function generate() {
    const orderMap = getOrderMap();
    const allFiles = fs.readdirSync(CARDS_DIR).filter(f => f.endsWith('.md') && !['README.md', 'workflow-new-card.md'].includes(f));

    const files = [...allFiles].sort((a, b) => {
        const oa = orderMap[a] ?? 999;
        const ob = orderMap[b] ?? 999;
        if (oa !== ob) return oa - ob;
        return a.localeCompare(b);
    });

    const cards = files.map(filename => {
        const content = fs.readFileSync(path.join(CARDS_DIR, filename), 'utf-8');
        const blocks = splitByHeader(content);
        const levelBlock = blocks['🎮 过关方式'] || blocks['过关方式'] || '';
        const levels = parseLevels(levelBlock);
        return { filename, name: extractNavName(filename), title: extractTitle(content), blocks, levels };
    });

    const navItems = cards.map((c, i) =>
        `<a href="#" class="nav-item${i === 0 ? ' active' : ''}" data-index="${i}" onclick="showCard(${i});return false;">${c.name}</a>`
    ).join('\n');

    const cardSections = cards.map((card, i) => {
        if (card.filename.includes('快捷账号')) {
            const raw = fs.readFileSync(path.join(CARDS_DIR, card.filename), 'utf-8');
            return `<div class="card-section${i === 0 ? ' active' : ''}" id="card-${i}">
                <div class="card-header"><h1>🔑 ${card.title}</h1></div>
                <div class="info-block">${mdToHtml(raw)}</div>
            </div>`;
        }
        const b = card.blocks;
        return `<div class="card-section${i === 0 ? ' active' : ''}" id="card-${i}">
            <div class="card-header"><h1>${card.title}</h1></div>
            <div class="main-grid">
                <div class="col-left">
                    ${b['🧩 任务目标'] || b['任务目标'] ? `<div class="block"><h2>🧩 任务目标</h2>${mdToHtml(b['🧩 任务目标'] || b['任务目标'])}</div>` : ''}
                    ${card.levels.green || card.levels.blue || card.levels.red ? `<div class="block"><h2>🎮 过关方式</h2>
                        ${card.levels.green ? `<div class="level"><h3 class="green">🟢 过关 ⭐</h3>${card.levels.green}</div>` : ''}
                        ${card.levels.blue ? `<div class="level"><h3 class="blue">🔵 进阶 ⭐⭐</h3>${card.levels.blue}</div>` : ''}
                        ${card.levels.red ? `<div class="level"><h3 class="red">🔴 高手 ⭐⭐⭐</h3>${card.levels.red}</div>` : ''}
                    </div>` : ''}
                    ${b['🚀 快速开始'] || b['快速开始'] ? `<div class="block"><h2>🚀 快速开始</h2>${mdToHtml(b['🚀 快速开始'] || b['快速开始'])}</div>` : ''}
                </div>
                <div class="col-right">
                    ${b['🧠 通关提示'] || b['通关提示'] ? `<div class="block"><h2 class="purple">🧠 通关提示</h2>${mdToHtml(b['🧠 通关提示'] || b['通关提示'])}</div>` : ''}
                    ${b['🌟 隐藏玩法'] || b['隐藏玩法'] ? `<div class="block"><h2 class="pink">🌟 隐藏玩法</h2>${mdToHtml(b['🌟 隐藏玩法'] || b['隐藏玩法'])}</div>` : ''}
                </div>
            </div>
            <div class="bottom-grid">
                ${b['👀 展示环节'] || b['展示环节'] ? `<div class="block"><h2 class="teal">👀 展示环节</h2>${mdToHtml(b['👀 展示环节'] || b['展示环节'])}</div>` : ''}
                ${b['📚 小知识'] || b['小知识'] ? `<div class="block"><h2>📚 小知识</h2>${mdToHtml(b['📚 小知识'] || b['小知识'])}</div>` : ''}
            </div>
            ${b['🧭 流程提醒'] || b['流程提醒'] ? `<div class="block full"><h2 class="orange">🧭 流程提醒</h2>${mdToHtml(b['🧭 流程提醒'] || b['流程提醒'])}</div>` : ''}
        </div>`;
    }).join('\n');

    const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>闯关卡 - 第1课 · 智能体入门</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f0f2f5;color:#333;line-height:1.7;display:flex;min-height:100vh}
.sidebar{width:240px;background:#1a1a2e;color:#fff;flex-shrink:0;overflow-y:auto;padding:20px 0}
.sidebar-title{padding:0 20px 16px;font-size:1em;font-weight:bold;border-bottom:1px solid #333;margin-bottom:12px;color:#ffd700}
.nav-item{display:block;padding:10px 20px;color:#aaa;text-decoration:none;font-size:0.88em;cursor:pointer;transition:.2s;border-left:3px solid transparent}
.nav-item:hover{color:#fff;background:#16213e}
.nav-item.active{color:#ffd700;background:#16213e;border-left-color:#ffd700}
.main{flex:1;padding:28px 32px;overflow-y:auto}
.card-section{display:none}
.card-section.active{display:block}
.card-header{background:#fff;border-radius:12px;padding:18px 24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
.card-header h1{font-size:1.5em;color:#1a1a2e}
.main-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px}
.col-left,.col-right{display:flex;flex-direction:column;gap:16px}
.bottom-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px}
.block{background:#fff;border-radius:12px;padding:18px 22px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
.block h2{font-size:1.05em;margin-bottom:10px;color:#2563eb}
.block h2.purple{color:#7c3aed}
.block h2.pink{color:#db2777}
.block h2.teal{color:#0d9488}
.block h2.orange{color:#ea580c}
.block h3{font-size:0.95em;margin:8px 0 4px}
.block p{margin:4px 0}
.block ul,.block ol{padding-left:22px;margin:4px 0}
.block li{margin:3px 0}
.block pre{background:#f4f4f4;padding:10px 14px;border-radius:8px;overflow-x:auto;font-size:.85em;margin:6px 0}
.block code{background:#f4f4f4;padding:2px 5px;border-radius:4px;font-size:.85em}
.block hr{border:none;border-top:1px solid #eee;margin:12px 0}
.level-green{color:#059669}
.level-blue{color:#2563eb}
.level-red{color:#dc2626}
.full{grid-column:1/-1}
.info-block{background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
.info-block h2{font-size:1.1em;margin:16px 0 8px;color:#2563eb}
.info-block h2:first-child{margin-top:0}
.info-block p{margin:4px 0}
.info-block ul,.info-block ol{padding-left:22px;margin:4px 0}
.info-block li{margin:3px 0}
.info-block pre{background:#f4f4f4;padding:10px 14px;border-radius:8px;overflow-x:auto;font-size:.85em;margin:6px 0;border-left:3px solid #ffd700}
.info-block blockquote{background:#fef3c7;border-left:4px solid #f59e0b;padding:10px 14px;margin:10px 0;border-radius:0 6px 6px 0;font-size:0.92em}
</style>
</head>
<body>
<div class="sidebar">
<div class="sidebar-title">📚 第1课 · 智能体入门</div>
${navItems}
</div>
<div class="main">
${cardSections}
</div>
<script>
function showCard(i){
    document.querySelectorAll('.card-section').forEach((e,j)=>e.classList.toggle('active',j===i));
    document.querySelectorAll('.nav-item').forEach((e,j)=>e.classList.toggle('active',j===i));
}
showCard(0);
</script>
</body>
</html>`;

    fs.writeFileSync(OUTPUT_FILE, html, 'utf-8');
    console.log(`✅ 已生成 ${OUTPUT_FILE}，共 ${cards.length} 张`);
}

generate();
