<?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 = '';
$result = null;
$domains = array();
$models = array();
$articleTasks = array();
$batchStatus = isset($_GET['batch_status']) ? trim((string)$_GET['batch_status']) : '';
$batchAction = isset($_GET['batch_action']) ? trim((string)$_GET['batch_action']) : '';
$batchCount = isset($_GET['batch_count']) ? (int)$_GET['batch_count'] : 0;
$articleTaskKeyword = isset($_GET['task_keyword']) ? trim((string)$_GET['task_keyword']) : '';
$articleTaskStatus = isset($_GET['task_status']) ? trim((string)$_GET['task_status']) : '';
$articleTaskStatusOptions = article_generation_task_status_options();
$articleTaskEditableStatusOptions = article_generation_task_editable_status_options();
$initialMode = 'homepage';
if (isset($_GET['mode'])) {
    $m = trim((string)$_GET['mode']);
    if ($m === 'scheduler') $initialMode = 'scheduler';
    elseif ($m === 'tasklist' || $m === 'article') $initialMode = 'tasklist';
}
$form = array(
    'task_type' => 'homepage',
    'domain_id' => 0,
    'domain_ids' => array(),
    'model_id' => 0,
    'keyword' => '',
    'site_name' => '',
    'site_description' => '',
    'custom_prompt' => '',
    'keywords_text' => '',
    'article_length' => '1200-1800字',
    'path_prefix' => 'article',
    'interval_seconds' => 0,
    'generate_image' => 1,
    'remark' => '',
    'publish_now' => 0
);

$regenContentId = isset($_GET['regen']) ? (int)$_GET['regen'] : 0;
$regenContent = null;
$regenDomainLocked = false;
if ($regenContentId > 0) {
    $regenContent = find_content_by_id($regenContentId);
    if ($regenContent) {
        $regenDomainLocked = true;
        $form['domain_id'] = isset($regenContent['domain_id']) ? (int)$regenContent['domain_id'] : 0;
        $form['keyword'] = isset($regenContent['seo_keywords']) ? trim((string)$regenContent['seo_keywords']) : '';
        $form['site_name'] = isset($regenContent['title']) ? trim((string)$regenContent['title']) : '';
        $form['site_description'] = isset($regenContent['seo_description']) ? trim((string)$regenContent['seo_description']) : '';
        $initialMode = 'homepage';
    }
}

