/**
 * RSS Feeds Page JavaScript
 *
 * @package Wisewand
 * @since 1.0.0
 */

jQuery(document).ready(function ($) {
    // WPML detection for conditional language column display
    const isWPMLActive = wisewandRSS.isWPMLActive;

    loadFeeds();

    // Test connection button
    $('#test-rss-connection').on('click', function () {
        const $btn = $(this);
        $btn.prop('disabled', true).text('🔍 Testing...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_test_connection',
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                let html = '<div class="notice notice-info" style="padding: 12px;"><h3>🔍 Diagnostic Results:</h3>';

                if (response.success) {
                    html += '<p><strong>✅ AJAX Handler:</strong> Working</p>';
                    html += '<p><strong>API Key:</strong> ' + (response.data.api_key_configured ? '✅ Configured' : '❌ Not Configured') + '</p>';
                    html += '<p><strong>Classes Loaded:</strong></p><ul>';
                    for (let [className, loaded] of Object.entries(response.data.classes_loaded)) {
                        html += '<li>' + className + ': ' + (loaded ? '✅' : '❌') + '</li>';
                    }
                    html += '</ul>';
                } else {
                    html += '<p><strong>❌ Error:</strong> ' + response.data.message + '</p>';
                }

                html += '</div>';
                $('#diagnostic-info').html(html);
                $btn.prop('disabled', false).text('🔍 Test Connection');
            },
            error: function (xhr, status, error) {
                console.error('Test failed:', xhr.responseText);
                let html = '<div class="notice notice-error" style="padding: 12px;">';
                html += '<h3>❌ Diagnostic Test Failed</h3>';
                html += '<p><strong>Status:</strong> ' + xhr.status + ' ' + error + '</p>';
                html += '<p><strong>Response:</strong></p>';
                html += '<pre style="background: #f0f0f0; padding: 10px; overflow-x: auto;">' + xhr.responseText + '</pre>';
                html += '<p><strong>Possible Issues:</strong></p>';
                html += '<ul>';
                html += '<li>PHP fatal error preventing AJAX response</li>';
                html += '<li>Missing class files or autoloading issue</li>';
                html += '<li>Server configuration blocking AJAX</li>';
                html += '<li>Plugin conflict</li>';
                html += '</ul>';
                html += '<p>Check PHP error logs for details: wp-content/debug.log</p>';
                html += '</div>';
                $('#diagnostic-info').html(html);
                $btn.prop('disabled', false).text('🔍 Test Connection');
            }
        });
    });

    // RSS v2.0: Open global publication settings (redirects to Calendar settings)
    $(document).on('click', '#open-global-publication-settings', function () {
        const confirmMsg = 'This will open the Calendar settings page where you can configure global publication time and allowed days.\n\nThese settings apply to both Calendar roadmap and RSS feeds (unless you set custom per-feed settings).\n\nContinue?';
        if (confirm(confirmMsg)) {
            window.location.href = 'admin.php?page=wisewand-settings#calendar-defaults';
        }
    });

    // RSS Cleanup Button Handler (v1.1.0)
    $(document).on('click', '#cleanup-rss-data', function () {
        const confirmMsg = '⚠️ WARNING: This will permanently delete ALL RSS feeds and articles from the database!\n\n' +
            'This action CANNOT be undone.\n\n' +
            'Use this to start fresh if you want to re-sync feeds from Wisewand.\n\n' +
            'Type "DELETE" in the next prompt to confirm:';

        if (!confirm(confirmMsg)) {
            return;
        }

        const typedConfirm = prompt('Type DELETE (all caps) to confirm deletion:');
        if (typedConfirm !== 'DELETE') {
            alert('❌ Cleanup cancelled. You must type DELETE exactly.');
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).text('🗑️ Cleaning...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_cleanup_data',
                nonce: wisewandRSS.nonce,
                confirmed: 'true'
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ ' + response.data.message + '\n\nRefreshing page...');
                    location.reload();
                } else {
                    alert('❌ Cleanup failed: ' + (response.data.message || 'Unknown error'));
                    $btn.prop('disabled', false).text('🗑️ Cleanup RSS Data');
                }
            },
            error: function (xhr, status, error) {
                alert('❌ Network error during cleanup: ' + error);
                $btn.prop('disabled', false).text('🗑️ Cleanup RSS Data');
            }
        });
    });

    function loadFeeds() {
        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_list_feeds',
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    // RSS v2.0: Handle project and unassigned feeds separately
                    const projectFeeds = response.data.feeds || [];
                    const unassignedFeeds = response.data.unassigned_feeds || [];
                    const projectId = response.data.project_id || '';

                    renderFeeds(projectFeeds, unassignedFeeds, projectId);
                } else {
                    const errorMsg = response.data && response.data.message ? response.data.message : 'Failed to load feeds';
                    $('#feeds-container').html('<div class="notice notice-error"><p><strong>Error:</strong> ' + errorMsg + '</p>' +
                        (response.data && response.data.debug_info ? '<details><summary>Debug Info</summary><pre>' + response.data.debug_info + '</pre></details>' : '') +
                        '</div>');
                }
            },
            error: function (xhr, status, error) {
                console.error('RSS AJAX Error:', xhr.responseText);
                let errorMsg = 'Failed to connect to Wisewand API';

                if (xhr.responseText) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.data && response.data.message) {
                            errorMsg = response.data.message;
                        }
                    } catch (e) {
                        errorMsg = 'Server error: ' + xhr.status + ' ' + error;
                    }
                }

                $('#feeds-container').html('<div class="notice notice-error"><p><strong>Error:</strong> ' + errorMsg + '</p><p style="font-size: 12px; color: #666;">Check browser console and PHP error logs for details. Make sure your Wisewand API key is configured in Settings.</p></div>');
            }
        });
    }

    function renderFeeds(projectFeeds, unassignedFeeds, projectId) {
        // RSS v2.0: Render project feeds and unassigned feeds separately
        if (projectFeeds.length === 0 && unassignedFeeds.length === 0) {
            $('#feeds-container').html(`
                        <div class="notice notice-info">
                            <p><strong>No feeds found.</strong> Create your first feed in Wisewand to get started.</p>
                            <p><a href="https://app.wisewand.ai/feeds" target="_blank" class="button button-primary">Create Feed in Wisewand</a></p>
                        </div>
                    `);
            return;
        }

        // Update auto-import status widget
        updateStatusWidget(projectFeeds.concat(unassignedFeeds));

        let html = '';

        // Project feeds section
        if (projectFeeds.length > 0) {
            html += '<h3 style="margin: 20px 0 12px 0; padding: 12px; background: linear-gradient(135deg, #10b981 0%, #3b82f6 100%); color: white; border-radius: 6px;">📂 Project Feeds (' + projectFeeds.length + ')</h3>';
            html += renderFeedsTable(projectFeeds);
        }

        // Unassigned feeds section (collapsible)
        if (unassignedFeeds.length > 0 && projectId) {
            html += '<div id="unassigned-feeds-section" style="margin-top: 40px;">';
            html += '<div class="unassigned-header" style="padding: 16px; background: #f9fafb; border-left: 4px solid #f59e0b; border-radius: 4px; cursor: pointer;">';
            html += '<strong>🔍 Unassigned Feeds (' + unassignedFeeds.length + ')</strong>';
            html += '<span style="float: right;" id="unassigned-toggle">▼</span>';
            html += '<p style="margin: 4px 0 0 0; font-size: 13px; color: #6b7280;">These feeds don\'t have a project assigned. You can still activate them if needed.</p>';
            html += '</div>';
            html += '<div id="unassigned-feeds-container" style="display: none; margin-top: 16px;">';
            html += renderFeedsTable(unassignedFeeds);
            html += '</div>';
            html += '</div>';
        }

        $('#feeds-container').html(html);
    }

    // RSS v2.0: Update status widget with feed statistics
    function updateStatusWidget(allFeeds) {
        // Count activated feeds (sync_status = 'enabled')
        const activatedCount = allFeeds.filter(f => f.sync_status === 'enabled').length;
        $('#activated-feeds-count').text(activatedCount);

        // Find next sync time (earliest next_sync_at among enabled feeds)
        const enabledFeeds = allFeeds.filter(f => f.auto_import_enabled && f.next_sync_at);
        if (enabledFeeds.length > 0) {
            const nextSyncTimes = enabledFeeds.map(f => {
                // Use robust PHP-provided timestamp if available, else fallback to parsing string
                if (f.next_sync_ts) {
                    return f.next_sync_ts * 1000; // PHP timestamp is seconds, JS needs milliseconds
                }
                return new Date(f.next_sync_at).getTime();
            });
            const earliest = Math.min(...nextSyncTimes);
            const now = Date.now();
            const diffMinutes = Math.round((earliest - now) / 60000);

            if (diffMinutes > 60) {
                $('#next-sync-time').text(Math.round(diffMinutes / 60) + 'h');
            } else if (diffMinutes > 0) {
                $('#next-sync-time').text(diffMinutes + 'm');
            } else {
                $('#next-sync-time').text('Now');
            }
        } else {
            $('#next-sync-time').text('N/A');
        }

        // Calculate last 24h imported articles
        const last24h = allFeeds.reduce((sum, f) => {
            // This is approximate based on articles_imported count
            // Real implementation would query database for timestamp-filtered count
            return sum + (f.articles_imported || 0);
        }, 0);
        $('#last-24h-imported').text(last24h);
    }

    function renderFeedsTable(feeds) {
        let html = '<table class="wp-list-table widefat fixed striped"><thead><tr>';
        html += '<th style="width: 40px;"><input type="checkbox" class="select-all-feeds"></th>';
        html += '<th>Feed Name</th>';
        html += '<th>Source</th>';
        html += '<th>Status</th>';
        html += '<th>Articles</th>';
        html += '<th>Enabled</th>'; // RSS v2.0: New enabled_for_site column
        html += '<th>Automation</th>';
        if (isWPMLActive) {
            html += '<th>Language</th>'; // WPML: Language column (conditional)
        }
        html += '<th>Last Sync</th>';
        html += '<th>Actions</th>';
        html += '</tr></thead><tbody>';

        feeds.forEach(feed => {
            const statusClass = feed.is_active ? 'feed-status-active' : 'feed-status-inactive';
            const statusText = feed.is_active ? 'Active' : 'Inactive';
            const autoEnabled = feed.auto_import_enabled;
            const enabledForSite = (feed.sync_status === 'enabled') ? 1 : 0; // RSS v2.0: Use sync_status field

            html += '<tr data-feed-id="' + feed.id + '" data-wisewand-feed-id="' + feed.wisewand_feed_id + '">';
            html += '<td><input type="checkbox" class="select-feed-row" value="' + feed.id + '"></td>';
            html += '<td><strong>' + escapeHtml(feed.feed_name) + '</strong></td>';
            html += '<td><a href="' + escapeHtml(feed.feed_url) + '" target="_blank">' + escapeHtml(feed.feed_url) + '</a></td>';
            html += '<td><span class="feed-status-badge ' + statusClass + '">' + statusText + '</span></td>';
            html += '<td>' + (feed.total_articles || 0) + ' total<br><small>' + (feed.articles_success || 0) + ' success, ' + (feed.articles_imported || 0) + ' imported</small></td>';

            // RSS v2.0: Enabled column - Check both enabled_for_site and auto_import_enabled
            if (enabledForSite && autoEnabled) {
                html += '<td><span style="color: #10b981; font-weight: 600;">✅ Active</span></td>';
            } else if (enabledForSite) {
                html += '<td><span style="color: #f59e0b; font-weight: 600;">⚠️ Manual Only</span></td>';
            } else {
                html += '<td><span style="color: #6b7280;">⚪ Disabled</span></td>';
            }

            // v2.4.1: Show actual behavior (global frequency) instead of deprecated import_schedule_type
            html += '<td>' + (autoEnabled ? '✅ Enabled' : '⚪ Disabled') + '<br><small style="color: #2271b1;">Global frequency</small></td>';

            // WPML: Language cell (conditional)
            if (isWPMLActive) {
                const language = feed.target_language || 'Default';
                const langDisplay = language.toUpperCase();
                html += '<td><span style="padding: 2px 8px; background: #eff6ff; color: #1e40af; border-radius: 4px; font-size: 11px; font-weight: 600;">' + escapeHtml(langDisplay) + '</span></td>';
            }

            html += '<td>' + (feed.last_sync_text || 'Never') + '</td>';
            html += '<td>';
            html += '<button class="button view-articles" data-feed-id="' + feed.id + '">📥 Articles</button> ';
            html += '<button class="button configure-feed" data-feed-id="' + feed.id + '">⚙️ Configure</button> ';
            html += '<button class="button sync-feed-now" data-feed-id="' + feed.id + '">🔄 Sync Now</button>';
            html += '</td>';
            html += '</tr>';
        });

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

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Refresh feeds button
    $(document).on('click', '#refresh-feeds', function () {
        loadFeeds();
    });

    // RSS v2.0: Toggle unassigned feeds section (event delegation for dynamic content)
    $(document).on('click', '.unassigned-header', function () {
        const container = $('#unassigned-feeds-container');
        const toggle = $('#unassigned-toggle');

        if (container.is(':visible')) {
            container.slideUp();
            toggle.text('▼');
        } else {
            container.slideDown();
            toggle.text('▲');
        }
    });

    // =====================================================================
    // FEATURE 1: Feed Selection System
    // =====================================================================

    /**
     * Update Select All checkbox based on individual selections
     */
    function updateSelectAllCheckbox() {
        const $tables = $('.wp-list-table');
        $tables.each(function () {
            const $table = $(this);
            const total = $table.find('.select-feed-row').length;
            const checked = $table.find('.select-feed-row:checked').length;

            $table.find('.select-all-feeds').prop('checked', total > 0 && total === checked);
        });
    }

    /**
     * Show/hide bulk actions bar and update count
     */
    function updateBulkActionsBar() {
        const selectedCount = $('.select-feed-row:checked').length;

        if (selectedCount > 0) {
            $('#bulk-actions-bar').slideDown();
            $('#selected-count').text(selectedCount + ' feed' + (selectedCount !== 1 ? 's' : '') + ' selected');
        } else {
            $('#bulk-actions-bar').slideUp();
        }
    }

    /**
     * Get selected feed IDs
     * @returns {Array} Array of feed IDs
     */
    function getSelectedFeedIds() {
        const ids = [];
        $('.select-feed-row:checked').each(function () {
            ids.push($(this).val());
        });
        return ids;
    }

    // Select All checkbox toggle
    $(document).on('change', '.select-all-feeds', function () {
        const isChecked = $(this).is(':checked');
        $(this).closest('table').find('.select-feed-row').prop('checked', isChecked);
        updateBulkActionsBar();
    });

    // Individual checkbox changes
    $(document).on('change', '.select-feed-row', function () {
        updateBulkActionsBar();
        updateSelectAllCheckbox();
    });

    // Bulk activate feeds
    $(document).on('click', '#bulk-activate-feeds', function () {
        const selectedIds = $('.select-feed-row:checked').map(function () {
            return $(this).val();
        }).get();

        if (selectedIds.length === 0) {
            alert('Please select feeds first');
            return;
        }

        if (!confirm('Activate ' + selectedIds.length + ' feed(s) for this WordPress site?')) {
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).text('⏳ Activating...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_bulk_activate',
                feed_ids: selectedIds,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ Successfully activated ' + selectedIds.length + ' feed(s)');
                    loadFeeds();
                } else {
                    alert('❌ Failed: ' + (response.data.message || 'Unknown error'));
                }
            },
            error: function () {
                alert('❌ Network error occurred');
            },
            complete: function () {
                $btn.prop('disabled', false).text('⚡ Activate Selected');
            }
        });
    });

    // Bulk deactivate feeds
    $(document).on('click', '#bulk-deactivate-feeds', function () {
        const selectedIds = $('.select-feed-row:checked').map(function () {
            return $(this).val();
        }).get();

        if (selectedIds.length === 0) {
            alert('Please select feeds first');
            return;
        }

        if (!confirm('Deactivate ' + selectedIds.length + ' feed(s)? This will also disable auto-import.')) {
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).text('⏳ Deactivating...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_bulk_deactivate',
                feed_ids: selectedIds,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ Successfully deactivated ' + selectedIds.length + ' feed(s)');
                    loadFeeds();
                } else {
                    alert('❌ Failed: ' + (response.data.message || 'Unknown error'));
                }
            },
            error: function () {
                alert('❌ Network error occurred');
            },
            complete: function () {
                $btn.prop('disabled', false).text('⏸️ Deactivate Selected');
            }
        });
    });

    // RSS v2.0: Bulk configure feeds
    $(document).on('click', '#bulk-configure-feeds', function () {
        const selectedIds = $('.select-feed-row:checked').map(function () {
            return $(this).val();
        }).get();

        if (selectedIds.length === 0) {
            alert('Please select feeds first');
            return;
        }

        // Simple bulk configure: Enable auto-import + set schedule type
        const modalHtml = `
                    <div id="bulk-configure-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 100000; display: flex; align-items: center; justify-content: center; padding: 20px;">
                        <div style="background: white; width: 100%; max-width: 600px; border-radius: 8px; padding: 24px; max-height: 90vh; overflow-y: auto;">
                            <h2 style="margin: 0 0 20px 0;">⚙️ Configure ${selectedIds.length} Feed(s)</h2>

                            <div style="margin-bottom: 16px; padding: 12px; background: #ecfdf5; border-left: 3px solid #10b981; border-radius: 4px;">
                                <label style="display: flex; align-items: center; gap: 8px;">
                                    <input type="checkbox" id="bulk-enable-auto-import" checked>
                                    <strong>Enable auto-import for selected feeds</strong>
                                </label>
                            </div>

                            <div style="margin-bottom: 16px;">
                                <label style="display: block; font-weight: 600; margin-bottom: 8px;">Import Schedule</label>
                                <select id="bulk-import-schedule" class="regular-text" style="width: 100%;">
                                    <option value="every_5_minutes" ${wisewandRSS.globalDefaults.import_frequency === 'every_5_minutes' ? 'selected' : ''}>⚡ Every 5 Minutes (Live)</option>
                                    <option value="every_30_minutes" ${wisewandRSS.globalDefaults.import_frequency === 'every_30_minutes' ? 'selected' : ''}>⏱️ Every 30 Minutes</option>
                                    <option value="hourly" ${wisewandRSS.globalDefaults.import_frequency === 'hourly' ? 'selected' : ''}>⚡ Hourly</option>
                                    <option value="every_6_hours" ${wisewandRSS.globalDefaults.import_frequency === 'every_6_hours' ? 'selected' : ''}>🕐 Every 6 Hours (recommended)</option>
                                    <option value="daily" ${wisewandRSS.globalDefaults.import_frequency === 'daily' ? 'selected' : ''}>📆 Daily</option>
                                    <option value="custom" ${wisewandRSS.globalDefaults.import_frequency === 'custom' ? 'selected' : ''}>⚙️ Custom</option>
                                </select>
                            </div>

                            <div style="margin-bottom: 16px;">
                                <label style="display: block; font-weight: 600; margin-bottom: 8px;">Post Status</label>
                                <select id="bulk-post-status" class="regular-text" style="width: 100%;">
                                    <option value="publish" selected>✅ Published</option>
                                    <option value="draft">📄 Draft</option>
                                    <option value="pending">⏳ Pending</option>
                                </select>
                            </div>

                            <div style="display: flex; gap: 12px; margin-top: 24px; padding-top: 16px; border-top: 1px solid #e5e7eb;">
                                <button type="button" id="apply-bulk-config" class="button button-primary" style="flex: 1;">
                                    💾 Apply to ${selectedIds.length} Feed(s)
                                </button>
                                <button type="button" id="close-bulk-config" class="button">❌ Cancel</button>
                            </div>
                        </div>
                    </div>
                `;

        $('body').append(modalHtml);

        $('#close-bulk-config').on('click', () => $('#bulk-configure-modal').remove());

        $('#apply-bulk-config').on('click', function () {
            const settings = {
                auto_import_enabled: $('#bulk-enable-auto-import').is(':checked') ? 1 : 0,
                import_schedule_type: $('#bulk-import-schedule').val(),
                target_post_status: $('#bulk-post-status').val(),
            };

            $(this).prop('disabled', true).text('⏳ Applying...');

            // Apply settings to each selected feed
            let completed = 0;
            selectedIds.forEach(feedId => {
                $.ajax({
                    url: wisewandRSS.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_rss_save_feed_settings',
                        feed_id: feedId,
                        settings: settings,
                        nonce: wisewandRSS.nonce
                    },
                    success: function (response) {
                        completed++;
                        if (completed === selectedIds.length) {
                            alert('✅ Settings applied to ' + selectedIds.length + ' feed(s)');
                            $('#bulk-configure-modal').remove();
                            loadFeeds();
                        }
                    },
                    error: function () {
                        completed++;
                        if (completed === selectedIds.length) {
                            alert('⚠️ Some feeds failed to update. Please refresh and try again.');
                            $('#bulk-configure-modal').remove();
                            loadFeeds();
                        }
                    }
                });
            });
        });
    });

    // =====================================================================
    // FEATURE 2: Sync All Feeds
    // =====================================================================

    /**
     * Sync All Feeds
     * CLIENT-SIDE BATCH PROCESSING - Syncs feeds one at a time with live progress
     */
    $(document).on('click', '#sync-all-feeds', function (e) {
        e.preventDefault();

        const $btn = $(this);

        if (!confirm('Sync all enabled feeds? This will sync one feed at a time with live progress updates.')) {
            return;
        }

        // Disable button
        $btn.prop('disabled', true).html('⏳ Syncing All...');

        // Get all feed IDs from the table (all checkbox values)
        const feedIds = [];
        jQuery('tr[data-feed-id]').each(function () {
            const feedId = parseInt(jQuery(this).attr('data-feed-id'));
            if (feedId) {
                feedIds.push(feedId);
            }
        });

        if (feedIds.length === 0) {
            alert('No feeds found to sync');
            $btn.prop('disabled', false).html('⚡ Sync All Feeds');
            return;
        }

        // Start client-side batch sync
        if (!window.rssSyncProgress) {
            window.rssSyncProgress = new RssSyncProgress();
        }

        window.rssSyncProgress.syncFeedsSequentially(feedIds, true)
            .then(() => {
                $btn.prop('disabled', false).html('⚡ Sync All Feeds');
            })
            .catch((error) => {
                console.error('Sync error:', error);
                window.rssSyncProgress.hide();
                $btn.prop('disabled', false).html('⚡ Sync All Feeds');
                alert('❌ Sync failed: ' + error.message);
            });
    });

    // =====================================================================
    // FEATURE 3: Sync Selected Feeds
    // =====================================================================

    /**
     * Sync Selected Feeds
     * CLIENT-SIDE BATCH PROCESSING - Syncs selected feeds one at a time
     */
    $(document).on('click', '#bulk-sync-selected', function (e) {
        e.preventDefault();

        const selectedIds = getSelectedFeedIds();

        if (selectedIds.length === 0) {
            alert('Please select at least one feed to sync');
            return;
        }

        const $btn = $(this);

        if (!confirm('Sync ' + selectedIds.length + ' selected feed(s)? This will sync one feed at a time with live progress.')) {
            return;
        }

        $btn.prop('disabled', true).html('⏳ Syncing...');

        // Start client-side batch sync
        if (!window.rssSyncProgress) {
            window.rssSyncProgress = new RssSyncProgress();
        }

        window.rssSyncProgress.syncFeedsSequentially(selectedIds, true)
            .then(() => {
                $btn.prop('disabled', false).html('🔄 Sync Selected');

                // Clear selections
                $('.select-feed-row').prop('checked', false);
                updateBulkActionsBar();
            })
            .catch((error) => {
                console.error('Sync error:', error);
                window.rssSyncProgress.hide();
                $btn.prop('disabled', false).html('🔄 Sync Selected');
                alert('❌ Sync failed: ' + error.message);
            });
    });

    // =====================================================================
    // FEATURE 5: Enhanced Sync Button with Rate Limit Feedback
    // =====================================================================

    /**
     * Handle sync error with rate limit detection
     * @param {Object} response - AJAX response object
     * @param {string} feedName - Name of the feed being synced
     */
    function handleSyncError(response, feedName) {
        let errorMsg = 'Sync failed';

        if (response && response.data) {
            if (response.data.code === 'wisewand_rate_limit_exceeded' ||
                response.data.code === 'wisewand_rate_limited_client') {
                const retryAfter = response.data.retry_after || response.data.wait_time || 60;
                errorMsg = 'Rate limit reached for "' + feedName + '". Please wait ' + retryAfter + ' seconds before retrying.';
            } else {
                errorMsg = response.data.message || errorMsg;
            }
        }

        showErrorNotice(errorMsg);
    }

    // Sync feed now button (with rate limit detection)
    $(document).on('click', '.sync-feed-now', function () {
        const feedId = $(this).data('feed-id');
        const $btn = $(this);
        const $row = $btn.closest('tr');
        const feedName = $row.find('td:eq(1) strong').text();

        $btn.prop('disabled', true).text('⏳ Syncing...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_sync_feed',
                feed_id: feedId,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ Sync completed!\n\nDiscovered: ' + response.data.articles_discovered + '\nImported: ' + response.data.articles_imported + '\nFailed: ' + response.data.articles_failed);
                    loadFeeds();
                } else {
                    handleSyncError(response, feedName);
                }
            },
            error: function () {
                showErrorNotice('❌ Sync failed: Server error');
            },
            complete: function () {
                $btn.prop('disabled', false).text('🔄 Sync Now');
            }
        });
    });

    // View articles button - Opens modal with article list
    $(document).on('click', '.view-articles', function () {
        const feedId = $(this).data('feed-id');
        openArticlesModal(feedId);
    });

    // Configure feed button - Opens settings panel
    $(document).on('click', '.configure-feed', function () {
        const feedId = $(this).data('feed-id');
        openFeedSettings(feedId);
    });

    function openArticlesModal(feedId) {
        // Show modal with article list
        const modalHtml = `
                    <div id="rss-articles-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 100000; display: flex; align-items: center; justify-content: center;">
                        <div style="background: white; width: 90%; max-width: 1200px; max-height: 90%; overflow: auto; border-radius: 8px; padding: 24px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                                <h2 style="margin: 0;">📰 Feed Articles</h2>
                                <button class="button" id="close-articles-modal">✕ Close</button>
                            </div>
                            <div id="articles-table-container">
                                <div class="loading-spinner"><span class="spinner is-active"></span> Loading articles...</div>
                            </div>
                        </div>
                    </div>
                `;
        $('body').append(modalHtml);

        // Load articles
        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_get_articles',
                feed_id: feedId,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    renderArticlesTable(response.data.articles, feedId);
                } else {
                    $('#articles-table-container').html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>');
                }
            }
        });
    }

    function renderArticlesTable(articles, feedId) {
        if (articles.length === 0) {
            $('#articles-table-container').html('<p>No articles found for this feed.</p>');
            return;
        }

        let html = '<table class="wp-list-table widefat fixed striped"><thead><tr>';
        html += '<th><input type="checkbox" class="select-all-articles"></th>';
        html += '<th>Title</th>';
        html += '<th>Status</th>';
        html += '<th>Created</th>';
        html += '<th>Import Status</th>';
        html += '<th>Actions</th>';
        html += '</tr></thead><tbody>';

        articles.forEach(article => {
            const canImport = article.import_status === 'pending' && true;
            const isImported = article.import_status === 'imported';

            html += '<tr data-article-id="' + article.id + '" data-wisewand-article-id="' + article.wisewand_article_id + '">';
            html += '<td><input type="checkbox" class="select-article" value="' + article.wisewand_article_id + '" ' + (canImport ? '' : 'disabled') + '></td>';
            html += '<td><strong>' + escapeHtml(article.article_title) + '</strong></td>';
            html += '<td>' + formatDate(article.discovered_at) + '</td>';
            html += '<td>' + getImportStatusBadge(article.import_status, article.wordpress_post_id) + '</td>';
            html += '<td>';

            if (canImport) {
                html += '<button class="button button-small import-article" data-wisewand-article-id="' + article.wisewand_article_id + '" data-feed-id="' + feedId + '">📥 Import</button>';
            } else if (isImported && article.wordpress_post_id) {
                html += '<a href="post.php?post=' + article.wordpress_post_id + '&action=edit" class="button button-small">📝 Edit Post</a>';
            } else if (article.import_status === 'failed') {
                html += '<button class="button button-small retry-import" data-article-id="' + article.id + '">🔄 Retry</button>';
            }

            html += '</td>';
            html += '</tr>';
        });

        html += '</tbody></table>';
        html += '<div style="margin-top: 16px;">';
        html += '<button class="button button-primary" id="bulk-import-selected">📥 Import Selected Articles</button>';
        html += '</div>';

        $('#articles-table-container').html(html);
    }

    function getStatusBadge(status) {
        const badges = {
            'success': '<span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;">✅ Ready</span>',
            'error': '<span style="background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;">❌ Error</span>',
            'creating': '<span style="background: #dbeafe; color: #1e40af; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;">🔄 Creating</span>',
            'ready': '<span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;">✅ Ready</span>'
        };
        return badges[status] || status;
    }

    function getImportStatusBadge(status, postId) {
        const badges = {
            'pending': '<span style="color: #9ca3af;">⏳ Pending</span>',
            'importing': '<span style="color: #3b82f6;">🔄 Importing...</span>',
            'imported': '<span style="color: #10b981;">✅ Imported (#' + postId + ')</span>',
            'failed': '<span style="color: #ef4444;">❌ Failed</span>',
            'skipped': '<span style="color: #6b7280;">⊘ Skipped</span>'
        };
        return badges[status] || status;
    }

    function formatDate(dateStr) {
        if (!dateStr) return 'N/A';
        const date = new Date(dateStr);
        const now = new Date();
        const diff = now - date;
        const hours = Math.floor(diff / 3600000);
        const days = Math.floor(hours / 24);

        if (hours < 1) return 'Just now';
        if (hours < 24) return hours + 'h ago';
        if (days < 7) return days + 'd ago';
        return date.toLocaleDateString();
    }

    // Import single article
    $(document).on('click', '.import-article', function () {
        const $btn = $(this);
        const wisewandArticleId = $btn.data('wisewand-article-id');
        const feedId = $btn.data('feed-id');

        $btn.prop('disabled', true).text('⏳ Importing...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_import_article',
                wisewand_article_id: wisewandArticleId,
                feed_id: feedId,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ Article imported successfully!\n\nPost ID: #' + response.data.post_id);
                    $btn.closest('tr').find('td:eq(4)').html(getImportStatusBadge('imported', response.data.post_id));
                    $btn.replaceWith('<a href="post.php?post=' + response.data.post_id + '&action=edit" class="button button-small">📝 Edit Post</a>');
                } else {
                    alert('❌ Import failed: ' + response.data.message);
                    $btn.prop('disabled', false).text('📥 Import');
                }
            },
            error: function () {
                alert('❌ Import failed: Server error');
                $btn.prop('disabled', false).text('📥 Import');
            }
        });
    });

    // Select all checkbox
    $(document).on('change', '.select-all-articles', function () {
        $('.select-article:not(:disabled)').prop('checked', $(this).is(':checked'));
    });

    // Bulk import
    $(document).on('click', '#bulk-import-selected', function () {
        const selectedIds = $('.select-article:checked').map(function () {
            return $(this).val();
        }).get();

        if (selectedIds.length === 0) {
            alert('Please select articles to import');
            return;
        }

        if (!confirm('Import ' + selectedIds.length + ' articles?')) {
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).text('⏳ Importing ' + selectedIds.length + ' articles...');

        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_bulk_import',
                article_ids: selectedIds,
                feed_id: $('.select-article:checked').first().closest('tr').find('.import-article').data('feed-id'),
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    alert('✅ Bulk import completed!\n\nImported: ' + response.data.imported + '/' + response.data.total);
                    $('#close-articles-modal').click();
                } else {
                    alert('❌ Import failed: ' + response.data.message);
                }
            },
            complete: function () {
                $btn.prop('disabled', false).text('📥 Import Selected Articles');
            }
        });
    });

    // Close modal
    $(document).on('click', '#close-articles-modal', function () {
        $('#rss-articles-modal').remove();
    });

    function openFeedSettings(feedId) {
        // Load feed settings
        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_get_feed_settings',
                feed_id: feedId,
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success) {
                    renderSettingsPanel(response.data);
                } else {
                    alert('Failed to load feed settings: ' + response.data.message);
                }
            }
        });
    }

    function renderSettingsPanel(data) {
        const feed = data.feed;
        const authors = data.authors || [];
        const categories = data.categories || [];

        const modalHtml = `
                    <div id="rss-settings-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 100000; display: flex; align-items: center; justify-content: center; overflow-y: auto; padding: 20px;">
                        <div style="background: white; width: 100%; max-width: 800px; border-radius: 8px; padding: 0; max-height: 95vh; overflow-y: auto;">
                            <div style="padding: 24px; border-bottom: 1px solid #e2e8f0; background: linear-gradient(135deg, #3b82f6 0%, #00bcd4 100%); color: white; border-radius: 8px 8px 0 0;">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <h2 style="margin: 0; color: white;">⚙️ Feed Configuration</h2>
                                        <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 14px;">${escapeHtml(feed.feed_name)}</p>
                                    </div>
                                    <button class="button" id="close-settings-modal" style="background: rgba(255,255,255,0.2); border: none; color: white;">✕ Close</button>
                                </div>
                            </div>

                            <div style="padding: 24px;">
                                <!-- Feed Info -->
                                <div style="margin-bottom: 24px; padding: 16px; background: #f9fafb; border-radius: 6px; border-left: 3px solid #3b82f6;">
                                    <h3 style="margin: 0 0 12px 0; font-size: 14px; color: #6b7280;">📡 Feed Information (from Wisewand)</h3>
                                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; font-size: 13px;">
                                        <div><strong>Source:</strong> <a href="${escapeHtml(feed.feed_url)}" target="_blank">${escapeHtml(feed.feed_url)}</a></div>
                                        <div><strong>Frequency:</strong> ${escapeHtml(feed.wisewand_frequency)}</div>
                                        <div><strong>Limit:</strong> ${feed.wisewand_limit} article(s) per sync</div>
                                        <div><strong>Cost:</strong> ${feed.wisewand_cost} credits/article</div>
                                    </div>
                                    <p style="margin: 12px 0 0 0; font-size: 12px; color: #6b7280;">
                                        <a href="https://app.wisewand.ai/feeds" target="_blank">📝 Edit feed in Wisewand →</a>
                                    </p>
                                </div>

                                <!-- Effective Configuration Preview (v2.4.0) -->
                                <div class="wisewand-config-preview" style="background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:#fff; border-radius:8px; padding:20px; margin-bottom:20px; box-shadow:0 4px 6px rgba(0,0,0,0.1);">
                                    <h3 style="margin:0 0 15px 0; color:#fff; font-size:16px;">
                                        📋 Effective Configuration
                                    </h3>
                                    <p style="margin:0 0 10px 0; opacity:0.9; font-size:13px;">
                                        This feed will use the following settings:
                                    </p>
                                    <ul id="config-preview-list" style="margin:0; padding:0; list-style:none; font-size:14px;">
                                        <li style="padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.2);">
                                            <strong>⏱️ Check Frequency:</strong>
                                            <span id="preview-frequency">Every 5 minutes (global)</span>
                                        </li>
                                        <li style="padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.2);">
                                            <strong>📅 Publish Articles At:</strong>
                                            <span id="preview-publish" style="font-size:16px; font-weight:bold;">${data.global_settings?.schedule_time || '17:11'} (global)</span>
                                        </li>
                                        <li style="padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.2);">
                                            <strong>👤 Author:</strong>
                                            <span id="preview-author">${data.global_settings?.author_name || 'Default Author'} (${feed.inherit_author != 0 ? 'global' : 'custom'})</span>
                                        </li>
                                        <li style="padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.2);">
                                            <strong>📂 Categories:</strong>
                                            <span id="preview-categories">${feed.target_categories && feed.target_categories.length > 0 ? 'Custom categories' : 'From global settings (global)'}</span>
                                        </li>
                                        <li style="padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.2);">
                                            <strong>🔢 Max Articles/Sync:</strong>
                                            <span id="preview-max">${feed.inherit_max_articles != 0 ? (data.global_settings?.max_articles || '10') + ' (global)' : (feed.max_articles_per_sync || '10') + ' (custom)'}</span>
                                        </li>
                                        <li style="padding:6px 0;">
                                            <strong>🤖 AI Category Matching:</strong>
                                            <span id="preview-ai">${feed.inherit_ai_categories != 0 ? (data.global_settings?.ai_categories ? 'Enabled (global)' : 'Disabled (global)') : (feed.use_ai_category_matching ? 'Enabled (custom)' : 'Disabled (custom)')}</span>
                                        </li>
                                    </ul>
                                </div>

                                <p style="margin: 5px 0 0 24px; font-size: 12px; color: #0284c7;">
                                    When enabled, this feed will use the settings defined in <a href="admin.php?page=wisewand-settings#wisewand-rss-defaults" target="_blank">Global RSS Defaults</a>.
                                    Uncheck to override specific settings for this feed.
                                </p>
                                <form id="feed-settings-form">
                                    <input type="hidden" name="feed_id" value="${feed.id}">

                                    <!-- Auto-Import Enable -->
                                    <div style="margin-bottom: 24px;">
                                        <label style="display: flex; align-items: center; gap: 12px; cursor: pointer; padding: 16px; background: #ecfdf5; border: 2px solid #10b981; border-radius: 8px;">
                                            <input type="checkbox" name="auto_import_enabled" id="auto-import-toggle" value="1" ${feed.auto_import_enabled ? 'checked' : ''} style="width: 20px; height: 20px;">
                                            <div>
                                                <strong style="font-size: 15px; color: #065f46;">🤖 Enable Automatic Import</strong>
                                                <p style="margin: 4px 0 0 0; font-size: 12px; color: #047857;">WordPress will automatically import new articles from this feed based on the schedule below</p>
                                            </div>
                                        </label>
                                    </div>

                                    <div id="automation-settings" style="${feed.auto_import_enabled ? '' : 'display:none;'}">
                                        <!-- Import Schedule section REMOVED in v2.4.0 -->
                                        <!-- These fields (import_schedule_type, import_schedule_time, import_schedule_days) -->
                                        <!-- are deprecated and ignored by CRON system. -->
                                        <!-- Discovery frequency is controlled by Global RSS Defaults only. -->

                                        <!-- Max Articles -->
                                        <div class="feed-setting-row" style="margin-bottom: 20px;">
                                            <label class="inherit-label" style="display: block; margin-bottom: 12px; padding: 12px; background: #eff6ff; border-left: 3px solid #3b82f6; border-radius: 4px; cursor: pointer;">
                                                <input type="checkbox" name="inherit_max_articles" value="1" ${feed.inherit_max_articles != 0 ? 'checked' : ''} style="margin-right: 8px;">
                                                <strong>🌐 Use Global Max Articles</strong>
                                                <span style="color: #6b7280; font-size: 12px;"> (currently: ${data.global_settings?.max_articles || '10'})</span>
                                            </label>
                                            <div class="custom-control" style="${feed.inherit_max_articles != 0 ? 'display:none;' : ''}">
                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">📊 Max Articles per Sync</label>
                                                <input type="number" name="max_articles_per_sync" min="1" max="50" value="${feed.max_articles_per_sync || 10}" class="small-text">
                                                <p style="margin: 4px 0 0 0; font-size: 12px; color: #6b7280;">Limit how many articles to import in each sync to avoid overload</p>
                                            </div>
                                        </div>

                                        <!-- Post Status (Deprecated - kept for backward compatibility) -->
                                        <div style="margin-bottom: 20px; display: none;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">📝 WordPress Post Status</label>
                                            <select name="target_post_status" class="regular-text" style="width: 100%;">
                                                <option value="publish" ${feed.target_post_status === 'publish' ? 'selected' : ''}>✅ Published (live immediately)</option>
                                                <option value="draft" ${feed.target_post_status === 'draft' ? 'selected' : ''}>📄 Draft (review before publishing)</option>
                                                <option value="pending" ${feed.target_post_status === 'pending' ? 'selected' : ''}>⏳ Pending Review</option>
                                                <option value="future" ${feed.target_post_status === 'future' ? 'selected' : ''}>📅 Scheduled</option>
                                            </select>
                                        </div>

                                        <!-- When to Publish Articles (v2.4.0 - Simplified UX) -->
                                        <div style="margin-bottom: 20px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">
                                                🕐 When to Publish Articles
                                                <span class="dashicons dashicons-info-outline" title="Controls when imported articles appear on your website. Articles are imported immediately, then published at the time you choose." style="font-size: 16px; vertical-align: middle; color: #6b7280; cursor: help;"></span>
                                            </label>
                                            <select name="feed_publish_mode" id="feed_publish_mode" class="regular-text" style="width: 100%;">
                                                <option value="inherit" ${(!feed.inherit_publish_mode || feed.inherit_publish_mode == 1) && !feed.schedule_mode ? 'selected' : ''}>🌐 Use Global Setting (currently: ${data.global_settings?.schedule_time || '17:11'})</option>
                                                <option value="specific_time" ${feed.schedule_mode === 'custom' && feed.schedule_time ? 'selected' : ''}>🕐 Specific Time Daily</option>
                                                <option value="time_range" ${feed.publication_time_range && feed.schedule_mode !== 'custom' ? 'selected' : ''}>🎲 Random Time in Range</option>
                                                <option value="immediate" ${feed.publish_mode === 'publish' ? 'selected' : ''}>⚡ Publish Immediately</option>
                                                <option value="draft" ${feed.publish_mode === 'draft' ? 'selected' : ''}>📄 Save as Draft (Manual Review)</option>
                                            </select>
                                            <p class="description" style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">
                                                Articles are imported immediately when discovered. This setting controls when they become visible on your website.
                                            </p>

                                            <!-- Conditional: Specific Time Fields -->
                                            <div id="specific_time_fields" class="wisewand-conditional-field" style="display:none; margin-top:15px; padding:15px; background:#f6f7f7; border-left:3px solid #2271b1; border-radius:4px;">
                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">
                                                    Publication Time:
                                                </label>
                                                <input type="time"
                                                       name="feed_schedule_time"
                                                       id="feed_schedule_time"
                                                       value="${feed.schedule_time || '18:03'}"
                                                       class="regular-text" />
                                                <p class="description" style="margin: 8px 0 0 0; font-size: 12px;">
                                                    Example: 18:03 means articles will publish at 6:03 PM every day.
                                                </p>

                                                <!-- Days of Week -->
                                                <div style="margin-top:10px;">
                                                    <strong style="display: block; margin-bottom: 8px;">Days:</strong>
                                                    <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                                        ${generatePublicationDayCheckboxes(feed.publication_allowed_days)}
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Conditional: Time Range Fields -->
                                            <div id="time_range_fields" class="wisewand-conditional-field" style="display:none; margin-top:15px; padding:15px; background:#f6f7f7; border-left:3px solid #2271b1; border-radius:4px;">
                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">
                                                    Time Range:
                                                </label>
                                                <select name="feed_time_range" id="feed_time_range" class="regular-text" style="width: 100%;">
                                                    <option value="morning" ${feed.publication_time_range === 'morning' ? 'selected' : ''}>🌅 Morning (9 AM - 12 PM)</option>
                                                    <option value="afternoon" ${feed.publication_time_range === 'afternoon' ? 'selected' : ''}>☀️ Afternoon (12 PM - 5 PM)</option>
                                                    <option value="evening" ${(feed.publication_time_range === 'evening' || !feed.publication_time_range) ? 'selected' : ''}>🌆 Evening (5 PM - 8 PM)</option>
                                                    <option value="random" ${feed.publication_time_range === 'random' ? 'selected' : ''}>🎲 Random (9 AM - 8 PM)</option>
                                                </select>
                                                <p class="description" style="margin: 8px 0 0 0; font-size: 12px;">
                                                    Each article will be published at a random time within this range.
                                                </p>
                                            </div>
                                        </div>

                                        <!-- Author -->
                                        <div class="feed-setting-row" style="margin-bottom: 20px;">
                                            <label class="inherit-label" style="display: block; margin-bottom: 12px; padding: 12px; background: #eff6ff; border-left: 3px solid #3b82f6; border-radius: 4px; cursor: pointer;">
                                                <input type="checkbox" name="inherit_author" value="1" ${feed.inherit_author != 0 ? 'checked' : ''} style="margin-right: 8px;">
                                                <strong>🌐 Use Global Author</strong>
                                                <span style="color: #6b7280; font-size: 12px;"> (currently: ${data.global_settings?.author_name || 'default'})</span>
                                            </label>
                                            <div class="custom-control" style="${feed.inherit_author != 0 ? 'display:none;' : ''}">
                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">👤 Author</label>
                                                <select name="target_author" class="regular-text" style="width: 100%;">
                                                    <option value="">-- Select Author --</option>
                                                    ${authors.map(author =>
            `<option value="${author.ID}" ${feed.target_author == author.ID ? 'selected' : ''}>${escapeHtml(author.display_name)}</option>`
        ).join('')}
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Categories -->
                                        <div style="margin-bottom: 20px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">📁 Categories</label>
                                            <div id="categories-container" style="max-height: 200px; overflow-y: auto; border: 1px solid #d1d5db; border-radius: 4px; padding: 12px; background: white;">
                                                ${renderCategoriesCheckboxes(categories, feed.target_categories)}
                                            </div>
                                        </div>

                                        <!-- WPML Language Selector (Conditional) -->
                                        ${data.wpml_active ? `
                                        <div style="margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(16, 185, 129, 0.1) 100%); border-left: 3px solid #3b82f6; border-radius: 6px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">🌐 Target Language (WPML)</label>
                                            <select name="target_language" class="regular-text" style="width: 100%;">
                                                <option value="">-- Use Default Language --</option>
                                                ${(data.wpml_languages || []).map(lang =>
            `<option value="${lang.code}" ${feed.target_language === lang.code ? 'selected' : ''}>${escapeHtml(lang.display_name)} (${lang.code})</option>`
        ).join('')}
                                            </select>
                                            <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">
                                                📝 All articles imported from this feed will be assigned to the selected language.
                                                Leave as default to use the site's primary language.
                                            </p>
                                        </div>
                                        ` : ''}

                                        <!-- AI Category Matching -->
                                        <div class="feed-setting-row" style="margin-bottom: 20px;">
                                            <label class="inherit-label" style="display: block; margin-bottom: 12px; padding: 12px; background: #eff6ff; border-left: 3px solid #3b82f6; border-radius: 4px; cursor: pointer;">
                                                <input type="checkbox" name="inherit_ai_categories" value="1" ${feed.inherit_ai_categories != 0 ? 'checked' : ''} style="margin-right: 8px;">
                                                <strong>🌐 Use Global AI Category Setting</strong>
                                                <span style="color: #6b7280; font-size: 12px;"> (currently: ${data.global_settings?.ai_categories ? 'enabled' : 'disabled'})</span>
                                            </label>
                                            <div class="custom-control" style="${feed.inherit_ai_categories != 0 ? 'display:none;' : ''}">
                                                <div style="padding: 16px; background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%); border-left: 3px solid #10b981; border-radius: 6px;">
                                                    <label style="display: flex; align-items: start; gap: 12px; cursor: pointer;">
                                                        <input type="checkbox" name="use_ai_category_matching" value="1" ${feed.use_ai_category_matching ? 'checked' : ''} style="width: 20px; height: 20px; margin-top: 2px;">
                                                        <div>
                                                            <strong style="font-size: 14px; color: #065f46;">🤖 AI Category Matching</strong>
                                                            <p style="margin: 4px 0 0 0; font-size: 12px; color: #047857;">
                                                                When enabled and no manual categories selected, OpenAI will automatically match articles to relevant WordPress categories.
                                                                Uses the same AI matcher from SEO Intelligence.
                                                            </p>
                                                            ${!data.openai_configured ? '<p style="margin: 8px 0 0 0; font-size: 12px; color: #f59e0b;"><strong>⚠️ OpenAI API key required</strong> - Configure in Settings</p>' : '<p style="margin: 8px 0 0 0; font-size: 12px; color: #10b981;">✅ OpenAI configured (~$0.0001 per article)</p>'}
                                                        </div>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Publication Time Control section REMOVED in v2.4.0 -->
                                        <!-- Replaced by simplified "When to Publish Articles" dropdown above -->
                                    </div>

                                    <!-- Save Button -->
                                    <div style="display: flex; gap: 12px; padding-top: 20px; border-top: 1px solid #e2e8f0;">
                                        <button type="submit" class="button button-primary button-large" style="flex: 1;">💾 Save Settings</button>
                                        <button type="button" class="button button-large" id="close-settings-modal-btn">❌ Cancel</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                `;

        $('body').append(modalHtml);

        // Load and display global publication settings
        loadGlobalPublicationSettings();

        // v2.4.0: Update config preview in real-time
        function updateConfigPreview() {
            // 1. Check Frequency (always global in v2.3.0+)
            $('#preview-frequency').text('Every 5 minutes (global)');

            // 2. Publish Time
            const publishMode = $('#feed_publish_mode').val();
            let publishText = '';

            switch(publishMode) {
                case 'inherit':
                    const globalTime = data.global_settings?.schedule_time || '17:11';
                    publishText = globalTime + ' (global)';
                    break;
                case 'specific_time':
                    const time = $('#feed_schedule_time').val() || '18:03';
                    publishText = time + ' (custom for this feed)';
                    break;
                case 'time_range':
                    const range = $('#feed_time_range option:selected').text();
                    publishText = range + ' (custom for this feed)';
                    break;
                case 'immediate':
                    publishText = 'Immediately when discovered (custom)';
                    break;
                case 'draft':
                    publishText = 'Not published - saved as draft (custom)';
                    break;
            }
            $('#preview-publish').html(publishText);

            // 3. Author
            const useGlobalAuthor = $('input[name="inherit_author"]').is(':checked');
            if (useGlobalAuthor) {
                $('#preview-author').text((data.global_settings?.author_name || 'Default Author') + ' (global)');
            } else {
                const author = $('select[name="target_author"] option:selected').text();
                $('#preview-author').text(author + ' (custom)');
            }

            // 4. Categories
            const useGlobalCat = $('input[name="inherit_categories"]').is(':checked');
            if (useGlobalCat) {
                $('#preview-categories').text('From global settings (global)');
            } else {
                const cats = [];
                $('input[name="target_categories[]"]:checked').each(function() {
                    cats.push($(this).next('label').text().trim());
                });
                const catText = cats.length > 0 ? cats.join(', ') : 'None selected';
                $('#preview-categories').text(catText + ' (custom)');
            }

            // 5. Max Articles
            const useGlobalMax = $('input[name="inherit_max_articles"]').is(':checked');
            if (useGlobalMax) {
                $('#preview-max').text((data.global_settings?.max_articles || '10') + ' (global)');
            } else {
                const max = $('input[name="max_articles_per_sync"]').val();
                $('#preview-max').text(max + ' (custom)');
            }

            // 6. AI Category
            const useGlobalAI = $('input[name="inherit_ai_categories"]').is(':checked');
            if (useGlobalAI) {
                $('#preview-ai').text(data.global_settings?.ai_categories ? 'Enabled (global)' : 'Disabled (global)');
            } else {
                const aiEnabled = $('input[name="use_ai_category_matching"]').is(':checked');
                $('#preview-ai').text(aiEnabled ? 'Enabled (custom)' : 'Disabled (custom)');
            }
        }

        // v2.4.0: Show/hide conditional fields for publish mode
        function updatePublishModeFields() {
            const mode = $('#feed_publish_mode').val();

            // Hide all conditional fields
            $('.wisewand-conditional-field').hide();

            // Show relevant fields
            if (mode === 'specific_time') {
                $('#specific_time_fields').slideDown();
            } else if (mode === 'time_range') {
                $('#time_range_fields').slideDown();
            }

            // Update preview
            updateConfigPreview();
        }

        // Initialize and attach event handlers (v2.4.0)
        updatePublishModeFields(); // Initial state
        updateConfigPreview(); // Initial preview

        $('#feed_publish_mode').on('change', updatePublishModeFields);

        // Update preview on any field change
        $('#feed_schedule_time, #feed_time_range, input[name="inherit_author"], select[name="target_author"], input[name="inherit_categories"], input[name="target_categories[]"], input[name="inherit_max_articles"], input[name="max_articles_per_sync"], input[name="inherit_ai_categories"], input[name="use_ai_category_matching"]').on('change', updateConfigPreview);

        // Show/hide automation settings
        $('#auto-import-toggle').on('change', function () {
            $('#automation-settings').toggle($(this).is(':checked'));
        });

        // Handle inheritance checkbox toggle
        $('.inherit-label input[type="checkbox"]').on('change', function() {
            const $control = $(this).closest('.feed-setting-row').find('.custom-control');
            if ($(this).is(':checked')) {
                $control.slideUp(200);
            } else {
                $control.slideDown(200);
            }
            updateConfigPreview(); // Update preview when inheritance changes
        });

        // Close modal handlers
        $('#close-settings-modal, #close-settings-modal-btn').on('click', function () {
            $('#rss-settings-modal').remove();
        });

        // Save settings
        $('#feed-settings-form').on('submit', function (e) {
            e.preventDefault();

            const $form = $(this);
            const formData = $form.serializeArray();
            const settings = {};

            formData.forEach(field => {
                if (field.name.includes('schedule_days')) {
                    if (!settings.import_schedule_days) {
                        settings.import_schedule_days = [];
                    }
                    settings.import_schedule_days.push(field.value);
                } else if (field.name.includes('target_categories')) {
                    if (!settings.target_categories) {
                        settings.target_categories = [];
                    }
                    settings.target_categories.push(field.value);
                } else if (field.name.includes('publication_allowed_days')) {
                    // RSS v2.0: Publication allowed days
                    if (!settings.publication_allowed_days) {
                        settings.publication_allowed_days = [];
                    }
                    settings.publication_allowed_days.push(field.value);
                } else {
                    settings[field.name] = field.value;
                }
            });

            /**
             * Enhanced checkbox capture with comprehensive fallbacks
             * Layer 1: Multi-method checkbox value capture
             *
             * @param {string} fieldName - Name attribute of the checkbox
             * @return {number} 1 if checked, 0 if unchecked
             */
            function captureCheckboxValue(fieldName) {
                const $checkbox = $('#feed-settings-form input[name="' + fieldName + '"]');

                // Method 1: jQuery .is(':checked')
                const isCheckedJQuery = $checkbox.is(':checked');

                // Method 2: DOM .checked property
                const isCheckedDOM = $checkbox[0] ? $checkbox[0].checked : false;

                // Method 3: .prop('checked')
                const isCheckedProp = $checkbox.prop('checked');

                // Verification: All methods must agree
                if (isCheckedJQuery !== isCheckedDOM || isCheckedJQuery !== isCheckedProp) {
                    console.warn('⚠️ CHECKBOX CAPTURE MISMATCH for ' + fieldName + '!');
                    console.warn('  jQuery: ' + isCheckedJQuery);
                    console.warn('  DOM: ' + isCheckedDOM);
                    console.warn('  Prop: ' + isCheckedProp);
                }

                // Layer 2: Comprehensive logging
                const finalValue = isCheckedJQuery ? 1 : 0;
                console.log('📋 Checkbox capture for ' + fieldName + ': ' + finalValue + ' (checked: ' + isCheckedJQuery + ')');

                return finalValue;
            }

            // v1.2.9+: Explicitly handle ALL checkboxes with enhanced capture
            settings.auto_import_enabled = captureCheckboxValue('auto_import_enabled');
            settings.use_ai_category_matching = captureCheckboxValue('use_ai_category_matching');

            // Phase 1: Capture inheritance flags
            settings.inherit_import_frequency = captureCheckboxValue('inherit_import_frequency');
            settings.inherit_max_articles = captureCheckboxValue('inherit_max_articles');
            settings.inherit_publish_mode = captureCheckboxValue('inherit_publish_mode');
            settings.inherit_author = captureCheckboxValue('inherit_author');
            settings.inherit_ai_categories = captureCheckboxValue('inherit_ai_categories');

            // v1.3.2: CRITICAL FIX - Explicitly capture category checkboxes
            // serializeArray() only includes CHECKED checkboxes, so we must read them explicitly
            const selectedCategories = [];
            $('#feed-settings-form input[name="target_categories[]"]:checked').each(function () {
                const catId = parseInt($(this).val());
                if (catId > 0) {
                    selectedCategories.push(catId);
                }
            });
            settings.target_categories = selectedCategories;  // Array, will be stringified below

            console.log('📋 Captured category checkboxes: ' + selectedCategories.length + ' selected');
            console.log('  Category IDs: ' + JSON.stringify(selectedCategories));

            // Convert arrays to proper format
            if (settings.import_schedule_days) {
                settings.import_schedule_days = settings.import_schedule_days.join(',');
            }
            // Convert categories array to JSON string
            settings.target_categories = JSON.stringify(settings.target_categories);  // Always stringify, even if empty
            // RSS v2.0: Publication allowed days
            if (settings.publication_allowed_days) {
                settings.publication_allowed_days = JSON.stringify(settings.publication_allowed_days);
            }

            // RSS v2.0: Publication schedule mode (convert radio to boolean)
            settings.use_custom_publication_schedule = ($('input[name="publication_schedule_mode"]:checked').val() === 'custom') ? 1 : 0;

            // Layer 4: Pre-flight verification - Log EVERYTHING being sent
            console.log('🚀 PRE-FLIGHT CHECK: Settings being sent to server:');
            console.log('  feed_id: ' + settings.feed_id);
            console.log('  auto_import_enabled: ' + settings.auto_import_enabled);
            console.log('  use_ai_category_matching: ' + settings.use_ai_category_matching);
            console.log('  use_custom_publication_schedule: ' + settings.use_custom_publication_schedule);
            console.log('  target_categories: ' + settings.target_categories);  // v1.3.2: Added
            console.log('  target_author: ' + settings.target_author);  // v1.3.2: Added
            console.log('  custom_interval_hours: ' + settings.custom_interval_hours);
            console.log('  publication_time_range: ' + settings.publication_time_range);
            console.log('  publication_allowed_days: ' + settings.publication_allowed_days);
            console.log('  Full settings object:', settings);

            // Save
            $.ajax({
                url: wisewandRSS.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wisewand_rss_save_feed_settings',
                    feed_id: settings.feed_id,
                    settings: settings,
                    nonce: wisewandRSS.nonce
                },
                success: function (response) {
                    if (response.success) {
                        // Layer 5: Server echo verification
                        if (response.data.saved_values) {
                            console.log('✅ SERVER ECHO - Values confirmed saved:');
                            console.log('  auto_import_enabled: ' + response.data.saved_values.auto_import_enabled);
                            console.log('  use_ai_category_matching: ' + response.data.saved_values.use_ai_category_matching);
                            console.log('  use_custom_publication_schedule: ' + response.data.saved_values.use_custom_publication_schedule);
                            console.log('  custom_interval_hours: ' + response.data.saved_values.custom_interval_hours);

                            // Verify client vs server match
                            const mismatches = [];
                            if (settings.auto_import_enabled != response.data.saved_values.auto_import_enabled) {
                                mismatches.push('auto_import_enabled: sent ' + settings.auto_import_enabled + ' but saved ' + response.data.saved_values.auto_import_enabled);
                            }
                            if (settings.use_ai_category_matching != response.data.saved_values.use_ai_category_matching) {
                                mismatches.push('use_ai_category_matching: sent ' + settings.use_ai_category_matching + ' but saved ' + response.data.saved_values.use_ai_category_matching);
                            }
                            if (settings.use_custom_publication_schedule != response.data.saved_values.use_custom_publication_schedule) {
                                mismatches.push('use_custom_publication_schedule: sent ' + settings.use_custom_publication_schedule + ' but saved ' + response.data.saved_values.use_custom_publication_schedule);
                            }

                            if (mismatches.length > 0) {
                                console.error('❌ CLIENT/SERVER MISMATCH DETECTED:');
                                mismatches.forEach(function (msg) {
                                    console.error('  - ' + msg);
                                });
                            } else {
                                console.log('✅ All values match between client and server!');
                            }
                        } else {
                            console.warn('⚠️ Server did not return saved_values for verification');
                        }

                        alert('✅ Settings saved successfully!');
                        $('#rss-settings-modal').remove();
                        loadFeeds(); // Refresh feeds list
                    } else {
                        alert('❌ Failed to save: ' + response.data.message);
                    }
                },
                error: function () {
                    alert('❌ Failed to save settings');
                }
            });
        });
    }

    function generateDayCheckboxes(selectedDays) {
        const days = [
            { value: '1', label: 'Mon' },
            { value: '2', label: 'Tue' },
            { value: '3', label: 'Wed' },
            { value: '4', label: 'Thu' },
            { value: '5', label: 'Fri' },
            { value: '6', label: 'Sat' },
            { value: '7', label: 'Sun' }
        ];

        const selected = selectedDays ? selectedDays.split(',') : ['1', '2', '3', '4', '5'];

        return days.map(day => {
            const checked = selected.includes(day.value) ? 'checked' : '';
            return `<label style="padding: 8px 16px; background: white; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px;">
                        <input type="checkbox" name="import_schedule_days[]" value="${day.value}" ${checked}>
                        <span style="font-size: 13px; font-weight: 500;">${day.label}</span>
                    </label>`;
        }).join('');
    }

    function renderCategoriesCheckboxes(categories, selectedCategoriesJson) {
        const selected = selectedCategoriesJson ? JSON.parse(selectedCategoriesJson) : [];

        if (categories.length === 0) {
            return '<p style="color: #6b7280;">No categories available. Create categories in WordPress first.</p>';
        }

        return categories.map(cat => {
            const checked = selected.includes(cat.term_id) ? 'checked' : '';
            return `<label style="display: block; padding: 8px; border-bottom: 1px solid #f3f4f6; cursor: pointer;">
                        <input type="checkbox" name="target_categories[]" value="${cat.term_id}" ${checked}>
                        <span style="margin-left: 8px; font-size: 13px;">${escapeHtml(cat.name)}</span>
                    </label>`;
        }).join('');
    }

    // RSS v2.0: Generate publication day checkboxes
    function generatePublicationDayCheckboxes(selectedDaysJson) {
        const days = [
            { value: '1', label: 'Mon' },
            { value: '2', label: 'Tue' },
            { value: '3', label: 'Wed' },
            { value: '4', label: 'Thu' },
            { value: '5', label: 'Fri' },
            { value: '6', label: 'Sat' },
            { value: '7', label: 'Sun' }
        ];

        let selected = ['1', '2', '3', '4', '5']; // Default: Mon-Fri
        if (selectedDaysJson) {
            try {
                selected = JSON.parse(selectedDaysJson);
            } catch (e) {
                selected = selectedDaysJson.split(',');
            }
        }

        return days.map(day => {
            const checked = selected.includes(day.value) ? 'checked' : '';
            return `<label style="padding: 8px 16px; background: white; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px;">
                        <input type="checkbox" name="publication_allowed_days[]" value="${day.value}" ${checked}>
                        <span style="font-size: 13px; font-weight: 500;">${day.label}</span>
                    </label>`;
        }).join('');
    }

    // RSS v2.1: Generate hour options (00:00 - 23:00)
    function generateHourOptions(selectedTime) {
        let html = '';
        // Extract hour from "HH:MM:SS" or "HH:MM" string
        let selectedHour = 9; // Default 9 AM
        if (selectedTime) {
            const parts = selectedTime.split(':');
            if (parts.length > 0) {
                selectedHour = parseInt(parts[0], 10);
            }
        }

        for (let i = 0; i < 24; i++) {
            const hourStr = i.toString().padStart(2, '0') + ':00';
            const isSelected = (i === selectedHour) ? 'selected' : '';
            const label = hourStr; // e.g. "09:00"

            // Add friendly label for common times
            let suffix = '';
            if (i === 0) suffix = ' (Midnight)';
            else if (i === 12) suffix = ' (Noon)';
            else if (i < 12) suffix = ' AM';
            else suffix = ' PM';

            // Simple 12h format for readability
            let displayHour = i;
            if (i > 12) displayHour = i - 12;
            if (i === 0) displayHour = 12;

            html += `<option value="${hourStr}" ${isSelected}>${hourStr} (${displayHour}${suffix})</option>`;
        }
        return html;
    }

    // RSS v2.0: Load and display global publication settings
    function loadGlobalPublicationSettings() {
        // Fetch global settings from WordPress options
        $.ajax({
            url: wisewandRSS.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wisewand_rss_get_global_publication_settings',
                nonce: wisewandRSS.nonce
            },
            success: function (response) {
                if (response.success && response.data) {
                    const timeRangeMap = {
                        'random': 'Random (9 AM - 8 PM)',
                        'morning': 'Morning (9 AM - 12 PM)',
                        'afternoon': 'Afternoon (12 PM - 5 PM)',
                        'evening': 'Evening (5 PM - 8 PM)'
                    };

                    const dayMap = { 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun' };
                    const allowedDays = (response.data.allowed_days || []).map(d => dayMap[d]).join(', ');

                    const preview = `${timeRangeMap[response.data.time_range] || 'Random'}, ${allowedDays || 'Mon-Fri'}`;
                    $('#global-settings-preview').text(preview);
                }
            }
        });
    }

    // =====================================================================
    // FEATURE 4: RSS Sync Progress UI (v1.2.0)
    // Beautiful progress modal with gradient bar and live logs
    // =====================================================================

    /**
     * RSS Sync Progress UI (v1.2.0)
     * Beautiful progress modal with gradient bar and live logs
     */
    class RssSyncProgress {
        constructor() {
            this.totalFeeds = 0;
            this.completedFeeds = 0;
            this.logs = [];
            this.modalId = 'rss-sync-progress-modal';
        }

        /**
         * Show progress modal
         */
        show(totalFeeds = 0) {
            this.totalFeeds = totalFeeds;
            this.completedFeeds = 0;
            this.logs = [];

            const html = `
                        <div id="${this.modalId}" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.25); z-index: 100000; min-width: 600px; max-width: 700px;">
                            <h2 style="margin: 0 0 24px 0; font-size: 22px; font-weight: 600; color: #1d2327;">RSS Feed Synchronization</h2>

                            <!-- Progress Bar Container -->
                            <div style="margin-bottom: 20px;">
                                <div style="background: #e0e0e0; height: 8px; border-radius: 4px; overflow: hidden; position: relative;">
                                    <div id="rss-progress-bar" style="width: 0%; height: 100%; background: linear-gradient(90deg, #00a32a 0%, #0073aa 100%); transition: width 0.3s ease; position: relative;">
                                        <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(90deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 50%, rgba(255,255,255,0.3) 100%); animation: shimmer 2s infinite;"></div>
                                    </div>
                                </div>
                                <div id="rss-progress-text" style="margin-top: 8px; font-size: 14px; color: #50575e; font-weight: 500; text-align: center;">
                                    Initializing...
                                </div>
                            </div>

                            <!-- Current Feed -->
                            <div id="rss-current-feed" style="margin-bottom: 20px; padding: 12px; background: #f6f7f7; border-radius: 6px; min-height: 48px; display: flex; align-items: center; justify-content: center;">
                                <span style="font-size: 14px; color: #646970;">Preparing to sync...</span>
                            </div>

                            <!-- Live Logs -->
                            <div style="margin-bottom: 16px;">
                                <div style="font-size: 12px; color: #646970; margin-bottom: 8px; font-weight: 500;">Live Activity:</div>
                                <div id="rss-sync-logs" style="max-height: 200px; overflow-y: auto; background: #1e1e1e; border-radius: 6px; padding: 12px; font-family: 'Courier New', Consolas, monospace; font-size: 12px; color: #d4d4d4; line-height: 1.6;">
                                    <div style="color: #608b4e;">→ Starting sync process...</div>
                                </div>
                            </div>

                            <style>
                                @keyframes shimmer {
                                    0% { transform: translateX(-100%); }
                                    100% { transform: translateX(100%); }
                                }
                                #rss-sync-logs::-webkit-scrollbar {
                                    width: 8px;
                                }
                                #rss-sync-logs::-webkit-scrollbar-track {
                                    background: #2d2d30;
                                    border-radius: 4px;
                                }
                                #rss-sync-logs::-webkit-scrollbar-thumb {
                                    background: #464648;
                                    border-radius: 4px;
                                }
                                #rss-sync-logs::-webkit-scrollbar-thumb:hover {
                                    background: #5a5a5c;
                                }
                            </style>
                        </div>
                        <div id="rss-sync-overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 99999; backdrop-filter: blur(2px);"></div>
                    `;

            jQuery('body').append(html);
        }

        /**
         * Update progress
         */
        updateProgress(completed, total, currentFeedName = '') {
            this.completedFeeds = completed;
            this.totalFeeds = total || this.totalFeeds;

            const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;

            // Update progress bar
            jQuery('#rss-progress-bar').css('width', percentage + '%');

            // Update progress text
            const progressText = `${completed} / ${total} feeds completed (${percentage}%)`;
            jQuery('#rss-progress-text').text(progressText);

            // Update current feed
            if (currentFeedName) {
                const feedHtml = `
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div class="spinner is-active" style="float: none; margin: 0; width: 20px; height: 20px;"></div>
                                <span style="font-size: 14px; color: #1d2327; font-weight: 500;">Syncing: ${this.escapeHtml(currentFeedName)}</span>
                                <span style="font-size: 12px; color: #646970;">(feed ${completed + 1} of ${total})</span>
                            </div>
                        `;
                jQuery('#rss-current-feed').html(feedHtml);
            }
        }

        /**
         * Add log entry
         */
        addLog(message, type = 'info') {
            const colors = {
                'success': '#4ec9b0',
                'error': '#f48771',
                'warning': '#dcdcaa',
                'info': '#9cdcfe',
                'comment': '#608b4e'
            };

            const color = colors[type] || colors.info;
            const icon = type === 'success' ? '✓' : type === 'error' ? '✗' : type === 'warning' ? '⚠' : '▸';

            const logHtml = `<div style="color: ${color}; margin-bottom: 4px;">${icon} ${this.escapeHtml(message)}</div>`;

            jQuery('#rss-sync-logs').append(logHtml);

            // Auto-scroll to bottom
            const logsContainer = document.getElementById('rss-sync-logs');
            if (logsContainer) {
                logsContainer.scrollTop = logsContainer.scrollHeight;
            }
        }

        /**
         * Process feed result and add to logs
         */
        processFeedResult(feedSummary) {
            const { feed_name, discovered, imported, failed, status } = feedSummary;

            if (status === 'success') {
                this.addLog(`${feed_name}: ${discovered} discovered, ${imported} imported`, 'success');
            } else if (status === 'partial') {
                this.addLog(`${feed_name}: ${discovered} discovered, ${imported} imported, ${failed} failed`, 'warning');
            } else {
                this.addLog(`${feed_name}: ${failed} failed`, 'error');
            }
        }

        /**
         * Hide modal
         */
        hide() {
            jQuery(`#${this.modalId}, #rss-sync-overlay`).remove();
        }

        /**
         * Escape HTML for safe display
         */
        escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, m => map[m]);
        }

        /**
         * Sync feeds one at a time with progress updates
         * CLIENT-SIDE BATCH PROCESSING - fixes stuck "Preparing to sync..." UI
         */
        async syncFeedsSequentially(feedIds, forceImport = false) {
            this.show(feedIds.length);

            for (let i = 0; i < feedIds.length; i++) {
                const feedId = feedIds[i];

                try {
                    // Get feed name first
                    const feedName = await this.getFeedName(feedId);

                    // Update UI to show current feed
                    this.updateProgress(i, feedIds.length, feedName);
                    this.addLog(`Starting sync for ${feedName}...`, 'info');

                    // Sync this feed
                    const result = await this.syncSingleFeed(feedId, forceImport);

                    // Process result
                    if (result.success) {
                        const data = result.data;

                        // v1.2.0: Display ALL server logs first
                        if (data.logs && Array.isArray(data.logs)) {
                            data.logs.forEach(logEntry => {
                                const level = logEntry.level || 'info';
                                const message = `[${logEntry.time}] ${logEntry.message}`;
                                this.addLog(message, level);
                            });
                        }

                        const discovered = data.results?.articles_discovered || data.articles_discovered || 0;
                        const imported = data.results?.articles_imported || data.articles_imported || 0;
                        const failed = data.results?.articles_failed || data.articles_failed || 0;

                        const summary = {
                            feed_name: feedName,
                            discovered: discovered,
                            imported: imported,
                            failed: failed,
                            status: failed > 0 ? (imported > 0 ? 'partial' : 'failed') : 'success'
                        };

                        this.processFeedResult(summary);
                    } else {
                        this.addLog(`${feedName}: Failed - ${result.message}`, 'error');
                    }

                } catch (error) {
                    this.addLog(`Error syncing feed: ${error.message}`, 'error');
                }
            }

            // Final update
            this.updateProgress(feedIds.length, feedIds.length);
            this.addLog('✅ Sync complete!', 'success');

            // Auto-hide after 3 seconds
            setTimeout(() => {
                this.hide();
                if (typeof loadFeeds === 'function') {
                    loadFeeds();
                }
            }, 3000);
        }

        /**
         * Get feed name by ID from the table
         */
        getFeedName(feedId) {
            return new Promise((resolve) => {
                // Look up feed name from the feeds table
                const row = jQuery(`tr[data-feed-id="${feedId}"]`).find('td:eq(1) strong').text();
                resolve(row || `Feed ${feedId}`);
            });
        }

        /**
         * Sync a single feed via AJAX
         */
        syncSingleFeed(feedId, forceImport) {
            return new Promise((resolve) => {
                jQuery.ajax({
                    url: wisewandRSS.ajaxUrl,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'wisewand_rss_sync_feed',
                        nonce: wisewandRSS.nonce,
                        feed_id: feedId,
                        force_import: forceImport ? 1 : 0
                    },
                    timeout: 180000, // 3 minutes (handles feeds with 9+ articles)
                    success: function (response) {
                        resolve({
                            success: response.success,
                            data: response.data,
                            message: response.data?.message || ''
                        });
                    },
                    error: function (xhr, status, error) {
                        resolve({
                            success: false,
                            message: error || 'Network error'
                        });
                    }
                });
            });
        }
    }

    // Legacy function wrappers for backward compatibility
    function showBulkSyncProgress(message, totalFeeds) {
        if (!window.rssSyncProgress) {
            window.rssSyncProgress = new RssSyncProgress();
        }
        window.rssSyncProgress.show(totalFeeds);
        if (message) {
            window.rssSyncProgress.addLog(message, 'comment');
        }
    }

    function hideBulkSyncProgress() {
        if (window.rssSyncProgress) {
            window.rssSyncProgress.hide();
        }
    }

    /**
     * Show success notice
     * @param {string} message - Success message to display
     */
    function showSuccessNotice(message) {
        const html = '<div class="notice notice-success is-dismissible" style="margin: 16px 0; padding: 12px;"><p>' + escapeHtml(message) + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>';
        $('.wrap > h1').after(html);

        // Auto-dismiss after 8 seconds
        setTimeout(function () {
            $('.notice-success').fadeOut(400, function () {
                $(this).remove();
            });
        }, 8000);
    }

    /**
     * Show error notice
     * @param {string} message - Error message to display
     */
    function showErrorNotice(message) {
        const html = '<div class="notice notice-error is-dismissible" style="margin: 16px 0; padding: 12px;"><p>' + escapeHtml(message) + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>';
        $('.wrap > h1').after(html);
    }
});
