/**
 * CloudScale Code Block Migrator - Admin JS
 */
(function () {
    'use strict';

    var scanBtn      = document.getElementById('cs-scan-btn');
    var migrateAllBtn = document.getElementById('cs-migrate-all-btn');
    var statusEl     = document.getElementById('cs-scan-status');
    var resultsArea  = document.getElementById('cs-results-area');
    var modal        = document.getElementById('cs-preview-modal');
    var modalTitle   = document.getElementById('cs-modal-title');
    var modalBody    = document.getElementById('cs-modal-body');
    var modalMigrateBtn = document.getElementById('cs-modal-migrate-btn');

    // Bail if the migrate tab elements aren't present
    if (!scanBtn || !modal) return;

    var scannedPosts = [];

    // =========================================================================
    //  Helpers
    // =========================================================================

    function ajax(action, data, callback) {
        var fd = new FormData();
        fd.append('action', action);
        fd.append('nonce', csdtDevtoolsMigrate.nonce);
        if (data) {
            Object.keys(data).forEach(function (k) {
                fd.append(k, data[k]);
            });
        }
        fetch(csdtDevtoolsMigrate.ajaxUrl, { method: 'POST', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (resp) {
                if (resp && resp.success) {
                    callback(null, resp.data);
                } else if (resp && resp.data) {
                    callback(resp.data);
                } else if (resp === -1 || resp === 0) {
                    callback('Session expired, please reload the page and try again.');
                } else {
                    callback('Server error. Please check you are logged in and try again.');
                }
            })
            .catch(function (err) {
                callback(err.message || 'Network error');
            });
    }

    function setStatus(msg, type) {
        statusEl.textContent = msg;
        statusEl.className = 'cs-status' + (type ? ' ' + type : '');
    }

    function escHtml(str) {
        var div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    // =========================================================================
    //  Scan
    // =========================================================================

    function doScan() {
        scanBtn.disabled = true;
        setStatus('Scanning...', '');
        resultsArea.innerHTML = '<p class="cs-loading"><span class="cs-spinner"></span> Scanning all posts for legacy code blocks...</p>';

        ajax('csdt_devtools_migrate_scan', {}, function (err, data) {
            scanBtn.disabled = false;

            if (err) {
                setStatus('Scan failed: ' + err, 'error');
                return;
            }

            scannedPosts = data.posts;

            if (data.total_posts === 0) {
                setStatus('No legacy code blocks found.', 'success');
                resultsArea.innerHTML = '<p class="cs-migrate-hint">No posts with legacy code blocks were found. Everything is already migrated.</p>';
                migrateAllBtn.disabled = true;
                return;
            }

            setStatus('Found ' + data.total_blocks + ' block(s) across ' + data.total_posts + ' post(s).', 'success');
            migrateAllBtn.disabled = false;
            renderResults(data);
        });
    }

    function renderResults(data) {
        var html = '';

        // Summary
        html += '<div class="cs-migrate-summary">';
        html += '<div class="cs-stat"><strong>' + data.total_posts + '</strong>Posts with legacy blocks</div>';
        html += '<div class="cs-stat"><strong>' + data.total_blocks + '</strong>Total code blocks to migrate</div>';
        html += '</div>';

        // Table
        html += '<table class="cs-migrate-table">';
        html += '<thead><tr>';
        html += '<th>Post</th>';
        html += '<th style="width:90px;text-align:center;">Blocks</th>';
        html += '<th style="width:80px;">Status</th>';
        html += '<th style="width:200px;">Actions</th>';
        html += '</tr></thead>';
        html += '<tbody>';

        data.posts.forEach(function (post) {
            html += '<tr id="cs-row-' + post.id + '">';
            html += '<td>';
            html += '<div class="cs-post-title"><a href="' + escHtml(post.view_url) + '" target="_blank">' + escHtml(post.title) + '</a></div>';
            html += '<div class="cs-post-meta">' + escHtml(post.date) + ' &middot; ' + escHtml(post.status) + ' &middot; ID: ' + post.id + '</div>';
            html += '</td>';
            html += '<td style="text-align:center;"><span class="cs-block-count">' + post.block_count + '</span></td>';
            html += '<td class="cs-status-cell">Pending</td>';
            html += '<td class="cs-actions">';
            html += '<button class="button button-small cs-preview-btn" data-post-id="' + post.id + '">Preview</button> ';
            html += '<button class="button button-primary button-small cs-single-migrate-btn" data-post-id="' + post.id + '">Migrate</button>';
            html += '</td>';
            html += '</tr>';
        });

        html += '</tbody></table>';

        resultsArea.innerHTML = html;

        // Bind preview buttons
        resultsArea.querySelectorAll('.cs-preview-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                openPreview(parseInt(this.getAttribute('data-post-id')));
            });
        });

        // Bind single migrate buttons
        resultsArea.querySelectorAll('.cs-single-migrate-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                migrateSingle(parseInt(this.getAttribute('data-post-id')), this);
            });
        });
    }

    // =========================================================================
    //  Preview Modal
    // =========================================================================

    function openPreview(postId) {
        modal.style.display = 'flex';
        modalTitle.textContent = 'Loading preview...';
        modalBody.innerHTML = '<p class="cs-loading"><span class="cs-spinner"></span> Loading block preview...</p>';
        modalMigrateBtn.setAttribute('data-post-id', postId);

        ajax('csdt_devtools_migrate_preview', { post_id: postId }, function (err, data) {
            if (err) {
                modalBody.innerHTML = '<p style="color:#d63638;">Error: ' + escHtml(err) + '</p>';
                return;
            }

            modalTitle.textContent = data.title + ' (' + data.block_count + ' block' + (data.block_count !== 1 ? 's' : '') + ')';

            var html = '';
            data.blocks.forEach(function (block) {
                html += '<div class="cs-preview-block">';
                html += '<div class="cs-preview-block-header">';
                html += '<span class="cs-block-num">' + block.index + '</span>';
                html += '<span class="cs-block-lang">' + escHtml(block.language) + '</span>';
                html += '<span class="cs-block-lang" style="background:#f3e8ff;color:#7c3aed;">' + escHtml(block.type || 'wp:code') + '</span>';
                html += '<span class="cs-block-firstline">' + escHtml(block.first_line) + '</span>';
                html += '</div>';
                html += '<div class="cs-preview-diff">';
                html += '<div class="cs-preview-side cs-before">';
                html += '<div class="cs-preview-side-label">Before (wp:code)</div>';
                html += '<pre>' + block.original + '</pre>';
                html += '</div>';
                html += '<div class="cs-preview-side cs-after">';
                html += '<div class="cs-preview-side-label">After (cloudscale/code-block)</div>';
                html += '<pre>' + block.converted + '</pre>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
            });

            modalBody.innerHTML = html;
        });
    }

    function closeModal() {
        modal.style.display = 'none';
    }

    // Modal close handlers
    modal.querySelector('.cs-modal-backdrop').addEventListener('click', closeModal);
    modal.querySelectorAll('.cs-modal-close, .cs-modal-close-btn').forEach(function (el) {
        el.addEventListener('click', closeModal);
    });

    // Migrate from modal
    modalMigrateBtn.addEventListener('click', function () {
        var postId = parseInt(this.getAttribute('data-post-id'));
        if (!postId) return;

        this.disabled = true;
        this.textContent = 'Migrating...';

        ajax('csdt_devtools_migrate_single', { post_id: postId }, function (err, data) {
            modalMigrateBtn.disabled = false;
            modalMigrateBtn.innerHTML = '<span class="dashicons dashicons-yes-alt"></span> Migrate This Post';

            if (err) {
                alert('Migration failed: ' + err);
                return;
            }

            closeModal();
            markRowMigrated(postId, data.blocks_migrated);
            setStatus(data.message, 'success');
        });
    });

    // =========================================================================
    //  Single Migrate (from table button)
    // =========================================================================

    function migrateSingle(postId, btn) {
        if (!confirm('Migrate all code blocks in this post to CloudScale format?')) return;

        btn.disabled = true;
        btn.textContent = 'Migrating...';

        ajax('csdt_devtools_migrate_single', { post_id: postId }, function (err, data) {
            if (err) {
                btn.disabled = false;
                btn.textContent = 'Migrate';
                alert('Migration failed: ' + err);
                return;
            }

            markRowMigrated(postId, data.blocks_migrated);
            setStatus(data.message, 'success');
        });
    }

    function markRowMigrated(postId, blockCount) {
        var row = document.getElementById('cs-row-' + postId);
        if (!row) return;

        row.classList.add('cs-migrated');

        var statusCell = row.querySelector('.cs-status-cell');
        if (statusCell) {
            statusCell.innerHTML = '<span class="cs-migrated-badge"><span class="dashicons dashicons-yes"></span> Done</span>';
        }

        var actionsCell = row.querySelector('.cs-actions');
        if (actionsCell) {
            actionsCell.innerHTML = '<a href="' + getViewUrl(postId) + '" target="_blank" class="button button-small">View Post</a>';
        }

        // Check if all rows are migrated
        var pending = document.querySelectorAll('.cs-single-migrate-btn');
        if (pending.length === 0) {
            migrateAllBtn.disabled = true;
            setStatus('All posts migrated successfully!', 'success');
        }
    }

    function getViewUrl(postId) {
        for (var i = 0; i < scannedPosts.length; i++) {
            if (scannedPosts[i].id === postId) return scannedPosts[i].view_url;
        }
        return '#';
    }

    // =========================================================================
    //  Migrate All
    // =========================================================================

    function doMigrateAll() {
        var pending = document.querySelectorAll('.cs-single-migrate-btn');
        var count = pending.length;

        if (count === 0) {
            alert('No remaining posts to migrate.');
            return;
        }

        if (!confirm('This will migrate ' + count + ' remaining post(s) to CloudScale Code Blocks. Continue?')) {
            return;
        }

        migrateAllBtn.disabled = true;
        migrateAllBtn.textContent = 'Migrating all...';
        setStatus('Migrating all remaining posts...', '');

        ajax('csdt_devtools_migrate_all', {}, function (err, data) {
            migrateAllBtn.innerHTML = '<span class="dashicons dashicons-update"></span> Migrate All Remaining';

            if (err) {
                migrateAllBtn.disabled = false;
                setStatus('Batch migration failed: ' + err, 'error');
                return;
            }

            setStatus(
                'Migrated ' + data.migrated_blocks + ' block(s) across ' + data.migrated_posts + ' post(s).',
                'success'
            );

            // Mark all rows as done
            data.details.forEach(function (detail) {
                var match = detail.match(/^#(\d+)/);
                if (match) {
                    markRowMigrated(parseInt(match[1]), 0);
                }
            });

            migrateAllBtn.disabled = true;
        });
    }

    // =========================================================================
    //  Event Bindings
    // =========================================================================

    scanBtn.addEventListener('click', doScan);
    migrateAllBtn.addEventListener('click', doMigrateAll);

    // ── Default-theme picker (lives in the same Re-apply panel) ──────────
    var restyleSaveBtn  = document.getElementById('cs-restyle-save-btn');
    var restylePairSel  = document.getElementById('cs-restyle-pair');
    var restyleThemeSel = document.getElementById('cs-restyle-theme');
    if (restyleSaveBtn && restylePairSel && restyleThemeSel) {
        restyleSaveBtn.addEventListener('click', function () {
            var statusEl = document.getElementById('cs-restyle-status');
            restyleSaveBtn.disabled = true;
            if (statusEl) statusEl.textContent = 'Saving…';

            var fd = new FormData();
            fd.append('action',     'csdt_devtools_save_theme_setting');
            fd.append('nonce',      csdtDevtoolsMigrate.settingsNonce);
            fd.append('theme',      restyleThemeSel.value);
            fd.append('theme_pair', restylePairSel.value);

            fetch(csdtDevtoolsMigrate.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (resp) {
                    restyleSaveBtn.disabled = false;
                    if (statusEl) {
                        statusEl.textContent = resp && resp.success ? 'Saved ✓' : 'Save failed';
                        statusEl.style.color = resp && resp.success ? '#16a34a' : '#b91c1c';
                        setTimeout(function () { statusEl.textContent = ''; statusEl.style.color = ''; }, 4000);
                    }
                })
                .catch(function () {
                    restyleSaveBtn.disabled = false;
                    if (statusEl) {
                        statusEl.textContent = 'Network error';
                        statusEl.style.color = '#b91c1c';
                    }
                });
        });
    }

    // ── Re-apply default theme to all blocks ─────────────────────────────
    var restyleBtn     = document.getElementById('cs-restyle-all-btn');
    var restyleStatus  = document.getElementById('cs-restyle-status');
    var restyleResults = document.getElementById('cs-restyle-results');

    if (restyleBtn) {
        restyleBtn.addEventListener('click', function () {
            var msg = 'Reset the per-block theme override on EVERY CloudScale Code Block across ALL posts?\n\n' +
                      'Blocks will inherit the site-wide default theme. Other settings (language, title, GitHub source, etc.) are left untouched. ' +
                      'This cannot be undone without a database backup.\n\nProceed?';
            if (!window.confirm(msg)) return;

            restyleBtn.disabled = true;
            restyleStatus.textContent = 'Working…';
            restyleResults.innerHTML = '';

            ajax('csdt_devtools_reset_theme_all', null, function (res) {
                restyleBtn.disabled = false;
                if (!res || !res.success) {
                    restyleStatus.textContent = 'Error';
                    restyleResults.innerHTML =
                        '<div style="color:#b91c1c;font-size:13px;">' +
                        ((res && res.data) ? res.data : 'Reset failed.') +
                        '</div>';
                    return;
                }
                var d = res.data || {};
                restyleStatus.textContent = 'Done';
                var html = '<div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;padding:10px 14px;font-size:13px;color:#166534;">' +
                    '<strong>Scanned ' + (d.posts_scanned || 0) + ' posts</strong> · ' +
                    'changed ' + (d.posts_changed || 0) + ' · ' +
                    'reset ' + (d.blocks_reset || 0) + ' blocks.</div>';
                if (Array.isArray(d.details) && d.details.length) {
                    html += '<details style="margin-top:8px;font-size:12px;color:#374151;">' +
                            '<summary style="cursor:pointer;color:#6366f1;">Show affected posts</summary>' +
                            '<ul style="margin:8px 0 0 18px;line-height:1.5;">' +
                            d.details.map(function (s) { return '<li>' + s + '</li>'; }).join('') +
                            '</ul></details>';
                }
                restyleResults.innerHTML = html;
            });
        });
    }

    // Escape key closes modal
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.style.display !== 'none') {
            closeModal();
        }
    });

})();
