/**
 * 小栈AI V5 — 经典编辑器 Metabox 交互
 *
 * 单工具执行 + 一键处理 + 备份恢复
 */
(function () {
    'use strict';

    var config = window.xzdEditorAI || {};
    if (!config.restUrl || !config.nonce) return;

    function callTool(toolId, params) {
        return fetch(config.restUrl + '/chat/execute', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': config.nonce },
            body: JSON.stringify({ tool_id: toolId, params: Object.assign({ post_id: config.postId }, params || {}) }),
        }).then(function (r) { return r.json(); });
    }

    function showLog(msg) {
        var log = document.getElementById('xzd-ai-log');
        if (log) { log.style.display = 'block'; log.textContent = msg; }
    }

    function updateStatus(toolId, done) {
        var el = document.querySelector('[data-tool-status="' + toolId + '"]');
        if (el) { el.innerHTML = done ? '<span class="xzd-status-done">已处理</span>' : '<span class="xzd-status-none">未处理</span>'; }
    }

    // 单工具按钮
    document.querySelectorAll('[data-tool-btn]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var toolId = this.getAttribute('data-tool-btn');
            var postId = parseInt(this.getAttribute('data-post'), 10);
            this.disabled = true; this.textContent = '处理中...';
            showLog('正在处理 ' + toolId + ' ...');

            var params = {};
            if (toolId === 'generate_cover') params.mode = 'full';

            callTool(toolId, params)
                .then(function (res) {
                    btn.disabled = false;
                    if (res.success) {
                        btn.textContent = '重新处理';
                        updateStatus(toolId, true);
                        showLog('✅ ' + toolId + ' 完成');
                    } else {
                        btn.textContent = '重试';
                        showLog('❌ ' + ((res.data && res.data.message) || res.message || '失败'));
                    }
                })
                ['catch'](function (err) {
                    btn.disabled = false; btn.textContent = '重试';
                    showLog('网络错误: ' + err.message);
                });
        });
    });

    // 仅填充空白
    var fillEmptyBtn = document.getElementById('xzd-ai-fill-empty');
    if (fillEmptyBtn) {
        fillEmptyBtn.addEventListener('click', function () {
            if (!confirm('确定处理所有未处理的项吗？')) return;
            processBatch('fill_empty');
        });
    }

    // 一键全处理
    var processAllBtn = document.getElementById('xzd-ai-process-all');
    if (processAllBtn) {
        processAllBtn.addEventListener('click', function () {
            if (!confirm('确定处理所有项目吗？已有结果将被覆盖。')) return;
            processBatch('overwrite');
        });
    }

    // 全部覆盖重做
    var redoAllBtn = document.getElementById('xzd-ai-redo-all');
    if (redoAllBtn) {
        redoAllBtn.addEventListener('click', function () {
            if (!confirm('确定清除所有标记并重新生成吗？此操作不可恢复！')) return;
            processBatch('overwrite');
        });
    }

    function processBatch(mode) {
        var toolIds = Object.keys(config.tools);
        var idx = 0;

        var btns = [fillEmptyBtn, processAllBtn, redoAllBtn];
        btns.forEach(function (b) { if (b) b.disabled = true; });

        function next() {
            if (idx >= toolIds.length) {
                btns.forEach(function (b) { if (b) b.disabled = false; });
                showLog('✅ 全部处理完成');
                return;
            }
            var toolId = toolIds[idx];
            showLog('[' + (idx + 1) + '/' + toolIds.length + '] ' + (config.tools[toolId] || {}).label + '...');

            var params = { _processing_mode: mode };
            if (toolId === 'generate_cover') params.mode = 'full';

            callTool(toolId, params)
                .then(function (res) { if (res.success) updateStatus(toolId, true); })
                ['finally'](function () { idx++; setTimeout(next, 800); });
        }
        next();
    }

    // 恢复备份按钮
    var restoreBtn = document.getElementById('xzd-ai-restore-backup');
    if (restoreBtn) {
        restoreBtn.addEventListener('click', function () {
            if (!confirm('确定恢复AI修改前的原文吗？当前内容将被替换。')) return;
            this.disabled = true; this.textContent = '恢复中...';
            callTool('restore_backup', { post_id: config.postId })
                .then(function (res) {
                    if (res.success) {
                        showLog('✅ 原文已恢复，请刷新页面');
                        setTimeout(function () { window.location.reload(); }, 1500);
                    } else {
                        showLog('❌ ' + ((res.data && res.data.message) || res.message || '恢复失败'));
                        restoreBtn.disabled = false; restoreBtn.textContent = '恢复AI修改前原文';
                    }
                })
                ['catch'](function () {
                    showLog('❌ 网络错误');
                    restoreBtn.disabled = false; restoreBtn.textContent = '恢复AI修改前原文';
                });
        });
    }

})();