$allMenuOptions = array();
$homepageDomainIds = array();
try {
    $domains = list_enabled_domain_options();
    $models = list_enabled_ai_model_options();
    $homepageDomainIds = list_domain_ids_with_published_homepage();
    $articleTasks = list_article_generation_tasks($articleTaskKeyword, $articleTaskStatus);
    foreach ($domains as $d) {
        $dMenus = list_enabled_menu_options((int)$d['id']);
        foreach ($dMenus as $dm) {
            if (!empty($dm['is_home'])) continue;
            if (isset($dm['custom_url']) && trim((string)$dm['custom_url']) !== '') continue;
            $dm['_domain'] = isset($d['domain']) ? (string)$d['domain'] : '';
            $dm['_domain_id'] = (int)$d['id'];
            $allMenuOptions[] = $dm;
        }
    }
    usort($domains, function($a, $b) use ($homepageDomainIds) {
        $aHas = isset($homepageDomainIds[(int)$a['id']]) ? 1 : 0;
        $bHas = isset($homepageDomainIds[(int)$b['id']]) ? 1 : 0;
        if ($aHas !== $bHas) return $bHas - $aHas;
        return (int)$b['id'] - (int)$a['id'];
    });
} catch (Exception $e) {
    $error = $e->getMessage();
}
$taskForm = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['task_type']) && $_POST['task_type'] === 'scheduler') {
    require_csrf();
    $taskForm = normalize_article_task_form_data($_POST);
    try {
        $newTaskId = create_article_generation_task($taskForm);
        redirect('/admin/site-build/index.php?mode=tasklist&saved=1');
    } catch (Exception $e) {
        $error = $e->getMessage();
        $initialMode = 'scheduler';
    }
}
$tf = is_array($taskForm) ? $taskForm : array();
if (isset($_GET['saved']) && $_GET['saved'] === '1' && $success === '') {
    $success = '文章任务已创建成功。';
}
$progressPercent = 0;
$progressState = 'idle';
$progressCurrentStep = 0;
$progressMessage = '提交任务后将展示阶段进度';
?><!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); ?> - 一键建站</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .site-build-grid { display:grid; grid-template-columns:minmax(0, 1.65fr) 340px; gap:20px; align-items:start; }
    .site-build-progress { position:sticky; top:24px; }
    .progress-shell { padding:22px; border-radius:24px; background:linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); border:1px solid rgba(148,163,184,0.18); box-shadow:0 22px 54px rgba(15,23,42,0.08); }
    .progress-bar-track { height:12px; border-radius:999px; background:#e2e8f0; overflow:hidden; }
    .progress-bar-value { height:100%; width:0; border-radius:999px; background:linear-gradient(90deg, #7c3aed 0%, #8b5cf6 45%, #6366f1 100%); transition:width 0.45s ease; }
    .progress-meta { display:flex; justify-content:space-between; align-items:center; gap:12px; margin:12px 0 16px; color:#475569; font-size:13px; }
    .progress-steps { display:grid; gap:12px; margin-top:18px; }
    .progress-step { display:flex; gap:12px; align-items:center; padding:12px 14px; border-radius:999px; background:#fff; border:1px solid rgba(226,232,240,0.9); box-shadow:0 6px 18px rgba(15,23,42,0.04); position:relative; }
    .progress-step-dot { width:28px; height:28px; border-radius:999px; display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:700; color:#64748b; background:#e2e8f0; flex:0 0 auto; }
    .progress-step-body { display:flex; flex-direction:column; gap:2px; }
    .progress-step strong { display:block; margin:0; color:#0f172a; font-size:13px; }
    .progress-step p { margin:0; color:#64748b; font-size:12px; line-height:1.65; }
    .progress-step-pill { margin-left:auto; padding:5px 12px; border-radius:999px; font-size:11px; font-weight:700; letter-spacing:0.02em; background:#e2e8f0; color:#475569; display:inline-flex; align-items:center; justify-content:center; min-width:72px; white-space:nowrap; line-height:1; }
    .progress-step-pill.state-pending { background:#e2e8f0; color:#475569; }
    .progress-step-pill.state-active { background:rgba(99,102,241,0.12); color:#4338ca; }
    .progress-step-pill.state-done { background:rgba(34,197,94,0.12); color:#15803d; }
    .progress-step-pill.state-error { background:rgba(239,68,68,0.12); color:#b91c1c; }
    .progress-step.is-active { border-color:rgba(99,102,241,0.28); background:rgba(99,102,241,0.08); }
    .progress-step.is-active .progress-step-dot { background:#6366f1; color:#fff; }
    .progress-step.is-done { background:rgba(34,197,94,0.08); border-color:rgba(34,197,94,0.28); }
    .progress-step.is-done .progress-step-dot { background:#22c55e; color:#fff; }
    .progress-step.is-error { border-color:rgba(239,68,68,0.26); background:rgba(239,68,68,0.08); }
    .progress-step.is-error .progress-step-dot { background:#ef4444; color:#fff; }
    .progress-notice { margin-top:16px; padding:14px 16px; border-radius:18px; background:#eef2ff; color:#4338ca; font-size:13px; line-height:1.7; }
    .site-build-form .input-group textarea.input { min-height:120px; padding-top:12px; padding-bottom:12px; resize:vertical; }
    .site-build-form .input-group.full-row { grid-column:1 / -1; }
    .result-hidden { display:none; }
    .build-mode-switch { display:flex; gap:12px; margin-bottom:18px; }
    .build-mode-switch button { border:1px solid rgba(148,163,184,0.24); background:#fff; color:#334155; border-radius:14px; padding:12px 18px; font-weight:700; cursor:pointer; }
    .build-mode-switch button.is-active { background:linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color:#fff; border-color:transparent; box-shadow:0 12px 30px rgba(79,70,229,0.22); }
    .build-mode-panel { display:none; }
    .build-mode-panel.is-active { display:block; }
    .domain-multi-grid { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:10px; padding:14px; border:1px solid rgba(148,163,184,0.16); border-radius:16px; background:#f8fafc; max-height:240px; overflow:auto; }
    .domain-multi-item { display:flex; align-items:flex-start; gap:8px; font-size:13px; color:#334155; }
    .domain-multi-item input { margin-top:2px; }
    .build-helper { margin-top:12px; padding:12px 14px; border-radius:16px; background:#f8fafc; color:#64748b; font-size:13px; line-height:1.7; }
    .task-entry-card { padding:24px; border:1px solid rgba(148,163,184,0.16); border-radius:20px; background:linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); }
    .task-entry-card h3 { margin:0 0 10px; font-size:20px; color:#0f172a; }
    .task-entry-card p { margin:0; color:#64748b; line-height:1.8; }
    .task-entry-actions { display:flex; gap:12px; margin-top:18px; flex-wrap:wrap; }
    .article-task-meta { font-size:12px; color:#94a3b8; margin-top:6px; }
    .task-model-switch { color:#6366f1; text-decoration:none; border-bottom:1px dashed #a5b4fc; cursor:pointer; transition:color .15s; }
    .task-model-switch:hover { color:#4338ca; border-bottom-color:#6366f1; }
    .site-build-grid.grid-full { grid-template-columns:1fr; }
    #scheduler-right-panel { display:none; grid-column:2; grid-row:1; position:sticky; top:24px; }
    #scheduler-right-panel .progress-shell .input-group { margin-bottom:14px; }
    #scheduler-right-panel .progress-shell .input-group:last-child { margin-bottom:0; }
    #scheduler-right-panel .progress-shell .input-group span:first-child { display:block; font-size:13px; font-weight:600; color:#334155; margin-bottom:6px; }
    .prompt-preset-btn { padding:5px 12px; font-size:12px; font-weight:600; border-radius:8px; border:1px solid rgba(148,163,184,.22); background:#f8fafc; color:#64748b; cursor:pointer; transition:all .15s; }
    .prompt-preset-btn:hover { border-color:rgba(99,102,241,.3); color:#4f46e5; background:rgba(99,102,241,.04); }
    .prompt-preset-btn.is-active { background:linear-gradient(135deg,#4f46e5,#6366f1); color:#fff; border-color:transparent; box-shadow:0 2px 8px rgba(79,70,229,.22); }
    /* ── 模式选择界面 ── */
    .mode-select-grid { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:20px; }
    .mode-select-card { position:relative; padding:32px 28px 28px; border-radius:20px; border:1px solid rgba(148,163,184,0.16); background:linear-gradient(160deg, #ffffff 0%, #f8fafc 100%); cursor:pointer; transition:all 0.3s ease; overflow:hidden; }
    .mode-select-card::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; background:linear-gradient(90deg, #6366f1, #8b5cf6, #a78bfa); opacity:0; transition:opacity 0.3s; }
    .mode-select-card:hover { border-color:rgba(99,102,241,0.3); box-shadow:0 16px 48px rgba(79,70,229,0.12); transform:translateY(-2px); }
    .mode-select-card:hover::before { opacity:1; }
    .mode-select-card .card-icon-wrap { display:inline-flex; align-items:center; justify-content:center; width:52px; height:52px; border-radius:16px; background:linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%); margin-bottom:18px; transition:all 0.2s; }
    .mode-select-card .card-icon-wrap svg { width:26px; height:26px; stroke-width:1.8; fill:none; stroke-linecap:round; stroke-linejoin:round; transition:all 0.2s; }
    .mode-select-card:hover .card-icon-wrap { background:linear-gradient(135deg, #6366f1, #8b5cf6); }
    .mode-select-card h3 { margin:0 0 8px; font-size:18px; font-weight:700; color:#0f172a; }
    .mode-select-card p { margin:0 0 6px; font-size:13px; color:#64748b; line-height:1.7; }
    .mode-select-card .card-badge { display:inline-block; padding:3px 10px; border-radius:6px; font-size:11px; font-weight:600; margin-top:8px; }
    .card-badge.classic { background:#f1f5f9; color:#475569; }
    .card-badge.wizard { background:linear-gradient(135deg, #eef2ff, #e0e7ff); color:#4f46e5; }
    /* Color accents for homepage vs scheduler */
    .mode-select-card.homepage-card { background:linear-gradient(145deg, rgba(99,102,241,0.08), rgba(139,92,246,0.08)); border-color:rgba(99,102,241,0.24); }
    .mode-select-card.homepage-card .card-icon-wrap { background:linear-gradient(135deg, #eef2ff, #e0e7ff); }
    .mode-select-card.homepage-card .card-icon-wrap svg { stroke:#6366f1; }
    .mode-select-card.homepage-card:hover .card-icon-wrap { background:linear-gradient(135deg, #6366f1, #8b5cf6); }
    .mode-select-card.homepage-card:hover .card-icon-wrap svg { stroke:#fff; }
    .mode-select-card.scheduler-card { background:linear-gradient(145deg, rgba(16,185,129,0.08), rgba(52,211,153,0.08)); border-color:rgba(16,185,129,0.24); }
    .mode-select-card.scheduler-card .card-icon-wrap { background:linear-gradient(135deg, #ecfdf3, #d1fae5); }
    .mode-select-card.scheduler-card .card-icon-wrap svg { stroke:#0f9f6e; }
    .mode-select-card.scheduler-card:hover .card-icon-wrap { background:linear-gradient(135deg, #10b981, #34d399); }
    .mode-select-card.scheduler-card:hover .card-icon-wrap svg { stroke:#fff; }
    /* Section titles: 22px centered with background */
    .mode-select-section-title { font-size:22px; font-weight:800; color:#0f172a; text-align:center; padding:12px 16px; border-radius:14px; margin:0 0 18px; background:#f4f6fb; letter-spacing:0; text-transform:none; display:block; }
    .mode-select-section-title.homepage-title { background:linear-gradient(135deg, #eef2ff, #e0e7ff); color:#312e81; }
    .mode-select-section-title.scheduler-title { background:linear-gradient(135deg, #ecfdf3, #d1fae5); color:#065f46; }
    .mode-select-hidden { display:none; }
    /* ── 向导模式 ── */
    .wizard-container { display:none; }
    .wizard-container.is-active { display:block; }
    .wizard-steps-bar { display:flex; align-items:center; justify-content:center; gap:0; margin-bottom:32px; padding:0 20px; }
    .wizard-step-dot-wrap { display:flex; align-items:center; gap:0; }
    .wizard-step-node { display:flex; flex-direction:column; align-items:center; gap:8px; cursor:pointer; position:relative; min-width:70px; }
    .wizard-step-node .step-circle { width:38px; height:38px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:14px; font-weight:700; border:2px solid #e2e8f0; background:#fff; color:#94a3b8; transition:all 0.3s; }
    .wizard-step-node .step-label { font-size:11px; color:#94a3b8; font-weight:500; white-space:nowrap; transition:color 0.3s; }
    .wizard-step-node.is-active .step-circle { border-color:#6366f1; background:linear-gradient(135deg, #6366f1, #8b5cf6); color:#fff; box-shadow:0 4px 16px rgba(99,102,241,0.3); }
    .wizard-step-node.is-active .step-label { color:#4f46e5; font-weight:700; }
    .wizard-step-node.is-done .step-circle { border-color:#22c55e; background:#22c55e; color:#fff; }
    .wizard-step-node.is-done .step-label { color:#15803d; }
    .wizard-step-line { width:40px; height:2px; background:#e2e8f0; margin:0 4px; margin-bottom:28px; transition:background 0.3s; }
    .wizard-step-line.is-done { background:#22c55e; }
    .wizard-step-panel { display:none; animation:wizardFadeIn 0.35s ease; }
    .wizard-step-panel.is-active { display:block; }
    @keyframes wizardFadeIn { from{opacity:0;transform:translateY(8px);} to{opacity:1;transform:translateY(0);} }
    .wizard-nav { display:flex; justify-content:space-between; align-items:center; margin-top:28px; padding-top:20px; border-top:1px solid rgba(148,163,184,0.14); }
    .wizard-nav button { padding:10px 24px; border-radius:12px; font-weight:600; font-size:14px; cursor:pointer; transition:all 0.2s; border:none; }
    .wizard-btn-prev { border:1px solid #e2e8f0 !important; background:#fff; color:#475569; }
    .wizard-btn-prev:hover { border-color:#cbd5e1 !important; background:#f8fafc; }
    .wizard-btn-next { background:linear-gradient(135deg, #6366f1, #8b5cf6) !important; color:#fff; box-shadow:0 4px 16px rgba(99,102,241,0.25); }
    .wizard-btn-next:hover { box-shadow:0 8px 24px rgba(99,102,241,0.35); transform:translateY(-1px); }
    .wizard-btn-next:disabled { opacity:0.5; cursor:not-allowed; transform:none; box-shadow:none; }
    .wizard-review-table { width:100%; border-collapse:collapse; }
    .wizard-review-table td { padding:10px 14px; border-bottom:1px solid #f1f5f9; font-size:13px; }
    .wizard-review-table td:first-child { color:#64748b; width:150px; font-weight:500; }
    .wizard-review-table td:last-child { color:#0f172a; font-weight:600; }
    .wizard-back-link { display:inline-flex; align-items:center; gap:6px; color:#6366f1; font-size:13px; font-weight:600; cursor:pointer; margin-bottom:20px; text-decoration:none; }
    .wizard-back-link:hover { color:#4338ca; }
    .wizard-back-link svg { width:16px; height:16px; }
    .wizard-summary-box { padding:18px 20px; border-radius:16px; background:linear-gradient(135deg, #eef2ff, #faf5ff); border:1px solid rgba(99,102,241,0.12); margin-bottom:20px; }
    .wizard-summary-box h4 { margin:0 0 6px; font-size:15px; color:#4f46e5; }
    .wizard-summary-box p { margin:0; font-size:13px; color:#475569; line-height:1.7; }
    @media (max-width: 1080px) { .site-build-grid { grid-template-columns:1fr; } .site-build-progress { position:static; } #scheduler-right-panel { position:static; grid-column:1; grid-row:auto; } .mode-select-grid { grid-template-columns:1fr; } }
    @media (max-width: 720px) { .domain-multi-grid { grid-template-columns:1fr; } .wizard-steps-bar { flex-wrap:wrap; gap:8px; } .wizard-step-line { width:20px; } }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('site_build', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>站点发布</h1></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/site-build/index.php?mode=tasklist">查看任务列表</a></div>
            </header>
            <?php $showSelection = !$regenDomainLocked && !isset($_GET['mode']) && !isset($_GET['saved']) && !isset($_GET['regen']); ?>
            <?php if ($showSelection): ?>
            <!-- ──────── 模式选择界面 ──────── -->
            <div id="mode-select-screen">
                <div class="mode-select-section-title homepage-title">发布首页</div>
                <div class="mode-select-grid" style="margin-bottom:28px;">
                    <div class="mode-select-card homepage-card" onclick="selectMode('homepage-classic')">
                        <div class="card-icon-wrap"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="21" x2="9" y2="9"/></svg></div>
                        <h3>经典模式</h3>
                        <p>传统表单操作，所有参数集中展示，适合熟练用户快速完成首页生成配置。</p>
                        <span class="card-badge classic">传统表单</span>
                    </div>
                    <div class="mode-select-card homepage-card" onclick="selectMode('homepage-wizard')">
                        <div class="card-icon-wrap"><svg viewBox="0 0 24 24"><polygon points="13,2 3,14 12,14 11,22 21,10 12,10"/></svg></div>
                        <h3>向导模式</h3>
                        <p>分步引导式操作，每一步聚焦一个配置维度，视觉化交互降低上手门槛。</p>
                        <span class="card-badge wizard">分步引导</span>
                    </div>
                </div>
                <div class="mode-select-section-title scheduler-title">新建定时任务</div>
                <div class="mode-select-grid">
                    <div class="mode-select-card scheduler-card" onclick="selectMode('scheduler-classic')">
                        <div class="card-icon-wrap"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12,6 12,12 16,14"/></svg></div>
                        <h3>经典模式</h3>
                        <p>传统表单操作，所有参数集中展示，适合熟练用户快速创建文章定时生成任务。</p>
                        <span class="card-badge classic">传统表单</span>
                    </div>
                    <div class="mode-select-card scheduler-card" onclick="selectMode('scheduler-wizard')">
                        <div class="card-icon-wrap"><svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div>
                        <h3>向导模式</h3>
                        <p>分步引导式操作，从基本信息到发布设置逐层递进，参数一应俱全。</p>
                        <span class="card-badge wizard">分步引导</span>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <div id="main-build-area" class="<?php echo $showSelection ? 'mode-select-hidden' : ''; ?>">
            <div class="site-build-grid">
                <div>
                    <section class="page-card site-build-form">
                        <div class="build-mode-switch" id="classic-mode-switch">
                            <button type="button" class="is-active" data-build-mode="homepage">首页生成</button>
                            <button type="button" data-build-mode="scheduler">新建定时任务</button>
                            <button type="button" data-build-mode="tasklist">任务列表</button>
                        </div>
                        <a class="wizard-back-link" id="wizard-back-link" style="display:none;" onclick="goBackToSelection()">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15,18 9,12 15,6"/></svg>返回模式选择
                        </a>
                        <?php if ($regenDomainLocked && $regenContent): ?><div class="mini-item" style="margin-bottom:16px; border-color:rgba(249,115,22,0.16); background:rgba(255,247,237,0.92);"><strong style="color:#c2410c;">重新生成首页</strong><p style="margin:0; color:#9a3412;">正在为「<?php echo e(isset($regenContent['title']) ? $regenContent['title'] : ''); ?>」重新生成首页，域名已锁定。已回填上次的 SEO 信息，你可以修改后点击生成。</p></div><?php endif; ?>
                        <div id="site-build-success" class="mini-item result-hidden" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                            <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;">
                                <div>
                                    <strong style="color:#15803d;">执行成功</strong>
                                    <p id="site-build-success-text" style="margin:0; color:#166534;"></p>
                                </div>
                                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                                    <button type="button" id="result-preview-btn" class="btn-primary">查看预览</button>
                                    <a id="result-edit-link" class="btn-soft" href="/admin/content/list.php">编辑内容</a>
                                    <a class="btn-ghost" href="/admin/content/list.php">返回内容列表</a>
                                </div>
                            </div>
                        </div>
                        <div id="site-build-error" class="mini-item<?php echo $error !== '' ? '' : ' result-hidden'; ?>" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">执行失败</strong><p id="site-build-error-text" style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p></div>
                        <form id="site-build-form" method="post" action="/admin/site-build/index.php">
                            <?php echo csrf_field(); ?>
                            <?php $regenDomainLanguage = 'zh-CN'; if ($regenDomainLocked) { foreach ($domains as $item) { if ((int)$item['id'] === $form['domain_id']) { $regenDomainLanguage = isset($item['site_language']) ? (string)$item['site_language'] : 'zh-CN'; break; } } } ?>
                            <input type="hidden" name="task_type" id="site-build-task-type" value="homepage">
                            <input type="hidden" name="site_language" id="site-build-site-language" value="<?php echo e($regenDomainLocked ? $regenDomainLanguage : ''); ?>">
                            <div id="homepage-build-panel" class="build-mode-panel is-active">
                            <div class="form-grid">
                                <div class="input-group">
                                    <span>* 绑定域名</span>
                                    <?php if ($regenDomainLocked): ?>
                                    <input type="hidden" name="domain_id" value="<?php echo (int)$form['domain_id']; ?>">
                                    <select class="select" disabled>
                                        <?php foreach ($domains as $item): ?>
                                            <?php if ((int)$item['id'] === $form['domain_id']): ?>
                                            <option selected data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>"><?php echo e($item['domain']); ?> <?php echo e($item['site_name']); ?></option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php else: ?>
                                    <select class="select" name="domain_id">
                                        <option value="0">请选择域名</option>
                                        <?php foreach ($domains as $item): $hasHomepage = isset($homepageDomainIds[(int)$item['id']]); ?>
                                            <option value="<?php echo (int)$item['id']; ?>" data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>"<?php echo $form['domain_id'] === (int)$item['id'] ? ' selected' : ''; ?><?php echo $hasHomepage ? ' disabled style="color:#94a3b8;"' : ''; ?>><?php echo e($item['domain']); ?> <?php echo e($item['site_name']); ?><?php echo $hasHomepage ? ' · 首页已生成' : ''; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php endif; ?>
                                </div>
                                <div class="input-group">
                                    <span>模板套件</span>
                                    <div class="input" style="display:flex; align-items:center; color:#64748b; background:#f8fafc;">自动使用域名绑定的模板套件（在域名管理中配置）</div>
                                </div>
                                <div class="input-group">
                                    <span>* AI 模型</span>
                                    <select class="select" name="model_id">
                                        <option value="0">请选择 AI 模型</option>
                                        <?php foreach ($models as $item): ?>
                                            <option value="<?php echo (int)$item['id']; ?>"<?php echo $form['model_id'] === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['name']); ?> <?php echo e($item['provider']); ?> / <?php echo e($item['model_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="input-group">
                                    <span>* 核心关键词</span>
                                    <input class="input" type="text" name="keyword" value="<?php echo e($form['keyword']); ?>" placeholder="如：北京装修公司">
                                </div>
                                <div class="input-group">
                                    <span>站点名称</span>
                                    <input class="input" type="text" name="site_name" value="<?php echo e($form['site_name']); ?>" placeholder="留空则优先使用域名配置中的站点名">
                                </div>
                                <div class="input-group">
                                    <span>备注</span>
                                    <input class="input" type="text" name="remark" value="<?php echo e($form['remark']); ?>" placeholder="记录本次建站用途或项目说明">
                                </div>
                                <div class="input-group full-row">
                                    <span>* 站点描述</span>
                                    <div style="display:flex;gap:10px;align-items:center;margin-bottom:8px;">
                                        <button type="button" class="btn-soft" id="btnAiDesc" style="white-space:nowrap;height:36px;font-size:13px;">AI 生成描述</button>
                                        <span id="aiDescStatus" style="font-size:13px;color:#6b7280;"></span>
                                    </div>
                                    <textarea class="input" name="site_description" id="siteDescription" placeholder="请输入站点主营业务、目标客户、服务范围、品牌特色、转化目标等，AI 将据此生成更精准的首页结构化字段。比如：我们是一家面向本地中小企业的工商注册与代理记账服务公司，提供公司注册、代理记账、税务筹划、许可证代办，强调专业、高效、可落地。\n"><?php echo e($form['site_description']); ?></textarea>
                                </div>
                                <div class="input-group full-row">
                                    <span>发布方式</span>
                                    <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="publish_now" value="1"<?php echo $form['publish_now'] ? ' checked' : ''; ?>> 生成后直接发布</label>
                                </div>
                            </div>
                            <div class="filter-row" style="margin-top:18px;">
                                <button id="site-build-submit" class="btn-primary" type="submit">立即生成首页</button>
                                <a class="btn-ghost" href="/admin/site-build/index.php">重置</a>
                            </div>
                            </div>
                        </form>

                        <form id="scheduler-form" method="post" action="/admin/site-build/index.php">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="task_type" value="scheduler">
                            <input type="hidden" name="model_id" id="sync_model_id" value="0">
                            <input type="hidden" name="article_length" id="sync_article_length" value="1200-1800字">
                            <input type="hidden" name="interval_seconds" id="sync_interval_seconds" value="0">
                            <input type="hidden" name="keywords_text" id="sync_keywords_text" value="">
                            <input type="hidden" name="custom_prompt" id="sync_custom_prompt" value="">
                            <input type="hidden" name="remark" id="sync_remark" value="">
                            <input type="hidden" name="reuse_keywords" id="sync_reuse_keywords" value="0">
                            <div id="scheduler-build-panel" class="build-mode-panel">
                                <?php if ($success !== ''): ?>
                                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);"><strong style="color:#15803d;">操作成功</strong><p style="margin:0; color:#166534;"><?php echo e($success); ?></p></div>
                                <?php endif; ?>
                                <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                                    <div class="input-group">
                                        <span>* 任务名称</span>
                                        <input class="input" type="text" name="task_name" value="<?php echo e(isset($tf['task_name']) ? $tf['task_name'] : ''); ?>" placeholder="例如：装修类文章日更任务">
                                    </div>
                                    <div class="input-group">
                                        <span>* 任务状态</span>
                                        <select class="select" name="status">
                                            <?php foreach ($articleTaskEditableStatusOptions as $key => $label): ?>
                                                <option value="<?php echo e($key); ?>"<?php echo (isset($tf['status']) && $tf['status'] === $key) ? ' selected' : ''; ?>><?php echo e($label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="input-group" style="grid-column:1/-1;">
                                        <span>* 执行域名（可多选）</span>
                                        <div class="domain-multi-grid">
                                            <?php foreach ($domains as $item): ?>
                                                <?php $hasHomepage = isset($homepageDomainIds[(int)$item['id']]); ?>
                                                <label class="domain-multi-item"<?php if (!$hasHomepage): ?> style="opacity:.45;cursor:not-allowed;pointer-events:none;" title="首页未生成，请先生成首页"<?php endif; ?>><input type="checkbox" name="domain_ids[]" value="<?php echo (int)$item['id']; ?>"<?php echo (!empty($tf['domain_ids']) && in_array((int)$item['id'], $tf['domain_ids']) && $hasHomepage) ? ' checked' : ''; ?><?php if (!$hasHomepage): ?> disabled<?php endif; ?>><span><?php echo e($item['domain']); ?><?php if ($hasHomepage): ?> <small style="color:#15803d;font-weight:600;">✓首页</small><?php else: ?> <small style="color:#dc2626;font-weight:500;">未建站</small><?php endif; ?><br><small style="color:#94a3b8;"><?php echo e($item['site_name']); ?></small></span></label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <div class="input-group">
                                        <span>模板套件</span>
                                        <input type="hidden" name="template_id" value="0">
                                        <div class="input" style="background:#f8fafc; color:#64748b; cursor:default;">自动使用域名绑定的模板套件</div>
                                    </div>
                                    <div class="input-group">
                                        <span>路径前缀（备用）</span>
                                        <input class="input" type="text" name="path_prefix" value="<?php echo e(isset($tf['path_prefix']) ? $tf['path_prefix'] : 'article'); ?>" placeholder="如：article / news">
                                        <div style="font-size:12px; color:#94a3b8; margin-top:4px;">已选目标菜单时自动使用菜单 slug 作为路径前缀。</div>
                                    </div>
                                    <div class="input-group" style="grid-column:1/-1;">
                                        <span>目标菜单（可多选，按已选域名筛选）</span>
                                        <div class="domain-multi-grid" id="scheduler-menu-grid">
                                            <?php if (empty($allMenuOptions)): ?>
                                                <div style="color:#94a3b8; padding:8px 0;">请先勾选执行域名</div>
                                            <?php endif; ?>
                                            <?php foreach ($allMenuOptions as $mi): ?>
                                                <label class="domain-multi-item scheduler-menu-item" data-domain-id="<?php echo (int)$mi['_domain_id']; ?>" style="display:none;"><input type="checkbox" name="target_menu_ids[]" value="<?php echo (int)$mi['id']; ?>"<?php echo (!empty($tf['target_menu_ids']) && in_array((int)$mi['id'], $tf['target_menu_ids'])) ? ' checked' : ''; ?>><span><?php echo e($mi['menu_name']); ?><br><small style="color:#94a3b8;">/<?php echo e($mi['menu_slug']); ?>/ · <?php echo e($mi['_domain']); ?></small></span></label>
                                            <?php endforeach; ?>
                                        </div>
                                        <div style="font-size:12px; color:#94a3b8; margin-top:6px;">勾选后，任务生成的文章会自动归入对应菜单栏目。</div>
                                    </div>
                                    <div class="input-group">
                                        <span>生成标题图</span>
                                        <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="generate_image" value="1" id="sb_chk_gen_img"<?php echo (!empty($tf) && empty($tf['generate_image'])) ? '' : ' checked'; ?>> 自动生成文章标题图（同时作为封面图）</label>
                                        <div id="sb_watermark_panel" style="margin-top:6px;<?php echo (!empty($tf) && empty($tf['generate_image'])) ? ' display:none;' : ''; ?>">
                                            <label style="display:flex; align-items:center; gap:8px; font-size:13px; color:#475569;"><input type="checkbox" name="cover_watermark" value="1" id="sb_chk_watermark"<?php echo (!isset($tf['cover_watermark']) || !empty($tf['cover_watermark'])) ? ' checked' : ''; ?>> 添加水印</label>
                                            <div id="sb_watermark_text_panel" style="margin-top:6px;<?php echo (isset($tf['cover_watermark']) && empty($tf['cover_watermark'])) ? ' display:none;' : ''; ?>">
                                                <input class="input" type="text" name="cover_watermark_text" value="<?php echo e(isset($tf['cover_watermark_text']) ? $tf['cover_watermark_text'] : ''); ?>" placeholder="自定义水印内容，留空默认使用域名对应的站点名" style="font-size:13px;">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="input-group">
                                        <span>生成后发布</span>
                                        <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="publish_now" value="1" id="sb_chk_publish_now"<?php echo (!empty($tf['publish_now'])) ? ' checked' : ''; ?>> 自动发布（生成后直接设为已发布状态）</label>
                                        <div id="sb_static_output_panel" style="margin-top:6px;<?php echo empty($tf['publish_now']) ? ' display:none;' : ''; ?>">
                                            <label style="display:flex; align-items:center; gap:8px; font-size:13px; color:#475569;"><input type="checkbox" name="static_output" value="1" id="sb_chk_static_output"<?php echo !empty($tf['static_output']) ? ' checked' : ''; ?>> 同时生成静态HTML文件</label>
                                            <div style="font-size:12px; color:#94a3b8; margin-top:4px;">使用伪静态（rewrite）方式访问的站点无需勾选此项。</div>
                                        </div>
                                    </div>
                                    <div class="input-group" style="grid-column:1/-1; border-top:1px solid rgba(148,163,184,0.12); padding-top:18px; margin-top:8px;">
                                        <span>插入本地图片</span>
                                        <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="insert_images" value="1" id="sb_chk_insert_images"<?php echo !empty($tf['insert_images']) ? ' checked' : ''; ?>> 从指定文件夹随机选取图片插入文章正文</label>
                                    </div>
                                    <div class="input-group" id="sb_image_config_panel" style="grid-column:1/-1;<?php echo empty($tf['insert_images']) ? ' display:none;' : ''; ?>">
                                        <div class="form-grid" style="gap:14px;">
                                            <div class="input-group full-row">
                                                <span>图片文件夹路径</span>
                                                <input class="input" type="text" name="image_folder" value="<?php echo e(isset($tf['image_folder']) ? $tf['image_folder'] : ''); ?>" placeholder="相对路径：uploads/images 或绝对路径如 d:/wwwroot/images">
                                                <div style="font-size:12px; color:#94a3b8; margin-top:4px;">支持 jpg/jpeg/png/gif/webp/svg/bmp，系统将随机抽取图片插入文章。</div>
                                            </div>
                                            <div class="input-group">
                                                <span>插入数量</span>
                                                <input class="input" type="number" name="image_count" min="1" max="10" value="<?php echo (int)(isset($tf['image_count']) && $tf['image_count'] > 0 ? $tf['image_count'] : 1); ?>">
                                                <div style="font-size:12px; color:#94a3b8; margin-top:4px;">1 张插入文章中间，多张自动平均分布在段落之间。</div>
                                            </div>
                                            <div class="input-group full-row">
                                                <label style="display:flex; align-items:center; gap:10px; min-height:36px; padding:0 2px; color:#334155;"><input type="checkbox" name="use_folder_cover" value="1"<?php echo !empty($tf['use_folder_cover']) ? ' checked' : ''; ?>> 将文件夹图片设为封面图（优先级高于标题图）</label>
                                                <div style="font-size:12px; color:#94a3b8; margin-top:4px;">勾选后，封面图从指定文件夹随机选取；未勾选则使用自动生成的标题图作为封面图。</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="filter-row" style="margin-top:18px;">
                                    <button class="btn-primary" type="submit">创建任务</button>
                                    <a class="btn-ghost" href="/admin/site-build/index.php?mode=scheduler">重置</a>
                                </div>
                            </div>
                        </form>

                        <div id="tasklist-build-panel" class="build-mode-panel">
                            <h3 style="margin:0 0 12px 0;">文章任务管理</h3>
                            <div class="filter-row" id="article-task-filter">
                                <input class="input" type="text" id="atf-keyword" value="<?php echo e($articleTaskKeyword); ?>" placeholder="搜索任务名称 / 备注">
                                <select class="select" id="atf-status">
                                    <option value="all">全部状态</option>
                                    <?php foreach ($articleTaskStatusOptions as $key => $label): ?>
                                        <option value="<?php echo e($key); ?>"<?php echo $articleTaskStatus === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button class="btn-soft" type="button" onclick="(function(){ var k=document.getElementById('atf-keyword').value,s=document.getElementById('atf-status').value,u='/admin/site-build/index.php?mode=tasklist';if(k)u+='&task_keyword='+encodeURIComponent(k);if(s&&s!=='all')u+='&task_status='+encodeURIComponent(s);location.href=u; })()">筛选</button>
                                <a class="btn-ghost" href="/admin/site-build/index.php?mode=tasklist">重置</a>
                            </div>
                            <?php if ($batchStatus === 'success'): ?>
                                <div class="mini-item" style="margin-bottom:12px;border-color:rgba(34,197,94,0.18);background:rgba(34,197,94,0.06);">
                                    <strong style="color:#15803d;">批量删除完成</strong>
                                    <p style="margin:0;color:#166534;">已删除 <?php echo (int)$batchCount; ?> 个任务。</p>
                                </div>
                            <?php elseif ($batchStatus === 'empty'): ?>
                                <div class="mini-item" style="margin-bottom:12px;border-color:rgba(220,38,38,0.18);background:rgba(220,38,38,0.06);">
                                    <strong style="color:#dc2626;">操作失败</strong>
                                    <p style="margin:0;color:#b91c1c;">请先勾选需要删除的任务。</p>
                                </div>
                            <?php elseif ($batchStatus === 'error'): ?>
                                <div class="mini-item" style="margin-bottom:12px;border-color:rgba(220,38,38,0.18);background:rgba(220,38,38,0.06);">
                                    <strong style="color:#dc2626;">批量删除失败</strong>
                                    <p style="margin:0;color:#b91c1c;">删除过程中发生异常，请稍后重试。</p>
                                </div>
                            <?php endif; ?>

                            <form id="taskBatchForm" method="post" action="/admin/article-task/batch.php" onsubmit="return beforeTaskBatchSubmit(this) && confirm('确认批量删除已勾选的任务吗？此操作不可恢复。');" style="margin:10px 0 12px;">
                                <?php echo csrf_field(); ?>
                                <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:10px 12px;border:1px solid rgba(148,163,184,0.2);border-radius:14px;background:#f8fafc;">
                                    <label style="display:inline-flex;align-items:center;gap:8px;font-size:13px;color:#334155;"><input type="checkbox" id="task-check-all"> 全选 / 取消全选</label>
                                    <div style="display:flex;gap:8px;">
                                        <button class="btn-soft" type="submit" name="batch_action" value="delete">批量删除</button>
                                    </div>
                                </div>
                            </form>
                            <table class="data-table">
                                <thead><tr><th style="width:42px;text-align:center;">选</th><th>ID</th><th>任务</th><th>模型</th><th>状态</th><th>关键词</th><th>生成概况</th><th>最近执行</th><th>操作</th></tr></thead>
                                <tbody>
                                <?php if (!empty($articleTasks)): ?>
                                    <?php foreach ($articleTasks as $item): ?>
                                        <tr>
                                            <td style="text-align:center;"><input type="checkbox" class="task-check-item" value="<?php echo (int)$item['id']; ?>"></td>
                                            <td><?php echo (int)$item['id']; ?></td>
                                            <td><strong><?php echo e($item['task_name']); ?></strong><?php if (isset($item['remark']) && trim((string)$item['remark']) !== ''): ?><div class="article-task-meta"><?php echo e($item['remark']); ?></div><?php endif; ?></td>
                                            <td><a href="javascript:;" class="task-model-switch" data-task-id="<?php echo (int)$item['id']; ?>" data-model-id="<?php echo (int)$item['model_id']; ?>" title="点击切换模型"><?php echo e(isset($item['model_name']) && $item['model_name'] !== '' ? $item['model_name'] : '未配置'); ?></a><div class="article-task-meta">域名 <?php echo (int)$item['domain_count']; ?> 个</div></td>
                                            <td><span class="badge <?php echo e(article_generation_task_status_badge_class(isset($item['status']) ? $item['status'] : 'draft')); ?>"><?php echo e(isset($articleTaskStatusOptions[$item['status']]) ? $articleTaskStatusOptions[$item['status']] : $item['status']); ?></span><div class="article-task-meta">下次执行：<?php echo e(isset($item['next_run_at']) && $item['next_run_at'] !== '' ? $item['next_run_at'] : '-'); ?></div><?php if (isset($item['last_error']) && trim((string)$item['last_error']) !== ''): ?><div class="article-task-meta" style="color:#dc2626; max-width:280px; white-space:normal; line-height:1.6;">异常原因：<?php echo e($item['last_error']); ?></div><?php endif; ?></td>
                                            <td>总数 <?php echo (int)$item['keyword_total']; ?><div class="article-task-meta">待处理 <?php echo (int)$item['pending_count']; ?> / 失败 <?php echo (int)$item['failed_keyword_count']; ?></div></td>
                                            <td>已生成 <?php echo (int)$item['generated_count']; ?><div class="article-task-meta">成功 <?php echo (int)$item['success_count']; ?> / 失败 <?php echo (int)$item['failed_count']; ?></div></td>
                                            <td><?php echo e(isset($item['last_generated_at']) && $item['last_generated_at'] !== '' ? $item['last_generated_at'] : '-'); ?><div class="article-task-meta">最近调度：<?php echo e(isset($item['last_run_at']) && $item['last_run_at'] !== '' ? $item['last_run_at'] : '-'); ?></div></td>
                                            <td><a href="/admin/article-task/edit.php?id=<?php echo (int)$item['id']; ?>">编辑</a> / <a href="/admin/article-task/run.php?id=<?php echo (int)$item['id']; ?>">立即执行</a> / <?php if (isset($item['status']) && $item['status'] === 'enabled'): ?><a href="/admin/article-task/status.php?id=<?php echo (int)$item['id']; ?>&status=paused">暂停</a><?php else: ?><a href="/admin/article-task/status.php?id=<?php echo (int)$item['id']; ?>&status=enabled">启用</a><?php endif; ?> / <form method="post" action="/admin/article-task/delete.php" style="display:inline;" onsubmit="return confirm('确认删除文章任务「<?php echo e($item['task_name']); ?>」吗？删除后不可恢复。');"><?php echo csrf_field(); ?><input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>"><button type="submit" class="link-btn" style="color:#dc2626;">删除</button></form></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="empty-note"><?php echo $error === '' ? '暂无文章任务，请先创建。' : '无法加载任务数据。'; ?></td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                            <div class="build-helper">建议流程：先创建文章任务并配置域名、文章模板、AI 模型和关键词池，再按需要手动执行或交给调度器静默运行。</div>
                        </div>
                    </section>
                    <!-- ════════ 向导模式：发布首页?════════ -->
                    <div class="wizard-container" id="wizard-homepage">
                        <div class="wizard-steps-bar" id="wiz-hp-steps">
                            <div class="wizard-step-node is-active" data-step="1"><div class="step-circle">1</div><span class="step-label">选择域名</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="2"><div class="step-circle">2</div><span class="step-label">AI 配置</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="3"><div class="step-circle">3</div><span class="step-label">站点信息</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="4"><div class="step-circle">4</div><span class="step-label">发布设置</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="5"><div class="step-circle">5</div><span class="step-label">确认生成</span></div>
                        </div>
                        <form id="wiz-hp-form" onsubmit="return false;">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="task_type" value="homepage">
                        <input type="hidden" name="site_language" id="wiz-hp-site-language" value="">
                        <!-- 第1步：选择域名 -->
                        <div class="wizard-step-panel is-active" data-step="1">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">选择目标域名</h3>
                            <p style="margin:0 0 20px;color:#64748b;">选择一个已配置的域名作为首页发布目标。</p>
                            <div class="form-grid">
                                <div class="input-group">
                                    <span>* 绑定域名</span>
                                    <select class="select" id="wiz-hp-domain" onchange="wizHpUpdateDomain()">
                                        <option value="0">请选择域名</option>
                                        <?php foreach ($domains as $item): $hasHomepage = isset($homepageDomainIds[(int)$item['id']]); ?>
                                            <option value="<?php echo (int)$item['id']; ?>" data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>"<?php echo $hasHomepage ? ' disabled style="color:#94a3b8;"' : ''; ?>><?php echo e($item['domain']); ?> <?php echo e($item['site_name']); ?><?php echo $hasHomepage ? ' · 首页已生成' : ''; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="input-group">
                                    <span>模板套件</span>
                                    <div class="input" style="display:flex;align-items:center;color:#64748b;background:#f8fafc;">自动使用域名绑定的模板套件</div>
                                </div>
                            </div>
                            <div class="wizard-summary-box" style="margin-top:20px;">
                                <h4><svg viewBox="0 0 24 24" style="width:18px;height:18px;vertical-align:-3px;stroke:#6366f1;fill:none;stroke-width:2;"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg> 提示</h4>
                                <p>请确保目标域名已完成基础配置（站点名称、模板套件等），这将直接影响首页生成质量。</p>
                            </div>
                        </div>
                        <!-- 第2步：AI 配置 -->
                        <div class="wizard-step-panel" data-step="2">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">AI 模型与关键词</h3>
                            <p style="margin:0 0 20px;color:#64748b;">选择 AI 模型并填写核心关键词，AI 将围绕该关键词生成首页内容。</p>
                            <div class="form-grid">
                                <div class="input-group">
                                    <span>* AI 模型</span>
                                    <select class="select" id="wiz-hp-model">
                                        <option value="0">请选择 AI 模型</option>
                                        <?php foreach ($models as $item): ?>
                                            <option value="<?php echo (int)$item['id']; ?>"<?php echo $form['model_id'] === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['name']); ?> <?php echo e($item['provider']); ?> / <?php echo e($item['model_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="input-group">
                                    <span>* 核心关键词</span>
                                    <input class="input" type="text" id="wiz-hp-keyword" placeholder="如：北京装修公司" value="<?php echo e($form['keyword']); ?>">
                                </div>
                            </div>
                        </div>
                        <!-- 第3步：站点信息 -->
                        <div class="wizard-step-panel" data-step="3">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">站点名称与描述</h3>
                            <p style="margin:0 0 20px;color:#64748b;">填写站点名称和详细描述，AI 将据此生成精准的首页结构化字段。</p>
                            <div class="form-grid">
                                <div class="input-group">
                                    <span>站点名称</span>
                                    <input class="input" type="text" id="wiz-hp-site-name" placeholder="留空则优先使用域名配置中的站点名" value="<?php echo e($form['site_name']); ?>">
                                </div>
                                <div class="input-group full-row">
                                    <span>* 站点描述</span>
                                    <div style="display:flex;gap:10px;align-items:flex-start;">
                                        <textarea class="input" id="wiz-hp-site-desc" placeholder="请输入站点主营业务、目标客户、服务范围、品牌特色、转化目标等。&#10;比如：我们是一家面向本地中小企业的工商注册与代理记账服务公司..." style="flex:1;min-height:140px;"><?php echo e($form['site_description']); ?></textarea>
                                        <div style="display:flex;flex-direction:column;gap:8px;min-width:132px;">
                                            <button type="button" class="btn-soft" id="wiz-btnAiDesc" style="white-space:nowrap;height:36px;font-size:13px;">AI 生成描述</button>
                                            <span id="wiz-aiDescStatus" style="font-size:13px;color:#6b7280;"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 第4步：发布设置 -->
                        <div class="wizard-step-panel" data-step="4">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">发布与备注</h3>
                            <p style="margin:0 0 20px;color:#64748b;">设置发布方式并添加备注信息。</p>
                            <div class="form-grid">
                                <div class="input-group">
                                    <span>发布方式</span>
                                    <label style="display:flex;align-items:center;gap:10px;min-height:44px;padding:0 2px;color:#334155;"><input type="checkbox" id="wiz-hp-publish" value="1"<?php echo $form['publish_now'] ? ' checked' : ''; ?>> 生成后直接发布</label>
                                </div>
                                <div class="input-group">
                                    <span>备注</span>
                                    <input class="input" type="text" id="wiz-hp-remark" placeholder="记录本次建站用途或项目说明" value="<?php echo e($form['remark']); ?>">
                                </div>
                            </div>
                        </div>
                        <!-- 第5步：确认生成 -->
                        <div class="wizard-step-panel" data-step="5">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">确认配置</h3>
                            <p style="margin:0 0 20px;color:#64748b;">请检查以下配置，确认无误后点击生成按钮。</p>
                            <table class="wizard-review-table">
                                <tr><td>绑定域名</td><td id="wiz-hp-review-domain">-</td></tr>
                                <tr><td>AI 模型</td><td id="wiz-hp-review-model">-</td></tr>
                                <tr><td>核心关键词</td><td id="wiz-hp-review-keyword">-</td></tr>
                                <tr><td>站点名称</td><td id="wiz-hp-review-name">-</td></tr>
                                <tr><td>站点描述</td><td id="wiz-hp-review-desc">-</td></tr>
                                <tr><td>备注</td><td id="wiz-hp-review-remark">-</td></tr>
                                <tr><td>发布方式</td><td id="wiz-hp-review-publish">-</td></tr>
                            </table>
                        </div>
                        <div class="wizard-nav" id="wiz-hp-nav">
                            <button type="button" class="wizard-btn-prev" id="wiz-hp-prev" onclick="wizHpPrev()" style="display:none;">← 上一步</button>
                            <span id="wiz-hp-step-indicator" style="font-size:13px;color:#94a3b8;">步骤 1 / 5</span>
                            <button type="button" class="wizard-btn-next" id="wiz-hp-next" onclick="wizHpNext()">下一步 →</button>
                        </div>
                        </form>
                    </div>
                    <!-- ════════ 向导模式：新建定时任务 ════════ -->
                    <div class="wizard-container" id="wizard-scheduler">
                        <div class="wizard-steps-bar" id="wiz-sc-steps">
                            <div class="wizard-step-node is-active" data-step="1"><div class="step-circle">1</div><span class="step-label">域名菜单</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="2"><div class="step-circle">2</div><span class="step-label">基本信息</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="3"><div class="step-circle">3</div><span class="step-label">AI 内容</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="4"><div class="step-circle">4</div><span class="step-label">内容参数</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="5"><div class="step-circle">5</div><span class="step-label">发布设置</span></div>
                            <div class="wizard-step-line"></div>
                            <div class="wizard-step-node" data-step="6"><div class="step-circle">6</div><span class="step-label">确认创建</span></div>
                        </div>
                        <form id="wiz-sc-form" onsubmit="return false;">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="task_type" value="scheduler">
                        <!-- 第1步：域名与菜单（调整为首步） -->
                        <div class="wizard-step-panel is-active" data-step="1">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">执行域名与目标菜单</h3>
                            <p style="margin:0 0 20px;color:#64748b;">选择任务在哪些域名下执行，并指定文章归属的菜单栏目。</p>
                            <div class="form-grid">
                                <div class="input-group full-row">
                                    <span>* 执行域名（可多选）</span>
                                    <div class="domain-multi-grid" id="wiz-sc-domain-grid">
                                        <?php foreach ($domains as $item): ?>
                                            <?php $hasHomepage = isset($homepageDomainIds[(int)$item['id']]); ?>
                                            <label class="domain-multi-item"<?php if (!$hasHomepage): ?> style="opacity:.45;cursor:not-allowed;pointer-events:none;" title="首页未生成，请先生成首页"<?php endif; ?>><input type="checkbox" name="wiz_domain_ids[]" value="<?php echo (int)$item['id']; ?>" data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>"<?php if (!$hasHomepage): ?> disabled<?php endif; ?>><span><?php echo e($item['domain']); ?><?php if ($hasHomepage): ?> <small style="color:#15803d;font-weight:600;">✓首页</small><?php else: ?> <small style="color:#dc2626;font-weight:500;">未建站</small><?php endif; ?><br><small style="color:#94a3b8;">&nbsp;<?php echo e($item['site_name']); ?></small></span></label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div class="input-group full-row">
                                    <span>目标菜单（可多选）</span>
                                    <div class="domain-multi-grid" id="wiz-sc-menu-grid">
                                        <?php if (empty($allMenuOptions)): ?>
                                            <div style="color:#94a3b8;padding:8px 0;">请先勾选执行域名</div>
                                        <?php endif; ?>
                                        <?php foreach ($allMenuOptions as $mi): ?>
                                            <label class="domain-multi-item wiz-sc-menu-item" data-domain-id="<?php echo (int)$mi['_domain_id']; ?>" style="display:none;"><input type="checkbox" name="wiz_target_menu_ids[]" value="<?php echo (int)$mi['id']; ?>"><span><?php echo e($mi['menu_name']); ?><br><small style="color:#94a3b8;">/<?php echo e($mi['menu_slug']); ?>/ · <?php echo e($mi['_domain']); ?></small></span></label>
                                        <?php endforeach; ?>
                                    </div>
                                    <div style="font-size:12px;color:#94a3b8;margin-top:6px;">勾选后，任务生成的文章会自动归入对应菜单栏目。</div>
                                </div>
                            </div>
                        </div>
                        <!-- 第2步：基本信息 -->
                        <div class="wizard-step-panel" data-step="2">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">任务基本信息</h3>
                            <p style="margin:0 0 20px;color:#64748b;">为定时任务命名并设置初始状态。</p>
                            <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                                <div class="input-group">
                                    <span>* 任务名称</span>
                                    <input class="input" type="text" id="wiz-sc-task-name" placeholder="例如：装修类文章日更任务">
                                </div>
                                <div class="input-group">
                                    <span>* 任务状态</span>
                                    <select class="select" id="wiz-sc-status">
                                        <?php foreach ($articleTaskEditableStatusOptions as $key => $label): ?>
                                            <option value="<?php echo e($key); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="input-group full-row">
                                    <span>备注</span>
                                    <input class="input" type="text" id="wiz-sc-remark" placeholder="记录任务用途、分组、项目说明等">
                                </div>
                            </div>
                        </div>
                        <!-- 第3步：AI 与内容 -->
                        <div class="wizard-step-panel" data-step="3">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">AI 模型与关键词</h3>
                            <p style="margin:0 0 20px;color:#64748b;">配置 AI 模型、关键词池和自定义指令。</p>
                            <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                                <div class="input-group">
                                    <span>* AI 模型</span>
                                    <select class="select" id="wiz-sc-model">
                                        <option value="0">请选择 AI 模型</option>
                                        <?php foreach ($models as $item): ?>
                                            <option value="<?php echo (int)$item['id']; ?>"><?php echo e($item['name']); ?> <?php echo e($item['provider']); ?> / <?php echo e($item['model_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="input-group">
                                    <span>文章字数</span>
                                    <input class="input" type="text" id="wiz-sc-article-length" value="1200-1800字" placeholder="如：1200-1800字">
                                </div>
                                <div class="input-group full-row">
                                    <span>* 关键词池</span>
                                    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
                                        <input type="number" id="wiz-kwAiQty" class="input" min="1" max="500" value="50" style="width:80px;height:34px;margin:0;padding:4px 8px;font-size:13px;" placeholder="数量">
                                        <span style="font-size:13px;color:#64748b;">个</span>
                                        <button type="button" class="btn-soft" id="wiz-btnAiKeywords" style="white-space:nowrap;height:34px;font-size:13px;">AI 生成关键词</button>
                                        <span id="wiz-kwAiStatus" style="font-size:13px;color:#6b7280;"></span>
                                    </div>
                                    <textarea class="input" id="wiz-sc-keywords" placeholder="一行一个关键词，也支持逗号分隔。&#10;任务执行成功后，关键词将从待处理池中消费。" style="min-height:160px;"></textarea>
                                    <label style="display:inline-flex;align-items:center;gap:6px;margin-top:6px;cursor:pointer;font-size:13px;color:#64748b;">
                                        <input type="checkbox" id="wiz-sc-reuse-kw" value="1"> 重复使用关键词（执行完最后一个后从头循环）                                    </label>
                                </div>
                                <div class="input-group full-row">
                                    <span>自定义 AI 指令</span>
                                    <textarea class="input" id="wiz-sc-custom-prompt" placeholder="例如：采用问答式结构、避免营销语气、小标题贴近真实搜索表达" style="min-height:100px;"></textarea>
                                    <div class="prompt-presets" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;">
                                        <button type="button" class="prompt-preset-btn is-active" data-prompt-key="0">拟人化风格</button>
                                        <button type="button" class="prompt-preset-btn" data-prompt-key="1">专业化写作</button>
                                        <button type="button" class="prompt-preset-btn" data-prompt-key="2">幽默化写作</button>
                                        <button type="button" class="prompt-preset-btn" data-prompt-key="3">Google SEO</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 第4步：内容参数与图片 -->
                        <div class="wizard-step-panel" data-step="4">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">内容与图片设置</h3>
                            <p style="margin:0 0 20px;color:#64748b;">配置文章路径前缀、标题图、水印与本地图片插入。</p>
                            <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                                <div class="input-group">
                                    <span>路径前缀（备用）</span>
                                    <input class="input" type="text" id="wiz-sc-path-prefix" value="article" placeholder="如：article / news">
                                    <div style="font-size:12px;color:#94a3b8;margin-top:4px;">已选目标菜单时自动使用菜单 slug 作为路径前缀。</div>
                                </div>
                                <div class="input-group">
                                    <span>模板套件</span>
                                    <div class="input" style="background:#f8fafc;color:#64748b;cursor:default;">自动使用域名绑定的模板套件</div>
                                </div>
                                <div class="input-group">
                                    <span>生成标题图</span>
                                    <label style="display:flex;align-items:center;gap:10px;min-height:44px;padding:0 2px;color:#334155;"><input type="checkbox" id="wiz-sc-gen-img" value="1" checked> 自动生成文章标题图（同时作为封面图）</label>
                                    <div id="wiz-sc-watermark-panel" style="margin-top:6px;">
                                        <label style="display:flex;align-items:center;gap:8px;font-size:13px;color:#475569;"><input type="checkbox" id="wiz-sc-watermark" value="1" checked> 添加水印</label>
                                        <div id="wiz-sc-watermark-text-panel" style="margin-top:6px;">
                                            <input class="input" type="text" id="wiz-sc-watermark-text" placeholder="自定义水印内容，留空默认使用域名对应的站点名" style="font-size:13px;">
                                        </div>
                                    </div>
                                </div>
                                <div class="input-group">
                                    <span>插入本地图片</span>
                                    <label style="display:flex;align-items:center;gap:10px;min-height:44px;padding:0 2px;color:#334155;"><input type="checkbox" id="wiz-sc-insert-images" value="1"> 从指定文件夹随机选取图片插入文章正文</label>
                                </div>
                                <div class="input-group full-row" id="wiz-sc-image-config" style="display:none;">
                                    <div class="form-grid" style="gap:14px;">
                                        <div class="input-group full-row">
                                            <span>图片文件夹路径</span>
                                            <input class="input" type="text" id="wiz-sc-image-folder" placeholder="相对路径：uploads/images 或绝对路径">
                                            <div style="font-size:12px;color:#94a3b8;margin-top:4px;">支持 jpg/jpeg/png/gif/webp/svg/bmp。</div>
                                        </div>
                                        <div class="input-group">
                                            <span>插入数量</span>
                                            <input class="input" type="number" id="wiz-sc-image-count" min="1" max="10" value="1">
                                        </div>
                                        <div class="input-group full-row">
                                            <label style="display:flex;align-items:center;gap:10px;min-height:36px;padding:0 2px;color:#334155;"><input type="checkbox" id="wiz-sc-use-folder-cover" value="1"> 将文件夹图片设为封面图（优先级高于标题图）</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 第5步：发布与间隔 -->
                        <div class="wizard-step-panel" data-step="5">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">发布与执行间隔</h3>
                            <p style="margin:0 0 20px;color:#64748b;">设置发布方式、静态输出以及任务执行间隔。</p>
                            <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                                <div class="input-group">
                                    <span>生成后发布</span>
                                    <label style="display:flex;align-items:center;gap:10px;min-height:44px;padding:0 2px;color:#334155;"><input type="checkbox" id="wiz-sc-publish-now" value="1"> 自动发布（生成后直接设为已发布状态）</label>
                                    <div id="wiz-sc-static-panel" style="margin-top:6px;display:none;">
                                        <label style="display:flex;align-items:center;gap:8px;font-size:13px;color:#475569;"><input type="checkbox" id="wiz-sc-static-output" value="1"> 同时生成静态HTML文件</label>
                                        <div style="font-size:12px;color:#94a3b8;margin-top:4px;">使用伪静态（rewrite）方式访问的站点无需勾选此项。</div>
                                    </div>
                                </div>
                                <div class="input-group">
                                    <span>执行间隔（秒）</span>
                                    <input class="input" type="number" min="0" max="86400" id="wiz-sc-interval" value="0">
                                    <div style="font-size:12px;color:#94a3b8;margin-top:4px;">0 表示不间隔，连续执行。</div>
                                </div>
                            </div>
                        </div>
                        <!-- 第6步：确认创建 -->
                        <div class="wizard-step-panel" data-step="6">
                            <h3 style="margin:0 0 6px;font-size:20px;color:#0f172a;">确认配置</h3>
                            <p style="margin:0 0 20px;color:#64748b;">请检查以下配置，确认无误后点击创建任务。</p>
                            <table class="wizard-review-table">
                                <tr><td>任务名称</td><td id="wiz-sc-review-name">-</td></tr>
                                <tr><td>任务状态</td><td id="wiz-sc-review-status">-</td></tr>
                                <tr><td>执行域名</td><td id="wiz-sc-review-domains">-</td></tr>
                                <tr><td>目标菜单</td><td id="wiz-sc-review-menus">-</td></tr>
                                <tr><td>AI 模型</td><td id="wiz-sc-review-model">-</td></tr>
                                <tr><td>文章字数</td><td id="wiz-sc-review-length">-</td></tr>
                                <tr><td>关键词数量</td><td id="wiz-sc-review-kw-count">-</td></tr>
                                <tr><td>路径前缀</td><td id="wiz-sc-review-path">-</td></tr>
                                <tr><td>标题图</td><td id="wiz-sc-review-img">-</td></tr>
                                <tr><td>执行间隔</td><td id="wiz-sc-review-interval">-</td></tr>
                                <tr><td>发布方式</td><td id="wiz-sc-review-publish">-</td></tr>
                                <tr><td>本地图片</td><td id="wiz-sc-review-insert-img">-</td></tr>
                                <tr><td>备注</td><td id="wiz-sc-review-remark">-</td></tr>
                            </table>
                        </div>
                        <div class="wizard-nav" id="wiz-sc-nav">
                            <button type="button" class="wizard-btn-prev" id="wiz-sc-prev" onclick="wizScPrev()" style="display:none;">← 上一步</button>
                            <span id="wiz-sc-step-indicator" style="font-size:13px;color:#94a3b8;">步骤 1 / 6</span>
                            <button type="button" class="wizard-btn-next" id="wiz-sc-next" onclick="wizScNext()">下一步 →</button>
                        </div>
                        </form>
                    </div>
                </div>

                <aside class="site-build-progress">
                    <div class="progress-shell">
                        <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:8px;">
                            <strong style="font-size:18px; color:#0f172a;">生成进度</strong>
                            <span id="build-progress-badge" style="display:inline-flex; align-items:center; padding:6px 10px; border-radius:999px; background:rgba(99,102,241,0.08); color:#4f46e5; font-size:12px;">待开始</span>
                        </div>
                        <div class="progress-bar-track"><div id="build-progress-value" class="progress-bar-value" style="width:0%;"></div></div>
                        <div class="progress-meta">
                            <span id="build-progress-text">提交任务后将展示阶段进度</span>
                            <strong id="build-progress-percent">0%</strong>
                        </div>
                        <div id="build-progress-steps" class="progress-steps"></div>
                        <div class="progress-notice">建议先完善“站点描述”，它会直接影响首屏标题、服务卡片、亮点模块和 CTA 文案的精准度。</div>
                    </div>
                </aside>

                <aside id="scheduler-right-panel">
                    <div class="progress-shell">
                        <strong style="display:block; font-size:18px; color:#0f172a; margin-bottom:16px;">AI 与内容配置</strong>
                        <div class="input-group">
                            <span>* AI 模型</span>
                            <select class="select" id="rp_model_id">
                                <option value="0">请选择 AI 模型</option>
                                <?php foreach ($models as $item): ?>
                                    <option value="<?php echo (int)$item['id']; ?>"<?php echo (isset($tf['model_id']) && (int)$tf['model_id'] === (int)$item['id']) ? ' selected' : ''; ?>><?php echo e($item['name']); ?> <?php echo e($item['provider']); ?> / <?php echo e($item['model_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group">
                            <span>文章字数</span>
                            <input class="input" type="text" id="rp_article_length" value="<?php echo e(isset($tf['article_length']) ? $tf['article_length'] : '1200-1800字'); ?>" placeholder="如：1200-1800字">
                        </div>
                        <div class="input-group">
                            <span>执行间隔（秒）</span>
                            <input class="input" type="number" min="0" max="86400" id="rp_interval_seconds" value="<?php echo (int)(isset($tf['interval_seconds']) ? $tf['interval_seconds'] : 0); ?>">
                        </div>
                        <div class="input-group">
                            <span>* 关键词池</span>
                            <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
                                <input type="number" id="kwAiQty" class="input" min="1" max="500" value="50" style="width:80px;height:34px;margin:0;padding:4px 8px;font-size:13px;" placeholder="数量">
                                <span style="font-size:13px;color:#64748b;">个</span>
                                <button type="button" class="btn-soft" id="btnAiKeywords" style="white-space:nowrap;height:34px;font-size:13px;">AI 生成关键词</button>
                                <span id="kwAiStatus" style="font-size:13px;color:#6b7280;"></span>
                            </div>
                            <textarea class="input" id="schedulerKeywordsText" placeholder="一行一个关键词，也支持逗号分隔。&#10;任务执行成功后，关键词将从待处理池中消费。" style="min-height:180px;"><?php echo e(isset($tf['keywords_text']) ? $tf['keywords_text'] : ''); ?></textarea>
                            <label style="display:inline-flex; align-items:center; gap:6px; margin-top:6px; cursor:pointer; font-size:13px; color:#64748b;">
                                <input type="checkbox" id="rp_reuse_keywords" value="1"<?php echo !empty($tf['reuse_keywords']) ? ' checked' : ''; ?>>
                                重复使用关键词（执行完最后一个后从头循环，不消费关键词）
                            </label>
                        </div>
                        <div class="input-group">
                            <span>自定义 AI 指令</span>
                            <textarea class="input" id="scheduler-custom-prompt" placeholder="例如：采用问答式结构、避免营销语气、小标题贴近真实搜索表达" style="min-height:100px;"><?php echo e(isset($tf['custom_prompt']) ? $tf['custom_prompt'] : ''); ?></textarea>
                            <div class="prompt-presets" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;">
                                <button type="button" class="prompt-preset-btn is-active" data-prompt-key="0">拟人化风格</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="1">专业化写作</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="2">幽默化写作</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="3">Google SEO</button>
                            </div>
                        </div>
                        <div class="input-group">
                            <span>备注</span>
                            <input class="input" type="text" id="rp_remark" value="<?php echo e(isset($tf['remark']) ? $tf['remark'] : ''); ?>" placeholder="记录任务用途、分组、项目说明等">
                        </div>
                    </div>
                </aside>
            </div>

            <section id="site-build-result-panel" class="page-card result-hidden" style="margin-top:20px;">
                <div class="card-head" style="display:flex;justify-content:space-between;align-items:center;gap:12px;">
                    <div><h2 style="color:#15803d;">✓ 生成完成</h2><p id="result-summary-text">内容已写入数据库。</p></div>
                    <div style="display:flex;gap:8px;flex-wrap:wrap;"></div>
                </div>
                <div id="result-hidden-data" style="display:none;">
                    <span id="result-content-id"></span>
                    <span id="result-title"></span>
                    <span id="result-path"></span>
                    <span id="result-status"></span>
                    <span id="result-access-text"></span>
                    <textarea id="result-seo-title"></textarea>
                    <textarea id="result-seo-description"></textarea>
                    <textarea id="result-ai-response"></textarea>
                </div>
            </section>

            <section id="site-build-preview-panel" class="page-card result-hidden" style="margin-top:20px;">
                <div class="card-head"><div><h2>模板预览</h2><p>基于本次生成变量渲染的前端页面预览。</p></div></div>
                <div style="border:1px solid rgba(0,0,0,0.08); border-radius:12px; overflow:hidden; background:#fff;">
                    <iframe id="site-build-preview-frame" title="site-preview" style="width:100%; height:720px; border:0; background:#fff;"></iframe>
                </div>
            </section>
        </div>
            </div><!-- /main-build-area -->
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function () {
    var initialMode = <?php echo json_encode($initialMode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var form = document.getElementById('site-build-form');
    var submitButton = document.getElementById('site-build-submit');
    var wizardNextBtn = document.getElementById('wiz-hp-next');
    var progressValue = document.getElementById('build-progress-value');
    var progressText = document.getElementById('build-progress-text');
    var progressPercent = document.getElementById('build-progress-percent');
    var progressBadge = document.getElementById('build-progress-badge');
    var progressStepsContainer = document.getElementById('build-progress-steps');
    var errorBox = document.getElementById('site-build-error');
    var errorText = document.getElementById('site-build-error-text');
    var successBox = document.getElementById('site-build-success');
    var successText = document.getElementById('site-build-success-text');
    var resultPanel = document.getElementById('site-build-result-panel');
    var previewPanel = document.getElementById('site-build-preview-panel');
    var previewFrame = document.getElementById('site-build-preview-frame');
    var previewButton = document.getElementById('result-preview-btn');
    var resultContentId = document.getElementById('result-content-id');
    var resultTitle = document.getElementById('result-title');
    var resultPath = document.getElementById('result-path');
    var resultStatus = document.getElementById('result-status');
    var resultEditLink = document.getElementById('result-edit-link');
    var resultAccessText = document.getElementById('result-access-text');
    var resultSeoTitle = document.getElementById('result-seo-title');
    var resultSeoDescription = document.getElementById('result-seo-description');
    var resultAiResponse = document.getElementById('result-ai-response');
    var taskTypeInput = document.getElementById('site-build-task-type');
    var modeButtons = document.querySelectorAll('[data-build-mode]');
    var homepagePanel = document.getElementById('homepage-build-panel');
    var schedulerPanel = document.getElementById('scheduler-build-panel');
    var tasklistPanel = document.getElementById('tasklist-build-panel');
    var progressAside = document.querySelector('.site-build-progress');
    var stepConfig = {
        homepage: [
            { title: '校验建站参数', desc: '检查域名、首页模板、关键词与模型参数是否齐全。' },
            { title: '读取域名 / 模板 / AI模型', desc: '加载首页模板与模型配置。' },
            { title: '生成结构化站点 JSON', desc: 'AI 仅返回字段数据，不直接输出 HTML 布局。' },
            { title: '写入内容记录与模板变量', desc: '将首页字段回填至内容记录，便于二次编辑。' },
            { title: '渲染模板预览', desc: '基于模板变量生成预览结果。' },
            { title: '静态发布首页', desc: '勾选立即发布时输出静态首页文件。' }
        ],
        article: [
            { title: '校验文章生成参数', desc: '检查域名、文章模板、关键词与模型参数。' },
            { title: '读取域名 / 模板 / AI模型', desc: '加载文章模板与 AI 模型配置。' },
            { title: '生成标题与文章内容', desc: '按关键词逐条生成标题、SEO 和正文。' },
            { title: '生成文章标题图', desc: '按标题生成随机配色标题图。' },
            { title: '写入文章内容记录', desc: '将文章、关键词和封面图写入内容库。' },
            { title: '静态发布文章', desc: '勾选立即发布时输出静态文章文件。' }
        ]
    };
    var currentTaskToken = '';
    var pollTimer = null;
    var lastStepIndex = 1;
    var lastStepChangedAt = Date.now();
    var pendingStepTimer = null;
    var MIN_STEP_MS = 3000;
    var lastPreviewHtml = '';
    var lastPreviewUrl = '';
    function minDelayForStep(stepIndex) {
        // Steps 4-6 are system-fast; keep same 3s minimum for visual flow
        return MIN_STEP_MS;
    }
    if (!form || !submitButton || !progressValue || !progressText || !progressPercent || !progressBadge || !progressStepsContainer) {
        return;
    }

    function setHidden(element, hidden) {
        if (!element) {
            return;
        }
        if (hidden) {
            element.classList.add('result-hidden');
        } else {
            element.classList.remove('result-hidden');
        }
    }

    function resetWizardButton(label) {
        if (!wizardNextBtn) return;
        wizardNextBtn.disabled = false;
        wizardNextBtn.textContent = label || '重新生成';
    }

    function renderProgressSteps(mode) {
        var items = stepConfig[mode] || stepConfig.homepage;
        progressStepsContainer.innerHTML = items.map(function (item, index) {
            return '<div class="progress-step" data-step-index="' + (index + 1) + '">' +
                '<div class="progress-step-dot">' + (index + 1) + '</div>' +
                '<div class="progress-step-body"><strong>' + item.title + '</strong><p>' + item.desc + '</p></div>' +
                '<span class="progress-step-pill state-pending">待开始</span>' +
                '</div>';
        }).join('');
    }

    function getSteps() {
        return progressStepsContainer.querySelectorAll('.progress-step');
    }

    function resetResultPanels() {
        setHidden(resultPanel, true);
        setHidden(previewPanel, true);
        var previewBtn = document.getElementById('result-preview-btn');
        if (previewBtn) previewBtn.style.display = '';
        lastPreviewHtml = '';
        lastPreviewUrl = '';
        renderProgressSteps(currentMode());
    }

    function currentMode() {
        return taskTypeInput && taskTypeInput.value === 'article' ? 'article' : 'homepage';
    }

    function applyMode(mode) {
        if (taskTypeInput) {
            taskTypeInput.value = 'homepage';
        }
        var panels = [
            { el: homepagePanel, key: 'homepage' },
            { el: schedulerPanel, key: 'scheduler' },
            { el: tasklistPanel, key: 'tasklist' }
        ];
        panels.forEach(function (p) {
            if (!p.el) return;
            var active = p.key === mode;
            p.el.classList.toggle('is-active', active);
            p.el.querySelectorAll('input, select, textarea').forEach(function (field) {
                field.disabled = !active;
            });
        });
        modeButtons.forEach(function (button) {
            button.classList.toggle('is-active', button.getAttribute('data-build-mode') === mode);
        });
        if (progressAside) {
            progressAside.style.display = mode === 'homepage' ? '' : 'none';
        }
        var schedulerRight = document.getElementById('scheduler-right-panel');
        if (schedulerRight) {
            schedulerRight.style.display = mode === 'scheduler' ? 'block' : 'none';
        }
        var gridEl = document.querySelector('.site-build-grid');
        if (gridEl) { gridEl.classList.toggle('grid-full', mode === 'tasklist'); }
        renderProgressSteps('homepage');
    }

    function showError(message) {
        if (errorText) {
            errorText.textContent = message || '执行过程中出现错误，请稍后重试。';
        }
        setHidden(errorBox, false);
    }

    function hideError() {
        setHidden(errorBox, true);
    }

    // Expose to global for wizard bridge safety
    window.hideError = hideError;
    window.showError = showError;
    window.showSuccess = showSuccess;
    window.resetResultPanels = resetResultPanels;
    window.setProgressBadge = setProgressBadge;
    window.updateProgress = updateProgress;
    window.applyTaskState = applyTaskState;
    window.fillResultPanels = fillResultPanels;
    window.triggerTaskRun = triggerTaskRun;

    function showSuccess(message) {
        if (successText) {
            successText.textContent = message || '建站任务已完成。';
        }
        setHidden(successBox, false);
    }

    function updateProgress(percent, text, currentIndex, state) {
        progressValue.style.width = percent + '%';
        progressPercent.textContent = percent + '%';
        progressText.textContent = text;
        getSteps().forEach(function (item, idx) {
            item.classList.remove('is-active');
            item.classList.remove('is-done');
            item.classList.remove('is-error');
            var pill = item.querySelector('.progress-step-pill');
            var pillClass = 'state-pending';
            var pillText = '待开始';

            if (state === 'success') {
                if (idx < currentIndex) {
                    item.classList.add('is-done');
                    pillClass = 'state-done';
                    pillText = '已完成';
                }
            } else if (state === 'failed') {
                if (idx < currentIndex - 1) {
                    item.classList.add('is-done');
                    pillClass = 'state-done';
                    pillText = '已完成';
                } else if (idx === currentIndex - 1) {
                    item.classList.add('is-error');
                    pillClass = 'state-error';
                    pillText = '异常';
                }
            } else { // running
                if (idx < currentIndex - 1) {
                    item.classList.add('is-done');
                    pillClass = 'state-done';
                    pillText = '已完成';
                } else if (idx === currentIndex - 1) {
                    item.classList.add('is-active');
                    pillClass = 'state-active';
                    pillText = (currentIndex === 3 ? 'AI 生成中' : '进行中');
                }
            }

            if (pill) {
                pill.className = 'progress-step-pill ' + pillClass;
                pill.textContent = pillText;
            }
        });
    }

    function setProgressBadge(state) {
        if (state === 'success') {
            progressBadge.textContent = '已完成';
            progressBadge.style.background = 'rgba(34,197,94,0.08)';
            progressBadge.style.color = '#15803d';
            return;
        }
        if (state === 'failed') {
            progressBadge.textContent = '执行异常';
            progressBadge.style.background = 'rgba(239,68,68,0.08)';
            progressBadge.style.color = '#dc2626';
            return;
        }
        if (state === 'running') {
            progressBadge.textContent = '进行中';
            progressBadge.style.background = 'rgba(99,102,241,0.08)';
            progressBadge.style.color = '#4f46e5';
            return;
        }
        progressBadge.textContent = '待开始';
        progressBadge.style.background = 'rgba(99,102,241,0.08)';
        progressBadge.style.color = '#4f46e5';
    }

    function fillResultPanels(task) {
        if (!task || !task.result) {
            return;
        }
        var result = task.result;
        var domainSelect = form.querySelector('select[name="domain_id"]');
        var domainHost = '';
        if (domainSelect && domainSelect.options && domainSelect.selectedIndex >= 0) {
            var opt = domainSelect.options[domainSelect.selectedIndex];
            domainHost = (opt.textContent || '').trim().split(' ')[0];
        }
        if (!domainHost && result.domain_url) domainHost = result.domain_url.replace(/^https?:\/\//i, '');
        if (!domainHost && result.domain) domainHost = result.domain.replace(/^https?:\/\//i, '');
        if (task.task_type === 'article') {
            var items = Array.isArray(result.items) ? result.items : [];
            var latest = result.content_data || {};
            var uniqueKeywords = {};
            items.forEach(function (item) {
                if (item && item.keyword) {
                    uniqueKeywords[item.keyword] = true;
                }
            });
            var keywordCount = Object.keys(uniqueKeywords).length;
            if (resultContentId) resultContentId.textContent = latest.content_id || '-';
            if (resultTitle) resultTitle.textContent = latest.title || '-';
            if (resultPath) resultPath.textContent = latest.path || '-';
            if (resultStatus) resultStatus.textContent = latest.status || '-';
            if (resultEditLink) resultEditLink.href = latest.content_id ? ('/admin/content/edit.php?id=' + latest.content_id) : '/admin/content/list.php';
            if (resultAccessText) {
                resultAccessText.innerHTML = '本次共处理 <strong>' + keywordCount + '</strong> 个关键词，生成 <strong>' + items.length + '</strong> 篇文章（按域名分别写入），最近一篇访问路径为 <code>' + (latest.path || '-') + '</code>。';
            }
            if (resultSeoTitle) resultSeoTitle.value = latest.seo_title || '';
            if (resultSeoDescription) resultSeoDescription.value = latest.seo_description || '';
            if (resultAiResponse) resultAiResponse.value = result.ai_result && result.ai_result.response_body ? result.ai_result.response_body : '';
            lastPreviewHtml = result.preview_html || '';
            var latestPath = latest.path || '';
            if (latestPath && latestPath.charAt(0) !== '/') latestPath = '/' + latestPath;
            lastPreviewUrl = domainHost ? ('//' + domainHost + latestPath) : '';
            if (previewFrame) previewFrame.srcdoc = lastPreviewHtml;
            var summaryText = document.getElementById('result-summary-text');
            if (summaryText) summaryText.innerHTML = '本次共处理 <strong>' + keywordCount + '</strong> 个关键词，生成 <strong>' + items.length + '</strong> 篇文章，内容已写入数据库。';
            setHidden(resultPanel, false);
            return;
        }
        var contentData = result.content_data || {};
        var template = result.template || {};
        var contentId = result.content_id || 0;
        var pathValue = template.type === 'homepage' ? '/' : '/' + (contentData.path || contentData.slug || '');
        if (resultContentId) resultContentId.textContent = contentId || '-';
        if (resultTitle) resultTitle.textContent = contentData.title || '-';
        if (resultPath) resultPath.textContent = pathValue;
        if (resultStatus) resultStatus.textContent = contentData.status || '-';
        if (resultEditLink) resultEditLink.href = contentId ? ('/admin/content/edit.php?id=' + contentId) : '/admin/content/list.php';
        if (resultAccessText) {
            resultAccessText.innerHTML = (contentData.status === 'published' ? '当前内容已发布，可通过当前绑定域名直接访问 ' : '将该内容状态改为 published 后，可通过当前绑定域名访问 ') + '<code>' + pathValue + '</code>。';
        }
        if (resultSeoTitle) resultSeoTitle.value = contentData.seo_title || '';
        if (resultSeoDescription) resultSeoDescription.value = contentData.seo_description || '';
        if (resultAiResponse) resultAiResponse.value = result.ai_result && result.ai_result.response_body ? result.ai_result.response_body : '';
        lastPreviewHtml = result.preview_html || '';
        lastPreviewUrl = domainHost ? ('//' + domainHost + pathValue) : '';
        if (previewFrame) previewFrame.srcdoc = lastPreviewHtml;
        var summaryText = document.getElementById('result-summary-text');
        if (summaryText) summaryText.innerHTML = '首页内容已生成，页面标题：<strong>' + (contentData.title || '-') + '</strong>，状态：' + (contentData.status === 'published' ? '已发布' : '草稿') + '。';
        setHidden(resultPanel, false);
    }

    function applyTaskState(task) {
        if (!task) {
            return;
        }
        var state = task.status || 'pending';
        var totalSteps = task.total_steps || getSteps().length || 1;
        if (state === 'pending') {
            state = 'running';
        }
        var targetStepIndex = task.current_step || 1;
        // If backend skips ahead, animate sequentially step-by-step for better UX
        var stepIndex = state === 'running' && targetStepIndex - lastStepIndex > 1
            ? lastStepIndex + 1
            : targetStepIndex;
        var applyStateNow = function () {
            setProgressBadge(state);
            updateProgress(task.progress_percent || 0, '第' + stepIndex + ' / ' + totalSteps + ' 步：' + (task.progress_message || '任务处理中...'), stepIndex, state);
            lastStepIndex = stepIndex;
            lastStepChangedAt = Date.now();

            if (state === 'failed') {
                showError(task.error_message || task.progress_message || '执行失败');
                submitButton.disabled = false;
                submitButton.textContent = '立即生成建站内容';
                resetWizardButton('重新生成');
                if (pollTimer) {
                    window.clearInterval(pollTimer);
                    pollTimer = null;
                }
                return;
            }

            if (state === 'success') {
                hideError();
                showSuccess(task.task_type === 'article'
                    ? (task.publish_now ? '文章批量生成已完成，系统已写入内容并执行发布。' : '文章批量生成已完成，系统已写入内容草稿。')
                    : (task.publish_now ? '一键建站已完成，系统已直接生成并发布内容，同时输出模板预览。' : '一键建站已完成，系统已自动生成内容记录并输出模板预览。'));
                fillResultPanels(task);
                submitButton.disabled = false;
                submitButton.textContent = '立即生成建站内容';
                resetWizardButton('重新生成');
                if (pollTimer) {
                    window.clearInterval(pollTimer);
                    pollTimer = null;
                }
            }
        };

        if (state !== 'running') {
            if (pendingStepTimer) {
                window.clearTimeout(pendingStepTimer);
                pendingStepTimer = null;
            }
            applyStateNow();
            return;
        }

        var elapsed = Date.now() - lastStepChangedAt;
        var minDelay = minDelayForStep(stepIndex);
        if (stepIndex > lastStepIndex && elapsed < minDelay) {
            if (pendingStepTimer) {
                window.clearTimeout(pendingStepTimer);
            }
            pendingStepTimer = window.setTimeout(function () {
                pendingStepTimer = null;
                applyStateNow();
            }, minDelay - elapsed);
            return;
        }

        applyStateNow();
    }

    function pollTaskStatus() {
        if (!currentTaskToken) {
            return;
        }
        fetch('/admin/site-build/task.php?task_token=' + encodeURIComponent(currentTaskToken), {
            credentials: 'same-origin'
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            if (!data || !data.success || !data.task) {
                throw new Error(data && data.message ? data.message : '获取任务状态失败。');
            }
            applyTaskState(data.task);
        }).catch(function (error) {
            setProgressBadge('failed');
            showError(error && error.message ? error.message : '获取任务状态失败。');
            submitButton.disabled = false;
            submitButton.textContent = '立即生成建站内容';
            if (pollTimer) {
                window.clearInterval(pollTimer);
                pollTimer = null;
            }
        });
    }

    function triggerTaskRun(taskToken) {
        fetch('/admin/site-build/run.php?task_token=' + encodeURIComponent(taskToken), {
            credentials: 'same-origin'
        }).catch(function () {
        });
    }

    modeButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            applyMode(button.getAttribute('data-build-mode') || 'homepage');
        });
    });

    applyMode(initialMode);

    // 定时任务表单提交前，将右侧面板字段值同步到表单内的隐藏字段
    var schedulerForm = document.getElementById('scheduler-form');
    if (schedulerForm) {
        schedulerForm.addEventListener('submit', function () {
            var syncMap = {
                'sync_model_id': 'rp_model_id',
                'sync_article_length': 'rp_article_length',
                'sync_interval_seconds': 'rp_interval_seconds',
                'sync_keywords_text': 'schedulerKeywordsText',
                'sync_custom_prompt': 'scheduler-custom-prompt',
                'sync_remark': 'rp_remark'
            };
            for (var hiddenId in syncMap) {
                var hidden = document.getElementById(hiddenId);
                var source = document.getElementById(syncMap[hiddenId]);
                if (hidden && source) {
                    hidden.value = source.value;
                }
            }
            var reuseCheckbox = document.getElementById('rp_reuse_keywords');
            var reuseHidden = document.getElementById('sync_reuse_keywords');
            if (reuseHidden && reuseCheckbox) {
                reuseHidden.value = reuseCheckbox.checked ? '1' : '0';
            }
        });
    }

    // 定时任务面板：域名勾选变化时，动态显示/隐藏对应菜单
    (function () {
        var schedulerForm = schedulerPanel ? schedulerPanel.closest('form') : null;
        if (!schedulerForm) return;
        var domainChecks = schedulerForm.querySelectorAll('input[name="domain_ids[]"]');
        var menuItems = schedulerForm.querySelectorAll('.scheduler-menu-item');
        function syncMenuVisibility() {
            var selectedDomainIds = {};
            domainChecks.forEach(function (cb) {
                if (cb.checked) selectedDomainIds[cb.value] = true;
            });
            menuItems.forEach(function (label) {
                var domainId = label.getAttribute('data-domain-id');
                var show = !!selectedDomainIds[domainId];
                label.style.display = show ? '' : 'none';
                if (!show) {
                    var cb = label.querySelector('input[type="checkbox"]');
                    if (cb) cb.checked = false;
                }
            });
        }
        domainChecks.forEach(function (cb) {
            cb.addEventListener('change', syncMenuVisibility);
        });
        syncMenuVisibility();
    })();

    // 插入本地图片复选框切换
    (function () {
        var chk = document.getElementById('sb_chk_insert_images');
        var panel = document.getElementById('sb_image_config_panel');
        if (chk && panel) {
            chk.addEventListener('change', function () { panel.style.display = chk.checked ? '' : 'none'; });
        }
    })();

    // 生成标题图与水印面板联动
    (function () {
        var chkGenImg = document.getElementById('sb_chk_gen_img');
        var wmPanel = document.getElementById('sb_watermark_panel');
        var chkWm = document.getElementById('sb_chk_watermark');
        var wmTextPanel = document.getElementById('sb_watermark_text_panel');
        if (chkGenImg && wmPanel) {
            chkGenImg.addEventListener('change', function () { wmPanel.style.display = chkGenImg.checked ? '' : 'none'; });
        }
        if (chkWm && wmTextPanel) {
            chkWm.addEventListener('change', function () { wmTextPanel.style.display = chkWm.checked ? '' : 'none'; });
        }
    })();

    // 发布与静态输出面板联动
    (function () {
        var chkPublish = document.getElementById('sb_chk_publish_now');
        var staticPanel = document.getElementById('sb_static_output_panel');
        if (chkPublish && staticPanel) {
            chkPublish.addEventListener('change', function () { staticPanel.style.display = chkPublish.checked ? '' : 'none'; });
        }
    })();

    window._domainLanguageMap = <?php
        $domainLangMap = array();
        foreach ($domains as $item) {
            $domainLangMap[(int)$item['id']] = isset($item['site_language']) ? (string)$item['site_language'] : 'zh-CN';
        }
        echo json_encode($domainLangMap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    ?>;

    form.addEventListener('submit', function (event) {
        event.preventDefault();
        submitButton.disabled = true;
        submitButton.textContent = '正在生成...';
        lastStepIndex = 1;
        lastStepChangedAt = Date.now();
        if (pendingStepTimer) {
            window.clearTimeout(pendingStepTimer);
            pendingStepTimer = null;
        }
        hideError();
        resetResultPanels();
        setProgressBadge('running');
        updateProgress(4, '正在创建建站任务...', 1, 'running');

        var payload = new FormData(form);
        var siteDomainSel = form.querySelector('select[name="domain_id"]');
        var siteDomainId = payload.get('domain_id') || (siteDomainSel ? siteDomainSel.value : '0');
        var siteLanguage = '';
        var siteLangInput = form.querySelector('input[name="site_language"]');
        if (siteLangInput && siteLangInput.value) {
            siteLanguage = siteLangInput.value;
        }
        if (!siteLanguage && siteDomainSel && siteDomainSel.options && siteDomainSel.selectedIndex >= 0) {
            var optLang = siteDomainSel.options[siteDomainSel.selectedIndex].getAttribute('data-language');
            if (optLang) siteLanguage = optLang;
        }
        if (!siteLanguage && siteDomainId && siteDomainId !== '0') {
            if (window._domainLanguageMap && window._domainLanguageMap[siteDomainId]) {
                siteLanguage = window._domainLanguageMap[siteDomainId];
            }
        }
        if (!siteLanguage) {
            siteLanguage = 'zh-CN';
        }
        if (siteLangInput) {
            siteLangInput.value = siteLanguage;
        }
        payload.append('site_language', siteLanguage);
        console.log('[AI Home Build] request payload', {
            task_type: payload.get('task_type'),
            domain_id: siteDomainId,
            site_language: siteLanguage,
            keyword: payload.get('keyword'),
            site_name: payload.get('site_name'),
            site_description: payload.get('site_description')
        });

        if (pollTimer) {
            window.clearInterval(pollTimer);
            pollTimer = null;
        }

        fetch('/admin/site-build/start.php', {
            method: 'POST',
            body: payload,
            credentials: 'same-origin'
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            console.log('[AI Home Build] response', data);
            if (!data || !data.success || !data.task) {
                throw new Error(data && data.message ? data.message : '创建建站任务失败。');
            }
            currentTaskToken = data.task.task_token || '';
            updateProgress(8, data.task.progress_message || '建站任务已创建，等待执行...', 1, 'running');
            applyTaskState(data.task);
            triggerTaskRun(currentTaskToken);
            pollTimer = window.setInterval(pollTaskStatus, 1200);
            window.setTimeout(pollTaskStatus, 300);
        }).catch(function (error) {
            console.error('[AI Home Build] request failed', error);
            showError(error && error.message ? error.message : '创建建站任务失败。');
            setProgressBadge('failed');
            updateProgress(0, '建站任务创建失败', 1, 'failed');
            submitButton.disabled = false;
            submitButton.textContent = '立即生成建站内容';
            resetWizardButton('重新生成');
        });
    });

    if (previewButton) {
        previewButton.addEventListener('click', function () {
            if (lastPreviewUrl) {
                window.open(lastPreviewUrl, '_blank');
                return;
            }
            var html = lastPreviewHtml || (previewFrame ? previewFrame.srcdoc : '');
            var win = window.open('about:blank', '_blank');
            if (win && win.document) {
                win.document.open();
                win.document.write(html || '<p style="font-family:Arial,sans-serif;padding:20px;">暂无预览内容，请稍后重试。</p>');
                win.document.close();
            }
        });
    }
})();

(function() {
    window._prompts = <?php
        $promptFile = __DIR__ . '/../../tools/AIcommand.txt';
        $promptTexts = array();
        if (file_exists($promptFile)) {
            $raw = file_get_contents($promptFile);
            $sections = preg_split('/^##[^\n]*/m', $raw);
            foreach ($sections as $s) {
                $s = trim($s);
                if ($s !== '') { $promptTexts[] = $s; }
            }
        }
        echo json_encode($promptTexts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    ?>;
    var textarea = document.getElementById('scheduler-custom-prompt');
    var buttons = document.querySelectorAll('.prompt-preset-btn');
    if (!textarea || !buttons.length) return;
    buttons.forEach(function(btn) {
        btn.addEventListener('click', function() {
            var key = parseInt(btn.getAttribute('data-prompt-key'), 10);
            textarea.value = (window._prompts || [])[key] || '';
            buttons.forEach(function(b) { b.classList.remove('is-active'); });
            btn.classList.add('is-active');
        });
    });
    textarea.value = (window._prompts || [])[0] || '';
})();

// AI 生成关键词（流式）
(function(){
    var btn = document.getElementById('btnAiKeywords');
    var status = document.getElementById('kwAiStatus');
    var qtyInput = document.getElementById('kwAiQty');
    var kwTA = document.getElementById('schedulerKeywordsText');
    if (!btn || !kwTA) return;

    var csrfInput = document.querySelector('#scheduler-form input[name="_csrf_token"]');
    var csrfVal = csrfInput ? csrfInput.value : '';

    btn.addEventListener('click', function(){
        var checkedMenus = document.querySelectorAll('#scheduler-menu-grid input[name="target_menu_ids[]"]:checked');
        var menuNames = [];
        checkedMenus.forEach(function(cb){
            var label = cb.closest('label');
            if (label) {
                var span = label.querySelector('span');
                if (span) {
                    var text = span.childNodes[0];
                    if (text) menuNames.push(text.textContent.trim());
                }
            }
        });
        if (menuNames.length === 0) {
            alert('请先勾选目标菜单作为核心关键词');
            return;
        }

        var modelSel = document.getElementById('rp_model_id');
        var modelId = modelSel ? modelSel.value : '0';
        if (!modelId || modelId === '0') { alert('请先选择 AI 模型'); return; }

        var checkedDomains = document.querySelectorAll('#scheduler-form input[name="domain_ids[]"]:checked');
        var domainId = checkedDomains.length > 0 ? checkedDomains[0].value : '0';
        var siteLang = 'zh-CN';
        if (checkedDomains.length > 0) {
            var lang = checkedDomains[0].getAttribute('data-language');
            if (lang) siteLang = lang;
        }
        console.log('[AI Keywords] request payload', {
            menu_names: menuNames,
            quantity: qtyInput ? qtyInput.value : 50,
            model_id: modelId,
            domain_id: domainId,
            site_language: siteLang
        });

        var qty = qtyInput ? parseInt(qtyInput.value, 10) : 50;
        if (isNaN(qty) || qty < 1) qty = 50;

        btn.disabled = true;
        btn.textContent = 'AI 生成中...';
        status.textContent = '';
        kwTA.value = '';

        var fd = new FormData();
        fd.append('_csrf_token', csrfVal);
        fd.append('menu_names', menuNames.join(','));
        fd.append('quantity', qty);
        fd.append('model_id', modelId);
        fd.append('domain_id', domainId);
        fd.append('site_language', siteLang);

        fetch('/admin/api/ai-generate-keywords.php', { method:'POST', body: fd })
            .then(function(response){
                var reader = response.body.getReader();
                var decoder = new TextDecoder();
                var buffer = '';

                function read(){
                    return reader.read().then(function(result){
                        if (result.done) {
                            var raw = kwTA.value;
                            raw = raw.replace(/[、，,。｜\|]/g, '\n');
                            raw = raw.replace(/(?<=[\u4e00-\u9fff\u3400-\u4dbf])\s+(?=[\u4e00-\u9fff\u3400-\u4dbf])/g, '\n');
                            raw = raw.replace(/^[#＃]\s*\d+[\.、\)\s]*/gm, '');
                            raw = raw.replace(/^\d+[\.\)、）]\s*/gm, '');
                            raw = raw.replace(/^[-–—·•●○◆▪]\s*/gm, '');
                            raw = raw.replace(/\n{2,}/g, '\n');
                            var lines = raw.trim().split('\n');
                            var seen = {};
                            var unique = [];
                            for (var li = 0; li < lines.length; li++) {
                                var kw = lines[li].trim();
                                if (kw === '') continue;
                                var key = kw.toLowerCase();
                                if (seen[key]) continue;
                                seen[key] = true;
                                unique.push(kw);
                            }
                            if (qty > 0 && unique.length > qty) unique = unique.slice(0, qty);
                            kwTA.value = unique.join('\n');
                            btn.disabled = false;
                            btn.textContent = 'AI 生成关键词';
                            var msg = '✓ 生成完成（' + unique.length + ' 条）';
                            if (lines.length !== unique.length) msg += '，已去重' + (lines.length - unique.length) + '✓';
                            status.textContent = msg;
                            status.style.color = '#15803d';
                            return;
                        }
                        buffer += decoder.decode(result.value, {stream:true});
                        var lines = buffer.split('\n');
                        buffer = lines.pop();
                        lines.forEach(function(line){
                            line = line.trim();
                            if (line === 'data: [DONE]') return;
                            if (line.indexOf('data: ') === 0) {
                                try {
                                    var d = JSON.parse(line.substring(6));
                                    if (d.error) {
                                        status.textContent = d.error;
                                        status.style.color = '#dc2626';
                                    } else if (d.text) {
                                        kwTA.value += d.text;
                                        kwTA.scrollTop = kwTA.scrollHeight;
                                    }
                                } catch(e){}
                            }
                        });
                        return read();
                    });
                }
                return read();
            })
            .catch(function(){
                status.textContent = '请求失败，请检查网络';
                status.style.color = '#dc2626';
                btn.disabled = false;
                btn.textContent = 'AI 生成关键词';
            });
    });
})();

// AI 生成站点描述
(function(){
    var btn = document.getElementById('btnAiDesc');
    var status = document.getElementById('aiDescStatus');
    var descTA = document.getElementById('siteDescription');
    if (!btn || !descTA) return;

    var csrfInput = document.querySelector('#site-build-form input[name="_csrf_token"]');
    var csrfVal = csrfInput ? csrfInput.value : '';

    btn.addEventListener('click', function(){
        var keywordInput = document.querySelector('input[name="keyword"]');
        var keyword = keywordInput ? keywordInput.value.trim() : '';
        var modelSel = document.querySelector('select[name="model_id"]');
        var modelId = modelSel ? modelSel.value : '0';
        var domainSel = document.querySelector('select[name="domain_id"]');
        var domainId = domainSel ? domainSel.value : '0';
        var siteLang = 'zh-CN';
        if (domainSel && domainSel.options && domainSel.selectedIndex >= 0) {
            var optLang = domainSel.options[domainSel.selectedIndex].getAttribute('data-language');
            if (optLang) siteLang = optLang;
        }

        if (!keyword) { alert('请先填写核心关键词'); return; }
        if (!modelId || modelId === '0') { alert('请先选择 AI 模型'); return; }

        console.log('[AI Home Description] request payload', {
            keyword: keyword,
            model_id: modelId,
            domain_id: domainId,
            site_language: siteLang
        });

        btn.disabled = true;
        btn.textContent = 'AI 生成中...';
        status.textContent = '';

        var fd = new FormData();
        fd.append('_csrf_token', csrfVal);
        fd.append('keyword', keyword);
        fd.append('model_id', modelId);
        fd.append('domain_id', domainId);
        fd.append('site_language', siteLang);

        fetch('/admin/api/ai-generate-site-desc.php', { method:'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(data){
                console.log('[AI Home Description] response', data);
                if (data.error) {
                    status.textContent = data.error;
                    status.style.color = '#dc2626';
                } else {
                    descTA.value = data.description || '';
                    status.textContent = '✓ 已生成';
                    status.style.color = '#15803d';
                }
            })
            .catch(function(err){
                console.error('[AI Home Description] request failed', err);
                status.textContent = '请求失败，请检查网络';
                status.style.color = '#dc2626';
            })
            .finally(function(){
                btn.disabled = false;
                btn.textContent = 'AI 生成描述';
            });
    });
})();

(function(){ // 任务列表 - 快速切换模型
    var modelData = <?php echo json_encode(array_map(function($m){ return array('id' => (int)$m['id'], 'name' => $m['name']); }, $models), JSON_UNESCAPED_UNICODE); ?>;
    var csrfToken = '<?php echo csrf_token(); ?>';
    var popup = null;

    function closePopup(){ if(popup && popup.parentNode){ popup.parentNode.removeChild(popup); } popup = null; }

    document.addEventListener('click', function(e){
        var trigger = e.target.closest('.task-model-switch');
        if (!trigger) { closePopup(); return; }
        e.preventDefault();
        e.stopPropagation();
        closePopup();

        var taskId = parseInt(trigger.getAttribute('data-task-id'), 10);
        var currentModelId = parseInt(trigger.getAttribute('data-model-id'), 10);

        popup = document.createElement('div');
        popup.style.cssText = 'position:fixed;z-index:9999;background:#fff;border:1px solid #e2e8f0;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.12);padding:6px 0;min-width:200px;max-height:320px;overflow-y:auto;';

        var title = document.createElement('div');
        title.style.cssText = 'padding:8px 14px 6px;font-size:12px;color:#94a3b8;border-bottom:1px solid #f1f5f9;margin-bottom:2px;';
        title.textContent = '选择模型';
        popup.appendChild(title);

        if (modelData.length === 0) {
            var empty = document.createElement('div');
            empty.style.cssText = 'padding:12px 14px;font-size:13px;color:#94a3b8;';
            empty.textContent = '暂无可用模型';
            popup.appendChild(empty);
        }

        modelData.forEach(function(m){
            var opt = document.createElement('div');
            opt.style.cssText = 'padding:8px 14px;font-size:13px;cursor:pointer;display:flex;align-items:center;gap:8px;';
            if (m.id === currentModelId) {
                opt.style.background = '#f0f4ff';
                opt.style.color = '#4f46e5';
                opt.style.fontWeight = '600';
            }
            opt.onmouseover = function(){ if(m.id !== currentModelId) this.style.background='#f8fafc'; };
            opt.onmouseout = function(){ if(m.id !== currentModelId) this.style.background=''; };
            opt.textContent = m.name;
            if (m.id === currentModelId) {
                var check = document.createElement('span');
                check.textContent = '✓';
                check.style.cssText = 'margin-left:auto;font-size:14px;';
                opt.appendChild(check);
            }
            opt.addEventListener('click', function(){
                if (m.id === currentModelId) { closePopup(); return; }
                opt.style.opacity = '0.5';
                opt.style.pointerEvents = 'none';
                var fd = new FormData();
                fd.append('_csrf_token', csrfToken);
                fd.append('task_id', taskId);
                fd.append('model_id', m.id);
                fetch('/admin/article-task/switch-model.php', { method:'POST', body: fd })
                    .then(function(r){ return r.json(); })
                    .then(function(data){
                        if (data.ok) {
                            trigger.textContent = data.model_name;
                            trigger.setAttribute('data-model-id', m.id);
                            closePopup();
                        } else {
                            alert(data.error || '切换失败');
                            opt.style.opacity = '1';
                            opt.style.pointerEvents = '';
                        }
                    })
                    .catch(function(){
                        alert('网络错误，请重试');
                        opt.style.opacity = '1';
                        opt.style.pointerEvents = '';
                    });
            });
            popup.appendChild(opt);
        });

        document.body.appendChild(popup);
        var rect = trigger.getBoundingClientRect();
        var popH = popup.offsetHeight;
        var top = rect.bottom + 4;
        if (top + popH > window.innerHeight - 10) { top = rect.top - popH - 4; }
        var left = rect.left;
        if (left + popup.offsetWidth > window.innerWidth - 10) { left = window.innerWidth - popup.offsetWidth - 10; }
        popup.style.top = top + 'px';
        popup.style.left = left + 'px';
    });
    // Bridge for wizard mode - exposes IIFE internals
    window._beeai = {
        hideError: hideError, showError: showError, showSuccess: showSuccess,
        resetResultPanels: resetResultPanels, setProgressBadge: setProgressBadge,
        updateProgress: updateProgress, applyTaskState: applyTaskState,
        fillResultPanels: fillResultPanels, triggerTaskRun: triggerTaskRun,
        pollTaskStatus: pollTaskStatus, renderProgressSteps: renderProgressSteps,
        get ct() { return currentTaskToken; }, set ct(v) { currentTaskToken = v; },
        get pt() { return pollTimer; }, set pt(v) { pollTimer = v; },
        get sb() { return submitButton; }
    };
})();
</script>
<script>
// ════════ 模式选择与向导系统 ════════
function _q(id) { return document.getElementById(id); }
function selectMode(mode) {
    _q('mode-select-screen').style.display = 'none';
    _q('main-build-area').classList.remove('mode-select-hidden');
    var grid = document.querySelector('.site-build-grid');
    var classicSwitch = _q('classic-mode-switch');
    var backLink = _q('wizard-back-link');
    var progressAside = document.querySelector('.site-build-progress');
    var schedRight = _q('scheduler-right-panel');
    var hpPanel = _q('homepage-build-panel');
    var scPanel = _q('scheduler-build-panel');
    var tlPanel = _q('tasklist-build-panel');
    var taskTypeInp = _q('site-build-task-type');
    // hide all
    ['wizard-homepage','wizard-scheduler'].forEach(function(id){ var el=_q(id); if(el)el.classList.remove('is-active'); });
    [hpPanel, scPanel, tlPanel].forEach(function(p){ if(p)p.classList.remove('is-active'); });
    if (mode === 'homepage-classic') {
        classicSwitch.style.display = ''; backLink.style.display = 'none';
        if (hpPanel) hpPanel.classList.add('is-active');
        if (grid) grid.classList.remove('grid-full');
        if (progressAside) progressAside.style.display = '';
        if (schedRight) schedRight.style.display = 'none';
        if (taskTypeInp) taskTypeInp.value = 'homepage';
        // classic mode: highlight button and enable fields
        document.querySelectorAll('[data-build-mode]').forEach(function(b){ b.classList.toggle('is-active', b.getAttribute('data-build-mode')==='homepage'); });
        var sf = _q('site-build-form'); if (sf) sf.querySelectorAll('input,select,textarea').forEach(function(f){ f.disabled = false; });
        if (window._beeai && window._beeai.renderProgressSteps) window._beeai.renderProgressSteps('homepage');
    } else if (mode === 'homepage-wizard') {
        classicSwitch.style.display = 'none'; backLink.style.display = 'inline-flex';
        document.getElementById('wizard-homepage').classList.add('is-active');
        if (grid) grid.classList.remove('grid-full');
        if (progressAside) progressAside.style.display = '';
        if (schedRight) schedRight.style.display = 'none';
        wizHpGoTo(1);
    } else if (mode === 'scheduler-classic') {
        classicSwitch.style.display = ''; backLink.style.display = 'none';
        if (scPanel) scPanel.classList.add('is-active');
        if (grid) grid.classList.remove('grid-full');
        if (progressAside) progressAside.style.display = 'none';
        if (schedRight) schedRight.style.display = 'block';
        if (taskTypeInp) taskTypeInp.value = 'scheduler';
        document.querySelectorAll('[data-build-mode]').forEach(function(b){ b.classList.toggle('is-active', b.getAttribute('data-build-mode')==='scheduler'); });
        var sf = _q('scheduler-form'); if (sf) sf.querySelectorAll('input,select,textarea').forEach(function(f){ f.disabled = false; });
        if (window._beeai && window._beeai.renderProgressSteps) window._beeai.renderProgressSteps('homepage');
    } else if (mode === 'scheduler-wizard') {
        classicSwitch.style.display = 'none'; backLink.style.display = 'inline-flex';
        document.getElementById('wizard-scheduler').classList.add('is-active');
        if (grid) grid.classList.add('grid-full');
        if (progressAside) progressAside.style.display = 'none';
        if (schedRight) schedRight.style.display = 'none';
        wizScGoTo(1);
    }
    // enable all fields in active panels
    var activePanel = document.querySelector('.build-mode-panel.is-active, .wizard-container.is-active');
    if (activePanel) {
        activePanel.querySelectorAll('input, select, textarea').forEach(function(f){ f.disabled = false; });
    }
}
function goBackToSelection() {
    document.getElementById('mode-select-screen').style.display = '';
    document.getElementById('main-build-area').classList.add('mode-select-hidden');
    ['wizard-homepage','wizard-scheduler'].forEach(function(id){ var el=document.getElementById(id); if(el)el.classList.remove('is-active'); });
}

// ── 首页向导 ──
function wizHpGoTo(step) {
    var steps = document.querySelectorAll('#wiz-hp-steps .wizard-step-node');
    var lines = document.querySelectorAll('#wiz-hp-steps .wizard-step-line');
    var panels = document.querySelectorAll('#wizard-homepage .wizard-step-panel');
    steps.forEach(function(s){ s.classList.remove('is-active','is-done'); });
    lines.forEach(function(l){ l.classList.remove('is-done'); });
    steps.forEach(function(s, i){
        var sNum = parseInt(s.getAttribute('data-step'));
        if (sNum < step) { s.classList.add('is-done'); }
        if (sNum === step) { s.classList.add('is-active'); }
    });
    lines.forEach(function(l, i){ if (i < step - 1) l.classList.add('is-done'); });
    panels.forEach(function(p){ p.classList.remove('is-active'); });
    var target = document.querySelector('#wizard-homepage .wizard-step-panel[data-step="' + step + '"]');
    if (target) target.classList.add('is-active');
    // update nav bar
    var prevBtn = document.getElementById('wiz-hp-prev');
    var nextBtn = document.getElementById('wiz-hp-next');
    var indicator = document.getElementById('wiz-hp-step-indicator');
    if (prevBtn) prevBtn.style.display = step <= 1 ? 'none' : '';
    if (indicator) indicator.textContent = '步骤 ' + step + ' / 5';
    if (step >= 5) {
        if (nextBtn) { nextBtn.style.display = ''; nextBtn.textContent = '🚀 立即生成首页'; nextBtn.onclick = wizHpSubmit; }
    } else {
        if (nextBtn) { nextBtn.style.display = ''; nextBtn.textContent = '下一步 →'; nextBtn.onclick = wizHpNext; }
    }
    if (step === 5) wizHpUpdateReview();
}
function wizHpValidateStep(step) {
    if (step === 1) {
        var domain = document.getElementById('wiz-hp-domain').value;
        if (domain === '0') { alert('请选择目标域名'); return false; }
    }
    if (step === 2) {
        var model = document.getElementById('wiz-hp-model').value;
        var keyword = document.getElementById('wiz-hp-keyword').value.trim();
        if (model === '0') { alert('请选择 AI 模型'); return false; }
        if (!keyword) { alert('请填写核心关键词'); return false; }
    }
    if (step === 3) {
        var desc = document.getElementById('wiz-hp-site-desc').value.trim();
        if (!desc) { alert('请填写站点描述'); return false; }
    }
    return true;
}
function wizHpNext() {
    var an = document.querySelector('#wiz-hp-steps .wizard-step-node.is-active');
    var cs = an ? parseInt(an.getAttribute('data-step')) : 1;
    if (!wizHpValidateStep(cs)) return;
    if (cs < 5) wizHpGoTo(cs + 1);
}
function wizHpPrev() {
    var an = document.querySelector('#wiz-hp-steps .wizard-step-node.is-active');
    var cs = an ? parseInt(an.getAttribute('data-step')) : 1;
    if (cs > 1) wizHpGoTo(cs - 1);
}
function wizHpUpdateDomain() {
    var sel = document.getElementById('wiz-hp-domain');
    var langInput = document.getElementById('wiz-hp-site-language');
    if (sel && langInput && sel.selectedIndex >= 0) {
        var opt = sel.options[sel.selectedIndex];
        var lang = opt.getAttribute('data-language');
        if (lang) langInput.value = lang;
        if (!lang && window._domainLanguageMap && sel.value !== '0') {
            if (window._domainLanguageMap[sel.value]) langInput.value = window._domainLanguageMap[sel.value];
        }
    }
}
function wizHpUpdateReview() {
    var domainSel = document.getElementById('wiz-hp-domain');
    var modelSel = document.getElementById('wiz-hp-model');
    document.getElementById('wiz-hp-review-domain').textContent = domainSel && domainSel.selectedIndex > 0 ? domainSel.options[domainSel.selectedIndex].text.replace(/ · 首页已生成/, '') : '未选择';
    document.getElementById('wiz-hp-review-model').textContent = modelSel && modelSel.selectedIndex > 0 ? modelSel.options[modelSel.selectedIndex].text : '未选择';
    document.getElementById('wiz-hp-review-keyword').textContent = document.getElementById('wiz-hp-keyword').value || '未填写';
    document.getElementById('wiz-hp-review-name').textContent = document.getElementById('wiz-hp-site-name').value || '（使用域名配置）';
    document.getElementById('wiz-hp-review-desc').textContent = document.getElementById('wiz-hp-site-desc').value ? (document.getElementById('wiz-hp-site-desc').value.substring(0,80) + '...') : '未填写';
    document.getElementById('wiz-hp-review-remark').textContent = document.getElementById('wiz-hp-remark').value || '（无）';
    document.getElementById('wiz-hp-review-publish').textContent = document.getElementById('wiz-hp-publish').checked ? '生成后直接发布' : '仅生成草稿';
}
function wizHpSubmit() {
    var domain = document.getElementById('wiz-hp-domain').value;
    var model = document.getElementById('wiz-hp-model').value;
    var keyword = document.getElementById('wiz-hp-keyword').value.trim();
    if (domain === '0') { alert('请选择目标域名'); wizHpGoTo(1); return; }
    if (model === '0') { alert('请选择 AI 模型'); wizHpGoTo(2); return; }
    if (keyword === '') { alert('请填写核心关键词'); wizHpGoTo(2); return; }
    var desc = document.getElementById('wiz-hp-site-desc').value.trim();
    if (!desc) { alert('请填写站点描述'); wizHpGoTo(3); return; }
    wizHpUpdateDomain();
    // 复用经典模式提交流程：把向导表单值写入主表单后直接触发原 submit
    var mainForm = document.getElementById('site-build-form');
    if (!mainForm) { alert('表单未加载'); return; }
    mainForm.querySelector('input[name="task_type"]').value = 'homepage';
    mainForm.querySelector('select[name="domain_id"]').value = domain;
    mainForm.querySelector('select[name="model_id"]').value = model;
    mainForm.querySelector('input[name="keyword"]').value = keyword;
    mainForm.querySelector('input[name="site_name"]').value = document.getElementById('wiz-hp-site-name').value;
    mainForm.querySelector('textarea[name="site_description"]').value = document.getElementById('wiz-hp-site-desc').value;
    mainForm.querySelector('input[name="site_language"]').value = document.getElementById('wiz-hp-site-language').value || 'zh-CN';
    mainForm.querySelector('input[name="remark"]').value = document.getElementById('wiz-hp-remark').value;
    mainForm.querySelector('input[name="publish_now"]').checked = document.getElementById('wiz-hp-publish').checked;
    var btn = document.getElementById('wiz-hp-next');
    btn.disabled = true; btn.textContent = '正在生成...';
    mainForm.dispatchEvent(new Event('submit'));
}

// ── 定时任务向导 ──
var wizScAllMenuOptions = <?php echo json_encode($allMenuOptions, JSON_UNESCAPED_UNICODE); ?>;
function wizScGoTo(step) {
    var steps = document.querySelectorAll('#wiz-sc-steps .wizard-step-node');
    var lines = document.querySelectorAll('#wiz-sc-steps .wizard-step-line');
    var panels = document.querySelectorAll('#wizard-scheduler .wizard-step-panel');
    steps.forEach(function(s){ s.classList.remove('is-active','is-done'); });
    lines.forEach(function(l){ l.classList.remove('is-done'); });
    steps.forEach(function(s, i){
        var sNum = parseInt(s.getAttribute('data-step'));
        if (sNum < step) s.classList.add('is-done');
        if (sNum === step) s.classList.add('is-active');
    });
    lines.forEach(function(l, i){ if (i < step - 1) l.classList.add('is-done'); });
    panels.forEach(function(p){ p.classList.remove('is-active'); });
    var target = document.querySelector('#wizard-scheduler .wizard-step-panel[data-step="' + step + '"]');
    if (target) target.classList.add('is-active');
    // update nav bar
    var prevBtn = document.getElementById('wiz-sc-prev');
    var nextBtn = document.getElementById('wiz-sc-next');
    var indicator = document.getElementById('wiz-sc-step-indicator');
    if (prevBtn) prevBtn.style.display = step <= 1 ? 'none' : '';
    if (indicator) indicator.textContent = '步骤 ' + step + ' / 6';
    if (step >= 6) {
        if (nextBtn) { nextBtn.style.display = ''; nextBtn.textContent = '🚀 创建任务'; nextBtn.onclick = wizScSubmit; }
    } else {
        if (nextBtn) { nextBtn.style.display = ''; nextBtn.textContent = '下一步 →'; nextBtn.onclick = wizScNext; }
    }
    if (step === 1 || step === 2) wizScUpdateMenuGrid();
    if (step === 6) wizScUpdateReview();
}
function wizScNext() {
    var an = document.querySelector('#wiz-sc-steps .wizard-step-node.is-active');
    var cs = an ? parseInt(an.getAttribute('data-step')) : 1;
    if (!wizScValidateStep(cs)) return;
    if (cs < 6) wizScGoTo(cs + 1);
}
function wizScPrev() {
    var an = document.querySelector('#wiz-sc-steps .wizard-step-node.is-active');
    var cs = an ? parseInt(an.getAttribute('data-step')) : 1;
    if (cs > 1) wizScGoTo(cs - 1);
}
function wizScUpdateMenuGrid() {
    var checkedDomains = document.querySelectorAll('#wiz-sc-domain-grid input[name=\"wiz_domain_ids[]\"]:checked');
    var domainIds = [];
    checkedDomains.forEach(function(cb){ domainIds.push(parseInt(cb.value)); });
    var items = document.querySelectorAll('#wiz-sc-menu-grid .wiz-sc-menu-item');
    items.forEach(function(item){
        var dId = parseInt(item.getAttribute('data-domain-id'));
        item.style.display = domainIds.indexOf(dId) >= 0 ? '' : 'none';
        if (domainIds.indexOf(dId) < 0) {
            var cb = item.querySelector('input[type=\"checkbox\"]');
            if (cb) cb.checked = false;
        }
    });
}
function wizScUpdateReview() {
    var taskName = document.getElementById('wiz-sc-task-name').value.trim() || '未填写';
    var statusSel = document.getElementById('wiz-sc-status');
    var statusLabel = statusSel && statusSel.selectedIndex >= 0 ? statusSel.options[statusSel.selectedIndex].text : '-';
    var checkedDomains = document.querySelectorAll('#wiz-sc-domain-grid input[name=\"wiz_domain_ids[]\"]:checked');
    var domainNames = []; checkedDomains.forEach(function(cb){ var lbl=cb.closest('label'); if(lbl){ var span=lbl.querySelector('span'); if(span) domainNames.push(span.childNodes[0].textContent.trim()); } });
    var modelSel = document.getElementById('wiz-sc-model');
    var modelLabel = modelSel && modelSel.selectedIndex > 0 ? modelSel.options[modelSel.selectedIndex].text : '-';
    var articleLength = document.getElementById('wiz-sc-article-length').value || '1200-1800字';
    var kwText = document.getElementById('wiz-sc-keywords').value.trim();
    var kwLines = kwText ? kwText.split(/[\\n,，]+/).filter(function(s){ return s.trim() !== ''; }) : [];
    var checkedMenus = document.querySelectorAll('#wiz-sc-menu-grid input[name=\"wiz_target_menu_ids[]\"]:checked');
    var menuNames = []; checkedMenus.forEach(function(cb){ var lbl=cb.closest('label'); if(lbl){ var span=lbl.querySelector('span'); if(span) menuNames.push(span.childNodes[0].textContent.trim()); } });
    document.getElementById('wiz-sc-review-name').textContent = taskName;
    document.getElementById('wiz-sc-review-status').textContent = statusLabel;
    document.getElementById('wiz-sc-review-domains').textContent = domainNames.length > 0 ? domainNames.join('...') : '未选择';
    document.getElementById('wiz-sc-review-menus').textContent = menuNames.length > 0 ? menuNames.join('...') : '未选择';
    document.getElementById('wiz-sc-review-model').textContent = modelLabel;
    document.getElementById('wiz-sc-review-length').textContent = articleLength;
    document.getElementById('wiz-sc-review-kw-count').textContent = kwLines.length + ' 个';
    document.getElementById('wiz-sc-review-path').textContent = document.getElementById('wiz-sc-path-prefix').value || 'article';
    document.getElementById('wiz-sc-review-img').textContent = document.getElementById('wiz-sc-gen-img').checked ? (document.getElementById('wiz-sc-watermark').checked ? '生成 + 水印' : '生成（无水印）') : '不生成';
    document.getElementById('wiz-sc-review-interval').textContent = (document.getElementById('wiz-sc-interval').value || '0') + ' 个';
    document.getElementById('wiz-sc-review-publish').textContent = document.getElementById('wiz-sc-publish-now').checked ? (document.getElementById('wiz-sc-static-output').checked ? '发布 + 静态文件' : '发布') : '不发布';
    document.getElementById('wiz-sc-review-insert-img').textContent = document.getElementById('wiz-sc-insert-images').checked ? ('是（' + (document.getElementById('wiz-sc-image-count').value || '1') + ' 张）') : '✓';
    document.getElementById('wiz-sc-review-remark').textContent = document.getElementById('wiz-sc-remark').value || '（无）';
}
function wizScValidateStep(step) {
    if (step === 1) {
        var domains = document.querySelectorAll('#wiz-sc-domain-grid input[name="wiz_domain_ids[]"]:checked');
        if (domains.length === 0) { alert('请选择至少一个执行域名'); return false; }
        var menus = document.querySelectorAll('#wiz-sc-menu-grid input[name="wiz_target_menu_ids[]"]:checked');
        if (menus.length === 0) { alert('请选择至少一个目标菜单'); return false; }
    }
    if (step === 2) {
        var name = document.getElementById('wiz-sc-task-name').value.trim();
        if (name === '') { alert('请填写任务名称'); return false; }
    }
    if (step === 3) {
        var model = document.getElementById('wiz-sc-model').value;
        if (model === '0') { alert('请选择 AI 模型'); return false; }
        var kwText = document.getElementById('wiz-sc-keywords').value.trim();
        if (kwText === '') { alert('请填写关键词池'); return false; }
    }
    if (step === 4) {
        var insertImg = document.getElementById('wiz-sc-insert-images');
        var imgFolder = document.getElementById('wiz-sc-image-folder');
        if (insertImg && insertImg.checked) {
            if (!imgFolder || imgFolder.value.trim() === '') { alert('请填写图片文件夹路径'); return false; }
        }
    }
    return true;
}
function wizScSubmit() {
    var taskName = document.getElementById('wiz-sc-task-name').value.trim();
    if (taskName === '') { alert('请填写任务名称'); wizScGoTo(1); return; }
    var checkedDomains = document.querySelectorAll('#wiz-sc-domain-grid input[name=\"wiz_domain_ids[]\"]:checked');
    if (checkedDomains.length === 0) { alert('请选择至少一个执行域名'); wizScGoTo(2); return; }
    var model = document.getElementById('wiz-sc-model').value;
    if (model === '0') { alert('请选择 AI 模型'); wizScGoTo(3); return; }
    var kwText = document.getElementById('wiz-sc-keywords').value.trim();
    if (kwText === '') { alert('请填写关键词池'); wizScGoTo(3); return; }
    var insertImg = document.getElementById('wiz-sc-insert-images');
    var imgFolder = document.getElementById('wiz-sc-image-folder');
    if (insertImg && insertImg.checked) {
        if (!imgFolder || imgFolder.value.trim() === '') { alert('请填写图片文件夹路径'); wizScGoTo(4); return; }
    }
    // Build form data and submit
    var fd = new FormData();
    fd.append('_csrf_token', document.querySelector('#wiz-sc-form input[name="_csrf_token"]').value);
    fd.append('task_type', 'scheduler');
    fd.append('task_name', taskName);
    fd.append('status', document.getElementById('wiz-sc-status').value);
    fd.append('model_id', model);
    fd.append('article_length', document.getElementById('wiz-sc-article-length').value || '1200-1800字');
    fd.append('interval_seconds', document.getElementById('wiz-sc-interval').value || '0');
    fd.append('keywords_text', kwText);
    fd.append('custom_prompt', document.getElementById('wiz-sc-custom-prompt').value);
    fd.append('remark', document.getElementById('wiz-sc-remark').value || '');
    fd.append('reuse_keywords', document.getElementById('wiz-sc-reuse-kw').checked ? '1' : '0');
    fd.append('path_prefix', document.getElementById('wiz-sc-path-prefix').value || 'article');
    fd.append('generate_image', document.getElementById('wiz-sc-gen-img').checked ? '1' : '0');
    fd.append('cover_watermark', document.getElementById('wiz-sc-watermark').checked ? '1' : '0');
    fd.append('cover_watermark_text', document.getElementById('wiz-sc-watermark-text').value || '');
    fd.append('publish_now', document.getElementById('wiz-sc-publish-now').checked ? '1' : '0');
    fd.append('static_output', document.getElementById('wiz-sc-static-output').checked ? '1' : '0');
    fd.append('insert_images', document.getElementById('wiz-sc-insert-images').checked ? '1' : '0');
    fd.append('image_folder', document.getElementById('wiz-sc-image-folder').value || '');
    fd.append('image_count', document.getElementById('wiz-sc-image-count').value || '1');
    fd.append('use_folder_cover', document.getElementById('wiz-sc-use-folder-cover').checked ? '1' : '0');
    fd.append('template_id', '0');
    checkedDomains.forEach(function(cb){ fd.append('domain_ids[]', cb.value); });
    var checkedMenus = document.querySelectorAll('#wiz-sc-menu-grid input[name=\"wiz_target_menu_ids[]\"]:checked');
    checkedMenus.forEach(function(cb){ fd.append('target_menu_ids[]', cb.value); });
    var btn = document.getElementById('wiz-sc-next');
    btn.disabled = true; btn.textContent = '创建中...';
    fetch('/admin/site-build/index.php', { method:'POST', body: fd, credentials:'same-origin' })
        .then(function(r){ if(r.redirected){ window.location.href = r.url; return; } return r.text(); })
        .then(function(html){
            if (html) { document.open(); document.write(html); document.close(); }
        })
        .catch(function(){ alert('提交失败，请重试'); btn.disabled = false; btn.textContent = '🚀 创建任务'; });
}

// ── Scheduler wizard UI bindings ──
(function(){
    // Domain checkbox → menu grid update
    var domainChecks = document.querySelectorAll('#wiz-sc-domain-grid input[name="wiz_domain_ids[]"]');
    domainChecks.forEach(function(cb){ cb.addEventListener('change', wizScUpdateMenuGrid); });
    var chkPub = document.getElementById('wiz-sc-publish-now');
    var staticPanel = document.getElementById('wiz-sc-static-panel');
    if (chkPub && staticPanel) { chkPub.addEventListener('change', function(){ staticPanel.style.display = chkPub.checked ? '' : 'none'; }); }
    var chkImg = document.getElementById('wiz-sc-insert-images');
    var imgConfig = document.getElementById('wiz-sc-image-config');
    if (chkImg && imgConfig) { chkImg.addEventListener('change', function(){ imgConfig.style.display = chkImg.checked ? '' : 'none'; }); }
    var chkGenImg = document.getElementById('wiz-sc-gen-img');
    var wmPanel = document.getElementById('wiz-sc-watermark-panel');
    if (chkGenImg && wmPanel) { chkGenImg.addEventListener('change', function(){ wmPanel.style.display = chkGenImg.checked ? '' : 'none'; }); }
    var chkWm = document.getElementById('wiz-sc-watermark');
    var wmTextPanel = document.getElementById('wiz-sc-watermark-text-panel');
    if (chkWm && wmTextPanel) { chkWm.addEventListener('change', function(){ wmTextPanel.style.display = chkWm.checked ? '' : 'none'; }); }
    // preset buttons
    var scPrompts = document.querySelectorAll('#wizard-scheduler .prompt-preset-btn');
    var scPromptTA = document.getElementById('wiz-sc-custom-prompt');
    if (scPrompts.length && scPromptTA) {
        scPrompts.forEach(function(btn){ btn.addEventListener('click', function(){
            var key = parseInt(btn.getAttribute('data-prompt-key'), 10);
            scPromptTA.value = (window._prompts || [])[key] || '';
            scPrompts.forEach(function(b){ b.classList.remove('is-active'); });
            btn.classList.add('is-active');
        }); });
        if (window._prompts && window._prompts.length) scPromptTA.value = window._prompts[0];
    }
    // AI generate keywords (wizard)
    var wizKwBtn = document.getElementById('wiz-btnAiKeywords');
    if (wizKwBtn) {
        wizKwBtn.addEventListener('click', function(){
            var checkedMenus = document.querySelectorAll('#wiz-sc-menu-grid input[name=\"wiz_target_menu_ids[]\"]:checked');
            var menuNames = [];
            checkedMenus.forEach(function(cb){
                var label = cb.closest('label'); if (label) { var span = label.querySelector('span'); if (span) { var text = span.childNodes[0]; if (text) menuNames.push(text.textContent.trim()); } }
            });
            if (menuNames.length === 0) { alert('请先在步骤2勾选目标菜单作为核心关键词'); return; }
            var modelSel = document.getElementById('wiz-sc-model');
            var modelId = modelSel ? modelSel.value : '0';
            if (!modelId || modelId === '0') { alert('请先选择 AI 模型'); return; }
            var csrfInput = document.querySelector('#wiz-sc-form input[name=\"_csrf_token\"]');
            var csrfVal = csrfInput ? csrfInput.value : '';
            var qtyInput = document.getElementById('wiz-kwAiQty');
            var qty = qtyInput ? parseInt(qtyInput.value, 10) : 50;
            if (isNaN(qty) || qty < 1) qty = 50;
            var kwTA = document.getElementById('wiz-sc-keywords');
            var status = document.getElementById('wiz-kwAiStatus');
            var checkedDomains = document.querySelectorAll('#wiz-sc-domain-grid input[name=\"wiz_domain_ids[]\"]:checked');
            var domainId = checkedDomains.length > 0 ? checkedDomains[0].value : '0';
            var siteLang = 'zh-CN';
            wizKwBtn.disabled = true; wizKwBtn.textContent = 'AI 生成中...';
            if (status) status.textContent = ''; kwTA.value = '';
            var fd = new FormData();
            fd.append('_csrf_token', csrfVal);
            fd.append('menu_names', menuNames.join(','));
            fd.append('quantity', qty);
            fd.append('model_id', modelId);
            fd.append('domain_id', domainId);
            fd.append('site_language', siteLang);
fetch('/admin/api/ai-generate-keywords.php', { method:'POST', body: fd })
    .then(function(response){
        if (!response.ok) { throw new Error('HTTP ' + response.status); }
        var reader = response.body.getReader();
        var decoder = new TextDecoder();
        var buffer = '';
        function processParts(parts) {
            parts.forEach(function (part) {
                if (part.indexOf('data: ') === 0) {
                    try {
                        var json = JSON.parse(part.substring(6));
                        if (json.text) { kwTA.value += json.text; kwTA.scrollTop = kwTA.scrollHeight; }
                        if (json.error && status) { status.textContent = json.error; status.style.color = '#dc2626'; }
                    } catch (e) {}
                }
            });
        }
        function read(){
            return reader.read().then(function(result){
                if (result.done) {
                    if (buffer.trim() !== '') { processParts(buffer.split('\n\n')); buffer = ''; }
                    var raw = kwTA.value;
                    raw = raw.replace(/[、，,。｜\\|]/g, '\n');
                    raw = raw.replace(/(?<=[\u4e00-\u9fff\u3400-\u4dbf])\s+(?=[\u4e00-\u9fff\u3400-\u4dbf])/g, '\n');
                    raw = raw.replace(/^[#＃]\s*\d+[\.、\)\s]*/gm, '');
                    raw = raw.replace(/^\d+[\.\)、）]\s*/gm, '');
                    raw = raw.replace(/^[-–—·•●○◆▪]\s*/gm, '');
                    raw = raw.replace(/\n{2,}/g, '\n');
                    var lines = raw.trim().split('\n');
                    var seen = {}, unique = [];
                    for (var li = 0; li < lines.length; li++) { var kw = lines[li].trim(); if (kw === '') continue; var key = kw.toLowerCase(); if (seen[key]) continue; seen[key] = true; unique.push(kw); }
                    if (qty > 0 && unique.length > qty) unique = unique.slice(0, qty);
                    kwTA.value = unique.join('\n');
                    wizKwBtn.disabled = false; wizKwBtn.textContent = 'AI 生成关键词';
                    var msg = '✓ 生成完成（' + unique.length + ' 条）';
                    if (lines.length !== unique.length) msg += '，已去重' + (lines.length - unique.length) + '✓';
                    if (status) { status.textContent = msg; status.style.color = '#15803d'; }
                    return;
                }
                buffer += decoder.decode(result.value, {stream:true});
                var parts = buffer.split('\n\n'); buffer = parts.pop();
                processParts(parts);
                return read();
            });
        }
        return read();
    })
    .catch(function(err){ if (status) { status.textContent = '请求失败：' + (err && err.message ? err.message : '未知错误'); status.style.color = '#dc2626'; } wizKwBtn.disabled = false; wizKwBtn.textContent = 'AI 生成关键词'; });
        });
    }
    // AI generate description (wizard homepage)
    var wizDescBtn = document.getElementById('wiz-btnAiDesc');
    if (wizDescBtn) {
        wizDescBtn.addEventListener('click', function(){
            var keyword = document.getElementById('wiz-hp-keyword').value.trim();
            var modelSel = document.getElementById('wiz-hp-model');
            var modelId = modelSel ? modelSel.value : '0';
            var domainSel = document.getElementById('wiz-hp-domain');
            var domainId = domainSel ? domainSel.value : '0';
            var siteLang = document.getElementById('wiz-hp-site-language').value || 'zh-CN';
            var descTA = document.getElementById('wiz-hp-site-desc');
            var status = document.getElementById('wiz-aiDescStatus');
            var csrfInput = document.querySelector('#wiz-hp-form input[name=\"_csrf_token\"]');
            var csrfVal = csrfInput ? csrfInput.value : '';
            if (!keyword) { alert('请先填写核心关键词'); return; }
            if (!modelId || modelId === '0') { alert('请先选择 AI 模型'); return; }
            wizDescBtn.disabled = true; wizDescBtn.textContent = 'AI 生成中...';
            if (status) status.textContent = '';
            var fd = new FormData();
            fd.append('_csrf_token', csrfVal);
            fd.append('keyword', keyword);
            fd.append('model_id', modelId);
            fd.append('domain_id', domainId);
            fd.append('site_language', siteLang);
            fetch('/admin/api/ai-generate-site-desc.php', { method:'POST', body: fd })
                .then(function(r){ return r.json(); })
                .then(function(data){
                    if (data.error) { if (status) { status.textContent = data.error; status.style.color = '#dc2626'; } }
                    else { descTA.value = data.description || ''; if (status) { status.textContent = '✓ 已生成'; status.style.color = '#15803d'; } }
                })
                .catch(function(){ if (status) { status.textContent = '请求失败'; status.style.color = '#dc2626'; } })
                .finally(function(){ wizDescBtn.disabled = false; wizDescBtn.textContent = 'AI 生成描述'; });
        });
    }
})();
// ── 任务列表：批量删除多选逻辑 ──
(function(){
    var checkAll = document.getElementById('task-check-all');
    var form = document.getElementById('taskBatchForm');
    function syncAllState(){
        var items = Array.prototype.slice.call(document.querySelectorAll('.task-check-item'));
        var checkedCount = items.filter(function(i){ return i.checked; }).length;
        if (checkAll) {
            checkAll.checked = items.length>0 && checkedCount===items.length;
            checkAll.indeterminate = checkedCount>0 && checkedCount<items.length;
        }
    }
    if (checkAll) {
        checkAll.addEventListener('change', function(){
            document.querySelectorAll('.task-check-item').forEach(function(cb){ cb.checked = checkAll.checked; });
            syncAllState();
        });
    }
    document.querySelectorAll('.task-check-item').forEach(function(cb){ cb.addEventListener('change', syncAllState); });
    window.beforeTaskBatchSubmit = function(f){
        try {
            var items = Array.prototype.slice.call(document.querySelectorAll('.task-check-item:checked'));
            if (items.length===0) { alert('请先勾选需要删除的任务。'); return false; }
            // 清理历史注入
            Array.prototype.slice.call(f.querySelectorAll('input[type="hidden"][name="ids[]"]')).forEach(function(el){ el.parentNode.removeChild(el); });
            items.forEach(function(cb){ var hid=document.createElement('input'); hid.type='hidden'; hid.name='ids[]'; hid.value=cb.value; f.appendChild(hid); });
            return true;
        } catch(e) { alert('提交失败：'+e.message); return false; }
    };
})();
</script>
</body>
</html>
