{% extends "base.html" %}
{% block title %}任务调度 - AutoMusic{% endblock %}
{% block content %}
<div class="page-header">
    <h1>定时与日常任务</h1>
    <p class="subtitle" style="color: var(--text-secondary); margin-top: 4px;">自动化执行Suno音乐生成及AI作词任务</p>
</div>

<style>
    .modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(15, 23, 42, 0.6);
        backdrop-filter: blur(4px);
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }
    .modal-card {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        width: 550px;
        max-width: 90%;
        box-shadow: var(--shadow-lg);
        padding: 24px;
        animation: modalFadeIn 0.2s ease-out;
    }
    @keyframes modalFadeIn {
        from { transform: scale(0.95); opacity: 0; }
        to { transform: scale(1); opacity: 1; }
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 12px;
        margin-bottom: 16px;
    }
    
    .modal-body {
        font-size: 13px;
        line-height: 1.6;
        color: var(--text-primary);
    }

    .scheduler-container {
        display: grid;
        grid-template-columns: 1.4fr 1fr;
        gap: 24px;
        align-items: stretch;
    }
    
    .panel-card {
        background: var(--bg-card);
        backdrop-filter: blur(16px);
        -webkit-backdrop-filter: blur(16px);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-sm);
        padding: 28px;
        margin-bottom: 0;
    }
    
    .panel-card h3 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 18px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .form-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
    }
    
    .form-row .form-group {
        flex: 1;
        margin-bottom: 0;
    }
    
    .template-checkbox-group {
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
        max-height: 200px;
        overflow-y: auto;
        padding: 12px;
        background: var(--bg-primary);
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
    }
    
    .template-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        cursor: pointer;
    }
    
    .log-terminal {
        background: #0f172a;
        color: #e2e8f0;
        font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
        font-size: 12px;
        padding: 16px;
        border-radius: var(--radius-sm);
        flex: 1;
        min-height: 480px;
        max-height: 620px;
        overflow-y: auto;
        line-height: 1.5;
    }
    
    .log-line {
        margin-bottom: 6px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        padding-bottom: 4px;
        font-size: 11.5px;
    }
    
    .log-time {
        color: #64748b;
        margin-right: 6px;
    }
    
    .log-level-info { color: #34d399; }
    .log-level-warning { color: #fbbf24; }
    .log-level-error { color: #f87171; }
    
    .badge-completed { background-color: #d1fae5; color: #065f46; }
    .badge-active { background-color: #dbeafe; color: #1e40af; }
    .badge-paused { background-color: #f1f5f9; color: #475569; }
    
    .action-btn {
        background: none;
        border: none;
        color: var(--accent-blue);
        cursor: pointer;
        padding: 4px 8px;
        font-weight: 500;
        font-size: 13px;
        transition: var(--transition);
        border-radius: var(--radius-sm);
    }
    .action-btn:hover {
        background: rgba(102, 126, 234, 0.08);
        color: var(--accent-purple);
    }
    .action-btn-danger {
        color: #ef4444;
    }
    .action-btn-danger:hover {
        background: rgba(239, 68, 68, 0.08);
        color: #dc2626;
    }
</style>

<div class="scheduler-container">
    <!-- Left Column: Create Task -->
    <div class="panel-card" style="display: flex; flex-direction: column; justify-content: space-between;">
            <h3>⏰ 新建调度任务</h3>
            <form action="{{ url_for('scheduler.add_task') }}" method="POST" id="add-task-form">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                
                <div class="form-row">
                    <div class="form-group">
                        <label>任务名称</label>
                        <input type="text" name="name" required placeholder="例如: 每日Suno推歌" style="width: 100%;">
                    </div>
                    <div class="form-group">
                        <label>执行账号</label>
                        <select name="account_id" id="account_select" required style="width: 100%;">
                            <option value="">-- 选择账号 --</option>
                        </select>
                    </div>
                </div>

                <div class="form-row" id="suno_persona_row" style="display: none; margin-bottom: 16px;">
                    <div class="form-group">
                        <label>Suno 声音/作曲模型 (Persona)</label>
                        <select name="suno_persona_uuid" id="suno_persona_select" style="width: 100%;">
                            <option value="">-- 选择声音/模型 --</option>
                        </select>
                        <input type="hidden" name="suno_persona_name" id="suno_persona_name_input">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>任务类型</label>
                        <select name="task_type" id="task_type" onchange="toggleTimeFields()" style="width: 100%;">
                            <option value="daily" selected>日常任务（每日不定时）</option>
                            <option value="one_shot">单次任务（指定时间点）</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>执行动作</label>
                        <select name="target_type" id="target_type" onchange="onTargetTypeChange()" style="width: 100%;">
                            <option value="suno_task" selected>Suno 任务（自动 Suno 作曲）</option>
                            <option value="ai_lyrics_generation">原AI作词任务（仅自动作词）</option>
                        </select>
                    </div>
                </div>

                <!-- Time setting fields -->
                <div class="form-group" id="daily_time_fields">
                    <label>不定时区间 <span style="font-weight:normal; color:#999; font-size:12px;">（系统会在每日此区间内随机选取时间自动执行）</span></label>
                    <div style="display:flex; align-items:center; gap:8px;">
                        <input type="time" name="run_time_daily_start" value="09:00" style="width:120px;">
                        <span>至</span>
                        <input type="time" name="run_time_daily_end" value="21:00" style="width:120px;">
                    </div>
                </div>

                <div class="form-group" id="one_shot_time_fields" style="display:none;">
                    <label>执行时间</label>
                    <input type="datetime-local" name="run_time_one_shot" style="width:260px;">
                </div>

                <!-- Templates multiple selection for Suno Tasks -->
                <div class="form-group" id="suno-templates-section">
                    <label>选择 Suno 描述词模板 <span style="font-weight:normal; color:#999; font-size:12px;">（多选，每次执行会从 templates_data/suno_prompts 中随机选择一个）</span></label>
                    <div class="template-category-container" style="border: 1px solid var(--border-color); border-radius: var(--radius-sm); max-height: 250px; overflow-y: auto; padding: 12px; background: var(--bg-primary);">
                        {% set ns_suno = namespace(by_cat={}) %}
                        {% for t in suno_templates %}
                            {% set cat = t.category or "其他" %}
                            {% if cat not in ns_suno.by_cat %}
                                {% set _ = ns_suno.by_cat.update({cat: []}) %}
                            {% endif %}
                            {% set _ = ns_suno.by_cat[cat].append(t) %}
                        {% endfor %}
                        {% for category, items in ns_suno.by_cat.items() %}
                        <div style="margin-bottom: 12px;">
                            <div style="font-weight: 600; font-size: 13px; margin-bottom: 6px; color: var(--text-primary); border-left: 3px solid var(--accent-blue); padding-left: 6px;">{{ category }}</div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-left: 8px;">
                                {% for t in items %}
                                <div class="template-item-wrapper" style="display: flex; align-items: center; justify-content: space-between; padding: 4px 8px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-card);">
                                    <label class="template-item" title="{{ t.description }}" style="flex: 1; display: flex; align-items: center; gap: 6px; margin: 0; cursor: pointer;">
                                        <input type="checkbox" class="suno-tpl-cb" value="{{ t.filename }}" onchange="toggleSunoQty(this); updateSunoJobCount();">
                                        <span>{{ t.name }}</span>
                                    </label>
                                    <div class="suno-qty-container" style="display: none; align-items: center; gap: 4px;">
                                        <span style="font-size: 11px; color: var(--text-secondary);">×</span>
                                        <input type="number" class="suno-tpl-qty" min="1" max="20" value="1" oninput="updateSunoJobCount()" onchange="updateSunoJobCount()" style="width: 46px; padding: 2px 4px; font-size: 12px; height: 22px; border-radius: var(--radius-sm); border: 1px solid var(--border-color); background: var(--bg-primary); color: var(--text-primary); text-align: center;">
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                <div class="form-group" id="suno-job-count-section">
                    <label>每次执行生成歌曲数 <span style="font-weight:normal; color:#999; font-size:12px;">（由已选描述词模板的数量自动累加得出）</span></label>
                    <input type="number" name="suno_job_count" id="suno_job_count" value="0" min="0" max="100" readonly style="width: 80px; background-color: var(--bg-primary); cursor: not-allowed; text-align: center; border: 1px solid var(--border-color); border-radius: var(--radius-sm);">
                </div>

                <!-- Templates multiple selection for AI Lyrics Tasks -->
                <div class="form-group" id="lyrics-templates-section" style="display:none;">
                    <label>选择 AI 作词模板 <span style="font-weight:normal; color:#999; font-size:12px;">（多选，每次执行会从 lyrics_templates 中随机选择一个）</span></label>
                    <div class="template-category-container" style="border: 1px solid var(--border-color); border-radius: var(--radius-sm); max-height: 250px; overflow-y: auto; padding: 12px; background: var(--bg-primary);">
                        {% set ns_lyrics = namespace(by_cat={}) %}
                        {% for t in templates %}
                            {% set cat = t.category or "其他" %}
                            {% if cat not in ns_lyrics.by_cat %}
                                {% set _ = ns_lyrics.by_cat.update({cat: []}) %}
                            {% endif %}
                            {% set _ = ns_lyrics.by_cat[cat].append(t) %}
                        {% endfor %}
                        {% for category, items in ns_lyrics.by_cat.items() %}
                        <div style="margin-bottom: 12px;">
                            <div style="font-weight: 600; font-size: 13px; margin-bottom: 6px; color: var(--text-primary); border-left: 3px solid var(--accent-purple); padding-left: 6px;">{{ category }}</div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-left: 8px;">
                                {% for t in items %}
                                <label class="template-item" title="{{ t.description }}">
                                    <input type="checkbox" class="lyrics-tpl-cb" value="{{ t.filename }}">
                                    <span>{{ t.name }}</span>
                                </label>
                                {% endfor %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                <!-- Lyrics auto compose & auto publish controls -->
                <div id="lyrics-compose-options" style="display:none; margin-top:16px; padding:12px; background:var(--bg-primary); border: 1px solid var(--border-color); border-radius:var(--radius-sm);">
                    <div class="form-group" style="margin-bottom:8px;">
                        <label style="display:inline-flex; align-items:center; cursor:pointer; font-weight:600;">
                            <input type="checkbox" name="auto_compose" id="auto_compose" value="1" onchange="toggleComposeModel()" style="margin-right:6px;">
                            作词完成后自动作曲
                        </label>
                    </div>
                    <div class="form-group" id="compose_model_container" style="display:none; margin-bottom:8px; margin-left:20px;">
                        <label>作曲模型选择</label>
                        <select name="compose_model" style="width:200px;">
                            {% for m in compose_models %}
                            <option value="{{ m.id }}" {% if m.id == 7 %}selected{% endif %}>{{ m.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom:0;">
                        <label style="display:inline-flex; align-items:center; cursor:pointer; font-weight:600;">
                            <input type="checkbox" name="auto_publish" id="auto_publish" value="1" style="margin-right:6px;">
                            作曲完成后自动发行 (需 SmsForwarder)
                        </label>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" style="margin-top: 10px;">创建并激活</button>
            </form>
    </div>

    <!-- Right Column: Live Logs -->
    <div class="panel-card" style="display: flex; flex-direction: column; height: 100%;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 18px;">
            <h3 style="margin: 0;">📋 调度器日志</h3>
            <button onclick="fetchSchedulerLogs()" class="btn" style="padding: 4px 12px; font-size:12px; height:auto; margin:0;">刷新</button>
        </div>
        <div class="log-terminal" id="log-terminal-container">
            {% if logs %}
                {% for log in logs %}
                <div class="log-line">
                    <span class="log-time">{{ log.timestamp[11:19] }}</span>
                    <span class="log-level-{{ log.level }}">[{{ log.level.upper() }}]</span>
                    <span>{{ log.message }}</span>
                </div>
                {% endfor %}
            {% else %}
                <div style="color: #64748b; text-align:center; padding: 20px 0;">暂无日志输出</div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Bottom Section: Full Width Task List -->
<div class="panel-card" style="margin-top: 24px; padding: 28px 0 0 0;">
    <h3 style="padding: 0 28px; margin-bottom: 16px;">⚡ 任务列表</h3>
            {% if tasks %}
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="border-bottom: 1px solid var(--border-color); text-align: left;">
                        <th style="padding: 12px 24px; font-weight: 500;">ID</th>
                        <th style="padding: 12px 12px; font-weight: 500;">任务名称</th>
                        <th style="padding: 12px 12px; font-weight: 500;">执行账号</th>
                        <th style="padding: 12px 12px; font-weight: 500;">类型/时间</th>
                        <th style="padding: 12px 12px; font-weight: 500;">目标动作</th>
                        <th style="padding: 12px 12px; font-weight: 500;">详细信息</th>
                        <th style="padding: 12px 12px; font-weight: 500;">状态</th>
                        <th style="padding: 12px 12px; font-weight: 500;">下一次运行</th>
                        <th style="padding: 12px 24px; font-weight: 500; text-align: right;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for t in tasks %}
                    <tr style="border-bottom: 1px solid var(--border-color); font-size: 13px;" id="task-row-{{ t.id }}">
                        <td style="padding: 14px 24px;">{{ t.id }}</td>
                        <td style="padding: 14px 12px; font-weight: 500;">{{ t.name }}</td>
                        <td style="padding: 14px 12px; color: var(--text-secondary);">{{ t.account_name }}</td>
                        <td style="padding: 14px 12px;">
                            {% if t.task_type == 'daily' %}
                            <span style="color:#2563eb;">每日不定时</span> ({{ t.run_time }})
                            {% else %}
                            <span style="color:#059669;">单次定时</span>
                            {% endif %}
                        </td>
                        <td style="padding: 14px 12px;">
                            {% if t.target_type == 'suno_task' %}
                            Suno 作曲
                            {% else %}
                            AI 作词
                            {% endif %}
                        </td>
                        <td style="padding: 14px 12px;">
                            <button onclick='showTaskDetails({{ t.id }}, {{ t.name|tojson|safe }}, {{ t.account_name|tojson|safe }}, {{ t.target_type|tojson|safe }}, {{ t.task_type|tojson|safe }}, {{ t.run_time|tojson|safe }}, {{ ("运行中" if t.status == "running" else ("激活" if t.status == "active" else ("暂停" if t.status == "paused" else "已完成")))|tojson|safe }}, {{ (t.next_run_at[:16].replace("T", " ") if t.next_run_at else "--")|tojson|safe }})' class="action-btn" style="padding: 4px 8px; font-size: 12px; font-weight: 500; background: rgba(102, 126, 234, 0.08); border-radius: var(--radius-sm);">
                                查看
                            </button>
                        </td>
                        <td style="padding: 14px 12px;">
                            <span class="badge badge-{{ t.status }} status-badge-{{ t.id }}">{{ '运行中' if t.status == 'running' else ('激活' if t.status == 'active' else ('暂停' if t.status == 'paused' else '已完成')) }}</span>
                        </td>
                        <td style="padding: 14px 12px; color: var(--text-secondary);" class="next-run-{{ t.id }}">
                            {{ t.next_run_at[:16].replace('T', ' ') if t.next_run_at else '--' }}
                        </td>
                        <td style="padding: 14px 24px; text-align: right;">
                            <button onclick="toggleTask({{ t.id }})" class="action-btn toggle-btn-{{ t.id }}">
                                {{ '暂停' if t.status == 'active' else '激活' }}
                            </button>
                            <button onclick="runTaskNow({{ t.id }})" class="action-btn">立即运行</button>
                            <button onclick="deleteTask({{ t.id }})" class="action-btn action-btn-danger">删除</button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% else %}
            <div style="padding: 40px 24px; text-align: center; color: var(--text-muted);">
                暂无调度任务
            </div>
            {% endif %}
</div>

<!-- Modal for Task Details -->
<div id="task-details-modal" class="modal-overlay" style="display: none;">
    <div class="modal-card">
        <div class="modal-header">
            <h3 style="margin: 0; font-size: 16px; font-weight: 600; display: flex; align-items: center; gap: 8px;">📋 任务详细配置</h3>
            <button onclick="closeDetailsModal()" style="background: none; border: none; font-size: 20px; cursor: pointer; color: var(--text-secondary);">&times;</button>
        </div>
        <div class="modal-body" id="modal-details-body">
            <!-- Content populated dynamically -->
        </div>
        <div class="modal-footer" style="display: flex; justify-content: flex-end; border-top: 1px solid var(--border-color); padding-top: 12px; margin-top: 16px;">
            <button onclick="closeDetailsModal()" class="btn" style="padding: 6px 16px; font-size: 13px; height: auto;">关闭</button>
        </div>
    </div>
</div>

<script>
// Data serialized from Flask views
const taskTemplatesDetail = {
    {% for t in tasks %}
    "{{ t.id }}": {{ t.templates_detail|tojson|safe }},
    {% endfor %}
};

const lyricsAccounts = [
    {% for acc in accounts %}
    { id: {{ acc.id }}, name: "{{ acc.name }}{% if acc.is_logged_in %} (已登录){% endif %}" },
    {% endfor %}
];

const sunoAccounts = [
    {% for acc in suno_accounts %}
    { id: {{ acc.id }}, name: "{{ acc.name }}{% if acc.is_logged_in %} (已登录){% endif %}" },
    {% endfor %}
];

function onTargetTypeChange() {
    const targetType = document.getElementById("target_type").value;
    const accountSelect = document.getElementById("account_select");
    
    // Cache the previous selected ID if any
    const previousSelectedVal = accountSelect.value;
    
    // Clear and repopulate account options
    accountSelect.innerHTML = '<option value="">-- 选择账号 --</option>';
    const accountsList = (targetType === "suno_task") ? sunoAccounts : lyricsAccounts;
    
    accountsList.forEach(acc => {
        const opt = document.createElement("option");
        opt.value = acc.id;
        opt.innerText = acc.name;
        accountSelect.appendChild(opt);
    });
    
    // Toggle templates sections and input names
    const sunoSection = document.getElementById("suno-templates-section");
    const lyricsSection = document.getElementById("lyrics-templates-section");
    const lyricsComposeSection = document.getElementById("lyrics-compose-options");
    const sunoPersonaRow = document.getElementById("suno_persona_row");
    const sunoJobCountSection = document.getElementById("suno-job-count-section");
    
    const sunoCBs = document.querySelectorAll(".suno-tpl-cb");
    const lyricsCBs = document.querySelectorAll(".lyrics-tpl-cb");
    
    if (targetType === "suno_task") {
        sunoSection.style.display = "block";
        lyricsSection.style.display = "none";
        lyricsComposeSection.style.display = "none";
        sunoPersonaRow.style.display = "block";
        sunoJobCountSection.style.display = "block";
        
        sunoCBs.forEach(cb => cb.name = "templates[]");
        lyricsCBs.forEach(cb => cb.name = "");
        
        fetchSunoPersonas(accountSelect.value);
    } else {
        sunoSection.style.display = "none";
        lyricsSection.style.display = "block";
        lyricsComposeSection.style.display = "block";
        sunoPersonaRow.style.display = "none";
        sunoJobCountSection.style.display = "none";
        
        sunoCBs.forEach(cb => cb.name = "");
        lyricsCBs.forEach(cb => cb.name = "templates[]");
    }
}

function toggleSunoQty(checkbox) {
    const wrapper = checkbox.closest(".template-item-wrapper");
    const qtyContainer = wrapper.querySelector(".suno-qty-container");
    if (checkbox.checked) {
        qtyContainer.style.display = "flex";
    } else {
        qtyContainer.style.display = "none";
        wrapper.querySelector(".suno-tpl-qty").value = "1";
    }
}

function updateSunoJobCount() {
    let total = 0;
    const checkedCBs = document.querySelectorAll(".suno-tpl-cb:checked");
    checkedCBs.forEach(cb => {
        const qtyInput = cb.closest(".template-item-wrapper").querySelector(".suno-tpl-qty");
        total += parseInt(qtyInput.value) || 1;
    });
    const jobCountInput = document.getElementById("suno_job_count");
    if (jobCountInput) {
        jobCountInput.value = total;
    }
}

function showTaskDetails(taskId, name, accountName, targetType, taskType, runTime, status, nextRunAt) {
    const details = taskTemplatesDetail[taskId] || [];
    const container = document.getElementById("modal-details-body");
    
    let html = `
        <div style="display: grid; grid-template-columns: 100px 1fr; gap: 8px 16px; margin-bottom: 16px;">
            <div style="color: var(--text-secondary);">任务 ID:</div>
            <div style="font-weight: 500;">${taskId}</div>
            
            <div style="color: var(--text-secondary);">任务名称:</div>
            <div style="font-weight: 500;">${name}</div>
            
            <div style="color: var(--text-secondary);">执行账号:</div>
            <div>${accountName}</div>
            
            <div style="color: var(--text-secondary);">执行动作:</div>
            <div><span style="background: rgba(102, 126, 234, 0.1); color: var(--accent-blue); padding: 2px 6px; border-radius: var(--radius-sm); font-size: 11px;">${targetType === 'suno_task' ? 'Suno 作曲' : 'AI 作词'}</span></div>
            
            <div style="color: var(--text-secondary);">时间规则:</div>
            <div>${taskType === 'daily' ? '每日不定时' : '单次定时'} (${runTime})</div>
            
            <div style="color: var(--text-secondary);">任务状态:</div>
            <div>${status}</div>
            
            <div style="color: var(--text-secondary);">下次运行:</div>
            <div style="color: var(--text-secondary);">${nextRunAt}</div>
        </div>
        
        <div style="margin-top: 16px; border-top: 1px solid var(--border-color); padding-top: 16px;">
            <div style="font-weight: 600; margin-bottom: 10px; font-size: 14px;">📋 已选描述词模板及数量分类:</div>
    `;
    
    if (details.length === 0) {
        html += `<div style="color: var(--text-muted); padding: 12px 0;">无已选模板</div>`;
    } else {
        html += `
            <table style="width: 100%; border-collapse: collapse; font-size: 12px; text-align: left;">
                <thead>
                    <tr style="border-bottom: 1px solid var(--border-color); color: var(--text-secondary);">
                        <th style="padding: 8px 4px; font-weight: 500;">模板名称</th>
                        <th style="padding: 8px 4px; font-weight: 500;">所属分类</th>
                        <th style="padding: 8px 4px; font-weight: 500; text-align: center;">执行数量</th>
                    </tr>
                </thead>
                <tbody>
        `;
        details.forEach(d => {
            html += `
                <tr style="border-bottom: 1px dashed var(--border-color);">
                    <td style="padding: 8px 4px; font-weight: 500; color: var(--text-primary);">${d.name}</td>
                    <td style="padding: 8px 4px;"><span style="background: rgba(139, 92, 246, 0.1); color: var(--accent-purple); padding: 1px 6px; border-radius: var(--radius-sm); font-size: 11px;">${d.category}</span></td>
                    <td style="padding: 8px 4px; text-align: center; font-weight: 600; color: var(--accent-blue);">${d.count}</td>
                </tr>
            `;
        });
        html += `
                </tbody>
            </table>
        `;
    }
    
    html += `</div>`;
    container.innerHTML = html;
    
    document.getElementById("task-details-modal").style.display = "flex";
}

function closeDetailsModal() {
    document.getElementById("task-details-modal").style.display = "none";
}

function toggleComposeModel() {
    const cb = document.getElementById("auto_compose");
    const container = document.getElementById("compose_model_container");
    container.style.display = cb.checked ? "block" : "none";
}

function toggleTimeFields() {
    const type = document.getElementById("task_type").value;
    const daily = document.getElementById("daily_time_fields");
    const oneShot = document.getElementById("one_shot_time_fields");
    if (type === "one_shot") {
        daily.style.display = "none";
        oneShot.style.display = "block";
    } else {
        daily.style.display = "block";
        oneShot.style.display = "none";
    }
}

function toggleTask(taskId) {
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
    fetch(`/schedule/toggle/${taskId}`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken
        }
    })
    .then(r => r.json())
    .then(data => {
        if (data.ok) {
            const badge = document.querySelector(`.status-badge-${taskId}`);
            const btn = document.querySelector(`.toggle-btn-${taskId}`);
            const nextRunCell = document.querySelector(`.next-run-${taskId}`);
            
            if (data.new_status === "active") {
                badge.className = `badge badge-active status-badge-${taskId}`;
                badge.innerText = "激活";
                btn.innerText = "暂停";
                nextRunCell.innerText = data.next_run_at ? data.next_run_at.substring(0, 16).replace('T', ' ') : "--";
            } else {
                badge.className = `badge badge-paused status-badge-${taskId}`;
                badge.innerText = "暂停";
                btn.innerText = "激活";
                nextRunCell.innerText = "--";
            }
            fetchSchedulerLogs();
        } else {
            alert(data.error || "操作失败");
        }
    });
}

function runTaskNow(taskId) {
    if (!confirm("确定要立即触发此任务运行吗？")) return;
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
    fetch(`/schedule/run/${taskId}`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken
        }
    })
    .then(r => r.json())
    .then(data => {
        if (data.ok) {
            alert("任务已成功触发，正在后台异步执行，请在日志中查看进度！");
            fetchSchedulerLogs();
        } else {
            alert("触发失败");
        }
    });
}

function deleteTask(taskId) {
    if (!confirm("确定要删除此调度任务及其所有相关日志吗？")) return;
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
    fetch(`/schedule/delete/${taskId}`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken
        }
    })
    .then(r => r.json())
    .then(data => {
        if (data.ok) {
            document.getElementById(`task-row-${taskId}`).remove();
            fetchSchedulerLogs();
        } else {
            alert("删除失败");
        }
    });
}

function fetchSchedulerLogs() {
    fetch("/schedule/logs")
    .then(r => r.json())
    .then(data => {
        if (data.ok && data.logs) {
            const container = document.getElementById("log-terminal-container");
            container.innerHTML = "";
            if (data.logs.length === 0) {
                container.innerHTML = '<div style="color: #64748b; text-align:center; padding: 20px 0;">暂无日志输出</div>';
                return;
            }
            data.logs.forEach(l => {
                const line = document.createElement("div");
                line.className = "log-line";
                
                const timeSpan = document.createElement("span");
                timeSpan.className = "log-time";
                timeSpan.innerText = l.timestamp.substring(11, 19);
                
                const levelSpan = document.createElement("span");
                levelSpan.className = `log-level-${l.level}`;
                levelSpan.innerText = `[${l.level.toUpperCase()}]`;
                
                const msgSpan = document.createElement("span");
                msgSpan.innerText = " " + l.message;
                
                line.appendChild(timeSpan);
                line.appendChild(levelSpan);
                line.appendChild(msgSpan);
                container.appendChild(line);
            });
        }
    });
}

async function fetchSunoPersonas(accountId) {
    const select = document.getElementById("suno_persona_select");
    const nameInput = document.getElementById("suno_persona_name_input");
    select.innerHTML = '<option value="">-- 正在加载声音/模型 --</option>';
    nameInput.value = '';
    
    if (!accountId) {
        select.innerHTML = '<option value="">-- 请选择账号 --</option>';
        return;
    }
    
    try {
        const r = await fetch(`/suno/personas?account_id=${accountId}`);
        const data = await r.json();
        select.innerHTML = '';
        
        if (data && data.length > 0) {
            data.forEach(p => {
                const opt = document.createElement("option");
                opt.value = p.uuid;
                opt.innerText = p.name;
                select.appendChild(opt);
            });
            nameInput.value = data[0].name;
        } else {
            select.innerHTML = '<option value="">-- 无可用声音/模型 (请先刷新同步) --</option>';
        }
    } catch(err) {
        console.error(err);
        select.innerHTML = '<option value="">-- 加载失败 --</option>';
    }
}

// Initial setup
document.addEventListener("DOMContentLoaded", () => {
    // Close details modal on clicking overlay
    const detailsModal = document.getElementById("task-details-modal");
    if (detailsModal) {
        detailsModal.addEventListener("click", function(e) {
            if (e.target === this) {
                closeDetailsModal();
            }
        });
    }

    // Add-task form submit handler
    document.getElementById("add-task-form").addEventListener("submit", function(e) {
        const targetType = document.getElementById("target_type").value;
        
        let rawInput = document.getElementById("templates_json_raw");
        if (!rawInput) {
            rawInput = document.createElement("input");
            rawInput.type = "hidden";
            rawInput.name = "templates_json_raw";
            rawInput.id = "templates_json_raw";
            this.appendChild(rawInput);
        }
        
        if (targetType === "suno_task") {
            const selected = [];
            const checkedCBs = document.querySelectorAll(".suno-tpl-cb:checked");
            checkedCBs.forEach(cb => {
                const filename = cb.value;
                const qtyInput = cb.closest(".template-item-wrapper").querySelector(".suno-tpl-qty");
                const count = parseInt(qtyInput.value) || 1;
                selected.push({ filename: filename, count: count });
            });
            
            if (selected.length === 0) {
                e.preventDefault();
                alert("请至少选择一个 Suno 描述词模板！");
                return;
            }
            
            rawInput.value = JSON.stringify(selected);
        } else {
            const selected = [];
            const checkedCBs = document.querySelectorAll(".lyrics-tpl-cb:checked");
            checkedCBs.forEach(cb => {
                selected.push(cb.value);
            });
            
            if (selected.length === 0) {
                e.preventDefault();
                alert("请至少选择一个 AI 作词模板！");
                return;
            }
            
            rawInput.value = JSON.stringify(selected);
        }
    });

    document.getElementById("account_select").addEventListener("change", (e) => {
        const targetType = document.getElementById("target_type").value;
        if (targetType === "suno_task") {
            fetchSunoPersonas(e.target.value);
        }
    });

    document.getElementById("suno_persona_select").addEventListener("change", (e) => {
        const select = e.target;
        const nameInput = document.getElementById("suno_persona_name_input");
        if (select.selectedIndex >= 0) {
            nameInput.value = select.options[select.selectedIndex].text;
        } else {
            nameInput.value = '';
        }
    });

    onTargetTypeChange();
    toggleTimeFields();
    fetchSchedulerLogs();
    updateSunoJobCount();
});

// Auto-refresh logs every 15 seconds
setInterval(fetchSchedulerLogs, 15000);
</script>
{% endblock %}
