/**
 * Admin JavaScript for Content Performance Analyzer
 *
 * @package ContentPerformanceAnalyzer
 * @since 1.0.0
 */

(function($) {
    'use strict';
    
    $(document).ready(function() {
        // Debug: Log when script loads
        if (typeof console !== 'undefined' && console.log) {
            console.log('CPA Admin JS loaded successfully');
            console.log('cpanalyzer_ajax object:', typeof cpanalyzer_ajax !== 'undefined' ? cpanalyzer_ajax : 'UNDEFINED');
            if (typeof cpanalyzer_ajax !== 'undefined' && Array.isArray(cpanalyzer_ajax.serper_debug) && cpanalyzer_ajax.serper_debug.length) {
                console.groupCollapsed('CPA Serper debug');
                cpanalyzer_ajax.serper_debug.forEach(function(entry, index) {
                    console.log('Serper event #' + (index + 1), entry);
                });
                console.groupEnd();
                window.cpaSerperDebug = cpanalyzer_ajax.serper_debug;
            }
        }
        
        // Enhanced search functionality
        $('#cpanalyzer-search-input').on('keypress', function(e) {
            if (e.which === 13) { // Enter key
                $(this).closest('form').submit();
            }
        });
        
        // Auto-focus search input if search parameter exists
        if (window.location.search.indexOf('search=') > -1) {
            $('#cpanalyzer-search-input').focus();
        }
        
        // Pagination functionality
        var showingRows = window.cpaData ? window.cpaData.showingRows : 25;
        var totalRows = window.cpaData ? window.cpaData.totalRows : 0;
        var perPageIncrement = 25;
        
        function updateRowVisibility() {
            $('#cpanalyzer-insights-table .cpanalyzer-row').each(function(index) {
                if (index < showingRows) {
                    $(this).removeClass('cpanalyzer-hidden-row').show();
                } else {
                    $(this).addClass('cpanalyzer-hidden-row').hide();
                }
            });
            
            // Update counter
            $('#cpanalyzer-showing').text(Math.min(showingRows, totalRows));
            
            // Update buttons
            if (showingRows >= totalRows) {
                $('#cpanalyzer-show-more, #cpanalyzer-show-all').hide();
                if (totalRows > 25) {
                    $('#cpanalyzer-show-less').show();
                }
            } else {
                $('#cpanalyzer-show-more, #cpanalyzer-show-all').show();
                $('#cpanalyzer-show-less').hide();
            }
        }
        
        // Show more button
        $('#cpanalyzer-show-more').on('click', function() {
            showingRows = Math.min(showingRows + perPageIncrement, totalRows);
            updateRowVisibility();
        });
        
        // Show all button
        $('#cpanalyzer-show-all').on('click', function() {
            showingRows = totalRows;
            updateRowVisibility();
        });
        
        // Show less button
        $('#cpanalyzer-show-less').on('click', function() {
            showingRows = 25;
            updateRowVisibility();
            // Scroll to top of table
            $('html, body').animate({
                scrollTop: $('#cpanalyzer-insights-table').offset().top - 100
            }, 500);
        });
        
        // Initial setup
        if (totalRows > 0) {
            updateRowVisibility();
        }

        var $aiModal = $('#cpanalyzer-ai-action-modal');

        function closeAiActionModal() {
            if (!$aiModal.length) {
                return;
            }

            $aiModal.removeClass('is-open').attr('aria-hidden', 'true').prop('hidden', true);
            $('body').removeClass('cpanalyzer-modal-open');
        }

        function toggleModalSection(sectionName, value) {
            var $section = $aiModal.find('[data-section="' + sectionName + '"]');
            var $target = $('#cpanalyzer-ai-modal-' + sectionName);
            var hasValue = typeof value === 'string' ? $.trim(value) !== '' : Array.isArray(value) && value.length > 0;

            if (!$section.length || !$target.length) {
                return;
            }

            if (!hasValue) {
                $section.prop('hidden', true);
                $target.empty();
                return;
            }

            $section.prop('hidden', false);
            $target.text(value);
        }

        function toggleMetaItem(metaName, value) {
            var $item = $aiModal.find('[data-meta="' + metaName + '"]');
            var hasValue = $.trim(value || '') !== '';

            if (!$item.length) {
                return;
            }

            $item.prop('hidden', !hasValue);
            if (hasValue) {
                $('#cpanalyzer-ai-modal-' + metaName).text(value);
            }
        }

        function renderChipList(targetSelector, values) {
            var $target = $(targetSelector);
            var list = Array.isArray(values) ? values.filter(function(value) {
                return $.trim(value || '') !== '';
            }) : [];

            $target.empty();

            if (!list.length) {
                return false;
            }

            list.forEach(function(value) {
                $('<span/>', {
                    'class': 'cpanalyzer-ai-modal__chip',
                    text: value
                }).appendTo($target);
            });

            return true;
        }

        function renderIssueList(values) {
            var $section = $aiModal.find('[data-section="issues"]');
            var $target = $('#cpanalyzer-ai-modal-issues');
            var list = Array.isArray(values) ? values.filter(function(value) {
                return $.trim(value || '') !== '';
            }) : [];

            $target.empty();

            if (!list.length) {
                $section.prop('hidden', true);
                return;
            }

            $section.prop('hidden', false);
            list.forEach(function(value) {
                $('<li/>', { text: value }).appendTo($target);
            });
        }

        function activateModalTab(tab) {
            $aiModal.find('.cpanalyzer-ai-modal__tab').each(function() {
                $(this).toggleClass('is-active', $(this).data('tab') === tab);
            });
            $aiModal.find('[data-tab-panel]').each(function() {
                var $panel = $(this);
                var inTab = $panel.data('tab-panel') === tab;
                $panel.prop('hidden', !(inTab && $panel.data('cpaHasContent')));
            });
            $aiModal.find('.cpanalyzer-ai-modal__empty').remove();
            if (!$aiModal.find('[data-tab-panel="' + tab + '"]').filter(function() {
                return $(this).data('cpaHasContent');
            }).length) {
                $('<p/>', {
                    'class': 'cpanalyzer-ai-modal__empty',
                    text: cpanalyzer_ajax.strings.tab_empty
                }).appendTo($aiModal.find('.cpanalyzer-ai-modal__body').first());
            }
        }

        // Sections mark their own content state as they render; the tab
        // switcher only shows panels that actually have something in them.
        function syncPanelStates() {
            $aiModal.find('[data-tab-panel]').each(function() {
                var $panel = $(this);
                $panel.data('cpaHasContent', !$panel.prop('hidden'));
            });
        }

        $(document).on('click', '.cpanalyzer-ai-modal__tab', function() {
            activateModalTab($(this).data('tab'));
        });

        

        function renderMissingAltImages(images, pageUrl) {
            var $section = $aiModal.find('[data-section="missingAltImages"]');
            var $target = $('#cpanalyzer-ai-modal-missingAltImages');
            var $button = $('#cpanalyzer-fix-alt-text');
            var $status = $('#cpanalyzer-fix-alt-status');
            var list = Array.isArray(images) ? images.filter(function(value) {
                return $.trim(value || '') !== '';
            }) : [];

            $target.empty();
            $status.text('');

            if (!list.length) {
                $section.prop('hidden', true);
                return;
            }

            list.forEach(function(src) {
                var fileName = src.split('/').pop().split('?')[0] || src;
                $('<li/>', { title: src, text: fileName }).appendTo($target);
            });

            var aiReady = !!(typeof cpanalyzer_ajax !== 'undefined' && cpanalyzer_ajax.ai_ready);
            $button.prop('disabled', !aiReady).data('page-url', pageUrl || '');
            if (!aiReady && typeof cpanalyzer_ajax !== 'undefined') {
                $status.text(cpanalyzer_ajax.strings.fix_alt_ai_missing);
            }

            $section.prop('hidden', false);
        }

        function renderAeoReadiness(readiness) {
            var $section = $aiModal.find('[data-section="aeoReadiness"]');
            if (!readiness || typeof readiness.score !== 'number') {
                $section.prop('hidden', true);
                return;
            }
            $('#cpanalyzer-ai-modal-aeoScore').text('Score: ' + readiness.score + '/100');
            var $list = $('#cpanalyzer-ai-modal-aeoChecks').empty();
            (readiness.checks || []).forEach(function(check) {
                $('<li/>', {
                    text: (check.pass ? '✓ ' : '✗ ') + check.label,
                    css: { color: check.pass ? '#00a32a' : '#d63638' }
                }).appendTo($list);
            });
            $section.prop('hidden', false);
        }

        function renderDecayDiagnosis(diagnosis, trend) {
            var $section = $aiModal.find('[data-section="decayDiagnosis"]');
            if (!diagnosis || !diagnosis.type || diagnosis.type === 'none') {
                $section.prop('hidden', true);
                return;
            }

            var confidence = diagnosis.confidence ? ' (' + diagnosis.confidence + ')' : '';
            $('#cpanalyzer-ai-modal-decayType').text((diagnosis.label || diagnosis.type) + confidence);
            $('#cpanalyzer-ai-modal-decayEvidence').text(diagnosis.evidence || '');

            var trendText = $.trim(diagnosis.trend_note || '');
            if (!trendText && trend && typeof trend.declining_periods === 'number' && trend.declining_periods >= 2) {
                trendText = 'Clicks have declined for ' + trend.declining_periods + ' consecutive 28-day periods.';
            }
            $('#cpanalyzer-ai-modal-decayTrend').text(trendText).prop('hidden', trendText === '');

            var fixText = $.trim(diagnosis.fix_hint || '');
            $('#cpanalyzer-ai-modal-decayFix').text(fixText).prop('hidden', fixText === '');

            $section.prop('hidden', false);
        }

        function renderCannibalization(conflicts) {
            var $section = $aiModal.find('[data-section="cannibalization"]');
            var list = Array.isArray(conflicts) ? conflicts : [];
            if (!list.length) {
                $section.prop('hidden', true);
                return;
            }

            var $target = $('#cpanalyzer-ai-modal-cannibalization').empty();
            list.forEach(function(conflict) {
                var competing = (conflict.competing || []).map(function(other) {
                    return other.page + ' (pos ' + other.position + ', ' + other.clicks + ' clicks)';
                }).join(', ');
                $('<li/>', {
                    text: '"' + conflict.query + '" — this page: pos ' + conflict.own_position + ', ' +
                        conflict.own_clicks + ' clicks. Also ranking: ' + competing
                }).appendTo($target);
            });
            $section.prop('hidden', false);
        }

        function renderInboundLinks(count, isOrphan) {
            var $section = $aiModal.find('[data-section="inboundLinks"]');
            if (count === null || typeof count === 'undefined') {
                $section.prop('hidden', true);
                return;
            }

            var text;
            if (isOrphan) {
                text = '⚠ Orphan page: no other post or page links to this URL in its content (menus and widgets not counted). ' +
                    'Pages without internal links lose crawl priority and link equity — add links from related high-traffic pages.';
            } else {
                text = count + ' published ' + (count === 1 ? 'page links' : 'pages link') + ' to this URL from within content.';
                if (count <= 2) {
                    text += ' That is low — consider adding links from related high-traffic pages.';
                }
            }
            $('#cpanalyzer-ai-modal-inboundLinks').text(text).css('color', isOrphan || count <= 2 ? '#b32d2e' : '');
            $section.prop('hidden', false);
        }

        function renderQuestionGaps(gaps, pageUrl) {
            var $section = $aiModal.find('[data-section="questionGaps"]');
            var list = Array.isArray(gaps) ? gaps : [];
            if (!list.length) {
                $section.prop('hidden', true);
                return;
            }
            var aiReady = !!(typeof cpanalyzer_ajax !== 'undefined' && cpanalyzer_ajax.ai_ready);
            var $target = $('#cpanalyzer-ai-modal-questionGaps').empty();
            list.forEach(function(gap) {
                var $item = $('<li/>', {
                    text: '"' + gap.query + '" — position ' + gap.position + ', ' + gap.impressions + ' impressions '
                });
                if (aiReady && pageUrl) {
                    $('<button/>', {
                        type: 'button',
                        'class': 'button button-small cpanalyzer-write-answer',
                        text: cpanalyzer_ajax.strings.write_answer,
                        'data-query': gap.query,
                        'data-url': pageUrl
                    }).appendTo($item);
                }
                $item.appendTo($target);
            });
            $section.prop('hidden', false);
        }

        $(document).on('click', '.cpanalyzer-write-answer', function() {
            var $button = $(this);
            var $item = $button.closest('li');

            if (!window.confirm(cpanalyzer_ajax.strings.answer_confirm)) {
                return;
            }

            $button.prop('disabled', true).text(cpanalyzer_ajax.strings.writing_answer);

            $.post(cpanalyzer_ajax.ajax_url, {
                action: 'cpanalyzer_generate_answer_block',
                nonce: cpanalyzer_ajax.answer_nonce,
                url: $button.data('url'),
                query: $button.data('query')
            })
                .done(function(res) {
                    if (res && res.success) {
                        $item.css('color', '#00a32a').text('✓ ' + res.data.question + ' — ' + res.data.answer);
                    } else {
                        var message = res && res.data && res.data.message ? res.data.message : cpanalyzer_ajax.strings.answer_failed;
                        $button.prop('disabled', false).text(cpanalyzer_ajax.strings.write_answer);
                        $item.append($('<small/>', { text: ' ' + message, css: { color: '#d63638' } }));
                    }
                })
                .fail(function() {
                    $button.prop('disabled', false).text(cpanalyzer_ajax.strings.write_answer);
                    $item.append($('<small/>', { text: ' ' + cpanalyzer_ajax.strings.answer_failed, css: { color: '#d63638' } }));
                });
        });

        function openAiActionModal(payload) {
            var title = $.trim(payload.headline || '');
            var statusText = payload.isExpired ? 'This recommendation is expired. Refresh AI to generate a new version.' : '';
            var priority = $.trim(payload.contentPriority || '');
            var issues = Array.isArray(payload.technicalIssues) ? payload.technicalIssues : [];

            $('#cpanalyzer-ai-modal-title').text(title || 'AI recommendation');
            $('#cpanalyzer-ai-modal-url').text(payload.url || '');

            if (statusText) {
                $('#cpanalyzer-ai-modal-status').text(statusText).prop('hidden', false);
            } else {
                $('#cpanalyzer-ai-modal-status').text('').prop('hidden', true);
            }

            if (priority) {
                priority = priority.charAt(0).toUpperCase() + priority.slice(1);
            }

            toggleMetaItem('priority', priority);
            toggleMetaItem('keyword', payload.primaryKeyword || '');
            toggleMetaItem('model', payload.modelUsed || '');
            toggleModalSection('issueSummary', payload.issueSummary || '');
            toggleModalSection('whyNow', payload.whyNow || '');
            toggleModalSection('seoRecommendation', payload.seoRecommendation || '');
            toggleModalSection('aeoRecommendation', payload.aeoRecommendation || '');
            toggleModalSection('geoRecommendation', payload.geoRecommendation || '');
            toggleModalSection('engagementRecommendation', payload.engagementRecommendation || '');

            $aiModal.find('[data-section="suggestedKeywords"]').prop(
                'hidden',
                !renderChipList('#cpanalyzer-ai-modal-suggestedKeywords', payload.suggestedKeywords)
            );

            renderIssueList(issues);
            renderDecayDiagnosis(payload.decayDiagnosis, payload.clickTrend);
            renderCannibalization(payload.cannibalization);
            renderInboundLinks(
                typeof payload.inboundLinks === 'number' ? payload.inboundLinks : null,
                !!payload.isOrphan
            );
            renderAeoReadiness(payload.aeoReadiness);
            

            syncPanelStates();
            activateModalTab('overview');
            renderQuestionGaps(payload.questionGaps, payload.url);
            renderMissingAltImages(payload.missingAltImages, payload.url);

            $aiModal.prop('hidden', false).addClass('is-open').attr('aria-hidden', 'false');
            $('body').addClass('cpanalyzer-modal-open');
        }

        $(document).on('click', '#cpanalyzer-fix-alt-text', function() {
            var $button = $(this);
            var $status = $('#cpanalyzer-fix-alt-status');
            var pageUrl = $button.data('page-url');

            if (!pageUrl || typeof cpanalyzer_ajax === 'undefined') {
                return;
            }

            if (!window.confirm(cpanalyzer_ajax.strings.fix_alt_confirm)) {
                return;
            }

            $button.prop('disabled', true).text(cpanalyzer_ajax.strings.fix_alt_working);
            $status.text('');

            $.post(cpanalyzer_ajax.ajax_url, {
                action: 'cpanalyzer_fix_image_alt',
                nonce: cpanalyzer_ajax.fix_alt_nonce,
                url: pageUrl
            })
                .done(function(response) {
                    if (response && response.success) {
                        $status.text(response.data.summary);

                        var $target = $('#cpanalyzer-ai-modal-missingAltImages');
                        $target.empty();
                        (response.data.results || []).forEach(function(result) {
                            var fileName = (result.image || '').split('/').pop().split('?')[0];
                            var text = fileName + ' — ' + (result.status === 'fixed' ? (result.alt || '') : (result.note || ''));
                            $('<li/>', { title: result.image, text: text }).appendTo($target);
                        });

                        if (!(response.data.remaining || []).length) {
                            $button.hide();
                        } else {
                            $button.prop('disabled', false).text(cpanalyzer_ajax.strings.fix_alt_button);
                        }
                    } else {
                        var message = response && response.data && response.data.message
                            ? response.data.message
                            : cpanalyzer_ajax.strings.fix_alt_failed;
                        $status.text(message);
                        $button.prop('disabled', false).text(cpanalyzer_ajax.strings.fix_alt_button);
                    }
                })
                .fail(function() {
                    $status.text(cpanalyzer_ajax.strings.fix_alt_failed);
                    $button.prop('disabled', false).text(cpanalyzer_ajax.strings.fix_alt_button);
                });
        });

        // Mark a page as fixed (or undo). Reload on success so the flag
        // chip, actions column, and dashboard counts all stay consistent.
        $(document).on('click', '.cpanalyzer-mark-fixed', function(e) {
            e.preventDefault();
            var $link = $(this);
            if ($link.data('cpaBusy')) {
                return;
            }
            $link.data('cpaBusy', true).text(cpanalyzer_ajax.strings.mark_working);

            $.post(cpanalyzer_ajax.ajax_url, {
                action: 'cpanalyzer_mark_page_fixed',
                nonce: cpanalyzer_ajax.mark_fixed_nonce,
                url: $link.data('url'),
                mode: $link.data('mode') || 'mark'
            })
                .done(function(response) {
                    if (response && response.success) {
                        window.location.reload();
                    } else {
                        var message = response && response.data && response.data.message
                            ? response.data.message
                            : cpanalyzer_ajax.strings.mark_failed;
                        $link.data('cpaBusy', false).text(message);
                    }
                })
                .fail(function() {
                    $link.data('cpaBusy', false).text(cpanalyzer_ajax.strings.mark_failed);
                });
        });

        // One-click refresh draft: create (or reuse) the draft, then open it.
        $(document).on('click', '.cpanalyzer-create-refresh-draft', function(e) {
            e.preventDefault();
            var $link = $(this);
            if ($link.data('cpaBusy')) {
                return;
            }
            $link.data('cpaBusy', true).text(cpanalyzer_ajax.strings.draft_working);

            $.post(cpanalyzer_ajax.ajax_url, {
                action: 'cpanalyzer_create_refresh_draft',
                nonce: cpanalyzer_ajax.refresh_draft_nonce,
                url: $link.data('url')
            })
                .done(function(response) {
                    if (response && response.success && response.data && response.data.edit_link) {
                        $link.data('cpaBusy', false)
                            .text(cpanalyzer_ajax.strings.draft_open)
                            .attr('href', response.data.edit_link)
                            .attr('target', '_blank')
                            .removeClass('cpanalyzer-create-refresh-draft');
                        window.open(response.data.edit_link, '_blank');
                    } else {
                        var message = response && response.data && response.data.message
                            ? response.data.message
                            : cpanalyzer_ajax.strings.draft_failed;
                        $link.data('cpaBusy', false).text(message);
                    }
                })
                .fail(function() {
                    $link.data('cpaBusy', false).text(cpanalyzer_ajax.strings.draft_failed);
                });
        });

        $(document).on('click', '.cpanalyzer-view-ai-action', function() {
            var rawPayload = $(this).attr('data-ai-payload');
            var payload;

            if (!rawPayload) {
                return;
            }

            try {
                payload = JSON.parse(rawPayload);
            } catch (error) {
                if (typeof console !== 'undefined' && console.error) {
                    console.error('Failed to parse AI action payload', error);
                }
                return;
            }

            openAiActionModal(payload);
        });

        $aiModal.on('click', '[data-modal-close="1"], .cpanalyzer-ai-modal__close', function() {
            closeAiActionModal();
        });

        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $aiModal.hasClass('is-open')) {
                closeAiActionModal();
            }
        });

        $(document).on('click', '.cpanalyzer-retry-url-scan', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            var url = $button.data('url') || '';
            var didSucceed = false;

            if (!url) {
                return;
            }

            if (!confirm(cpanalyzer_ajax.strings.retry_scan_confirm || 'Retry scan for this URL?')) {
                return;
            }

            $button.prop('disabled', true);
            $message.text(cpanalyzer_ajax.strings.retry_scan_working || 'Reprocessing URL…').css('color', '#0073aa');

            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_reprocess_one_url',
                    nonce: cpanalyzer_ajax.batch_nonce,
                    url: url
                },
                success: function(response) {
                    if (response.success) {
                        didSucceed = true;
                        $message.text(response.data.message || cpanalyzer_ajax.strings.retry_scan_done);
                        $message.css('color', response.data && response.data.has_psi ? '#27ae60' : '#dba617');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1800);
                    } else {
                        $message.text(response.data.message || cpanalyzer_ajax.strings.retry_failed);
                        $message.css('color', '#e74c3c');
                    }
                },
                error: function() {
                    $message.text(cpanalyzer_ajax.strings.retry_failed);
                    $message.css('color', '#e74c3c');
                },
                complete: function() {
                    $button.prop('disabled', false);

                    setTimeout(function() {
                        if (!didSucceed) {
                            $message.text('').css('color', '');
                        }
                    }, 6000);
                }
            });
        });
        
        // Retry missing AI suggestions
        $('#cpanalyzer-retry-missing').on('click', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            
            // Disable button and show loading message
            $button.prop('disabled', true);
            $message.text(cpanalyzer_ajax.strings.contacting_ai).css('color', '#0073aa');
            
            // Make AJAX request
            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_retry_missing_ai',
                    nonce: cpanalyzer_ajax.retry_nonce
                },
                success: function(response) {
                    if (response.success) {
                        $message.text(response.data.message || cpanalyzer_ajax.strings.done_refresh);
                        $message.css('color', '#27ae60');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        $message.text(response.data.message || cpanalyzer_ajax.strings.retry_failed);
                        $message.css('color', response.data && response.data.code === 'no_missing' ? '#27ae60' : '#e74c3c');
                    }
                },
                error: function() {
                    $message.text(cpanalyzer_ajax.strings.retry_failed);
                    $message.css('color', '#e74c3c');
                },
                complete: function() {
                    $button.prop('disabled', false);
                    
                    // Clear message after 5 seconds
                    setTimeout(function() {
                        $message.text('').css('color', '');
                    }, 5000);
                }
            });
        });
        
        // Sync batch data functionality
        $('#cpanalyzer-sync-batch-data').on('click', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            
            // Debug: Log button click
            if (typeof console !== 'undefined' && console.log) {
                console.log('Sync All URLs button clicked');
            }
            
            // Immediate visual feedback
            $button.text('Syncing...').prop('disabled', true).css('background-color', '#0073aa');
            $message.text('🔄 Syncing batch data...').css('color', '#0073aa').show();
            
            // Make AJAX request
            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_sync_batch_data',
                    nonce: cpanalyzer_ajax.batch_nonce
                },
                success: function(response) {
                    if (typeof console !== 'undefined' && console.log) {
                        console.log('Sync All URLs response:', response);
                    }
                    
                    if (response.success) {
                        $message.text('✅ Sync complete! Refresh page to see all URLs.');
                        $message.css('color', '#27ae60');
                        $button.text('Sync Complete').css('background-color', '#27ae60');
                        
                        // Auto-refresh after 2 seconds
                        setTimeout(function() {
                            window.location.reload();
                        }, 2000);
                    } else {
                        $message.text(response.data.message || 'Sync failed. Please try again.');
                        $message.css('color', '#e74c3c');
                        $button.text('Sync All URLs').prop('disabled', false).css('background-color', '');
                    }
                },
                error: function(xhr, status, error) {
                    if (typeof console !== 'undefined' && console.log) {
                        console.log('Sync All URLs error:', xhr, status, error);
                    }
                    
                    $message.text('Sync failed. Error: ' + (error || 'Connection error'));
                    $message.css('color', '#e74c3c');
                    $button.text('Sync All URLs').prop('disabled', false).css('background-color', '');
                },
                complete: function() {
                    // Reset button after delay if not successful
                    if (!$message.text().includes('✅')) {
                        setTimeout(function() {
                            $button.text('Sync All URLs').prop('disabled', false).css('background-color', '');
                            $message.text('').css('color', '');
                        }, 5000);
                    }
                }
            });
        });
        
        // Safe manual scan functionality
        $('#cpanalyzer-safe-manual-scan').on('click', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            
            // Debug: Log button click
            if (typeof console !== 'undefined' && console.log) {
                console.log('Process Pending URLs button clicked');
            }
            
            // Immediate visual feedback
            $button.text('Processing...').prop('disabled', true).css('background-color', '#d63638');
            $message.text('🔄 Initializing batch processing...').css('color', '#0073aa').show();
            
            if (!confirm('Start processing pending URLs in background? This is safe and won\'t timeout your browser.')) {
                // Reset button if user cancels
                $button.text('Process Pending URLs').prop('disabled', false).css('background-color', '');
                $message.text('').hide();
                return;
            }
            
            $message.text('▶️ Starting background processing...').css('color', '#0073aa');
            
            // Make AJAX request
            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_start_batch_process',
                    nonce: cpanalyzer_ajax.batch_nonce
                },
                success: function(response) {
                    if (typeof console !== 'undefined' && console.log) {
                        console.log('Process Pending URLs response:', response);
                    }
                    
                    if (response.success) {
                        $message.text(response.data.message || 'Background processing started.');
                        $message.css('color', '#27ae60');
                        $button.text('Processing Started').css('background-color', '#27ae60');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        $message.text(response.data.message || 'Failed to start processing.');
                        $message.css('color', '#e74c3c');
                        $button.text('Process Pending URLs').prop('disabled', false).css('background-color', '');
                    }
                },
                error: function(xhr, status, error) {
                    if (typeof console !== 'undefined' && console.log) {
                        console.log('Process Pending URLs error:', xhr, status, error);
                    }
                    
                    $message.text('Failed to start processing. Error: ' + (error || 'Unknown error'));
                    $message.css('color', '#e74c3c');
                    $button.text('Process Pending URLs').prop('disabled', false).css('background-color', '');
                },
                complete: function() {
                    // Reset button after delay if not successful
                    setTimeout(function() {
                        if (!$message.text().includes('✅')) {
                            $button.text('Process Pending URLs').prop('disabled', false).css('background-color', '');
                            $message.text('').css('color', '');
                        }
                    }, 8000);
                }
            });
        });
        
        // Force restart processing functionality
        $('#cpanalyzer-force-restart').on('click', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            
            if (!confirm('⚠️ Force restart processing? This will clear all locks and reset stuck URLs. Only use if processing appears completely stuck.')) {
                return;
            }
            
            // Disable button and show loading message
            $button.prop('disabled', true);
            $message.text('🔄 Restarting processing...').css('color', '#d63638');
            
            // Make AJAX request
            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_force_restart_processing',
                    nonce: cpanalyzer_ajax.batch_nonce
                },
                success: function(response) {
                    if (response.success) {
                        $message.text(response.data.message);
                        $message.css('color', '#27ae60');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        $message.text(response.data.message || 'Failed to restart processing.');
                        $message.css('color', '#e74c3c');
                    }
                },
                error: function() {
                    $message.text('Failed to restart. Please try again.');
                    $message.css('color', '#e74c3c');
                },
                complete: function() {
                    $button.prop('disabled', false);
                    
                    // Clear message after 10 seconds
                    setTimeout(function() {
                        $message.text('').css('color', '');
                    }, 10000);
                }
            });
        });
        
        // Reset all data functionality (with strong confirmation)
        $('#cpanalyzer-reset-all-data').on('click', function() {
            var $button = $(this);
            var $message = $('#cpanalyzer-retry-msg');
            
            // First confirmation
            if (!confirm('⚠️ DANGER: This will permanently delete ALL processed data including:\n\n' +
                        '• All GA4 and GSC data\n' +
                        '• All content analysis results\n' +
                        '• All AI suggestions\n' +
                        '• All URL processing status\n' +
                        '• All insights and flags\n\n' +
                        'Your API settings will be preserved.\n\n' +
                        'Are you absolutely sure you want to continue?')) {
                return;
            }
            
            // Second confirmation with typing requirement
            var confirmation = prompt('⚠️ FINAL WARNING: This action cannot be undone!\n\n' +
                                    'To confirm you want to delete all processed data, type exactly:\n\n' +
                                    'RESET-ALL-DATA\n\n' +
                                    '(Case sensitive, no spaces before or after)');
            
            if (confirmation !== 'RESET-ALL-DATA') {
                alert('❌ Reset cancelled. You must type exactly: RESET-ALL-DATA');
                return;
            }
            
            // Disable button and show warning message
            $button.prop('disabled', true);
            $message.text('🗑️ DELETING ALL DATA... This may take 30 seconds...').css('color', '#b32d2e');
            
            // Make AJAX request
            $.ajax({
                url: cpanalyzer_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_reset_all_data',
                    nonce: cpanalyzer_ajax.batch_nonce,
                    confirmation: confirmation
                },
                timeout: 60000, // 60 second timeout for reset operation
                success: function(response) {
                    if (response.success) {
                        $message.text(response.data.message);
                        $message.css('color', '#27ae60');
                        
                        // Auto-refresh page after successful reset
                        setTimeout(function() {
                            window.location.reload();
                        }, 3000);
                    } else {
                        $message.text(response.data.message || 'Reset failed. Please try again.');
                        $message.css('color', '#e74c3c');
                    }
                },
                error: function(xhr, status, error) {
                    if (status === 'timeout') {
                        $message.text('Reset is taking longer than expected. Please refresh the page in 2 minutes.');
                    } else {
                        $message.text('Reset failed due to connection error. Please try again.');
                    }
                    $message.css('color', '#e74c3c');
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        });
        
        // Export functionality
        $('#cpanalyzer-export-csv').on('click', function() {
            var csv = [];
            var headers = [];
            
            // Get headers
            $('#cpanalyzer-insights-table thead th').each(function() {
                headers.push('"' + $(this).text().replace(/"/g, '""').replace(/\n/g, ' ') + '"');
            });
            csv.push(headers.join(','));
            
            // Get all rows data (not just visible)
            $('#cpanalyzer-insights-table tbody tr.cpanalyzer-row').each(function() {
                var row = [];
                $(this).find('td').each(function() {
                    var text = $(this).text().replace(/"/g, '""').replace(/\n/g, ' ').trim();
                    row.push('"' + text + '"');
                });
                csv.push(row.join(','));
            });
            
            // Download CSV
            var csvContent = csv.join('\n');
            var blob = new Blob([csvContent], { type: 'text/csv' });
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = 'content-insights-' + new Date().toISOString().split('T')[0] + '.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        });
        
        // Table sorting functionality
        $('#cpanalyzer-insights-table th').on('click', function() {
            var $table = $('#cpanalyzer-insights-table');
            var $th = $(this);
            var columnIndex = $th.index();
            var isAscending = !$th.hasClass('sort-asc');
            
            // Remove existing sort classes
            $table.find('th').removeClass('sort-asc sort-desc');
            
            // Add new sort class
            $th.addClass(isAscending ? 'sort-asc' : 'sort-desc');
            
            // Sort rows
            var rows = $table.find('tbody tr.cpanalyzer-row').get();
            rows.sort(function(a, b) {
                var aVal = $(a).find('td').eq(columnIndex).text().trim();
                var bVal = $(b).find('td').eq(columnIndex).text().trim();
                
                // Try to parse as numbers
                var aNum = parseFloat(aVal.replace(/[^\d.-]/g, ''));
                var bNum = parseFloat(bVal.replace(/[^\d.-]/g, ''));
                
                if (!isNaN(aNum) && !isNaN(bNum)) {
                    return isAscending ? aNum - bNum : bNum - aNum;
                } else {
                    return isAscending ? 
                        aVal.localeCompare(bVal) : 
                        bVal.localeCompare(aVal);
                }
            });
            
            // Reattach sorted rows and update row indices
            $.each(rows, function(index, row) {
                $(row).attr('data-row-index', index);
                $table.find('tbody').append(row);
            });
            
            // Update visibility after sorting
            updateRowVisibility();
        });
        
        // Keyboard shortcuts
        $(document).on('keydown', function(e) {
            // Ctrl/Cmd + Shift + R for manual refresh
            if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'R') {
                e.preventDefault();
                if (confirm('Run manual data collection? This may take a few minutes.')) {
                    var manualUrl = window.location.href.split('?')[0] + 
                        '?page=content-insights&cpanalyzer_run=1&cpanalyzer_nonce=' + 
                        (cpanalyzer_ajax.manual_nonce || '');
                    window.location.href = manualUrl;
                }
            }
        });
        
        // PageSpeed Insights API key validation
        $('#validate-psi-key').on('click', function() {
            var $button = $(this);
            var $status = $('#psi-key-status');
            var $apiKeyInput = $('#cpanalyzer_pagespeed_api_key');
            var apiKey = $apiKeyInput.val().trim();
            
            if (!apiKey) {
                $status.html('<span style="color: #d63638;">❌ Please enter an API key first</span>');
                $apiKeyInput.focus();
                return;
            }
            
            $button.prop('disabled', true).text('Validating...');
            $status.html('<span style="color: #666;">⏳ Testing API key...</span>');
            
            var data = {
                action: 'cpanalyzer_validate_psi_key',
                nonce: cpanalyzer_ajax.batch_nonce,
                api_key: apiKey
            };
            
            $.post(cpanalyzer_ajax.ajax_url, data)
                .done(function(response) {
                    if (response.success) {
                        $status.html('<span style="color: #00a32a;">✅ ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span style="color: #d63638;">❌ ' + response.data.message + '</span>');
                    }
                })
                .fail(function() {
                    $status.html('<span style="color: #d63638;">❌ Network error occurred</span>');
                })
                .always(function() {
                    $button.prop('disabled', false).text('Validate Key');
                });
        });
        
        // Enable/disable PSI fields based on enable checkbox
        $('#cpanalyzer_pagespeed_enable').on('change', function() {
            var isEnabled = $(this).is(':checked');
            var $psiFields = $('#cpanalyzer_pagespeed_api_key, #cpanalyzer_pagespeed_strategy, #cpanalyzer_pagespeed_rate_limit, #cpanalyzer_pagespeed_cache_hours');
            var $psiCheckboxes = $('input[name="cpanalyzer_pagespeed_categories[]"]');
            var $validateButton = $('#validate-psi-key');
            
            if (isEnabled) {
                $psiFields.prop('disabled', false).css('opacity', '1');
                $psiCheckboxes.prop('disabled', false).closest('label').css('opacity', '1');
                $validateButton.prop('disabled', false).css('opacity', '1');
                $('#cpanalyzer_pagespeed_api_key').focus();
            } else {
                $psiFields.prop('disabled', true).css('opacity', '0.5');
                $psiCheckboxes.prop('disabled', true).closest('label').css('opacity', '0.5');
                $validateButton.prop('disabled', true).css('opacity', '0.5');
                $('#psi-key-status').empty();
            }
        }).trigger('change'); // Initialize on page load
    });

    // OAuth disconnect button handler (settings page)
    $(document).on('click', '#cpanalyzer-oauth-disconnect', function() {
        if (!confirm(cpanalyzer_ajax.strings.oauth_disconnect_confirm)) {
            return;
        }
        var $btn = $(this).prop('disabled', true).text(cpanalyzer_ajax.strings.oauth_disconnecting);
        $.post(cpanalyzer_ajax.ajax_url, {
            action: 'cpanalyzer_google_oauth_disconnect',
            nonce:  cpanalyzer_ajax.batch_nonce
        }, function(res) {
            if (res.success) {
                location.reload();
            } else {
                alert(res.data.message);
                $btn.prop('disabled', false).text(cpanalyzer_ajax.strings.oauth_disconnect);
            }
        });
    });

    // ── Model dropdown follows the selected AI provider ───────────────────
    function cpanalyzerFilterModelDropdown() {
        var provider = $('input[name="cpanalyzer_ai_provider"]:checked').val();
        var $select = $('#cpanalyzer_ai_model');

        // The hosted provider brings its own key and picks its own model
        // server-side, so both bring-your-own rows are irrelevant then.
        $('.cpanalyzer-byo-key-setting').toggle(provider !== 'hosted');

        if (!$select.length || !provider) {
            return;
        }
        $select.find('optgroup').each(function() {
            var matches = $(this).data('provider') === provider;
            $(this).prop('disabled', !matches).toggle(matches);
        });
        // If the saved model belongs to another provider, fall back to Automatic.
        var $selected = $select.find('option:selected');
        if ($selected.length && $selected.parent().is('optgroup') && $selected.parent().data('provider') !== provider) {
            $select.val('');
        }
    }

    $(document).on('change', 'input[name="cpanalyzer_ai_provider"]', cpanalyzerFilterModelDropdown);
    $(cpanalyzerFilterModelDropdown);

    // ── PageSpeed sub-settings: only visible while the feature is on ─────
    function cpanalyzerTogglePsiSettings() {
        var $enable = $('#cpanalyzer_pagespeed_enable');
        if ($enable.length) {
            $('.cpanalyzer-psi-setting').toggle($enable.is(':checked'));
        }
    }

    $(document).on('change', '#cpanalyzer_pagespeed_enable', cpanalyzerTogglePsiSettings);
    $(cpanalyzerTogglePsiSettings);

    // ── PageSpeed page picker: live search filter ─────────────────────────
    $(document).on('input', '#cpanalyzer-psi-page-search', function() {
        var query = this.value.toLowerCase();
        $('#cpanalyzer-psi-pages-list .cpanalyzer-page-row').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(query) !== -1);
        });
    });

    // ── PageSpeed page picker: enforce the selection cap (15 free, 30 Pro) ──
    function cpanalyzerPsiLimit() {
        var limit = parseInt(
            (typeof cpanalyzer_ajax !== 'undefined' && cpanalyzer_ajax.psi_limit) || 15,
            10
        );
        return limit > 0 ? limit : 15;
    }

    function cpanalyzerUpdatePsiCount() {
        var checked = $('.cpanalyzer-psi-page-checkbox:checked').length;
        $('#cpanalyzer-psi-pages-count').text(checked + '/' + cpanalyzerPsiLimit() + ' selected. ');
    }

    $(document).on('change', '.cpanalyzer-psi-page-checkbox', function() {
        if (this.checked && $('.cpanalyzer-psi-page-checkbox:checked').length > cpanalyzerPsiLimit()) {
            this.checked = false;
        }
        cpanalyzerUpdatePsiCount();
    });

    $(function() {
        if ($('.cpanalyzer-psi-page-checkbox').length) {
            cpanalyzerUpdatePsiCount();
        }
    });

    // ── GA4 property / GSC site pickers (settings page) ──────────────────
    // Fetches both lists from the connected Google account and shows
    // dropdowns that fill the plain text inputs, which stay the source of
    // truth for the form submit.
    $(document).on('click', '#cpanalyzer-load-properties', function() {
        var $button = $(this).prop('disabled', true);
        var $status = $('#cpanalyzer-properties-status').text('…');

        function populate($picker, $select, items, valueKey, $input) {
            $select.empty();
            if (!items.length) {
                return;
            }
            $select.append($('<option/>', { value: '', text: '— select —' }));
            items.forEach(function(item) {
                $select.append($('<option/>', { value: item[valueKey], text: item.label }));
            });
            $picker.show();
            $select.off('change.cpanalyzer').on('change.cpanalyzer', function() {
                if (this.value) {
                    $input.val(this.value);
                }
            });
        }

        $.post(cpanalyzer_ajax.ajax_url, {
            action: 'cpanalyzer_list_google_properties',
            nonce:  cpanalyzer_ajax.batch_nonce
        }, function(res) {
            $button.prop('disabled', false);
            if (!res.success) {
                $status.text(res.data && res.data.message ? res.data.message : 'Failed to load.');
                return;
            }
            $status.text('');
            populate($('#cpanalyzer-property-picker'), $('#cpanalyzer-property-select'), res.data.properties || [], 'id', $('#cpanalyzer_property_id'));
            populate($('#cpanalyzer-site-picker'), $('#cpanalyzer-site-select'), res.data.sites || [], 'url', $('#cpanalyzer_site_url'));
        }).fail(function() {
            $button.prop('disabled', false);
            $status.text('Request failed. Please try again.');
        });
    });

})(jQuery);
