/**
 * 2fox4 WP Blog Agent - Admin JavaScript
 * Text Domain: wp-blog-agent
 */

jQuery(document).ready(function($) {
    'use strict';

    // ====================================
    // 0a. PREVIEW & REVISE MODAL
    // ====================================
    //
    // Exposed as wbagOpenPreviewModal(postId) so the write-success handlers
    // can pop the modal immediately after a post is generated. Inside the
    // modal the user can read the rendered HTML and ask Claude for targeted
    // revisions as many times as they want.

    var wbagCurrentPreviewPostId = 0;

    function wbagRenderPreview(data) {
        var $modal = $('#wbag-preview-modal');
        $modal.find('.wbag-modal-preview-title').text(data.title || '');
        $modal.find('.wbag-modal-preview-content').html(data.content || '');
        if (data.featured_url) {
            $modal.find('.wbag-modal-preview-featured img').attr('src', data.featured_url);
            $modal.find('.wbag-modal-preview-featured').show();
        } else {
            $modal.find('.wbag-modal-preview-featured').hide();
        }
        var wc = data.word_count || 0;
        $modal.find('.wbag-modal-wordcount').text(wc + ' Wörter');
        if (data.revision_num) {
            $modal.find('.wbag-modal-revision-badge')
                .text('Revision #' + data.revision_num)
                .show();
        }
        // Scroll preview back to top on re-render.
        $modal.find('.wbag-modal-body').scrollTop(0);
    }

    window.wbagOpenPreviewModal = function(postId) {
        if (!postId) { return; }
        wbagCurrentPreviewPostId = postId;
        var $modal = $('#wbag-preview-modal');
        $modal.find('.wbag-modal-preview-title').text('Vorschau wird geladen …');
        $modal.find('.wbag-modal-preview-content').html('<p style="color:#666;">Einen Moment bitte…</p>');
        $modal.find('.wbag-modal-preview-featured').hide();
        $modal.find('.wbag-modal-revision-badge').hide().text('');
        $modal.find('.wbag-modal-wordcount').text('');
        $modal.find('.wbag-modal-revise-status').text('');
        $modal.find('#wbag-modal-revise-input').val('');
        $modal.show();
        $('body').css('overflow', 'hidden');

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_preview_post',
                post_id: postId,
                nonce: wbag_admin.nonce
            },
            success: function(response) {
                if (response.success) {
                    wbagRenderPreview(response.data);
                    $modal.find('.wbag-modal-edit-link').attr('href', response.data.edit_url || '#');
                } else {
                    $modal.find('.wbag-modal-preview-content').html(
                        '<p style="color:#b00;"><strong>Fehler:</strong> ' +
                        ((response.data && response.data.message) || 'Vorschau konnte nicht geladen werden.') + '</p>'
                    );
                }
            },
            error: function() {
                $modal.find('.wbag-modal-preview-content').html(
                    '<p style="color:#b00;"><strong>Fehler:</strong> Verbindung zum Server fehlgeschlagen.</p>'
                );
            }
        });
    };

    function wbagClosePreviewModal() {
        $('#wbag-preview-modal').hide();
        $('body').css('overflow', '');
        wbagCurrentPreviewPostId = 0;
    }

    // Open preview from any success card (delegated).
    $(document).on('click', '.wbag-open-preview', function(e) {
        e.preventDefault();
        var pid = parseInt($(this).data('post-id'), 10);
        if (pid) { wbagOpenPreviewModal(pid); }
    });

    // Close handlers: X button, backdrop click, ESC key.
    $(document).on('click', '.wbag-modal-close, .wbag-modal-backdrop', function(e) {
        e.preventDefault();
        wbagClosePreviewModal();
    });
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('#wbag-preview-modal').is(':visible')) {
            wbagClosePreviewModal();
        }
    });

    // Submit a revision request.
    $(document).on('click', '.wbag-modal-revise-submit', function(e) {
        e.preventDefault();
        if (!wbagCurrentPreviewPostId) { return; }
        var $btn = $(this);
        var $input = $('#wbag-modal-revise-input');
        var instructions = ($input.val() || '').trim();
        if (!instructions) {
            $input.focus();
            return;
        }
        var $spinner = $('.wbag-modal-spinner');
        var $status = $('.wbag-modal-revise-status');
        $btn.prop('disabled', true);
        $spinner.css('display', 'inline-block').addClass('is-active');
        $status.text('Claude überarbeitet den Beitrag … dies kann 30–90 Sekunden dauern.');

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_revise_post',
                post_id: wbagCurrentPreviewPostId,
                instructions: instructions,
                nonce: wbag_admin.nonce
            },
            timeout: 300000,
            success: function(response) {
                if (response.success) {
                    wbagRenderPreview(response.data);
                    $input.val('');
                    $status.text('✓ ' + (response.data.message || 'Überarbeitung angewendet.'));
                } else {
                    $status.text('✗ ' + ((response.data && response.data.message) || 'Überarbeitung fehlgeschlagen.'));
                }
            },
            error: function() {
                $status.text('✗ Verbindung zum Server fehlgeschlagen.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.hide().removeClass('is-active');
            }
        });
    });

    // Ctrl/Cmd+Enter in the revise textarea submits.
    $(document).on('keydown', '#wbag-modal-revise-input', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            e.preventDefault();
            $('.wbag-modal-revise-submit').trigger('click');
        }
    });

    // ====================================
    // 0. PROGRESS WIDGET (reusable)
    // ====================================
    //
    // Shows an animated progress bar + stage messages for long-running
    // blog-writer operations. Since the AJAX call is blocking, the bar is
    // driven by a time-based heuristic that creeps toward 95 % so the user
    // always perceives progress without ever hitting 100 % before the
    // server responds. On success the bar snaps to 100 %.
    function wbagStartProgress($container, options) {
        options = options || {};
        var withImages = options.withImages !== false;
        var withAffiliates = !!options.withAffiliates;

        // Stage timeline in seconds (tuned for typical Claude + Gemini runs).
        // Each stage has: start, end, label, icon, fromPct, toPct.
        // Callers can pass a fully custom stages array via options._stages.
        var stages;
        if (options._stages) {
            stages = options._stages;
        } else if (withImages) {
            stages = [
                { start:   0, end:  95, label: 'Phase 1 von 3 · Blog-Text wird geschrieben', icon: 'dashicons-edit', from:  2, to: 55 },
                { start:  95, end: 115, label: 'Phase 2 von 3 · SEO-Metadaten werden analysiert', icon: 'dashicons-search', from: 55, to: 65 },
                { start: 115, end: 240, label: 'Phase 3 von 3 · Bilder werden erstellt', icon: 'dashicons-format-image', from: 65, to: 95 }
            ];
        } else {
            stages = [
                { start:   0, end:  90, label: 'Phase 1 von 2 · Blog-Text wird geschrieben', icon: 'dashicons-edit', from:  2, to: 80 },
                { start:  90, end: 130, label: 'Phase 2 von 2 · SEO-Metadaten werden analysiert', icon: 'dashicons-search', from: 80, to: 95 }
            ];
        }

        var extraInfo = '';
        if (withAffiliates) {
            extraInfo = '<div class="wbag-progress-info"><span class="dashicons dashicons-admin-links"></span> Affiliate-Links werden integriert, Transparenzhinweis wird angehängt.</div>';
        }

        var html =
            '<div class="wbag-progress-card" role="status" aria-live="polite">' +
                '<div class="wbag-progress-header">' +
                    '<span class="wbag-progress-spinner" aria-hidden="true"></span>' +
                    '<div class="wbag-progress-titles">' +
                        '<div class="wbag-progress-title">Ihr Blog-Beitrag wird erstellt</div>' +
                        '<div class="wbag-progress-stage"><span class="dashicons dashicons-edit"></span><span class="wbag-progress-stage-text">Wird gestartet …</span></div>' +
                    '</div>' +
                    '<div class="wbag-progress-elapsed">0:00</div>' +
                '</div>' +
                '<div class="wbag-progress-track"><div class="wbag-progress-fill" style="width:0%;"></div></div>' +
                '<div class="wbag-progress-footer">' +
                    '<span class="wbag-progress-hint">' + (withImages ? 'Geschätzte Dauer: 2–4 Minuten' : 'Geschätzte Dauer: 1–2 Minuten') + '</span>' +
                    '<span class="wbag-progress-percent">0&nbsp;%</span>' +
                '</div>' +
                extraInfo +
            '</div>';

        $container.html(html);

        var $card = $container.find('.wbag-progress-card');
        var $fill = $card.find('.wbag-progress-fill');
        var $stageText = $card.find('.wbag-progress-stage-text');
        var $stageIcon = $card.find('.wbag-progress-stage .dashicons');
        var $elapsed = $card.find('.wbag-progress-elapsed');
        var $percent = $card.find('.wbag-progress-percent');

        var startTime = Date.now();
        var stopped = false;
        var lastPct = 0;

        function formatTime(seconds) {
            var m = Math.floor(seconds / 60);
            var s = Math.floor(seconds % 60);
            return m + ':' + (s < 10 ? '0' + s : s);
        }

        function tick() {
            if (stopped) return;
            var elapsedSec = (Date.now() - startTime) / 1000;
            $elapsed.text(formatTime(elapsedSec));

            // Find active stage based on elapsed time.
            var active = stages[stages.length - 1];
            for (var i = 0; i < stages.length; i++) {
                if (elapsedSec < stages[i].end) { active = stages[i]; break; }
            }

            // Update stage label + icon (only if changed — avoids reflow flicker).
            if ($stageText.text() !== active.label) {
                $stageText.text(active.label);
                $stageIcon.attr('class', 'dashicons ' + active.icon);
            }

            // Calculate progress within stage.
            var stageElapsed = elapsedSec - active.start;
            var stageSpan = Math.max(1, active.end - active.start);
            var stageRatio = Math.min(1, stageElapsed / stageSpan);
            // Smooth easing: slow down toward the stage end.
            var eased = 1 - Math.pow(1 - stageRatio, 2);
            var targetPct = active.from + (active.to - active.from) * eased;

            // Never go backwards, never exceed 95 until finish() is called.
            if (targetPct > lastPct) lastPct = targetPct;
            if (lastPct > 95) lastPct = 95;

            $fill.css('width', lastPct.toFixed(1) + '%');
            $percent.text(Math.round(lastPct) + ' %');
        }

        var intervalId = setInterval(tick, 250);
        tick();

        return {
            finish: function(onDone) {
                stopped = true;
                clearInterval(intervalId);
                $fill.css('width', '100%');
                $percent.text('100 %');
                $stageText.text('Fertig!');
                $stageIcon.attr('class', 'dashicons dashicons-yes-alt');
                $card.addClass('wbag-progress-done');
                setTimeout(function() {
                    if (typeof onDone === 'function') onDone($card);
                }, 400);
            },
            fail: function() {
                stopped = true;
                clearInterval(intervalId);
                $card.addClass('wbag-progress-failed');
                $stageText.text('Fehlgeschlagen');
                $stageIcon.attr('class', 'dashicons dashicons-warning');
            }
        };
    }

    // Expose for potential reuse from other handlers / modules.
    window.wbagStartProgress = wbagStartProgress;

    // ====================================
    // 1. TAB SWITCHING
    // ====================================
    $('.wbag-tab-button').on('click', function(e) {
        e.preventDefault();
        var $tab = $(this);
        var tabName = $tab.data('tab');

        // Update active tab
        $('.wbag-tab-button').removeClass('active');
        $tab.addClass('active');

        // Update active content
        $('.wbag-tab-content').removeClass('active');
        $('#tab-' + tabName).addClass('active');

        // Store in URL hash
        window.location.hash = '#' + tabName;

        // Update hidden field so the active tab survives form submit
        $('#wbag_active_tab').val(tabName);
    });

    // Before form submit, append the active tab hash to the action URL
    $('.wbag-settings-form').on('submit', function() {
        var activeTab = $('#wbag_active_tab').val();
        if (activeTab) {
            var $form = $(this);
            var action = $form.attr('action').split('#')[0];
            $form.attr('action', action + '#' + activeTab);
        }
    });

    // Restore active tab from URL hash on page load
    if (window.location.hash) {
        var hashTab = window.location.hash.substring(1);
        var $targetTab = $('.wbag-tab-button[data-tab="' + hashTab + '"]');
        if ($targetTab.length) {
            $targetTab.trigger('click');
        }
    }

    // ====================================
    // 2. API TEST BUTTON
    // ====================================
    $('#wbag_test_api_button').on('click', function() {
        var $button = $(this);
        var $spinner = $('#wbag_test_api_spinner');
        var $result = $('#wbag_test_api_result');

        $button.prop('disabled', true);
        $spinner.css('display', 'inline-block').addClass('is-active');
        $result.empty();

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_test_api',
                nonce: wbag_admin.nonce
            },
            timeout: 30000,
            success: function(response) {
                if (response.success) {
                    $result.html(
                        '<div class="notice notice-success inline"><p>' +
                        '<strong>Verbindung erfolgreich!</strong> Die API-Verbindung funktioniert.' +
                        '</p></div>'
                    );
                } else {
                    $result.html(
                        '<div class="notice notice-error inline"><p>' +
                        '<strong>Verbindung fehlgeschlagen:</strong> ' +
                        (response.data ? response.data.message : 'Unbekannter Fehler.') +
                        '</p></div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                $result.html(
                    '<div class="notice notice-error inline"><p>' +
                    '<strong>Verbindungsfehler:</strong> Server nicht erreichbar.' +
                    '</p></div>'
                );
            },
            complete: function() {
                $button.prop('disabled', false);
                $spinner.hide().removeClass('is-active');
            }
        });
    });

    // ====================================
    // 2b. GEMINI API TEST BUTTON
    // ====================================
    $('#wbag_test_gemini_api_button').on('click', function() {
        var $button = $(this);
        var $spinner = $('#wbag_test_gemini_api_spinner');
        var $result = $('#wbag_test_gemini_api_result');

        $button.prop('disabled', true);
        $spinner.css('display', 'inline-block').addClass('is-active');
        $result.empty();

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_test_gemini_api',
                nonce: wbag_admin.nonce
            },
            timeout: 30000,
            success: function(response) {
                if (response.success) {
                    $result.html(
                        '<div class="notice notice-success inline"><p>' +
                        '<strong>' + (wbag_admin.i18n_connection_success || 'Verbindung erfolgreich!') + '</strong> ' +
                        (response.data ? response.data.message : '') +
                        '</p></div>'
                    );
                } else {
                    $result.html(
                        '<div class="notice notice-error inline"><p>' +
                        '<strong>' + (wbag_admin.i18n_connection_failed || 'Verbindung fehlgeschlagen:') + '</strong> ' +
                        (response.data ? response.data.message : 'Unbekannter Fehler.') +
                        '</p></div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                $result.html(
                    '<div class="notice notice-error inline"><p>' +
                    '<strong>' + (wbag_admin.i18n_connection_error || 'Verbindungsfehler:') + '</strong> ' +
                    (wbag_admin.i18n_server_unreachable || 'Server nicht erreichbar.') +
                    '</p></div>'
                );
            },
            complete: function() {
                $button.prop('disabled', false);
                $spinner.hide().removeClass('is-active');
            }
        });
    });

        // ====================================
    // 2c. LOAD TEMPLATE INTO CUSTOM TOPIC FORM
    // ====================================
    $(document).on('click', '.wbag-load-template', function() {
        var $btn = $(this);
        var title = $btn.data('title') || '';
        var description = $btn.data('description') || '';
        var keyword = $btn.data('keyword') || '';

        $('#wbag_custom_topic_title').val(title);
        $('#wbag_custom_topic_description').val(description);
        $('#wbag_custom_topic_keyword').val(keyword);

        // Scroll to form and flash highlight
        var $form = $('#wbag_custom_topic_title');
        $('html, body').animate({ scrollTop: $form.offset().top - 120 }, 400);
        $form.css('background', '#eef2ff');
        setTimeout(function() { $form.css('background', ''); }, 1500);
    });

        // ====================================
    // 2d. DELETE TEMPLATE FROM HISTORY
    // ====================================
    $(document).on('click', '.wbag-delete-template', function() {
        var $btn = $(this);
        var index = $btn.data('index');
        var $row = $btn.closest('div[style*="display"]');

        if (!confirm('Vorlage wirklich entfernen?')) {
            return;
        }

        $btn.prop('disabled', true);

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_delete_custom_template',
                nonce: wbag_admin.nonce,
                template_index: index
            },
            timeout: 10000,
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() {
                        $(this).remove();
                        // Update count in summary
                        var $history = $('.wbag-template-history');
                        var newCount = response.data.count || 0;
                        var $summary = $history.find('summary');
                        $summary.html($summary.html().replace(/\(\d+/, '(' + newCount));
                        // Re-index remaining delete buttons
                        $history.find('.wbag-delete-template').each(function(i) {
                            $(this).data('index', i).attr('data-index', i);
                        });
                        // Hide history section if empty
                        if (newCount === 0) {
                            $history.fadeOut(300);
                        }
                    });
                } else {
                    alert(response.data ? response.data.message : 'Fehler beim Entfernen.');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert('Serverfehler.');
                $btn.prop('disabled', false);
            }
        });
    });

    // ====================================
    // 3. ACTION BUTTONS (Topic Scout + Blog Writer)
    // ====================================
    $(document).on('click', '.wbag-action-btn[data-action]', function() {
        var $button = $(this);
        var actionType = $button.data('action');
        var $card = $button.closest('.wbag-action-card');
        var $spinner = $card.find('.wbag-action-spinner');
        var $result = $card.find('.wbag-action-result');

        $button.prop('disabled', true);
        $spinner.show();
        $result.empty();

        if (actionType === 'topic-scout') {
            // Read inline topic count and sync to hidden settings field
            var topicCount = $('#wbag_topic_count_inline').val() || 5;
            if ($('#wbag_topic_count').length) {
                $('#wbag_topic_count').val(topicCount);
            }
            $.ajax({
                type: 'POST',
                url: wbag_admin.ajax_url,
                data: {
                    action: 'wbag_run_topic_scout',
                    nonce: wbag_admin.nonce,
                    topic_count: topicCount
                },
                timeout: 120000,
                success: function(response) {
                    if (response.success) {
                        $result.html(
                            '<div class="wbag-results success">' +
                            '<p><strong>Topic Scout abgeschlossen</strong><br/>' +
                            (response.data.message || 'Neue Themen wurden gefunden und zur Warteschlange hinzugefügt.') +
                            '</p></div>'
                        );
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        $result.html(
                            '<div class="wbag-results error">' +
                            '<p><strong>Scout fehlgeschlagen</strong><br/>' +
                            (response.data ? response.data.message : 'Topic Scout konnte nicht ausgeführt werden.') +
                            '</p></div>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    $result.html(
                        '<div class="wbag-results error">' +
                        '<p><strong>Scout Fehler</strong><br/>' +
                        'Verbindung zum Server fehlgeschlagen.' +
                        '</p></div>'
                    );
                },
                complete: function() {
                    $button.prop('disabled', false);
                    $spinner.hide();
                }
            });
        }
    });

    // ====================================
    // 4b. RESET DISMISSED TOPICS BLACKLIST
    // ====================================
    $(document).on('click', '#wbag_reset_dismissed', function() {
        var $btn = $(this);
        if (!confirm('Blacklist wirklich zurücksetzen? Alle gelöschten Themen können dann erneut vorgeschlagen werden.')) {
            return;
        }
        $btn.prop('disabled', true);
        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_reset_dismissed_topics',
                nonce: wbag_admin.nonce
            },
            success: function(response) {
                if (response.success) {
                    $btn.closest('.wbag-dismissed-info').fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data ? response.data.message : 'Fehler beim Zurücksetzen.');
                }
            },
            error: function() {
                alert('Verbindung fehlgeschlagen.');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // ====================================
    // 4c. QUEUE ITEM NOTES (toggle + save)
    // ====================================
    $(document).on('click', '.wbag-toggle-notes', function() {
        var $btn = $(this);
        var idx = $btn.data('index');
        var $notes = $btn.closest('.wbag-queue-item').find('.wbag-queue-notes[data-index="' + idx + '"]');
        $notes.slideToggle(200);
    });

    $(document).on('click', '.wbag-save-notes', function() {
        var $btn = $(this);
        var idx = $btn.data('index');
        var $container = $btn.closest('.wbag-queue-notes');
        var notes = $container.find('.wbag-notes-textarea').val();
        var $status = $container.find('.wbag-notes-status');
        var $toggleBtn = $btn.closest('.wbag-queue-item').find('.wbag-toggle-notes');

        $btn.prop('disabled', true);
        $status.text('Speichern …').css('color', '#64748b');

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_save_topic_notes',
                nonce: wbag_admin.nonce,
                topic_index: idx,
                user_notes: notes
            },
            success: function(response) {
                if (response.success) {
                    $status.text('✓ Gespeichert').css('color', '#16a34a');
                    if (notes.trim()) {
                        $toggleBtn.addClass('wbag-has-notes');
                    } else {
                        $toggleBtn.removeClass('wbag-has-notes');
                    }
                    setTimeout(function() { $status.text(''); }, 2000);
                } else {
                    $status.text('Fehler: ' + (response.data ? response.data.message : '?')).css('color', '#dc2626');
                }
            },
            error: function() {
                $status.text('Verbindung fehlgeschlagen.').css('color', '#dc2626');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // ====================================
    // 5. PER-TOPIC "BEITRAG SCHREIBEN" BUTTON
    // ====================================
    // Helper: re-sync data-index attributes on queue items after a removal,
    // so the frontend indices stay in sync with the backend's array_values() reindexing.
    function wbagReindexQueue() {
        $('.wbag-queue-item').each(function(i) {
            $(this).attr('data-index', i);
            $(this).find('[data-index]').attr('data-index', i);
        });
    }

    $(document).on('click', '.wbag-write-topic', function(e) {
        e.preventDefault();
        var $button = $(this);
        var topicIndex = parseInt($button.data('index'), 10);
        var $item = $button.closest('.wbag-queue-item');

        // Disable all action buttons on this item while writing.
        $item.find('button').prop('disabled', true);

        // Swap the item content for a progress widget.
        // Keep the item in place so the user sees it transition.
        var $progressHost = $('<div class="wbag-queue-progress-host"></div>');
        var $info = $item.find('.wbag-queue-info').first();
        var originalHtml = $item.html();
        $item.empty().append($progressHost);

        var hasGemini = !!(wbag_admin && wbag_admin.has_gemini_key);
        var progress = wbagStartProgress($progressHost, { withImages: hasGemini });

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_run_blog_writer',
                topic_index: topicIndex,
                nonce: wbag_admin.nonce
            },
            timeout: 600000,
            success: function(response) {
                if (response.success) {
                    var postTitle = response.data.post_title || 'Neuer Beitrag';
                    var postUrl = response.data.post_url || '#';
                    var postEditUrl = response.data.post_edit_url || '#';
                    var postId = response.data.post_id || 0;
                    var imageInfo = '';

                    if (response.data.images) {
                        var imgs = response.data.images;
                        var successCount = (imgs.featured_id ? 1 : 0) + (imgs.content_ids ? imgs.content_ids.length : 0);
                        var errorCount = imgs.errors ? imgs.errors.length : 0;
                        if (successCount > 0) {
                            imageInfo = '<br/><span style="color:#00a32a;"><span class="dashicons dashicons-format-image" style="vertical-align:middle;"></span> <strong>' + successCount + ' Bilder</strong> erfolgreich generiert</span>';
                        }
                        if (errorCount > 0) {
                            imageInfo += '<br/><span style="color:#d63638;"><span class="dashicons dashicons-warning" style="vertical-align:middle;"></span> ' + errorCount + ' Bild(er) fehlgeschlagen</span>';
                        }
                    }

                    var successHtml =
                        '<div class="wbag-results success" style="margin:0;">' +
                        '<p style="margin:0;"><strong><span class="dashicons dashicons-yes-alt" style="color:#00a32a;vertical-align:middle;"></span> Blog-Beitrag erstellt!</strong><br/>' +
                        '<strong>' + postTitle + '</strong>' +
                        imageInfo + '<br/>' +
                        '<a href="' + postUrl + '" target="_blank" class="button button-primary button-small" style="margin-top:8px;margin-right:6px;">Beitrag ansehen</a> ' +
                        '<a href="' + postEditUrl + '" class="button button-small" style="margin-top:8px;">Im Editor öffnen</a>' +
                        '</p></div>';

                    progress.finish(function() {
                        // Replace the entire queue item with the success card so the
                        // topic visibly disappears from the queue (backend already removed it).
                        $item.html(successHtml);
                        // Reindex remaining items to stay in sync with the backend.
                        wbagReindexQueue();
                    });
                } else {
                    progress.fail();
                    $item.html(originalHtml);
                    $item.find('button').prop('disabled', false);
                    alert('Fehler: ' + (response.data ? response.data.message : 'Blog-Beitrag konnte nicht erstellt werden.'));
                }
            },
            error: function(xhr, status) {
                progress.fail();
                $item.html(originalHtml);
                $item.find('button').prop('disabled', false);
                if (status === 'timeout') {
                    alert('Zeitüberschreitung: Die Anfrage hat zu lange gedauert (10 Min. Limit).');
                } else {
                    alert('Server-Fehler (HTTP ' + xhr.status + '). Bitte versuchen Sie es erneut.');
                }
            }
        });
    });

    // ====================================
    // 6. DELETE TOPIC BUTTONS
    // ====================================
    $(document).on('click', '.wbag-delete-topic', function(e) {
        e.preventDefault();
        var $button = $(this);
        var topicIndex = $button.data('index');
        var $item = $button.closest('.wbag-queue-item');

        if (!confirm('Möchten Sie dieses Thema wirklich löschen?')) {
            return;
        }

        $button.prop('disabled', true);

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_delete_topic',
                topic_index: topicIndex,
                nonce: wbag_admin.nonce
            },
            success: function(response) {
                if (response.success) {
                    $item.fadeOut(300, function() {
                        $(this).remove();
                        wbagReindexQueue();
                        if ($('.wbag-queue-item').length === 0) {
                            $('.wbag-queue-list').replaceWith(
                                '<p>Die Warteschlange ist leer. Verwenden Sie "Themen finden", um neue Themen hinzuzufügen.</p>'
                            );
                        }
                    });
                } else {
                    alert('Fehler: ' + (response.data ? response.data.message : 'Unbekannter Fehler'));
                    $button.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                alert('Fehler: Verbindung zum Server fehlgeschlagen.');
                $button.prop('disabled', false);
            }
        });
    });

    // ====================================
    // 7. GENERAL AJAX ERROR HANDLING
    // ====================================
    // ====================================
    // 8. REFERENCE URL ANALYSIS
    // ====================================
    $('#wbag_analyze_reference').on('click', function() {
        var $button = $(this);
        var $spinner = $('#wbag_analyze_spinner');
        var $result = $('#wbag_reference_analysis_result');
        var $styleField = $('#wbag_reference_style');
        var url = $('#wbag_reference_url').val();

        if (!url) {
            $result.html('<div class="notice notice-warning inline"><p>Bitte geben Sie eine URL ein.</p></div>');
            return;
        }

        $button.prop('disabled', true);
        $spinner.css('display', 'inline-block').addClass('is-active');
        $result.html('<div class="notice notice-info inline"><p>Seite wird analysiert... Dies kann 30-60 Sekunden dauern.</p></div>');

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_analyze_reference',
                url: url,
                nonce: wbag_admin.nonce
            },
            timeout: 120000,
            success: function(response) {
                if (response.success) {
                    $styleField.val(response.data.style);
                    $result.html('<div class="notice notice-success inline"><p><strong>Analyse abgeschlossen!</strong> Die Stilvorlage wurde ausgefüllt. Bitte speichern Sie die Einstellungen.</p></div>');
                } else {
                    $result.html('<div class="notice notice-error inline"><p><strong>Analyse fehlgeschlagen:</strong> ' + (response.data ? response.data.message : 'Unbekannter Fehler') + '</p></div>');
                }
            },
            error: function() {
                $result.html('<div class="notice notice-error inline"><p><strong>Fehler:</strong> Verbindung zum Server fehlgeschlagen.</p></div>');
            },
            complete: function() {
                $button.prop('disabled', false);
                $spinner.hide().removeClass('is-active');
            }
        });
    });

    // ====================================
    // 8b. STYLE SLOT SELECTOR (live chip highlight + label sync)
    // ====================================
    $(document).on('change', '.wbag-style-radio', function() {
        $('.wbag-style-chip').each(function() {
            var $chip = $(this);
            var checked = $chip.find('input.wbag-style-radio').is(':checked');
            if (checked) {
                $chip.addClass('is-active').css({
                    'background': 'rgba(255, 107, 53, 0.15)',
                    'border-color': '#FF6B35'
                });
            } else {
                $chip.removeClass('is-active').css({
                    'background': 'rgba(255,255,255,0.03)',
                    'border-color': 'rgba(255,255,255,0.15)'
                });
            }
        });

        // Show only the slot whose radio is active, hide the rest.
        var activeSlotId = $('.wbag-style-radio:checked').val();
        $('.wbag-style-slot').each(function() {
            var $slot = $(this);
            if ($slot.data('slot-id') === activeSlotId) {
                $slot.show();
            } else {
                $slot.hide();
            }
        });
    });

    $(document).on('input', '.wbag-style-label-input', function() {
        var slot = $(this).data('slot');
        var val = $(this).val();
        if (!val) {
            val = $(this).attr('placeholder') || '';
        }
        $('.wbag-style-chip-label[data-slot="' + slot + '"]').text(val);
    });

    // ====================================
    // RSS FEED CHIPS (toggle active state + auto-save)
    $(document).on('change', '.wbag-rss-feed-chip input[type="checkbox"]', function() {
        $(this).closest('.wbag-rss-feed-chip').toggleClass('wbag-rss-active', this.checked);
        saveRssSettings();
    });

    // ====================================
    // RSS AUTO-SAVE
    // Saves rss_keywords and rss_predefined via AJAX so the user never has
    // to click "Einstellungen speichern" for these two fields.
    // ====================================
    var rssAutoSaveTimer = null;

    function saveRssSettings() {
        var keywords = $('#wbag_rss_keywords').val() || '';
        var predefined = [];
        $('input[name="wbag_settings[rss_predefined][]"]:checked').each(function() {
            predefined.push($(this).val());
        });

        var $indicator = $('#wbag-rss-autosave-indicator');
        $indicator.text('…').css('color', '#646970').stop(true).show();

        $.ajax({
            url: wbag_admin.ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'wbag_save_rss_settings',
                nonce: wbag_admin.nonce,
                rss_keywords: keywords,
                rss_predefined: JSON.stringify(predefined)
            },
            success: function() {
                $indicator.text('✓ Gespeichert').css('color', '#00a32a').delay(2000).fadeOut(400);
            },
            error: function() {
                $indicator.text('⚠ Fehler beim Speichern').css('color', '#d63638').delay(3000).fadeOut(400);
            }
        });
    }

    // Debounced auto-save for keyword textarea (waits 1.2 s after last keystroke).
    $('#wbag_rss_keywords').on('input', function() {
        clearTimeout(rssAutoSaveTimer);
        rssAutoSaveTimer = setTimeout(saveRssSettings, 1200);
    });

    // ====================================
    // MANUAL AUTOPILOT — Two-step: Preview → Select → Write
    // ====================================

    // Helper: launch the actual blog-post creation for one selected item.
    function wbagRunAutopilotWrite($btn, $result, $progressWrap, selectedItem) {
        var originalHtml = $btn.data('originalHtml');
        var progressTimer = null;
        var progressShowTimer = null;
        var progress = null;

        $btn.prop('disabled', true).html(
            '<span class="dashicons dashicons-update" style="font-size:20px;width:20px;height:20px;animation:rotation 1s linear infinite;"></span> ' +
            wbag_admin.i18n_processing
        );

        var hasImages = !!(wbag_admin && wbag_admin.has_gemini_key);
        // No RSS-fetch phase when user pre-selected → shorter stage list.
        var writeStages;
        if (hasImages) {
            writeStages = [
                { start:   0, end:  95, label: 'Phase 1 von 3 · Blog-Text wird geschrieben', icon: 'dashicons-edit',         from:  2, to: 55 },
                { start:  95, end: 115, label: 'Phase 2 von 3 · SEO-Metadaten werden analysiert', icon: 'dashicons-search',  from: 55, to: 65 },
                { start: 115, end: 240, label: 'Phase 3 von 3 · Bilder werden erstellt',     icon: 'dashicons-format-image', from: 65, to: 95 }
            ];
        } else {
            writeStages = [
                { start:   0, end:  90, label: 'Phase 1 von 2 · Blog-Text wird geschrieben', icon: 'dashicons-edit',        from:  2, to: 80 },
                { start:  90, end: 130, label: 'Phase 2 von 2 · SEO-Metadaten werden analysiert', icon: 'dashicons-search', from: 80, to: 95 }
            ];
        }

        progressShowTimer = setTimeout(function() {
            $progressWrap.show();
            progress = wbagStartProgress($progressWrap, { withImages: hasImages, _stages: writeStages });
            function pollProgress() {
                $.ajax({
                    url: wbag_admin.ajax_url, type: 'POST', dataType: 'json',
                    data: { action: 'wbag_autopilot_progress', nonce: wbag_admin.nonce },
                    timeout: 5000,
                    success: function(res) {
                        if (res.success && res.data && res.data.detail) {
                            $progressWrap.find('.wbag-progress-stage-text').text(res.data.detail);
                        }
                    }
                });
            }
            progressTimer = setInterval(pollProgress, 2000);
        }, 800);

        $.ajax({
            url: wbag_admin.ajax_url, type: 'POST', dataType: 'json',
            data: {
                action: 'wbag_run_autopilot_now',
                nonce: wbag_admin.nonce,
                selected_item: JSON.stringify(selectedItem)
            },
            timeout: 300000,
            success: function(response) {
                clearInterval(progressTimer);
                clearTimeout(progressShowTimer);
                $btn.prop('disabled', false).html(originalHtml);
                if (response.success) {
                    var showResult = function() {
                        var editLink = response.data.edit_url
                            ? ' <a href="' + response.data.edit_url + '" target="_blank" style="color:inherit;text-decoration:underline;">Beitrag bearbeiten &rarr;</a>'
                            : '';
                        $result.css({ background: '#ecfdf5', color: '#065f46', border: '1px solid #a7f3d0' })
                               .html('<strong>&#9989; ' + response.data.message + '</strong>' + editLink)
                               .fadeIn();
                    };
                    if (progress) { progress.finish(function() { $progressWrap.slideUp(); showResult(); }); }
                    else { showResult(); }
                } else {
                    if (progress) { progress.fail(); setTimeout(function() { $progressWrap.slideUp(); }, 1500); }
                    var msg = (response.data && response.data.message) ? response.data.message : 'Unbekannter Fehler';
                    $result.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
                           .html('<strong>&#10060; ' + msg + '</strong>').fadeIn();
                }
            },
            error: function(xhr, status) {
                clearInterval(progressTimer);
                clearTimeout(progressShowTimer);
                $btn.prop('disabled', false).html(originalHtml);
                if (progress) { progress.fail(); setTimeout(function() { $progressWrap.slideUp(); }, 1500); }
                var detail = status === 'timeout' ? ' (Zeitüberschreitung)' : (xhr.status ? ' (HTTP ' + xhr.status + ')' : '');
                $result.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
                       .html('<strong>&#10060; Verbindungsfehler' + detail + '. Bitte erneut versuchen.</strong>').fadeIn();
            }
        });
    }

    // Step 1: Fetch & display RSS matches for selection.
    $('#wbag-run-autopilot-now').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var $result = $('#wbag-autopilot-now-result');
        var originalHtml = $btn.html();
        $btn.data('originalHtml', originalHtml);

        // Ensure containers exist.
        var $progressWrap = $('#wbag-autopilot-progress-wrap');
        if (!$progressWrap.length) {
            $result.before('<div id="wbag-autopilot-progress-wrap" style="display:none;margin-top:12px;"></div>');
            $progressWrap = $('#wbag-autopilot-progress-wrap');
        }
        var $matchList = $('#wbag-rss-match-list');
        if (!$matchList.length) {
            $result.before('<div id="wbag-rss-match-list" style="display:none;margin-top:16px;"></div>');
            $matchList = $('#wbag-rss-match-list');
        }

        $btn.prop('disabled', true).html(
            '<span class="dashicons dashicons-update" style="font-size:20px;width:20px;height:20px;animation:rotation 1s linear infinite;"></span> Feeds werden abgerufen …'
        );
        $result.hide();
        $matchList.hide();

        $.ajax({
            url: wbag_admin.ajax_url, type: 'POST', dataType: 'json',
            data: { action: 'wbag_preview_rss_matches', nonce: wbag_admin.nonce },
            timeout: 60000,
            success: function(response) {
                $btn.prop('disabled', false).html(originalHtml);
                if (!response.success) {
                    var msg = (response.data && response.data.message) ? response.data.message : 'Unbekannter Fehler';
                    $result.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
                           .html('<strong>&#10060; ' + msg + '</strong>').fadeIn();
                    return;
                }

                var items = response.data.items || [];
                if (!items.length) {
                    $result.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
                           .html('<strong>&#10060; Keine passenden Artikel gefunden.</strong>').fadeIn();
                    return;
                }

                // Build selection list.
                var html = '<div style="background:#f8f9fa;border:1px solid #dcdcde;border-radius:8px;padding:16px;">';
                html += '<p style="margin:0 0 12px;font-weight:600;color:#1d2327;">';
                html += '<span class="dashicons dashicons-rss" style="color:#2271b1;margin-right:6px;vertical-align:middle;"></span>';
                html += items.length + ' Treffer gefunden &mdash; Wählen Sie einen Artikel aus:';
                html += '</p>';
                html += '<div id="wbag-rss-items" style="display:flex;flex-direction:column;gap:8px;">';

                $.each(items, function(i, item) {
                    var safeTitle   = $('<span>').text(item.title || '').html();
                    var safeSource  = $('<span>').text(item.source || '').html();
                    var safeDate    = $('<span>').text(item.date || '').html();
                    var safeSummary = $('<span>').text(item.summary || '').html();
                    html += '<label class="wbag-rss-item-card" data-index="' + i + '" style="display:flex;align-items:flex-start;gap:10px;padding:12px 14px;background:#fff;border:2px solid #dcdcde;border-radius:6px;cursor:pointer;transition:border-color .15s,box-shadow .15s;">';
                    html += '<input type="radio" name="wbag_rss_selected" value="' + i + '" style="margin-top:3px;flex-shrink:0;">';
                    html += '<div style="min-width:0;">';
                    html += '<div style="font-weight:600;color:#1d2327;line-height:1.4;">' + safeTitle + '</div>';
                    if (safeSource || safeDate) {
                        html += '<div style="font-size:11px;color:#646970;margin-top:3px;">' + safeSource + (safeDate ? ' &middot; ' + safeDate : '') + '</div>';
                    }
                    if (safeSummary) {
                        html += '<div style="font-size:12px;color:#50575e;margin-top:5px;line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">' + safeSummary + '</div>';
                    }
                    html += '</div></label>';
                });

                html += '</div>';
                html += '<div style="margin-top:14px;display:flex;align-items:center;gap:10px;">';
                html += '<button id="wbag-write-selected" class="button button-primary" disabled style="display:flex;align-items:center;gap:6px;">';
                html += '<span class="dashicons dashicons-edit" style="font-size:16px;width:16px;height:16px;"></span> Ausgewählten Artikel schreiben';
                html += '</button>';
                html += '<button id="wbag-rss-cancel" class="button" style="color:#646970;">Abbrechen</button>';
                html += '</div></div>';

                $matchList.html(html).fadeIn();

                // Store items data for later use.
                $matchList.data('items', items);

                // Card highlight on radio change.
                $matchList.on('change', 'input[type="radio"]', function() {
                    $matchList.find('.wbag-rss-item-card').css({ 'border-color': '#dcdcde', 'box-shadow': 'none', 'background': '#fff' });
                    $(this).closest('.wbag-rss-item-card').css({ 'border-color': '#2271b1', 'box-shadow': '0 0 0 1px #2271b1', 'background': '#f0f6fc' });
                    $('#wbag-write-selected').prop('disabled', false);
                });

                // Step 2: write the selected article.
                $matchList.on('click', '#wbag-write-selected', function() {
                    var idx = $matchList.find('input[type="radio"]:checked').val();
                    if (idx === undefined) return;
                    var selectedItem = $matchList.data('items')[parseInt(idx, 10)];
                    $matchList.fadeOut(200, function() {
                        wbagRunAutopilotWrite($btn, $result, $progressWrap, selectedItem);
                    });
                });

                // Cancel.
                $matchList.on('click', '#wbag-rss-cancel', function() {
                    $matchList.fadeOut(200);
                    $result.hide();
                });
            },
            error: function(xhr, status) {
                $btn.prop('disabled', false).html(originalHtml);
                var detail = status === 'timeout' ? ' (Zeitüberschreitung)' : (xhr.status ? ' (HTTP ' + xhr.status + ')' : '');
                $result.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
                       .html('<strong>&#10060; Verbindungsfehler' + detail + '. Bitte erneut versuchen.</strong>').fadeIn();
            }
        });
    });

    // CUSTOM TOPIC + AFFILIATE LINKS
    // ====================================

    // Add affiliate link row
    // Remove affiliate link row
    // Write custom topic blog post
    $('#wbag_custom_topic_write').on('click', function() {
        var $button = $(this);
        var $spinner = $('#wbag_custom_topic_spinner');
        var $result = $('#wbag_custom_topic_result');

        var title = $.trim($('#wbag_custom_topic_title').val());
        if (!title) {
            $result.html(
                '<div class="wbag-results error" style="margin-top:12px;">' +
                '<p><strong>Bitte geben Sie ein Thema ein.</strong></p></div>'
            );
            $('#wbag_custom_topic_title').focus();
            return;
        }

        var description = $.trim($('#wbag_custom_topic_description').val());
        var keyword = $.trim($('#wbag_custom_topic_keyword').val());


        $button.prop('disabled', true);
        $spinner.show();

        var hasGeminiCustom = !!(wbag_admin && wbag_admin.has_gemini_key);
        var progress2 = wbagStartProgress($result, {
            withImages: hasGeminiCustom,
        });

        $.ajax({
            type: 'POST',
            url: wbag_admin.ajax_url,
            data: {
                action: 'wbag_write_custom_topic',
                nonce: wbag_admin.nonce,
                custom_title: title,
                custom_description: description,
                custom_keyword: keyword,
            },
            timeout: 600000,
            success: function(response) {
                if (response.success) {
                    var postTitle = response.data.post_title || 'Neuer Beitrag';
                    var postUrl = response.data.post_url || '#';
                    var postEditUrl = response.data.post_edit_url || '#';
                    var postId = response.data.post_id || 0;
                    var imageInfo = '';

                    if (response.data.images) {
                        var imgs = response.data.images;
                        var successCount = (imgs.featured_id ? 1 : 0) + (imgs.content_ids ? imgs.content_ids.length : 0);
                        if (successCount > 0) {
                            imageInfo = '<br/><span style="color:#00a32a;"><span class="dashicons dashicons-format-image" style="vertical-align:middle;"></span> <strong>' + successCount + ' Bilder</strong> erfolgreich generiert</span>';
                        }
                    }


                    var customSuccessHtml =
                        '<div class="wbag-results success" style="margin-top:12px;">' +
                        '<p><strong style="color:#00a32a;">&#10003; Beitrag erstellt:</strong> ' +
                        '<a href="' + postEditUrl + '" target="_blank">' + postTitle + '</a>' +
                        imageInfo +
                        '<br/><a href="' + postUrl + '" target="_blank" class="button button-primary button-small" style="margin-top:8px;margin-right:6px;">Beitrag ansehen</a>' +
                        ' <a href="' + postEditUrl + '" target="_blank" class="button button-small">Im Editor öffnen</a>' +
                        '</p></div>';
                    progress2.finish(function() {
                        $result.html(customSuccessHtml);
                    });

                    // Save values before clearing (for template history)
                    var savedTitle = title;
                    var savedDesc = description;
                    var savedKw = keyword;

                    // Clear the form
                    $('#wbag_custom_topic_title').val('');
                    $('#wbag_custom_topic_description').val('');
                    $('#wbag_custom_topic_keyword').val('');

                    // Dynamically add to template history list
                    (function() {
                        var $history = $('.wbag-template-history');
                        var now = new Date();
                        var dateStr = now.toLocaleDateString('de-DE') + ', ' + now.toLocaleTimeString('de-DE', {hour:'2-digit', minute:'2-digit'});
                        var editUrl = response.data.post_edit_url || '';
                        var newRow = '<div style="display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid #f1f5f9;font-size:13px;background:#f0fdf4;">' +
                            '<div style="flex:1;min-width:0;">' +
                            '<strong style="color:#0f172a;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + $('<span>').text(savedTitle).html() + '</strong>' +
                            (savedKw ? '<span style="color:#6366f1;font-size:11px;">' + $('<span>').text(savedKw).html() + '</span>' : '') +
                            '<span style="color:#94a3b8;font-size:11px;margin-left:6px;">' + dateStr + '</span>' +
                            '</div>' +
                            '<div style="display:flex;gap:6px;flex-shrink:0;">' +
                            '<button type="button" class="button button-small wbag-load-template" data-title="' + $('<span>').text(savedTitle).html() + '" data-description="' + $('<span>').text(savedDesc).html() + '" data-keyword="' + $('<span>').text(savedKw).html() + '" title="In Formular laden"><span class="dashicons dashicons-update" style="font-size:14px;width:14px;height:14px;vertical-align:-2px;"></span> Laden</button>' +
                            (editUrl ? '<a href="' + editUrl + '" target="_blank" class="button button-small" title="Beitrag bearbeiten"><span class="dashicons dashicons-edit" style="font-size:14px;width:14px;height:14px;vertical-align:-2px;"></span></a>' : '') +
                            '</div></div>';

                        if ($history.length) {
                            // History exists — prepend new row
                            $history.find('details > div').prepend(newRow);
                            // Update count in summary
                            var $summary = $history.find('summary');
                            var countMatch = $summary.text().match(/\((\d+)/);
                            if (countMatch) {
                                var newCount = parseInt(countMatch[1]) + 1;
                                $summary.html($summary.html().replace(/\(\d+/, '(' + newCount));
                            }
                            // Auto-open the details
                            $history.find('details').attr('open', '');
                        } else {
                            // No history yet — create the whole section
                            var historyHtml = '<div class="wbag-template-history" style="margin-top:24px;">' +
                                '<details open><summary style="cursor:pointer;font-size:14px;font-weight:600;color:#475569;padding:10px 0;user-select:none;">' +
                                '<span class="dashicons dashicons-archive" style="font-size:16px;width:16px;height:16px;vertical-align:-2px;margin-right:4px;"></span> Letzte Themen (1 gespeichert)</summary>' +
                                '<div style="margin-top:10px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;">' + newRow + '</div>' +
                                '</details></div>';
                            $('#wbag_custom_topic_result').after(historyHtml);
                        }
                        // Brief highlight
                        setTimeout(function() {
                            $history.find('div[style*="f0fdf4"]').css('background', '');
                        }, 2000);
                    })();
                } else {
                    progress2.fail();
                    $result.append(
                        '<div class="wbag-results error" style="margin-top:12px;">' +
                        '<p><strong>Fehler</strong><br/>' +
                        (response.data ? response.data.message : 'Beitrag konnte nicht erstellt werden.') +
                        '</p></div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                progress2.fail();
                if (status === 'timeout') {
                    $result.append(
                        '<div class="wbag-results error" style="margin-top:12px;">' +
                        '<p><strong>Zeitüberschreitung</strong><br/>' +
                        'Die Anfrage hat zu lange gedauert. Bitte versuchen Sie es erneut.</p></div>'
                    );
                } else {
                    $result.append(
                        '<div class="wbag-results error" style="margin-top:12px;">' +
                        '<p><strong>Server-Fehler</strong><br/>' +
                        'Verbindung zum Server fehlgeschlagen.</p></div>'
                    );
                }
            },
            complete: function() {
                $button.prop('disabled', false);
                $spinner.hide();
            }
        });
    });

    $(document).ajaxError(function(event, xhr, settings, thrownError) {
        // Log AJAX errors to console for debugging
        console.error('AJAX Error:', {
            status: xhr.status,
            statusText: xhr.statusText,
            responseText: xhr.responseText,
            url: settings.url
        });
    });

    // ── Global Affiliate Links: Add / Remove rows ──────────────────────
    (function () {
        var $list = $('#wbag-affiliate-list');
        var $addBtn = $('#wbag-add-affiliate');

        if (!$list.length) return;

        function getNextIndex() {
            var maxIdx = -1;
            $list.find('.wbag-affiliate-row').each(function () {
                var idx = parseInt($(this).attr('data-index'), 10);
                if (idx > maxIdx) maxIdx = idx;
            });
            return maxIdx + 1;
        }

        function reindexRows() {
            $list.find('.wbag-affiliate-row').each(function (i) {
                $(this).attr('data-index', i);
                $(this).find('input').each(function () {
                    var name = $(this).attr('name') || '';
                    name = name.replace(/\[global_affiliate_links\]\[\d+\]/, '[global_affiliate_links][' + i + ']');
                    $(this).attr('name', name);
                });
            });
        }

        $addBtn.on('click', function () {
            var idx = getNextIndex();
            var row = '<div class="wbag-affiliate-row" data-index="' + idx + '">'
                + '<div class="wbag-affiliate-fields">'
                + '<div class="wbag-affiliate-field">'
                + '<label>Bezeichnung</label>'
                + '<input type="text" name="wbag_settings[global_affiliate_links][' + idx + '][label]" value="" class="regular-text" placeholder="z.B. Hosting-Anbieter XY" />'
                + '</div>'
                + '<div class="wbag-affiliate-field">'
                + '<label>Affiliate-URL</label>'
                + '<input type="url" name="wbag_settings[global_affiliate_links][' + idx + '][url]" value="" class="regular-text" placeholder="https://partner.example.com/?ref=abc" />'
                + '</div>'
                + '<div class="wbag-affiliate-field wbag-affiliate-field-wide">'
                + '<label>Beschreibung / Kategorie</label>'
                + '<input type="text" name="wbag_settings[global_affiliate_links][' + idx + '][description]" value="" class="regular-text" placeholder="z.B. WordPress Hosting, SEO-Tool, E-Mail-Marketing" />'
                + '</div>'
                + '</div>'
                + '<button type="button" class="button wbag-remove-affiliate" title="Entfernen">'
                + '<span class="dashicons dashicons-trash"></span>'
                + '</button>'
                + '</div>';
            $list.append(row);
        });

        $list.on('click', '.wbag-remove-affiliate', function () {
            $(this).closest('.wbag-affiliate-row').remove();
            reindexRows();
        });
    })();

    // ── Topic Images: WordPress Media Uploader ─────────────────────────
    (function () {
        var frame;

        $(document).on('click', '.wbag-add-topic-image', function (e) {
            e.preventDefault();
            var $btn = $(this);
            var topicIndex = $btn.data('index');
            var $container = $btn.closest('.wbag-topic-images');
            var $thumbs = $container.find('.wbag-image-thumbs');

            if (frame) {
                frame.off('select');
            }

            frame = wp.media({
                title: 'Bild auswählen',
                button: { text: 'Bild verwenden' },
                multiple: true,
                library: { type: 'image' }
            });

            frame.on('select', function () {
                var selection = frame.state().get('selection');
                selection.each(function (attachment) {
                    var data = attachment.toJSON();
                    var thumbUrl = data.sizes && data.sizes.thumbnail
                        ? data.sizes.thumbnail.url
                        : data.url;

                    // Save to server
                    $.post(wbag_admin.ajax_url, {
                        action: 'wbag_save_topic_images',
                        nonce: wbag_admin.nonce,
                        topic_index: topicIndex,
                        image_id: data.id
                    });

                    // Add thumbnail preview
                    var thumb = '<div class="wbag-image-thumb" data-id="' + data.id + '">'
                        + '<img src="' + thumbUrl + '" alt="" />'
                        + '<button type="button" class="wbag-remove-image" data-id="' + data.id + '" data-index="' + topicIndex + '" title="Entfernen">&times;</button>'
                        + '</div>';
                    $thumbs.append(thumb);
                });

                // Highlight the notes button
                $('.wbag-toggle-notes[data-index="' + topicIndex + '"]').addClass('wbag-has-notes');
            });

            frame.open();
        });

        $(document).on('click', '.wbag-remove-image', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var $btn = $(this);
            var imageId = parseInt($btn.data('id'), 10);
            var topicIndex = $btn.data('index');

            $.post(wbag_admin.ajax_url, {
                action: 'wbag_remove_topic_image',
                nonce: wbag_admin.nonce,
                topic_index: topicIndex,
                image_id: imageId
            });

            $btn.closest('.wbag-image-thumb').fadeOut(200, function () {
                $(this).remove();
            });
        });
    })();

});
