// lyrics.js — AI 作词页面逻辑
(function() {
const batchForm = document.getElementById('batch-form');
const BATCH_CREATE_URL = batchForm.dataset.batchCreateUrl;
const INDEX_URL = batchForm.dataset.indexUrl;

// ── Toggle logic ──
const composeToggle = document.getElementById('auto-compose-toggle');
const composeOpts = document.getElementById('compose-options');
const publishToggle = document.getElementById('auto-publish-toggle');
const publishOpts = document.getElementById('publish-options');
const batchAuthType = document.getElementById('batch-auth-type');
const batchRegionGroup = document.getElementById('batch-region-group');

function syncToggles() {
    if (composeOpts) composeOpts.style.display = composeToggle.checked ? '' : 'none';
    if (publishToggle) {
        publishToggle.disabled = !composeToggle.checked;
        if (!composeToggle.checked) publishToggle.checked = false;
    }
    if (publishOpts) publishOpts.style.display = (publishToggle && publishToggle.checked) ? '' : 'none';
    if (batchRegionGroup && batchAuthType) {
        batchRegionGroup.style.display = (publishToggle && publishToggle.checked && batchAuthType.value === 'exclusive_agent') ? '' : 'none';
    }
}

if (composeToggle) composeToggle.addEventListener('change', syncToggles);
if (publishToggle) publishToggle.addEventListener('change', syncToggles);
if (batchAuthType) batchAuthType.addEventListener('change', syncToggles);
syncToggles();

// Dynamic compose model list
fetch('/lyrics/compose-models')
  .then(r => r.json())
  .then(models => {
      const sel = document.getElementById('compose-model-select');
      if (sel && models.length) {
          sel.innerHTML = models.map((m, i) =>
              '<option value="' + m.id + '"' + (i === 0 ? ' selected' : '') + '>' + m.name + '</option>'
          ).join('');
      }
  })
  .catch(() => {});

// ── Remember account (localStorage) ──
const accountSelect = document.getElementById('batch-account');
const ACCOUNT_KEY = 'lyrics_last_account_id';

(function restoreAccount() {
    const saved = localStorage.getItem(ACCOUNT_KEY);
    if (saved && accountSelect) {
        const opt = accountSelect.querySelector('option[value="' + saved + '"]');
        if (opt) accountSelect.value = saved;
    }
    if (accountSelect && accountSelect.options.length === 2) {
        accountSelect.selectedIndex = 1;
    }
})();

if (accountSelect) {
    accountSelect.addEventListener('change', function() {
        if (this.value) localStorage.setItem(ACCOUNT_KEY, this.value);
    });
}

// ── Load hashtags from soda-status ──
const hashtagSelect = document.getElementById('batch-hashtag');
(function loadHashtags() {
    fetch('/comments/soda-status')
        .then(r => r.json())
        .then(data => {
            if (data.ready && data.hashtags) {
                data.hashtags.forEach(tag => {
                    const opt = document.createElement('option');
                    opt.value = tag.text;
                    opt.textContent = '#' + tag.text;
                    hashtagSelect.appendChild(opt);
                });
                // Auto-select "快马加鞭" if available
                const target = Array.from(hashtagSelect.options).find(o => o.value === '快马加鞭');
                if (target) hashtagSelect.value = '快马加鞭';
            }
        })
        .catch(() => {});
})();

// ── Batch queue builder ──
const batchQueue = [];
const addBtn = document.getElementById('add-to-queue-btn');
const submitBtn = document.getElementById('submit-queue-btn');
const queueSection = document.getElementById('batch-queue-section');
const queueTable = document.getElementById('batch-queue-table');
const queueSummary = document.getElementById('queue-summary');
const countInput = document.getElementById('batch-count-input');

document.querySelectorAll('input[name="template_file"]').forEach(cb => {
    cb.addEventListener('change', function() {
        // 仅当该 checkbox 是"刚被勾选"且当前只有它一个被选中时，才用模板自身默认数量自动填入
        if (!this.checked) return;
        const checkedCount = document.querySelectorAll('input[name="template_file"]:checked').length;
        if (checkedCount !== 1) return;
        const bc = this.getAttribute('data-batch-count');
        if (bc && countInput) countInput.value = bc;
    });
});

function renderQueue() {
    const tbody = queueTable.querySelector('tbody');
    tbody.innerHTML = '';
    let totalSongs = 0;
    batchQueue.forEach((item, idx) => {
        totalSongs += item.total_count;
        const tr = document.createElement('tr');
        tr.innerHTML = '<td>' + (idx + 1) + '</td>'
            + '<td>' + item.name + '</td>'
            + '<td>' + item.total_count + '</td>'
            + '<td>' + item.language + '</td>'
            + '<td>' + item.voice + '</td>'
            + '<td>' + (item.style || '-') + '</td>'
            + '<td>' + (item.hashtag ? '#' + item.hashtag : '-') + '</td>'
            + '<td><button type="button" class="btn btn-sm btn-danger" data-remove="' + idx + '">删除</button></td>';
        tbody.appendChild(tr);
    });
    queueSection.style.display = batchQueue.length > 0 ? '' : 'none';
    queueSummary.textContent = '共 ' + batchQueue.length + ' 个批次, ' + totalSongs + ' 首歌词';
    if (batchQueue.length > 0) {
        submitBtn.disabled = false;
        submitBtn.textContent = '提交 ' + batchQueue.length + ' 个批次 (共 ' + totalSongs + ' 首)';
    } else {
        submitBtn.disabled = true;
        submitBtn.textContent = '请先添加批次到队列';
    }

    // Bind remove buttons via event delegation
    queueTable.querySelectorAll('[data-remove]').forEach(btn => {
        btn.addEventListener('click', function() {
            batchQueue.splice(parseInt(this.dataset.remove), 1);
            renderQueue();
        });
    });
}

addBtn.addEventListener('click', function() {
    const selectedList = document.querySelectorAll('input[name="template_file"]:checked');
    if (selectedList.length === 0) {
        alert('请先选择至少一个模板');
        return;
    }
    const count = parseInt(countInput.value) || 2;
    if (count < 1 || count > 50) {
        alert('生成数量须在 1-50 之间');
        return;
    }
    const language = document.getElementById('batch-language').value;
    const voice = document.getElementById('batch-voice').value;
    const style = document.getElementById('batch-style').value;
    const hashtag = hashtagSelect.value || '';
    selectedList.forEach(selected => {
        batchQueue.push({
            template_file: selected.value,
            name: selected.getAttribute('data-name') || selected.value.split(/[/\\]/).pop(),
            total_count: count,
            language: language,
            voice: voice,
            style: style,
            hashtag: hashtag,
        });
        selected.checked = false;
    });
    renderQueue();
});

submitBtn.addEventListener('click', async function() {
    const accountId = accountSelect.value;
    if (!accountId) {
        alert('请选择账号');
        return;
    }
    if (batchQueue.length === 0) {
        alert('请至少添加一个批次到队列');
        return;
    }

    localStorage.setItem(ACCOUNT_KEY, accountId);

    const payload = {
        account_id: parseInt(accountId),
        model: document.getElementById('batch-model').value,
        voice: document.getElementById('batch-voice').value,
        auto_compose: composeToggle.checked ? 1 : 0,
        compose_model: parseInt(document.getElementById('compose-model-select').value),
        auto_publish: (publishToggle.checked && composeToggle.checked) ? 1 : 0,
        auth_type: document.getElementById('batch-auth-type').value,
        auth_region: parseInt((document.getElementById('batch-auth-region') || {}).value || 1),
        items: batchQueue.map(item => ({
            template_file: item.template_file,
            total_count: item.total_count,
            language: item.language,
            style: item.style || '',
            hashtag: item.hashtag || '',
        })),
    };

    submitBtn.disabled = true;
    submitBtn.textContent = '提交中...';

    try {
        const resp = await fetch(BATCH_CREATE_URL, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload),
        });
        const result = await resp.json();
        if (result.ok) {
            window.location.href = INDEX_URL;
        } else {
            alert('提交失败: ' + (result.error || '未知错误'));
            submitBtn.disabled = false;
            renderQueue();
        }
    } catch (e) {
        alert('网络错误: ' + e.message);
        submitBtn.disabled = false;
        renderQueue();
    }
});
})();
