index.html 28.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Direct Console</title>
<style>
:root {
	--bg: #0d1117;
	--surface: #161b22;
	--surface-2: #1c2128;
	--border: #30363d;
	--text: #e6edf3;
	--text-dim: #8b949e;
	--accent: #58a6ff;
	--accent-bg: #1f6feb;
	--success: #3fb950;
	--warn: #d29922;
	--error: #f85149;
	--code-bg: #0d1117;
}
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif; background:var(--bg); color:var(--text); height:100vh; overflow:hidden; }
.app { display:grid; grid-template-columns:340px 1fr; grid-template-rows:48px 1fr; height:100vh; }
.topbar { grid-column:1/-1; display:flex; align-items:center; gap:16px; padding:0 20px; background:var(--surface); border-bottom:1px solid var(--border); }
.topbar h1 { font-size:15px; font-weight:600; white-space:nowrap; }
.topbar h1 span { color:var(--accent); }
.progress-steps { display:flex; gap:4px; flex:1; }
.step { display:flex; align-items:center; gap:4px; font-size:11px; color:var(--text-dim); padding:4px 8px; border-radius:12px; background:var(--surface-2); white-space:nowrap; transition:all 0.3s; }
.step.active { color:var(--accent); background:rgba(88,166,255,0.2); font-weight:600; border:1px solid rgba(88,166,255,0.4); }
.step.active .step-icon { animation:spin 1s linear infinite; border:2px solid var(--accent); border-top-color:transparent; background:none; }
.step.done { color:var(--success); background:rgba(63,185,80,0.15); font-weight:500; }
.step.done .step-icon::after { content:'✓'; font-size:9px; font-weight:bold; }
.step.done .step-icon { width:auto; height:auto; background:none; border-radius:0; }
.step.error { color:var(--error); background:rgba(248,81,73,0.1); }
.step-icon { width:6px; height:6px; border-radius:50%; background:currentColor; flex-shrink:0; }
@keyframes spin { to { transform:rotate(360deg); } }
.status-badge { font-size:12px; padding:3px 10px; border-radius:12px; font-weight:500; }
.status-badge.idle { background:var(--surface-2); color:var(--text-dim); }
.status-badge.running { background:rgba(88,166,255,0.15); color:var(--accent); animation:pulse 2s infinite; }
.status-badge.done { background:rgba(63,185,80,0.15); color:var(--success); }
.status-badge.error { background:rgba(248,81,73,0.1); color:var(--error); }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.6} }

.sidebar { overflow-y:auto; background:var(--surface); border-right:1px solid var(--border); padding:12px; display:flex; flex-direction:column; gap:8px; }
.sidebar::-webkit-scrollbar { width:4px; }
.sidebar::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }

.section { background:var(--surface-2); border:1px solid var(--border); border-radius:8px; overflow:hidden; }
.section-header { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; cursor:pointer; user-select:none; font-size:13px; font-weight:600; }
.section-header:hover { background:rgba(255,255,255,0.03); }
.section-header .arrow { transition:transform 0.2s; font-size:10px; color:var(--text-dim); }
.section-header .arrow.open { transform:rotate(90deg); }
.section-body { padding:8px 12px 12px; display:flex; flex-direction:column; gap:8px; }
.section-body.hidden { display:none; }

label { font-size:12px; color:var(--text-dim); display:flex; flex-direction:column; gap:3px; }
input,select,textarea { background:var(--bg); border:1px solid var(--border); border-radius:6px; padding:7px 10px; font-size:13px; color:var(--text); font-family:inherit; outline:none; transition:border-color 0.2s; width:100%; }
input:focus,select:focus,textarea:focus { border-color:var(--accent); }
input::placeholder { color:var(--text-dim); }
select { cursor:pointer; }

.checkbox-row { display:flex; align-items:center; gap:8px; font-size:13px; cursor:pointer; }
.checkbox-row input[type=checkbox] { width:auto; accent-color:var(--accent); cursor:pointer; }

.btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; padding:9px 16px; border:none; border-radius:8px; font-size:13px; font-weight:600; cursor:pointer; transition:all 0.15s; font-family:inherit; }
.btn-primary { background:var(--accent-bg); color:#fff; }
.btn-primary:hover { background:#388bfd; }
.btn-primary:disabled { opacity:0.4; cursor:not-allowed; }
.btn-danger { background:rgba(248,81,73,0.15); color:var(--error); border:1px solid rgba(248,81,73,0.3); }
.btn-danger:hover { background:rgba(248,81,73,0.25); }
.btn-ghost { background:transparent; color:var(--text-dim); border:1px solid var(--border); }
.btn-ghost:hover { color:var(--text); border-color:var(--text-dim); }
.btn-row { display:flex; gap:8px; }
.btn-row .btn { flex:1; }

.main { display:flex; flex-direction:column; overflow:hidden; }
.tabs { display:flex; background:var(--surface); border-bottom:1px solid var(--border); }
.tab { padding:10px 20px; font-size:13px; font-weight:500; cursor:pointer; border-bottom:2px solid transparent; color:var(--text-dim); transition:all 0.15s; }
.tab:hover { color:var(--text); }
.tab.active { color:var(--accent); border-bottom-color:var(--accent); }
.tab-content { flex:1; overflow:hidden; position:relative; }
.tab-panel { display:none; height:100%; }
.tab-panel.active { display:flex; flex-direction:column; }

.console { flex:1; overflow-y:auto; padding:12px 16px; font-family:'Cascadia Code',Consolas,'Courier New',monospace; font-size:12.5px; line-height:1.7; background:var(--code-bg); }
.console::-webkit-scrollbar { width:6px; }
.console::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.console-line { white-space:pre-wrap; word-break:break-all; }
.console-line.stderr { color:var(--error); }
.console-line.system { color:var(--accent); font-style:italic; }
.console-line.progress { color:var(--warn); font-weight:500; }
.console-line.heartbeat { color:var(--text-dim); }
.console-line.success { color:var(--success); }
.console-line.error { color:var(--error); font-weight:500; }
.console-line.warning { color:var(--warn); }
.console-line.info { color:var(--accent); }
.console-line.dim { color:var(--text-dim); }
.heartbeat-live { animation:hbPulse 1.2s ease-in-out infinite; }
@keyframes hbPulse { 0%,100%{opacity:0.5} 50%{opacity:1} }
.console-empty { color:var(--text-dim); text-align:center; padding-top:40vh; }

.file-panel { display:flex; height:100%; }
.file-tree { width:240px; min-width:200px; border-right:1px solid var(--border); overflow-y:auto; padding:8px; background:var(--surface); }
.file-tree::-webkit-scrollbar { width:4px; }
.file-tree::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.file-item { padding:6px 10px; font-size:12px; cursor:pointer; border-radius:6px; color:var(--text-dim); display:flex; align-items:center; gap:6px; }
.file-item:hover { background:var(--surface-2); color:var(--text); }
.file-item.active { background:rgba(88,166,255,0.1); color:var(--accent); }
.file-icon { font-size:14px; }
.code-viewer { flex:1; overflow:auto; padding:16px; background:var(--code-bg); }
.code-viewer::-webkit-scrollbar { width:6px; height:6px; }
.code-viewer::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.code-viewer pre { font-family:'Cascadia Code',Consolas,'Courier New',monospace; font-size:12.5px; line-height:1.6; white-space:pre; tab-size:2; }
.code-viewer .file-path { font-size:12px; color:var(--text-dim); margin-bottom:12px; padding-bottom:8px; border-bottom:1px solid var(--border); }
.code-empty { color:var(--text-dim); display:flex; align-items:center; justify-content:center; height:100%; font-size:14px; }

.preview-panel { flex:1; display:flex; flex-direction:column; background:var(--bg); }
.preview-toolbar { display:flex; align-items:center; gap:8px; padding:8px 12px; background:var(--surface); border-bottom:1px solid var(--border); }
.preview-toolbar .url-bar { flex:1; background:var(--bg); border:1px solid var(--border); border-radius:6px; padding:6px 10px; font-size:12px; color:var(--text); font-family:'Cascadia Code',Consolas,monospace; }
.preview-toolbar .btn { padding:6px 12px; font-size:12px; }
.preview-frame { flex:1; border:none; background:#fff; }
.preview-empty { flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; color:var(--text-dim); }
.preview-empty .icon { font-size:48px; opacity:0.3; }
.preview-empty .msg { font-size:14px; }
.preview-empty .hint { font-size:12px; color:var(--text-dim); opacity:0.6; }

.summary-panel { flex:1; overflow-y:auto; padding:16px; background:var(--code-bg); }
.summary-panel::-webkit-scrollbar { width:6px; }
.summary-panel::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.summary-card { background:var(--surface); border:1px solid var(--border); border-radius:8px; padding:16px; margin-bottom:12px; }
.summary-card h3 { font-size:13px; margin-bottom:8px; color:var(--accent); }
.summary-card pre { font-family:'Cascadia Code',Consolas,'Courier New',monospace; font-size:12px; line-height:1.5; white-space:pre-wrap; word-break:break-all; color:var(--text-dim); }
</style>
</head>
<body>
<div class="app">
	<div class="topbar">
		<h1>Venus <span>AI Direct</span></h1>
		<div class="progress-steps" id="progressSteps"></div>
		<div class="status-badge idle" id="statusBadge">空闲</div>
	</div>

	<div class="sidebar">
		<div class="section">
			<div class="section-header" onclick="toggleSection(this)">
				<span>AI 模型配置</span>
				<span class="arrow open">&#9654;</span>
			</div>
			<div class="section-body">
				<label>模型
					<select id="aiModel"></select>
				</label>
				<label>API Base URL
					<select id="aiUrlSelect" onchange="onUrlSelectChange(this)"></select>
				</label>
				<label>自定义 URL
					<input type="text" id="aiBaseUrl" placeholder="https://api.example.com/v1">
				</label>
				<label>API Key
					<input type="password" id="aiApiKey" placeholder="sk-...">
				</label>
				<label>视觉模型
					<input type="text" id="visionModel" placeholder="qwen-vl-max">
				</label>
			</div>
		</div>

		<div class="section">
			<div class="section-header" onclick="toggleSection(this)">
				<span>Figma 配置</span>
				<span class="arrow open">&#9654;</span>
			</div>
			<div class="section-body">
				<label>Figma API Key
					<input type="password" id="figmaApiKey" placeholder="figd_...">
				</label>
				<label>Figma 页面 URL
					<input type="text" id="figmaUrl" placeholder="https://www.figma.com/design/...">
				</label>
			</div>
		</div>

		<div class="section">
			<div class="section-header" onclick="toggleSection(this)">
				<span>项目配置</span>
				<span class="arrow open">&#9654;</span>
			</div>
			<div class="section-body">
				<label>项目来源
					<select id="projectSource" onchange="onProjectSourceChange()">
						<option value="new">新建预览项目</option>
						<option value="bundle">已有 Context Bundle</option>
					</select>
				</label>
				<div id="newProjectOptions">
					<label>页面名称 (PascalCase)
						<input type="text" id="pageName" placeholder="AllocationConfirmation">
					</label>
				</div>
				<div id="bundleOptions" style="display:none">
					<label>选择已有 Bundle
						<select id="bundleSelect"></select>
					</label>
				</div>
				<label class="checkbox-row">
					<input type="checkbox" id="refreshContext">
					重新生成 Context(从 Figma 重新拉取)
				</label>
				<label class="checkbox-row">
					<input type="checkbox" id="forceOverwrite" checked>
					覆盖已有预览项目
				</label>
				<label class="checkbox-row">
					<input type="checkbox" id="skipPreview">
					跳过预览项目启动
				</label>
			</div>
		</div>

		<div class="section">
			<div class="section-header" onclick="toggleSection(this)">
				<span>平台与组件库</span>
				<span class="arrow">&#9654;</span>
			</div>
			<div class="section-body hidden">
				<label>目标平台
					<select id="targetPlatform" onchange="onPlatformChange()">
						<option value="">自动检测</option>
						<option value="pc">PC 管理后台</option>
						<option value="mobile">移动端 H5</option>
						<option value="miniprogram">小程序</option>
						<option value="react">React PC</option>
					</select>
				</label>
				<label>降级组件库
					<select id="fallbackUi">
						<option value="">跟随平台默认</option>
					</select>
				</label>
				<div style="font-size:11px;color:var(--text-dim);line-height:1.5;margin-top:2px">
					自动检测会根据项目依赖和路径判断平台。若检测不准,可手动指定。降级组件库可在配置文件 <code style="color:var(--accent)">scripts/ai-direct-platform-ui.config.json</code> 中维护。
				</div>
			</div>
		</div>

		<div class="btn-row" style="margin-top:4px">
			<button class="btn btn-primary" id="btnGenerate" onclick="startGenerate()">&#9654; 开始生成</button>
			<button class="btn btn-danger" id="btnStop" onclick="stopGenerate()" disabled>&#9632; 停止</button>
		</div>
		<button class="btn btn-ghost" onclick="clearConsole()" style="width:100%">清空控制台</button>
	</div>

	<div class="main">
		<div class="tabs">
			<div class="tab active" onclick="switchTab('console',this)">控制台</div>
			<div class="tab" onclick="switchTab('preview',this)">预览</div>
			<div class="tab" onclick="switchTab('files',this)">生成文件</div>
			<div class="tab" onclick="switchTab('summary',this)">摘要</div>
		</div>
		<div class="tab-content">
			<div class="tab-panel active" id="panel-console">
				<div class="console" id="consoleOutput">
					<div class="console-empty">等待生成任务开始...</div>
				</div>
			</div>
			<div class="tab-panel" id="panel-preview">
				<div class="preview-panel" id="previewContainer">
					<div class="preview-empty" id="previewEmpty">
						<div class="icon">&#128421;</div>
						<div class="msg">预览尚未就绪</div>
						<div class="hint">流程运行到"启动预览"步骤后,将自动在此显示</div>
					</div>
				</div>
			</div>
			<div class="tab-panel" id="panel-files">
				<div class="file-panel">
					<div class="file-tree" id="fileTree">
						<div class="code-empty" style="width:100%">暂无文件</div>
					</div>
					<div class="code-viewer" id="codeViewer">
						<div class="code-empty">选择文件查看内容</div>
					</div>
				</div>
			</div>
			<div class="tab-panel" id="panel-summary">
				<div class="summary-panel" id="summaryContent">
					<div class="code-empty">等待生成完成...</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
const STEPS = [
	{ key: 'precheck', label: '[0] 环境预检' },
	{ key: 'context', label: '[1] Context' },
	{ key: 'messages', label: '[2] Messages' },
	{ key: 'project-decision', label: '[3] 项目决策' },
	{ key: 'ai-generate', label: '[4] AI 生成' },
	{ key: 'quality-check', label: '[5] 质量校验' },
	{ key: 'health-fix', label: '[6] 健康修复' },
	{ key: 'install-launch', label: '[7] 安装启动' },
	{ key: 'manual-confirm', label: '[8] 人工确认' },
	{ key: 'complete', label: '完成' },
];

let evtSource = null;
let consoleLines = [];
let heartbeatInterval = null;

function init() {
	fetch('/api/config').then(r=>r.json()).then(data => {
		const modelSel = document.getElementById('aiModel');
		data.modelCandidates.forEach(m => {
			const opt = document.createElement('option');
			opt.value = m.value; opt.textContent = m.label;
			if (m.value === data.defaults.aiModel) opt.selected = true;
			modelSel.appendChild(opt);
		});
		const urlSel = document.getElementById('aiUrlSelect');
		data.urlCandidates.forEach(u => {
			const opt = document.createElement('option');
			opt.value = u.value; opt.textContent = u.label;
			urlSel.appendChild(opt);
		});
		document.getElementById('aiBaseUrl').value = data.defaults.aiBaseUrl;
		document.getElementById('aiApiKey').value = data.defaults.aiApiKey;
		document.getElementById('visionModel').value = data.defaults.visionModel;
		document.getElementById('figmaApiKey').value = data.defaults.figmaApiKey;
	});
	loadProjects();
	connectSSE();
	renderProgress('');
	// 检查是否已有预览 URL
	fetch('/api/preview-url').then(r=>r.json()).then(data => {
		if (data.previewUrl) loadPreview(data.previewUrl);
	}).catch(()=>{});
}

function loadProjects() {
	fetch('/api/projects').then(r=>r.json()).then(data => {
		const sel = document.getElementById('bundleSelect');
		sel.innerHTML = '';
		data.bundlePages.forEach(p => {
			const opt = document.createElement('option');
			opt.value = p.bundleFile;
			opt.textContent = p.slug;
			sel.appendChild(opt);
		});
	});
}

function connectSSE() {
	if (evtSource) evtSource.close();
	evtSource = new EventSource('/api/stream');

	evtSource.addEventListener('output', (e) => {
		const data = JSON.parse(e.data);
		appendConsole(data.text, data.stream);
	});

	evtSource.addEventListener('status', (e) => {
		updateStatus(JSON.parse(e.data));
	});

	evtSource.addEventListener('files', (e) => {
		const data = JSON.parse(e.data);
		renderFileTree(data.project, data.files);
	});

	evtSource.addEventListener('preview', (e) => {
		const data = JSON.parse(e.data);
		loadPreview(data.url);
	});

	evtSource.addEventListener('error', (e) => {
		try {
			const data = JSON.parse(e.data);
			appendConsole(`[ERROR] ${data.message}\n`, 'stderr');
		} catch {
			setTimeout(connectSSE, 3000);
		}
	});

	evtSource.addEventListener('log', (e) => {
		const data = JSON.parse(e.data);
		appendConsole(`[server] ${data.message}\n`, 'system');
	});
}

function appendConsole(text, stream) {
	const el = document.getElementById('consoleOutput');
	if (el.querySelector('.console-empty')) el.innerHTML = '';

	// 心跳信息:原地更新,不刷屏
	if (stream === 'heartbeat') {
		let hb = el.querySelector('.heartbeat-live');
		if (!hb) {
			hb = document.createElement('div');
			hb.className = 'console-line heartbeat heartbeat-live';
			el.appendChild(hb);
		}
		// 启动本地动画帧,不依赖服务端事件
		if (!heartbeatInterval) {
			const frames = ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
			heartbeatInterval = setInterval(() => {
				const el2 = document.querySelector('.heartbeat-live');
				if (el2) {
					const idx = Math.floor(Date.now() / 100) % frames.length;
					el2.textContent = `${frames[idx]} 处理中...`;
				}
			}, 100);
		}
		el.scrollTop = el.scrollHeight;
		return;
	}

	// 有实际输出时移除心跳指示
	if (heartbeatInterval) { clearInterval(heartbeatInterval); heartbeatInterval = null; }
	const hb = el.querySelector('.heartbeat-live');
	if (hb) hb.remove();

	text.split('\n').forEach(line => {
		if (!line && text.indexOf(line) === text.length -1) return;
		const div = document.createElement('div');
		let cls = 'console-line';

		// 检测文本模式并应用对应样式
		if (stream === 'stderr') cls += ' stderr';
		else if (stream === 'system') cls += ' system';
		else if (stream === 'progress') cls += ' progress';
		else {
			// 成功模式:✓、通过、完成、success
			if (/[✓✔]/.test(line) || /通过|完成|success|ready/i.test(line)) {
				cls += ' success';
			}
			// 错误模式:✗、失败、错误、error、failed
			else if (/[✗✘]/.test(line) || /失败|错误|error|failed/i.test(line)) {
				cls += ' error';
			}
			// 警告模式:⚠、警告、warning
			else if (/⚠/.test(line) || /警告|warning/i.test(line)) {
				cls += ' warning';
			}
			// 信息模式:⏳、正在、等待、info、→
			else if (/⏳/.test(line) || /正在|等待|info/i.test(line)) {
				cls += ' info';
			}
			// 次要信息:→、步骤编号、DEBUG
			else if (/^\s*→/.test(line) || /\[\d+\/\d+\]/.test(line) || /DEBUG/.test(line)) {
				cls += ' dim';
			}
		}

		div.className = cls;
		div.textContent = line;
		el.appendChild(div);
	});
	el.scrollTop = el.scrollHeight;
}

function clearConsole() {
	if (heartbeatInterval) { clearInterval(heartbeatInterval); heartbeatInterval = null; }
	document.getElementById('consoleOutput').innerHTML = '<div class="console-empty">控制台已清空</div>';
}

function stopHeartbeatAnim() {
	if (heartbeatInterval) { clearInterval(heartbeatInterval); heartbeatInterval = null; }
	const hb = document.querySelector('.heartbeat-live');
	if (hb) hb.remove();
}

function updateStatus(data) {
	const badge = document.getElementById('statusBadge');
	const btnGen = document.getElementById('btnGenerate');
	const btnStop = document.getElementById('btnStop');

	if (data.running) {
		badge.className = 'status-badge running';
		badge.textContent = '运行中';
		btnGen.disabled = true;
		btnStop.disabled = false;
		renderProgress(data.step);
	} else if (data.step === 'done' || data.step === 'complete') {
		stopHeartbeatAnim();
		badge.className = data.exitCode === 0 ? 'status-badge done' : 'status-badge error';
		badge.textContent = data.exitCode === 0 ? '完成' : `失败 (${data.exitCode})`;
		btnGen.disabled = false;
		btnStop.disabled = true;
		renderProgress(data.exitCode === 0 ? 'complete' : '');
		loadProjects();
	} else if (data.step === 'error' || data.step === 'failed') {
		stopHeartbeatAnim();
		badge.className = 'status-badge error';
		badge.textContent = '错误';
		btnGen.disabled = false;
		btnStop.disabled = true;
	}
}

// Map server step keys to STEPS array keys
const STEP_KEY_MAP = {
	'precheck': 'precheck', 'precheck-done': 'precheck',
	'context': 'context', 'context-done': 'context',
	'messages': 'messages', 'messages-done': 'messages', 'messages-legacy': 'messages', 'messages-legacy-done': 'messages',
	'project-decision': 'project-decision', 'project-decision-done': 'project-decision', 'project-created': 'project-decision',
	'ai-generate': 'ai-generate', 'ai-generate-done': 'ai-generate',
	'apply-legacy': 'ai-generate', 'apply-legacy-done': 'ai-generate',
	'quality-check': 'quality-check', 'quality-check-done': 'quality-check',
	'fitness-item': 'quality-check',
	'validate-legacy': 'quality-check',
	'repair-legacy': 'quality-check',
	'health-fix': 'health-fix', 'health-fix-done': 'health-fix',
	'install-launch': 'install-launch', 'install': 'install-launch', 'launch': 'install-launch',
	'dev-ready': 'install-launch',
	'manual-confirm': 'manual-confirm',
	'complete': 'complete',
	'preview-legacy': 'project-decision', 'preview-legacy-done': 'project-decision',
};

function renderProgress(currentStep) {
	const container = document.getElementById('progressSteps');
	container.innerHTML = '';

	const mappedKey = STEP_KEY_MAP[currentStep] || currentStep;
	const isDone = currentStep.endsWith('-done') || currentStep === 'complete' || currentStep === 'dev-ready' || currentStep === 'project-created';
	const currentIdx = STEPS.findIndex(x => x.key === mappedKey);

	STEPS.forEach((s, i) => {
		const div = document.createElement('div');
		let cls = 'step';

		if (mappedKey === 'complete') {
			cls += ' done';
		} else if (s.key === mappedKey && !isDone) {
			cls += ' active';
		} else if (currentIdx > i || (s.key === mappedKey && isDone)) {
			cls += ' done';
		}

		div.className = cls;
		div.innerHTML = `<span class="step-icon"></span>${s.label}`;
		container.appendChild(div);
	});
}

function startGenerate() {
	const config = {
		aiModel: document.getElementById('aiModel').value.trim(),
		aiBaseUrl: document.getElementById('aiBaseUrl').value.trim(),
		aiApiKey: document.getElementById('aiApiKey').value.trim(),
		visionModel: document.getElementById('visionModel').value.trim(),
		figmaApiKey: document.getElementById('figmaApiKey').value.trim(),
		force: document.getElementById('forceOverwrite').checked,
		refreshContext: document.getElementById('refreshContext').checked,
		skipPreview: document.getElementById('skipPreview').checked,
		targetPlatform: document.getElementById('targetPlatform').value.trim(),
		fallbackUi: document.getElementById('fallbackUi').value.trim(),
	};

	const source = document.getElementById('projectSource').value;
	if (source === 'bundle') {
		const bundleFile = document.getElementById('bundleSelect').value.trim();
		if (!bundleFile) {
			alert('请选择一个已有的 Context Bundle');
			return;
		}
		config.bundleFile = bundleFile;
	} else {
		const figmaUrl = document.getElementById('figmaUrl').value.trim();
		const pageName = document.getElementById('pageName').value.trim();
		if (!figmaUrl) {
			alert('请提供 Figma URL');
			return;
		}
		config.figmaUrl = figmaUrl;
		if (pageName) config.pageName = pageName;
	}

	fetch('/api/generate', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(config),
	}).then(r => r.json()).then(data => {
		if (data.error) alert(data.error);
	}).catch(err => alert('请求失败: ' + err.message));
}

function stopGenerate() {
	fetch('/api/stop', { method: 'POST' });
}

function toggleSection(header) {
	const body = header.nextElementSibling;
	const arrow = header.querySelector('.arrow');
	body.classList.toggle('hidden');
	arrow.classList.toggle('open');
}

function onProjectSourceChange() {
	const v = document.getElementById('projectSource').value;
	document.getElementById('newProjectOptions').style.display = v === 'new' ? '' : 'none';
	document.getElementById('bundleOptions').style.display = v === 'bundle' ? '' : 'none';
}

function onUrlSelectChange(sel) {
	const input = document.getElementById('aiBaseUrl');
	if (sel.value) input.value = sel.value;
	else input.focus();
}

const PLATFORM_FALLBACKS = {
	pc: [
		{ value: 'element-plus', label: 'Element Plus' },
		{ value: '@vui/vue', label: 'VUI Vue (首选)' },
		{ value: 'ant-design-vue', label: 'Ant Design Vue' },
		{ value: 'naive-ui', label: 'Naive UI' },
	],
	mobile: [
		{ value: 'vant', label: 'Vant 4' },
		{ value: '@nutui/nutui', label: 'NutUI' },
		{ value: '@vui/vue', label: 'VUI Vue' },
		{ value: 'varlet', label: 'Varlet' },
	],
	miniprogram: [
		{ value: '@vant/weapp', label: 'Vant Weapp' },
		{ value: '@vui/uniapp', label: 'VUI UniApp' },
		{ value: 'tdesign-miniprogram', label: 'TDesign 小程序' },
		{ value: '@dcloudio/uni-ui', label: 'uni-ui' },
	],
	react: [
		{ value: 'antd', label: 'Ant Design' },
		{ value: '@vui/react', label: 'VUI React (首选)' },
		{ value: '@arco-design/web-react', label: 'Arco Design' },
		{ value: '@mui/material', label: 'Material UI' },
	],
};

function onPlatformChange() {
	const platform = document.getElementById('targetPlatform').value;
	const fallbackSel = document.getElementById('fallbackUi');
	fallbackSel.innerHTML = '<option value="">跟随平台默认</option>';
	const options = PLATFORM_FALLBACKS[platform] || [];
	options.forEach(o => {
		const opt = document.createElement('option');
		opt.value = o.value; opt.textContent = o.label;
		fallbackSel.appendChild(opt);
	});
}

function switchTab(name, tabEl) {
	document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
	document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
	tabEl.classList.add('active');
	document.getElementById('panel-' + name).classList.add('active');
}

function renderFileTree(project, files) {
	const tree = document.getElementById('fileTree');
	tree.innerHTML = '';
	if (!files || files.length === 0) {
		tree.innerHTML = '<div class="code-empty" style="width:100%">暂无文件</div>';
		return;
	}
	files.forEach(f => {
		const div = document.createElement('div');
		div.className = 'file-item';
		const icon = f.path.endsWith('.vue') ? '\u{1F4C4}' : f.path.endsWith('.ts') ? '\u{1F4DD}' : '\u{1F3A8}';
		const name = f.path.split('/').pop();
		div.innerHTML = `<span class="file-icon">${icon}</span>${name}`;
		div.title = f.path;
		div.onclick = () => {
			document.querySelectorAll('.file-item').forEach(i => i.classList.remove('active'));
			div.classList.add('active');
			loadFile(project, f.path);
		};
		tree.appendChild(div);
	});
}

function loadFile(project, filePath) {
	const viewer = document.getElementById('codeViewer');
	viewer.innerHTML = '<div class="code-empty">加载中...</div>';
	const fullPath = `${project}/${filePath}`;
	fetch('/api/file?path=' + encodeURIComponent(fullPath))
		.then(r => r.text())
		.then(content => {
			viewer.innerHTML = `<div class="file-path">${filePath}</div><pre>${escapeHtml(content)}</pre>`;
		})
		.catch(() => {
			viewer.innerHTML = '<div class="code-empty">文件加载失败</div>';
		});
}

function escapeHtml(text) {
	return text.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

function loadPreview(previewUrl) {
	const container = document.getElementById('previewContainer');
	container.innerHTML = `
		<div class="preview-toolbar">
			<span class="url-bar" id="previewUrlBar">${previewUrl}</span>
			<button class="btn btn-ghost" onclick="refreshPreview()">刷新</button>
			<button class="btn btn-ghost" onclick="openPreviewExternal()">新窗口打开</button>
		</div>
		<iframe class="preview-frame" id="previewFrame" src="/preview-proxy/"></iframe>
	`;
	container.dataset.previewUrl = previewUrl;
	// 自动切换到预览 tab
	const previewTab = document.querySelectorAll('.tab')[1];
	if (previewTab) switchTab('preview', previewTab);
}

function refreshPreview() {
	const frame = document.getElementById('previewFrame');
	if (frame) frame.src = frame.src;
}

function openPreviewExternal() {
	const container = document.getElementById('previewContainer');
	const url = container.dataset.previewUrl;
	if (url) window.open(url, '_blank');
}

init();
</script>
</body>
</html>