<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$error = '';
$success = '';
$packCode = isset($_GET['code']) ? trim((string)$_GET['code']) : '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pack_code'])) {
    $packCode = trim((string)$_POST['pack_code']);
}

ensure_template_packs_dir();
initialize_builtin_template_packs();

$manifest = load_template_pack_manifest($packCode);
if (!$manifest) {
    header('Location: /admin/template-pack/list.php');
    exit;
}

$fileKeys = template_pack_file_keys();
$aiModels = list_enabled_ai_model_options();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $action = isset($_POST['action']) ? trim((string)$_POST['action']) : '';

    if ($action === 'save_file') {
        $fileKey = isset($_POST['file_key']) ? trim((string)$_POST['file_key']) : '';
        $fileContent = isset($_POST['file_content']) ? (string)$_POST['file_content'] : '';
        try {
            save_template_pack_file($packCode, $fileKey, $fileContent);
            $success = '文件 ' . (isset($fileKeys[$fileKey]) ? $fileKeys[$fileKey] : $fileKey) . ' 已保存。';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    } elseif ($action === 'save_manifest') {
        $manifest['name'] = isset($_POST['name']) ? trim((string)$_POST['name']) : $manifest['name'];
        $manifest['description'] = isset($_POST['description']) ? trim((string)$_POST['description']) : '';
        $manifest['version'] = isset($_POST['version']) ? trim((string)$_POST['version']) : '1.0.0';
        try {
            save_template_pack_manifest($packCode, $manifest);
            $success = '套件信息已更新。';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        $manifest = load_template_pack_manifest($packCode);
    }
}

$packName = isset($manifest['name']) ? (string)$manifest['name'] : $packCode;
$packDesc = isset($manifest['description']) ? (string)$manifest['description'] : '';
$packVersion = isset($manifest['version']) ? (string)$manifest['version'] : '';
$packType = isset($manifest['pack_type']) ? (string)$manifest['pack_type'] : 'variation';
$packSerialNo = isset($manifest['serial_no']) ? (int)$manifest['serial_no'] : 0;

$isPageTemplate = ($packType === 'page');
$defaultFileTab = $isPageTemplate ? 'page' : 'homepage';
if ($isPageTemplate) {
    $fileKeys = array(
        'page'   => '页面模板',
        'header' => '页眉模板',
        'footer' => '页脚模板',
        'css'    => '共享样式 (CSS)',
        'js'     => '共享脚本 (JS)'
    );
}
$activeTab = isset($_GET['tab']) ? trim((string)$_GET['tab']) : $defaultFileTab;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['file_key'])) {
    $activeTab = trim((string)$_POST['file_key']);
}
if (!isset($fileKeys[$activeTab]) && $activeTab !== 'info') {
    $activeTab = $defaultFileTab;
}
?><!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 e(APP_NAME); ?> - 编辑模板套件 - <?php echo e($packName); ?></title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .pack-tabs { display:flex; gap:6px; margin-bottom:18px; flex-wrap:wrap; }
    .pack-tabs a { padding:10px 16px; border-radius:14px; font-size:13px; font-weight:600; color:#64748b; text-decoration:none; border:1px solid rgba(148,163,184,0.16); background:#fff; transition:all 0.2s; }
    .pack-tabs a:hover { background:#f1f5f9; color:#334155; }
    .pack-tabs a.is-active { background:linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color:#fff; border-color:transparent; box-shadow:0 6px 18px rgba(79,70,229,0.18); }
    .editor-layout { display:grid; grid-template-columns:240px minmax(0,1fr); gap:0; border:1px solid rgba(148,163,184,0.18); border-radius:16px; overflow:hidden; min-height:560px; }
    .var-panel { background:#f8fafc; border-right:1px solid rgba(148,163,184,0.14); overflow-y:auto; max-height:660px; }
    .var-panel-head { padding:12px 14px; font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.04em; border-bottom:1px solid rgba(148,163,184,0.12); position:sticky; top:0; background:#f8fafc; z-index:2; }
    .var-item { display:flex; align-items:center; gap:8px; padding:7px 14px; cursor:pointer; font-size:12px; border-bottom:1px solid rgba(148,163,184,0.07); transition:background 0.15s; }
    .var-item:hover { background:#eef2ff; }
    .var-item code { color:#4f46e5; font-family:"JetBrains Mono","Fira Code",monospace; font-size:11.5px; white-space:nowrap; }
    .var-item span { color:#94a3b8; font-size:11px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    .var-item.is-inserted { background:#e0e7ff; transition:background 0.08s; }
    .code-editor { width:100%; height:100%; min-height:540px; font-family:"JetBrains Mono","Fira Code","Consolas",monospace; font-size:13px; line-height:1.65; padding:16px; border:none; border-radius:0; background:#0f172a; color:#e2e8f0; resize:vertical; tab-size:4; display:block; }
    .code-editor:focus { outline:none; }
    .editor-actions { display:flex; gap:12px; margin-top:14px; align-items:center; flex-wrap:wrap; }
    .editor-hint { color:#94a3b8; font-size:12px; margin-left:auto; }
    .info-form { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
    .info-form .full { grid-column:1/-1; }
    .ai-panel { margin-top:18px; padding:18px; border:1px solid rgba(99,102,241,0.18); border-radius:14px; background:linear-gradient(135deg, rgba(99,102,241,0.04) 0%, rgba(168,85,247,0.04) 100%); }
    .ai-panel-head { display:flex; align-items:center; gap:8px; margin-bottom:12px; font-size:14px; font-weight:700; color:#4f46e5; }
    .ai-panel-head svg { width:18px; height:18px; }
    .ai-instruction { width:100%; min-height:64px; padding:12px; border:1px solid rgba(148,163,184,0.2); border-radius:10px; font-size:13px; line-height:1.6; background:#fff; color:#334155; resize:vertical; }
    .ai-instruction:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,0.1); }
    .btn-ai { display:inline-flex; align-items:center; gap:6px; padding:10px 20px; border-radius:10px; border:none; background:linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); color:#fff; font-size:13px; font-weight:600; cursor:pointer; transition:all 0.2s; }
    .btn-ai:hover { box-shadow:0 6px 20px rgba(99,102,241,0.3); transform:translateY(-1px); }
    .btn-ai:disabled { opacity:0.6; cursor:not-allowed; transform:none; box-shadow:none; }
    .btn-ai svg { width:16px; height:16px; }
    .ai-status { font-size:12px; color:#6366f1; margin-left:8px; }
    .ai-status.is-error { color:#dc2626; }
    /* AI Generation Panel - two column layout */
    .ai-gen-panel { margin-top:18px; border:1px solid rgba(99,102,241,0.18); border-radius:16px; background:linear-gradient(135deg, rgba(99,102,241,0.03) 0%, rgba(168,85,247,0.03) 100%); overflow:hidden; }
    .ai-gen-header { padding:16px 20px; border-bottom:1px solid rgba(99,102,241,0.1); display:flex; align-items:center; gap:8px; font-size:15px; font-weight:700; color:#4f46e5; }
    .ai-gen-header svg { width:20px; height:20px; }
    .ai-gen-body { display:grid; grid-template-columns:1fr 1fr; min-height:340px; }
    .ai-gen-left { padding:20px; border-right:1px solid rgba(99,102,241,0.1); display:flex; flex-direction:column; gap:14px; }
    .ai-gen-right { padding:20px; background:rgba(248,250,252,0.6); display:flex; flex-direction:column; gap:14px; }
    .ai-gen-label { font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.04em; }
    .ai-presets { display:flex; flex-wrap:wrap; gap:6px; }
    .ai-preset-btn { padding:6px 12px; border-radius:8px; border:1px solid rgba(148,163,184,0.2); background:#fff; font-size:12px; color:#475569; cursor:pointer; transition:all 0.15s; white-space:nowrap; }
    .ai-preset-btn:hover { border-color:#6366f1; color:#4f46e5; background:#eef2ff; }
    .ai-preset-btn.is-active { border-color:#6366f1; color:#fff; background:#6366f1; }
    .ai-gen-textarea { width:100%; flex:1; min-height:120px; padding:12px; border:1px solid rgba(148,163,184,0.2); border-radius:10px; font-size:13px; line-height:1.7; background:#fff; color:#334155; resize:vertical; }
    .ai-gen-textarea:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,0.1); }
    .ai-gen-actions { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
    .wf-progress { margin-bottom:14px; }
    .wf-progress-bar { height:8px; background:#e2e8f0; border-radius:99px; overflow:hidden; margin-bottom:8px; }
    .wf-progress-fill { height:100%; background:linear-gradient(90deg,#6366f1,#8b5cf6); border-radius:99px; transition:width 0.4s ease; width:0%; }
    .wf-progress-text { font-size:12px; color:#64748b; text-align:center; }
    .wf-steps { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:6px; flex:1; }
    .wf-step { display:flex; align-items:center; gap:10px; padding:8px 12px; border-radius:10px; font-size:13px; color:#64748b; background:#fff; border:1px solid transparent; transition:all 0.2s; }
    .wf-step .wf-icon { width:22px; height:22px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; background:#e2e8f0; color:#94a3b8; flex-shrink:0; transition:all 0.3s; }
    .wf-step.is-active { background:#eef2ff; border-color:rgba(99,102,241,0.2); color:#4338ca; }
    .wf-step.is-active .wf-icon { background:#6366f1; color:#fff; }
    .wf-step.is-done { color:#15803d; }
    .wf-step.is-done .wf-icon { background:#22c55e; color:#fff; }
    .wf-step.is-error { color:#dc2626; }
    .wf-step.is-error .wf-icon { background:#dc2626; color:#fff; }
    .wf-step-label { flex:1; }
    .wf-step-status { font-size:11px; color:#94a3b8; }
    .wf-step.is-done .wf-step-status { color:#22c55e; }
    .wf-step.is-error .wf-step-status { color:#dc2626; }
    .wf-retry-btn { padding:3px 10px; border-radius:6px; border:1px solid #dc2626; background:#fff; color:#dc2626; font-size:11px; font-weight:600; cursor:pointer; transition:all 0.15s; white-space:nowrap; margin-left:4px; }
    .wf-retry-btn:hover { background:#dc2626; color:#fff; }
    .wf-retry-btn:disabled { opacity:0.5; cursor:not-allowed; }
    .wf-step.is-active .wf-step-status { color:#6366f1; }
    .wf-result { padding:12px; border-radius:10px; font-size:13px; font-weight:600; text-align:center; }
    .wf-result.is-ok { background:#f0fdf4; color:#15803d; border:1px solid #bbf7d0; }
    .wf-result.is-fail { background:#fef2f2; color:#dc2626; border:1px solid #fecaca; }
    @keyframes wf-spin { to { transform: rotate(360deg); } }
    .wf-spinner { display:inline-block; width:14px; height:14px; border:2px solid rgba(99,102,241,0.3); border-top-color:#6366f1; border-radius:50%; animation:wf-spin 0.6s linear infinite; }
    /* AI Rewrite mini panel */
    .ai-rewrite-panel { margin-top:14px; padding:14px 18px; border:1px dashed rgba(99,102,241,0.25); border-radius:12px; background:rgba(99,102,241,0.02); }
    .ai-rewrite-row { display:flex; gap:10px; align-items:flex-end; }
    .ai-rewrite-row .ai-gen-textarea { min-height:48px; flex:1; }
    @media(max-width:900px) { .editor-layout { grid-template-columns:1fr; } .var-panel { max-height:200px; border-right:none; border-bottom:1px solid rgba(148,163,184,0.14); } .ai-gen-body { grid-template-columns:1fr; } .ai-gen-left { border-right:none; border-bottom:1px solid rgba(99,102,241,0.1); } }
    @media(max-width:640px) { .info-form { grid-template-columns:1fr; } }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('template_packs', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>编辑套件：<?php echo e($packName); ?> <span style="font-size:12px; font-weight:600; padding:3px 10px; border-radius:6px; vertical-align:middle; <?php echo $packType === 'standard' ? 'background:#f1f5f9; color:#64748b;' : 'background:#eef2ff; color:#4f46e5;'; ?>"><?php echo $packType === 'standard' ? '常规' : '变体'; ?></span></h1><p>编码：<code><?php echo e($packCode); ?></code> &nbsp;|&nbsp; 序号：<code><?php echo e(template_pack_serial_label($packSerialNo, $packType)); ?></code></p></div>
                <div class="topbar-actions">
                    <a class="btn-ghost" href="/admin/template-pack/list.php">返回列表</a>
                </div>
            </header>

            <?php if ($success !== ''): ?>
                <div class="page-card" style="border-left:4px solid #22c55e; margin-bottom:14px;">
                    <div class="card-head"><div><h2 style="color:#15803d;">保存成功</h2><p><?php echo e($success); ?></p></div></div>
                </div>
            <?php endif; ?>
            <?php if ($error !== ''): ?>
                <div class="page-card" style="border-left:4px solid #dc2626; margin-bottom:14px;">
                    <div class="card-head"><div><h2 style="color:#dc2626;">操作失败</h2><p><?php echo e($error); ?></p></div></div>
                </div>
            <?php endif; ?>

            <nav class="pack-tabs">
                <a href="?code=<?php echo urlencode($packCode); ?>&tab=info"<?php echo $activeTab === 'info' ? ' class="is-active"' : ''; ?>>套件信息</a>
                <?php foreach ($fileKeys as $fk => $fl): ?>
                    <a href="?code=<?php echo urlencode($packCode); ?>&tab=<?php echo urlencode($fk); ?>"<?php echo $activeTab === $fk ? ' class="is-active"' : ''; ?>><?php echo e($fl); ?></a>
                <?php endforeach; ?>
            </nav>

            <section class="page-card">
                <?php if ($activeTab === 'info'): ?>
                    <div class="card-head"><div><h2>套件基本信息</h2></div></div>
                    <form method="post" action="/admin/template-pack/edit.php?code=<?php echo urlencode($packCode); ?>&tab=info">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="pack_code" value="<?php echo e($packCode); ?>">
                        <input type="hidden" name="action" value="save_manifest">
                        <div class="info-form">
                            <div class="input-group">
                                <span>套件名称</span>
                                <input class="input" type="text" name="name" value="<?php echo e($packName); ?>">
                            </div>
                            <div class="input-group">
                                <span>版本</span>
                                <input class="input" type="text" name="version" value="<?php echo e($packVersion); ?>">
                            </div>
                            <div class="input-group full">
                                <span>描述</span>
                                <textarea class="input" name="description" rows="3"><?php echo e($packDesc); ?></textarea>
                            </div>
                        </div>
                        <div class="editor-actions">
                            <button class="btn-primary" type="submit">保存信息</button>
                        </div>
                    </form>
                    <?php include __DIR__ . '/_ai-gen-panel.php'; ?>
                <?php else: ?>
                    <?php
                        $currentFileKey = $activeTab;
                        $currentLabel = isset($fileKeys[$currentFileKey]) ? $fileKeys[$currentFileKey] : $currentFileKey;
                        $currentContent = load_template_pack_file($packCode, $currentFileKey);
                    ?>
                    <?php
                    $allVars = template_variables_for_file_key($currentFileKey);
                    ?>
                    <div class="card-head"><div><h2><?php echo e($currentLabel); ?></h2><p>文件路径：templates/<?php echo e(isset($manifest['pack_type']) ? $manifest['pack_type'] : 'variation'); ?>/<?php echo e($packCode); ?>/<?php echo e(isset($manifest['files'][$currentFileKey]) ? $manifest['files'][$currentFileKey] : ''); ?>&nbsp;&nbsp;·&nbsp;&nbsp;点击左侧变量可插入光标位置</p></div></div>
                    <form id="editorForm" method="post" action="/admin/template-pack/edit.php?code=<?php echo urlencode($packCode); ?>&tab=<?php echo urlencode($currentFileKey); ?>">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="pack_code" value="<?php echo e($packCode); ?>">
                        <input type="hidden" name="action" value="save_file">
                        <input type="hidden" name="file_key" value="<?php echo e($currentFileKey); ?>">
                        <div class="editor-layout">
                            <div class="var-panel">
                                <div class="var-panel-head">模板变量 <span style="font-weight:400;color:#94a3b8;">(点击插入)</span></div>
                                <?php foreach ($allVars as $var => $label): ?>
                                    <div class="var-item" data-var="<?php echo e($var); ?>" title="<?php echo e($var . ' — ' . $label); ?>">
                                        <code><?php echo e($var); ?></code>
                                        <span><?php echo e($label); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <textarea id="codeEditor" class="code-editor" name="file_content"><?php echo e($currentContent); ?></textarea>
                        </div>
                        <div class="editor-actions">
                            <button class="btn-primary" type="submit">保存文件</button>
                            <a class="btn-soft" href="/admin/template-pack/preview.php?code=<?php echo urlencode($packCode); ?>&tab=<?php echo urlencode($currentFileKey); ?>" target="_blank" style="display:inline-flex;align-items:center;gap:5px;text-decoration:none;"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>预览</a>
                            <span class="editor-hint">Ctrl+S 快速保存 · 支持 {{变量}} 占位符</span>
                        </div>
                    </form>
                    <div class="ai-rewrite-panel">
                        <div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:13px;font-weight:700;color:#4f46e5;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a4 4 0 0 1 4 4v1a1 1 0 0 0 1 1h1a4 4 0 0 1 0 8h-1a1 1 0 0 0-1 1v1a4 4 0 0 1-8 0v-1a1 1 0 0 0-1-1H6a4 4 0 0 1 0-8h1a1 1 0 0 0 1-1V6a4 4 0 0 1 4-4z"/><circle cx="12" cy="12" r="2"/></svg>
                            AI 局部重写当前文件
                        </div>
                        <div class="ai-rewrite-row">
                            <textarea id="aiInstruction" class="ai-gen-textarea" placeholder="输入修改指令，例如：&#10;• 在现有代码基础上增加一个FAQ模块&#10;• 把导航改成居中样式&#10;• 重新设计hero区域为左右分栏"></textarea>
                            <button type="button" id="btnAiGenerate" class="btn-ai" data-file-key="<?php echo e($currentFileKey); ?>" data-pack-code="<?php echo e($packCode); ?>" style="white-space:nowrap;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                                AI 重写
                            </button>
                        </div>
                        <span id="aiStatus" class="ai-status" style="display:block;margin-top:8px;"></span>
                    </div>
                    <?php include __DIR__ . '/_ai-gen-panel.php'; ?>
                <?php endif; ?>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {

    /* ========== Editor logic (per-file tab) ========== */
    var editor = document.getElementById('codeEditor');
    if (editor) {
        editor.addEventListener('keydown', function(e) {
            if (e.key === 'Tab') {
                e.preventDefault();
                var s = this.selectionStart, end = this.selectionEnd;
                this.value = this.value.substring(0, s) + '    ' + this.value.substring(end);
                this.selectionStart = this.selectionEnd = s + 4;
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                this.closest('form').submit();
            }
        });

        var items = document.querySelectorAll('.var-item[data-var]');
        for (var i = 0; i < items.length; i++) {
            items[i].addEventListener('click', function() {
                var tag = this.getAttribute('data-var');
                if (!tag) return;
                var s = editor.selectionStart, end = editor.selectionEnd;
                editor.value = editor.value.substring(0, s) + tag + editor.value.substring(end);
                editor.selectionStart = editor.selectionEnd = s + tag.length;
                editor.focus();
                this.classList.add('is-inserted');
                var el = this;
                setTimeout(function() { el.classList.remove('is-inserted'); }, 350);
            });
        }

        /* AI Rewrite for current file */
        var btnAi = document.getElementById('btnAiGenerate');
        var aiStatus = document.getElementById('aiStatus');
        if (btnAi) {
            btnAi.addEventListener('click', function() {
                var fileKey = this.getAttribute('data-file-key');
                var packCode = this.getAttribute('data-pack-code');
                var instruction = (document.getElementById('aiInstruction') || {}).value || '';
                var currentContent = editor.value;
                btnAi.disabled = true;
                aiStatus.textContent = 'AI 正在重写，请稍候…';
                aiStatus.className = 'ai-status';
                var fd = new FormData();
                fd.append('file_key', fileKey);
                fd.append('pack_code', packCode);
                fd.append('instruction', instruction);
                fd.append('current_content', currentContent);
                var modelSelect = document.getElementById('wfModelSelect');
                if (modelSelect && modelSelect.value) {
                    fd.append('model_id', modelSelect.value);
                }
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/admin/api/ai-template.php', true);
                xhr.timeout = 600000;
                xhr.onreadystatechange = function() {
                    if (xhr.readyState !== 4) return;
                    btnAi.disabled = false;
                    if (xhr.status === 200) {
                        try {
                            var data = JSON.parse(xhr.responseText);
                            if (data.success && data.html) {
                                editor.value = data.html;
                                var msg = '\u2713 重写完成';
                                if (data.continuations > 0) msg += '（续写' + data.continuations + '次）';
                                if (data.warning) msg += ' \u26a0 ' + data.warning;
                                msg += '，请检查后保存。';
                                aiStatus.textContent = msg;
                                aiStatus.className = 'ai-status' + (data.warning ? ' is-warning' : '');
                            } else {
                                aiStatus.textContent = '\u2717 ' + (data.error || '生成失败');
                                aiStatus.className = 'ai-status is-error';
                            }
                        } catch(e) {
                            aiStatus.textContent = '\u2717 响应解析失败';
                            aiStatus.className = 'ai-status is-error';
                        }
                    } else {
                        aiStatus.textContent = '\u2717 请求失败（HTTP ' + xhr.status + '）';
                        aiStatus.className = 'ai-status is-error';
                    }
                };
                xhr.ontimeout = function() { btnAi.disabled = false; aiStatus.textContent = '\u2717 请求超时'; aiStatus.className = 'ai-status is-error'; };
                xhr.send(fd);
            });
        }
    }

    /* ========== Preset buttons ========== */
    var presetBtns = document.querySelectorAll('.ai-preset-btn[data-prompt]');
    var wfTextarea = document.getElementById('wfInstruction');
    for (var p = 0; p < presetBtns.length; p++) {
        presetBtns[p].addEventListener('click', function() {
            if (!wfTextarea) return;
            wfTextarea.value = this.getAttribute('data-prompt');
            for (var j = 0; j < presetBtns.length; j++) presetBtns[j].classList.remove('is-active');
            this.classList.add('is-active');
            wfTextarea.focus();
        });
    }

    /* ========== Workflow: inline two-column generate all ========== */
    var btnWfStart = document.getElementById('btnWfStart');
    if (!btnWfStart) return;

    var fill      = document.getElementById('wfProgressFill');
    var progText  = document.getElementById('wfProgressText');
    var stepsEl   = document.getElementById('wfSteps');
    var resultEl  = document.getElementById('wfResult');
    var btnCancel = document.getElementById('wfCancel');

    var STEPS = ['header', 'footer', 'homepage', 'article', 'archive', 'css'];
    var STEP_LABELS = {
        header: '页头模板', footer: '页脚模板', homepage: '首页模板',
        article: '文章页模板', archive: '栏目页模板', css: '公共样式'
    };
    var cancelled = false;
    var running = false;

    function resetUI() {
        fill.style.width = '0%';
        progText.textContent = '准备就绪';
        resultEl.style.display = 'none';
        resultEl.className = 'wf-result';
        resultEl.textContent = '';
        btnCancel.style.display = 'none';
        btnWfStart.disabled = false;
        var lis = stepsEl.querySelectorAll('.wf-step');
        for (var i = 0; i < lis.length; i++) {
            lis[i].className = 'wf-step';
            lis[i].querySelector('.wf-step-status').textContent = '等待中';
            lis[i].querySelector('.wf-icon').innerHTML = '' + (i + 1);
            var rb = lis[i].querySelector('.wf-retry-btn');
            if (rb) rb.remove();
        }
    }

    function setStepState(key, state, statusText) {
        var li = stepsEl.querySelector('[data-key="' + key + '"]');
        if (!li) return;
        li.className = 'wf-step ' + state;
        var statusEl = li.querySelector('.wf-step-status');
        statusEl.textContent = statusText;
        /* Remove existing retry button */
        var oldBtn = li.querySelector('.wf-retry-btn');
        if (oldBtn) oldBtn.remove();
        if (state === 'is-active') {
            li.querySelector('.wf-icon').innerHTML = '<span class="wf-spinner"></span>';
        } else if (state === 'is-done') {
            li.querySelector('.wf-icon').innerHTML = '\u2713';
        } else if (state === 'is-error') {
            li.querySelector('.wf-icon').innerHTML = '\u2717';
            var retryBtn = document.createElement('button');
            retryBtn.type = 'button';
            retryBtn.className = 'wf-retry-btn';
            retryBtn.textContent = '重试';
            retryBtn.setAttribute('data-retry-key', key);
            li.appendChild(retryBtn);
        }
    }

    function updateProgress(done, total, msg) {
        var pct = Math.round((done / total) * 100);
        fill.style.width = pct + '%';
        progText.textContent = msg || (done + ' / ' + total);
    }

    function callStepAPI(packCode, fileKey, instruction, prevContext, callback) {
        var fd = new FormData();
        fd.append('pack_code', packCode);
        fd.append('file_key', fileKey);
        fd.append('instruction', instruction);
        fd.append('prev_context', prevContext);
        fd.append('auto_save', '1');
        var modelSelect = document.getElementById('wfModelSelect');
        if (modelSelect && modelSelect.value) {
            fd.append('model_id', modelSelect.value);
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/admin/api/ai-template-step.php', true);
        xhr.timeout = 600000;
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) return;
            if (xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    callback(null, data);
                } catch(e) {
                    var preview = xhr.responseText ? xhr.responseText.substring(0, 200) : '(空)';
                    callback('响应解析失败: ' + preview);
                }
            } else {
                callback('HTTP ' + xhr.status);
            }
        };
        xhr.ontimeout = function() { callback('请求超时'); };
        xhr.send(fd);
    }

    function runWorkflow(packCode, instruction) {
        cancelled = false;
        running = true;
        var context = '';
        var doneCount = 0;
        var errorCount = 0;
        var total = STEPS.length;

        btnWfStart.disabled = true;
        btnCancel.style.display = '';
        resultEl.style.display = 'none';
        updateProgress(0, total, '正在启动工作流…');

        function nextStep(idx) {
            if (cancelled) {
                running = false;
                progText.textContent = '已取消';
                btnCancel.style.display = 'none';
                btnWfStart.disabled = false;
                return;
            }
            if (idx >= total) {
                running = false;
                btnCancel.style.display = 'none';
                btnWfStart.disabled = false;
                updateProgress(total, total, '全部完成！');
                resultEl.style.display = '';
                if (errorCount === 0) {
                    resultEl.className = 'wf-result is-ok';
                    resultEl.innerHTML = '\u2713 全部 ' + total + ' 个模板组件已生成并保存！<a href="javascript:location.reload()" style="margin-left:8px;color:#4f46e5;text-decoration:underline;">刷新页面查看</a>';
                } else {
                    resultEl.className = 'wf-result is-fail';
                    resultEl.textContent = '完成 ' + doneCount + ' 个，失败 ' + errorCount + ' 个。失败文件可点击重试按钮重新生成。';
                }
                return;
            }

            var key = STEPS[idx];
            var label = STEP_LABELS[key] || key;
            setStepState(key, 'is-active', 'AI 生成中…');
            updateProgress(idx, total, '(' + (idx + 1) + '/' + total + ') 正在生成 ' + label + '…');

            callStepAPI(packCode, key, instruction, context, function(err, data) {
                if (cancelled) {
                    running = false;
                    return;
                }
                if (err || !data || !data.success) {
                    errorCount++;
                    var errMsg = err || (data && data.error ? data.error : '未知错误');
                    setStepState(key, 'is-error', '失败: ' + errMsg);
                } else {
                    doneCount++;
                    var doneMsg = data.saved ? '已生成并保存' : '已生成(未保存)';
                    if (data.continuations > 0) doneMsg += '(续写' + data.continuations + '次)';
                    if (data.warning) doneMsg += ' \u26a0';
                    setStepState(key, 'is-done', doneMsg);
                    if (data.summary) {
                        context += (context ? '\n\n' : '') + data.summary;
                    }
                }
                nextStep(idx + 1);
            });
        }

        nextStep(0);
    }

    btnWfStart.addEventListener('click', function() {
        if (running) return;
        var packCode = this.getAttribute('data-pack-code');
        var instruction = (document.getElementById('wfInstruction') || {}).value || '';
        if (instruction.trim() === '') {
            if (!confirm('未输入提示词，AI 将按默认风格生成全部模板文件。确认继续？')) return;
        }
        resetUI();
        runWorkflow(packCode, instruction);
    });

    btnCancel.addEventListener('click', function() {
        cancelled = true;
        this.disabled = true;
        progText.textContent = '正在取消…';
    });

    /* ========== Retry failed step ========== */
    stepsEl.addEventListener('click', function(e) {
        var btn = e.target.closest('.wf-retry-btn');
        if (!btn || btn.disabled) return;
        var key = btn.getAttribute('data-retry-key');
        if (!key) return;
        var packCode = btnWfStart.getAttribute('data-pack-code');
        var instruction = (document.getElementById('wfInstruction') || {}).value || '';
        btn.disabled = true;
        btn.textContent = '重试中…';
        setStepState(key, 'is-active', 'AI 重新生成中…');
        callStepAPI(packCode, key, instruction, '', function(err, data) {
            if (err || !data || !data.success) {
                var errMsg = err || (data && data.error ? data.error : '未知错误');
                setStepState(key, 'is-error', '失败: ' + errMsg);
            } else {
                var doneMsg = data.saved ? '已生成并保存' : '已生成(未保存)';
                if (data.continuations > 0) doneMsg += '(续写' + data.continuations + '次)';
                if (data.warning) doneMsg += ' \u26a0';
                setStepState(key, 'is-done', doneMsg);
                /* Update result summary */
                var errorSteps = stepsEl.querySelectorAll('.wf-step.is-error');
                resultEl.style.display = '';
                if (errorSteps.length === 0) {
                    resultEl.className = 'wf-result is-ok';
                    resultEl.textContent = '\u2713 全部模板已生成成功并保存，切换标签页查看或刷新当前页面。';
                } else {
                    resultEl.className = 'wf-result is-fail';
                    var doneSteps = stepsEl.querySelectorAll('.wf-step.is-done');
                    resultEl.textContent = '完成 ' + doneSteps.length + ' 个，失败 ' + errorSteps.length + ' 个。失败文件可点击重试按钮重新生成。';
                }
            }
        });
    });
});
</script>
</body>
</html>
