/**
 * 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 => 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>';
                    }

                    html += '<td>' + (autoEnabled ? '✅ Enabled' : '⚪ Disabled') + '<br><small>' + (feed.import_schedule_type || 'Not configured') + '</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="hourly">⚡ Hourly</option>
                                    <option value="every_6_hours" selected>🕐 Every 6 Hours (recommended)</option>
                                    <option value="daily">📆 Daily</option>
                                    <option value="custom">⚙️ 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' && article.article_status === 'success';
                    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>' + getStatusBadge(article.article_status) + '</td>';
                    html += '<td>' + formatDate(article.article_created_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>

                                <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;'}">
                                        <!-- Schedule Type -->
                                        <div style="margin-bottom: 20px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">📅 Import Schedule</label>
                                            <select name="import_schedule_type" id="schedule-type-select" class="regular-text" style="width: 100%;">
                                                <option value="hourly" ${feed.import_schedule_type === 'hourly' ? 'selected' : ''}>⚡ Hourly (for breaking news)</option>
                                                <option value="every_6_hours" ${feed.import_schedule_type === 'every_6_hours' ? 'selected' : ''}>🕐 Every 6 Hours (recommended)</option>
                                                <option value="daily" ${feed.import_schedule_type === 'daily' ? 'selected' : ''}>📆 Daily at specific time</option>
                                                <option value="custom" ${feed.import_schedule_type === 'custom' ? 'selected' : ''}>⚙️ Custom interval</option>
                                            </select>
                                        </div>

                                        <!-- Custom Interval Settings (RSS v2.0) -->
                                        <div id="custom-interval-settings" style="${feed.import_schedule_type === 'custom' ? '' : 'display:none;'} margin-bottom: 20px; padding: 16px; background: #f9fafb; border-radius: 6px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">⏱️ Custom Interval</label>
                                            <div style="display: flex; align-items: center; gap: 12px;">
                                                <span>Run every</span>
                                                <select name="custom_interval_hours" class="regular-text" style="width: auto;">
                                                    <option value="2" ${feed.custom_interval_hours === 2 ? 'selected' : ''}>2 hours</option>
                                                    <option value="4" ${feed.custom_interval_hours === 4 ? 'selected' : ''}>4 hours</option>
                                                    <option value="6" ${feed.custom_interval_hours === 6 ? 'selected' : ''}>6 hours</option>
                                                    <option value="8" ${feed.custom_interval_hours === 8 ? 'selected' : ''}>8 hours</option>
                                                    <option value="12" ${feed.custom_interval_hours === 12 || !feed.custom_interval_hours ? 'selected' : ''}>12 hours</option>
                                                    <option value="24" ${feed.custom_interval_hours === 24 ? 'selected' : ''}>24 hours (daily)</option>
                                                    <option value="48" ${feed.custom_interval_hours === 48 ? 'selected' : ''}>48 hours (every 2 days)</option>
                                                </select>
                                            </div>
                                            <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">💡 Recommended: 6-12 hours for balanced performance</p>
                                        </div>

                                        <!-- Daily Schedule Settings -->
                                        <div id="daily-schedule-settings" style="${feed.import_schedule_type === 'daily' ? '' : 'display:none;'} margin-bottom: 20px; padding: 16px; background: #f9fafb; border-radius: 6px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">🕐 Time of Day</label>
                                            <input type="time" name="import_schedule_time" value="${feed.import_schedule_time || '09:00'}" class="regular-text">

                                            <label style="display: block; font-weight: 600; margin: 16px 0 8px 0; color: #374151;">📆 Days of Week</label>
                                            <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                                ${generateDayCheckboxes(feed.import_schedule_days)}
                                            </div>
                                        </div>

                                        <!-- Max Articles -->
                                        <div style="margin-bottom: 20px;">
                                            <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>

                                        <!-- 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>
                                            </select>
                                        </div>

                                        <!-- Publish Mode (RSS v2.1) -->
                                        <div style="margin-bottom: 20px;">
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">🚀 ${wisewandRSS.publishModeLabels ? 'Publish Mode' : 'Publish Mode'}</label>
                                            <select name="publish_mode" id="feed-publish-mode" class="regular-text" style="width: 100%;">
                                                <option value="global" ${(feed.publish_mode === 'global' || !feed.publish_mode) ? 'selected' : ''}>🌐 ${wisewandRSS.publishModeLabels?.global || 'Use Global Default'}</option>
                                                <option value="schedule" ${feed.publish_mode === 'schedule' ? 'selected' : ''}>📅 ${wisewandRSS.publishModeLabels?.schedule || 'Schedule for Later'}</option>
                                                <option value="publish" ${feed.publish_mode === 'publish' ? 'selected' : ''}>✅ ${wisewandRSS.publishModeLabels?.publish || 'Publish Immediately'}</option>
                                                <option value="draft" ${feed.publish_mode === 'draft' ? 'selected' : ''}>📄 ${wisewandRSS.publishModeLabels?.draft || 'Save as Draft'}</option>
                                            </select>
                                            <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;" id="publish-mode-help">
                                                ${wisewandRSS.publishModeHelp || 'How articles from this feed should be published'}
                                            </p>
                                        </div>

                                        <!-- Author -->
                                        <div style="margin-bottom: 20px;">
                                            <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>

                                        <!-- 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 style="margin-bottom: 20px; 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>

                                        <!-- Publication Time Control (RSS v2.0) -->
                                        <div style="margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(251, 146, 60, 0.1) 100%); border-left: 3px solid #f59e0b; border-radius: 6px;">
                                            <h4 style="margin: 0 0 12px 0; color: #92400e;">🕐 Publication Time Control</h4>
                                            <p style="margin: 0 0 12px 0; font-size: 12px; color: #78350f;">
                                                Control when imported articles are published. Prevents inconvenient timing (e.g., 1 AM imports).
                                            </p>

                                            <label style="display: block; margin-bottom: 12px; cursor: pointer;">
                                                <input type="radio" name="publication_schedule_mode" value="global" ${!feed.use_custom_publication_schedule ? 'checked' : ''}>
                                                <strong>Use global Calendar settings</strong>
                                                <p style="margin: 4px 0 0 24px; font-size: 12px; color: #6b7280;" id="global-settings-preview">
                                                    Loading global settings...
                                                </p>
                                            </label>

                                            <label style="display: block; margin-bottom: 8px; cursor: pointer;">
                                                <input type="radio" name="publication_schedule_mode" value="custom" ${feed.use_custom_publication_schedule ? 'checked' : ''}>
                                                <strong>Custom publication schedule for this feed</strong>
                                            </label>

                                            <div id="custom-publication-settings" style="${feed.use_custom_publication_schedule ? '' : 'display:none;'} margin-top: 12px; padding-left: 24px;">
                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">Time Range</label>
                                                <select name="publication_time_range" class="regular-text" style="width: 100%; margin-bottom: 12px;">
                                                    <option value="random" ${(feed.publication_time_range || 'random') === 'random' ? 'selected' : ''}>🎲 Random (9 AM - 8 PM)</option>
                                                    <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' ? 'selected' : ''}>🌆 Evening (5 PM - 8 PM)</option>
                                                </select>

                                                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">Allowed Days</label>
                                                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                                    ${generatePublicationDayCheckboxes(feed.publication_allowed_days)}
                                                </div>
                                            </div>

                                            <p style="margin: 12px 0 0 0; font-size: 12px; color: #92400e; background: #fef3c7; padding: 8px; border-radius: 4px;">
                                                💡 <strong>How it works:</strong> Articles are scheduled for random times within your allowed window. WordPress automatically publishes them at the scheduled time shown in the calendar.
                                            </p>
                                        </div>
                                    </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();

                // Update publish mode help text based on selection (RSS v2.1)
                function updatePublishModeHelp() {
                    const selected = $('#feed-publish-mode').val();
                    const globalMode = (typeof wisewandRSS !== 'undefined' && wisewandRSS.globalPublishMode)
                        ? wisewandRSS.globalPublishMode
                        : 'schedule';

                    // Use translated labels from wisewandRSS
                    const modeLabels = (typeof wisewandRSS !== 'undefined' && wisewandRSS.publishModeLabels)
                        ? wisewandRSS.publishModeLabels
                        : {
                            'schedule': '📅 Schedule for Later',
                            'publish': '✅ Publish Immediately',
                            'draft': '📄 Save as Draft'
                        };

                    if (selected === 'global') {
                        const globalPrefix = (typeof wisewandRSS !== 'undefined' && wisewandRSS.publishModeGlobalPrefix)
                            ? wisewandRSS.publishModeGlobalPrefix
                            : 'Using global default';

                        $('#publish-mode-help').html(
                            `${globalPrefix}: <strong>${modeLabels[globalMode]}</strong>`
                        );
                    } else {
                        const helpText = (typeof wisewandRSS !== 'undefined' && wisewandRSS.publishModeHelp)
                            ? wisewandRSS.publishModeHelp
                            : 'How articles from this feed should be published';

                        $('#publish-mode-help').html(helpText);
                    }
                }

                // Initialize and handle publish mode changes
                updatePublishModeHelp();
                $('#feed-publish-mode').on('change', updatePublishModeHelp);

                // Show/hide daily settings and custom interval (RSS v2.0)
                $('#schedule-type-select').on('change', function() {
                    const val = $(this).val();
                    $('#daily-schedule-settings').toggle(val === 'daily');
                    $('#custom-interval-settings').toggle(val === 'custom');
                });

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

                // Show/hide custom publication settings (RSS v2.0)
                $('input[name="publication_schedule_mode"]').on('change', function() {
                    $('#custom-publication-settings').toggle($(this).val() === 'custom');
                });

                // 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');

                    // 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.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);
            }
        });
