<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Opening Insights counts as reviewing the latest findings — clear the
// "newly flagged pages" admin notice and the recovery-verdict news (the
// table shows every verdict inline via the row chips).
if ( get_option( 'cpanalyzer_new_flags' ) ) {
    delete_option( 'cpanalyzer_new_flags' );
}
if ( get_option( 'cpanalyzer_recovery_news' ) ) {
    delete_option( 'cpanalyzer_recovery_news' );
}
// Get data safely
$status = get_option( 'cpanalyzer_status_msg', '' );
$cpanalyzer_flags = (array) get_option( 'cpanalyzer_page_flags', array() );
$cpanalyzer_actions = (array) get_option( 'cpanalyzer_page_actions', array() );
$cpanalyzer_ga_rows = (array) get_option( 'cpanalyzer_ga_rows', array() );
$cpanalyzer_ga_prev_rows = (array) get_option( 'cpanalyzer_ga_prev_rows', array() );
$cpanalyzer_gsc_rows = (array) get_option( 'cpanalyzer_gsc_rows', array() );
$cpanalyzer_content_data = (array) get_option( 'cpanalyzer_content_data', array() );
// New content analysis data
$cpanalyzer_refreshed_map = (array) get_option( 'cpanalyzer_refreshed_map', array() );
// Pages marked as fixed (recovery tracking)
$cpanalyzer_pro_ready = false;
$cpanalyzer_hosted_ai_selected = false;
$cpanalyzer_psi_enabled = get_option( 'cpanalyzer_pagespeed_enable', 'no' );
// Hosted PSI needs no API key — enabling the feature is enough to retry.
$cpanalyzer_can_retry_psi = $cpanalyzer_psi_enabled === 'yes' || $cpanalyzer_psi_enabled === true;
?>

<div class="wrap">
    <h1><?php 
echo esc_html( get_admin_page_title() );
?></h1>

    <?php 
if ( function_exists( 'cpanalyzer_render_setup_mode_notice' ) ) {
    cpanalyzer_render_setup_mode_notice();
}
?>

    <?php 
// Whole data sources that came back empty, said plainly and where the
// user is looking — not discovered later inside an AI note.
$cpanalyzer_health = ( function_exists( 'cpanalyzer_evaluate_data_health' ) ? cpanalyzer_evaluate_data_health( $cpanalyzer_flags, $cpanalyzer_gsc_rows, $cpanalyzer_content_data ) : array() );
foreach ( $cpanalyzer_health as $cpanalyzer_issue ) {
    ?>
        <div class="notice notice-warning cpanalyzer-data-health">
            <p>
                <strong><?php 
    esc_html_e( 'Content Performance Analyzer:', 'content-performance-analyzer' );
    ?></strong>
                <?php 
    echo esc_html( $cpanalyzer_issue['message'] );
    ?>
                <?php 
    if ( !empty( $cpanalyzer_issue['action_url'] ) && !empty( $cpanalyzer_issue['action_label'] ) ) {
        ?>
                    <a href="<?php 
        echo esc_url( $cpanalyzer_issue['action_url'] );
        ?>"><?php 
        echo esc_html( $cpanalyzer_issue['action_label'] );
        ?></a>
                <?php 
    }
    ?>
            </p>
        </div>
    <?php 
}
?>

    <?php 
if ( !empty( $status ) ) {
    // Colour the banner by what the message actually reports: green only
    // when the run finished end to end, amber when the AI step did not.
    $cpanalyzer_status_class = 'notice-info';
    if ( 0 === strpos( $status, '✅' ) ) {
        $cpanalyzer_status_class = 'notice-success';
    } elseif ( 0 === strpos( $status, '⚠️' ) || 0 === strpos( $status, '⏳' ) ) {
        $cpanalyzer_status_class = 'notice-warning';
    }
    ?>
        <div class="notice <?php 
    echo esc_attr( $cpanalyzer_status_class );
    ?>">
            <p><?php 
    echo esc_html( $status );
    ?></p>
        </div>
    <?php 
}
?>
    
    <?php 
// Processing / attention banner. The spinner shows ONLY while work is
// genuinely in flight. Flagged pages missing AI output with nothing
// running is a failed-or-skipped state, not a pending one — showing a
// spinner for it (the old behavior) meant an eternal "Processing…"
// after any AI rate-limit failure.
$cpanalyzer_pending_content_analysis = get_transient( 'cpanalyzer_pending_content_analysis' );
$cpanalyzer_pending_ai_processing = get_transient( 'cpanalyzer_pending_ai_payload' );
// Build a URL-keyed lookup of completed AI actions. page_actions is a
// numerically-indexed list of {url: ...} rows, not keyed by URL — so the old
// isset($cpanalyzer_actions[$url]) check never matched.
$cpanalyzer_actions_by_url = array();
foreach ( $cpanalyzer_actions as $cpanalyzer_action ) {
    if ( !empty( $cpanalyzer_action['url'] ) ) {
        $cpanalyzer_actions_by_url[$cpanalyzer_action['url']] = $cpanalyzer_action;
    }
}
// Count only genuinely flagged pages (exclude 'none'/good pages, which never
// get content or AI work) and what they still need.
$cpanalyzer_flagged_needing_content = 0;
$cpanalyzer_flagged_needing_ai = 0;
foreach ( $cpanalyzer_flags as $cpanalyzer_url => $cpanalyzer_flag_type ) {
    if ( $cpanalyzer_flag_type === 'none' ) {
        continue;
    }
    if ( empty( $cpanalyzer_content_data[$cpanalyzer_url] ) ) {
        $cpanalyzer_flagged_needing_content++;
    }
    if ( empty( $cpanalyzer_actions_by_url[$cpanalyzer_url] ) ) {
        $cpanalyzer_flagged_needing_ai++;
    }
}
$cpanalyzer_total_remaining_urls = $cpanalyzer_flagged_needing_content + $cpanalyzer_flagged_needing_ai;
// Work is in flight only when the plugin's own table or locks say so —
// never inferred from missing results.
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Cheap COUNT on the plugin's own table for live status.
$cpanalyzer_active_url_rows = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . esc_sql( $wpdb->prefix . 'cpanalyzer_urls' ) . ' WHERE status IN (%s, %s)', 'pending', 'in_progress' ) );
$cpanalyzer_work_in_flight = $cpanalyzer_active_url_rows > 0 || get_transient( 'cpanalyzer_batch_running' ) || !empty( $cpanalyzer_pending_content_analysis ) || !empty( $cpanalyzer_pending_ai_processing );
$cpanalyzer_ai_key_present = cpanalyzer_ai_is_configured();
?>

    <?php 
if ( $cpanalyzer_work_in_flight ) {
    ?>
        <div class="notice notice-warning cpanalyzer-waiting-banner" style="border-left-color: #ff9800; background-color: #fff3e0; padding: 15px;">
            <div style="display: flex; align-items: center; gap: 15px;">
                <div class="cpanalyzer-progress-spinner" style="width: 20px; height: 20px; border: 2px solid #ff9800; border-top: 2px solid transparent; border-radius: 50%; animation: cpanalyzer-spin 1s linear infinite;"></div>
                <div>
                    <p style="margin: 0; font-weight: 600; color: #e65100;">
                        <?php 
    $cpanalyzer_in_flight_count = ( $cpanalyzer_active_url_rows > 0 ? $cpanalyzer_active_url_rows : $cpanalyzer_total_remaining_urls );
    /* translators: %d: number of URLs being processed */
    echo esc_html( sprintf( __( '🔄 Processing %d URLs... Each URL takes approximately 1 minute to analyze completely. Please wait.', 'content-performance-analyzer' ), max( 1, $cpanalyzer_in_flight_count ) ) );
    ?>
                    </p>
                    <p style="margin: 5px 0 0 0; font-size: 14px; color: #bf360c;">
                        <strong><?php 
    esc_html_e( 'Status:', 'content-performance-analyzer' );
    ?></strong>
                        <?php 
    if ( $cpanalyzer_flagged_needing_content > 0 ) {
        /* translators: %d: number of pages remaining for content analysis */
        echo esc_html( sprintf( __( 'Content analysis: %d pages remaining', 'content-performance-analyzer' ), $cpanalyzer_flagged_needing_content ) );
    } elseif ( $cpanalyzer_flagged_needing_ai > 0 ) {
        /* translators: %d: number of pages remaining for AI suggestions */
        echo esc_html( sprintf( __( 'AI suggestions: %d pages remaining', 'content-performance-analyzer' ), $cpanalyzer_flagged_needing_ai ) );
    } else {
        echo esc_html( __( 'Finalizing analysis...', 'content-performance-analyzer' ) );
    }
    ?>
                    </p>
                </div>
            </div>
        </div>
    <?php 
} elseif ( $cpanalyzer_total_remaining_urls > 0 ) {
    ?>
        <?php 
    $cpanalyzer_ai_drain_state = (array) get_option( 'cpanalyzer_ai_drain_state', array() );
    $cpanalyzer_ai_drain_next = wp_next_scheduled( 'cpanalyzer_ai_drain' );
    ?>
        <?php 
    if ( $cpanalyzer_ai_drain_next && $cpanalyzer_flagged_needing_ai > 0 ) {
        ?>
            <div class="notice notice-info" style="padding: 12px 15px;">
                <p style="margin: 0 0 4px 0; font-weight: 600;">
                    <?php 
        esc_html_e( 'Filling in AI suggestions automatically', 'content-performance-analyzer' );
        ?>
                </p>
                <p style="margin: 0;">
                    <?php 
        /* translators: 1: number of pages remaining, 2: next attempt time */
        echo esc_html( sprintf( __( '%1$d pages remaining. The plugin is processing one page every few minutes to stay inside free AI tier limits — next attempt at %2$s. You can also fill them all now with "Retry missing/expired AI suggestions" below.', 'content-performance-analyzer' ), $cpanalyzer_flagged_needing_ai, wp_date( get_option( 'time_format' ), $cpanalyzer_ai_drain_next ) ) );
        ?>
                </p>
            </div>
        <?php 
    } elseif ( 'daily_cap' === ($cpanalyzer_ai_drain_state['stopped'] ?? '') ) {
        ?>
            <div class="notice notice-warning" style="padding: 12px 15px;">
                <p style="margin: 0; font-weight: 600;">
                    <?php 
        /* translators: %d: number of pages remaining */
        echo esc_html( sprintf( __( 'Today\'s free AI quota is used up — the remaining %d pages will fill automatically tomorrow.', 'content-performance-analyzer' ), $cpanalyzer_flagged_needing_ai ) );
        ?>
                </p>
            </div>
        <?php 
    } else {
        ?>
        <div class="notice notice-warning" style="padding: 12px 15px;">
            <?php 
        if ( $cpanalyzer_flagged_needing_ai > 0 ) {
            ?>
                <p style="margin: 0 0 4px 0; font-weight: 600;">
                    <?php 
            /* translators: %d: number of flagged pages without AI suggestions */
            echo esc_html( sprintf( _n(
                '%d flagged page has no AI suggestions yet.',
                '%d flagged pages have no AI suggestions yet.',
                $cpanalyzer_flagged_needing_ai,
                'content-performance-analyzer'
            ), $cpanalyzer_flagged_needing_ai ) );
            ?>
                </p>
                <p style="margin: 0;">
                    <?php 
            if ( $cpanalyzer_ai_key_present ) {
                ?>
                        <?php 
                esc_html_e( 'The last run may have hit AI rate limits or stopped early — nothing is processing right now. Click "Retry missing/expired AI suggestions" below to fill them; pages that already completed are unaffected.', 'content-performance-analyzer' );
                ?>
                    <?php 
            } elseif ( $cpanalyzer_hosted_ai_selected ) {
                ?>
                        <?php 
                esc_html_e( 'The hosted AI service could not be reached, so recommendations cannot be generated. Check the license on the Settings page, then click "Retry missing/expired AI suggestions".', 'content-performance-analyzer' );
                ?>
                    <?php 
            } else {
                ?>
                        <?php 
                esc_html_e( 'No AI provider key is configured, so recommendations cannot be generated. Add a key on the Settings page (Groq and Gemini have free tiers), then click "Retry missing/expired AI suggestions".', 'content-performance-analyzer' );
                ?>
                    <?php 
            }
            ?>
                </p>
            <?php 
        }
        ?>
            <?php 
        if ( $cpanalyzer_flagged_needing_content > 0 ) {
            ?>
                <p style="margin: <?php 
            echo ( $cpanalyzer_flagged_needing_ai > 0 ? '8px' : '0' );
            ?> 0 0 0;">
                    <?php 
            /* translators: %d: number of flagged pages without content analysis */
            echo esc_html( sprintf( _n(
                '%d flagged page is missing content analysis — click "Process Pending URLs" below to complete it.',
                '%d flagged pages are missing content analysis — click "Process Pending URLs" below to complete them.',
                $cpanalyzer_flagged_needing_content,
                'content-performance-analyzer'
            ), $cpanalyzer_flagged_needing_content ) );
            ?>
                </p>
            <?php 
        }
        ?>
            <?php 
        if ( in_array( $cpanalyzer_ai_drain_state['stopped'] ?? '', array('fatal', 'quota'), true ) && !empty( $cpanalyzer_ai_drain_state['last_error'] ) ) {
            ?>
                <p style="margin: 8px 0 0 0;">
                    <?php 
            // Whatever stopped the drain says so in its own words. For
            // a hosted quota stop that is the relay's message, which
            // already names the limit and when it resets — rewriting
            // it here could only contradict it.
            echo esc_html( $cpanalyzer_ai_drain_state['last_error'] );
            ?>
                </p>
            <?php 
        }
        ?>
        </div>
        <?php 
    }
    ?>
    <?php 
}
?>
    
    
    <div class="cpanalyzer-legend">
        <p><strong><?php 
esc_html_e( 'Legend:', 'content-performance-analyzer' );
?></strong></p>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr( ( function_exists( 'cpanalyzer_get_flag_tooltip' ) ? cpanalyzer_get_flag_tooltip( 'decay' ) : '' ) );
?>">
            🛑 <?php 
esc_html_e( 'Decay', 'content-performance-analyzer' );
?>
        </span>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr( ( function_exists( 'cpanalyzer_get_flag_tooltip' ) ? cpanalyzer_get_flag_tooltip( 'seo' ) : '' ) );
?>">
            🔎 <?php 
esc_html_e( 'SEO', 'content-performance-analyzer' );
?>
        </span>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr( ( function_exists( 'cpanalyzer_get_flag_tooltip' ) ? cpanalyzer_get_flag_tooltip( 'conversion' ) : '' ) );
?>">
            💰 <?php 
esc_html_e( 'Conversion', 'content-performance-analyzer' );
?>
        </span>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr( ( function_exists( 'cpanalyzer_get_flag_tooltip' ) ? cpanalyzer_get_flag_tooltip( 'performance' ) : '' ) );
?>">
            ⚡ <?php 
esc_html_e( 'Performance', 'content-performance-analyzer' );
?>
        </span>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr__( 'Content has been analyzed for technical and quality issues', 'content-performance-analyzer' );
?>">
            📄 <?php 
esc_html_e( 'Content Analyzed', 'content-performance-analyzer' );
?>
        </span>
        <span class="cpanalyzer-legend-item" title="<?php 
echo esc_attr__( 'Page performing well, no issues detected', 'content-performance-analyzer' );
?>">
            ✅ <?php 
esc_html_e( 'Good', 'content-performance-analyzer' );
?>
        </span>
    </div>
    
    <?php 
if ( empty( $cpanalyzer_flags ) ) {
    ?>
        <?php 
    // Distinguish "nothing analyzed yet" from "no URLs added at all" so a
    // fresh install gets a getting-started path instead of a dead end.
    global $wpdb;
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Cheap COUNT on the plugin's own table for the empty state.
    $cpanalyzer_url_count = (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . esc_sql( $wpdb->prefix . 'cpanalyzer_urls' ) );
    ?>
        <?php 
    if ( 0 === $cpanalyzer_url_count ) {
        ?>
            <div class="notice notice-info">
                <p>
                    <strong><?php 
        esc_html_e( 'Get started in about two minutes', 'content-performance-analyzer' );
        ?></strong>
                    — <?php 
        esc_html_e( 'import your site\'s pages with one click and run a content check. No Google or AI setup required for the first scan.', 'content-performance-analyzer' );
        ?>
                </p>
                <p>
                    <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=cpanalyzer-url-management' ) );
        ?>" class="button button-primary">
                        <?php 
        esc_html_e( 'Import Your Pages', 'content-performance-analyzer' );
        ?>
                    </a>
                </p>
            </div>
        <?php 
    } else {
        ?>
            <div class="notice notice-warning">
                <p>
                    <?php 
        esc_html_e( 'No flagged pages yet. The system runs daily automatically.', 'content-performance-analyzer' );
        ?>
                    <br>
                    <?php 
        esc_html_e( 'For manual testing, visit:', 'content-performance-analyzer' );
        ?>
                    <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=content-insights&cpanalyzer_run=1&cpanalyzer_nonce=' . wp_create_nonce( 'cpanalyzer_manual_run' ) ) );
        ?>">
                        <?php 
        esc_html_e( 'Run Manual Analysis', 'content-performance-analyzer' );
        ?>
                    </a>
                </p>
            </div>
        <?php 
    }
    ?>
    <?php 
} else {
    ?>
        <div class="cpanalyzer-actions-top" style="display: flex; gap: 15px; align-items: center; margin-bottom: 20px;">
            <button type="button" id="cpanalyzer-retry-missing" class="button button-primary cpanalyzer-retry-button">
                <?php 
    esc_html_e( 'Retry missing/expired AI suggestions', 'content-performance-analyzer' );
    ?>
            </button>
            <button type="button" id="cpanalyzer-sync-batch-data" class="button button-secondary" title="<?php 
    esc_attr_e( 'Sync uploaded URLs from batch processing to insights display', 'content-performance-analyzer' );
    ?>">
                <?php 
    esc_html_e( '🔄 Sync All URLs', 'content-performance-analyzer' );
    ?>
            </button>
            <button type="button" id="cpanalyzer-safe-manual-scan" class="button" title="<?php 
    esc_attr_e( 'Process pending URLs safely in background (no timeout risk)', 'content-performance-analyzer' );
    ?>">
                <?php 
    esc_html_e( '▶️ Process Pending URLs', 'content-performance-analyzer' );
    ?>
            </button>
            <button type="button" id="cpanalyzer-force-restart" class="button" style="background: #d63638; color: white;" title="<?php 
    esc_attr_e( 'Force restart stuck processing (clears all locks and resets stuck URLs)', 'content-performance-analyzer' );
    ?>">
                <?php 
    esc_html_e( '🔄 Force Restart', 'content-performance-analyzer' );
    ?>
            </button>
            <span id="cpanalyzer-retry-msg" class="cpanalyzer-retry-message"></span>
        </div>
        
        <?php 
    // Get URL upload order for sorting
    $cpanalyzer_url_order = (array) get_option( 'cpanalyzer_url_upload_order', array() );
    // Sort flags: first by importance (decay > SEO > conversion), then by upload order
    $cpanalyzer_sorted_flags = $cpanalyzer_flags;
    uksort( $cpanalyzer_sorted_flags, function ( $a, $b ) use($cpanalyzer_flags, $cpanalyzer_url_order) {
        $priority_order = array(
            'decay'      => 0,
            'seo'        => 1,
            'conversion' => 2,
            'none'       => 3,
        );
        $priority_a = $priority_order[$cpanalyzer_flags[$a]] ?? 4;
        $priority_b = $priority_order[$cpanalyzer_flags[$b]] ?? 4;
        // If same flag priority, sort by upload order (preserving txt file sequence)
        if ( $priority_a === $priority_b ) {
            $order_a = $cpanalyzer_url_order[$a] ?? 999;
            $order_b = $cpanalyzer_url_order[$b] ?? 999;
            return $order_a <=> $order_b;
        }
        return $priority_a <=> $priority_b;
    } );
    $cpanalyzer_content_analyzed_count = count( $cpanalyzer_content_data );
    // Search functionality with nonce verification
    $cpanalyzer_search_query = '';
    if ( isset( $_GET['search'] ) ) {
        // Verify nonce for search functionality - required for security
        if ( isset( $_GET['cpanalyzer_insights_filter_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['cpanalyzer_insights_filter_nonce'] ) ), 'cpanalyzer_insights_filter' ) ) {
            $cpanalyzer_search_query = sanitize_text_field( wp_unslash( $_GET['search'] ) );
        }
        // If nonce is missing or invalid, ignore the search query (do not process it)
    }
    $cpanalyzer_filtered_flags = $cpanalyzer_sorted_flags;
    // Filter by search query if provided
    if ( !empty( $cpanalyzer_search_query ) ) {
        $cpanalyzer_filtered_flags = array_filter( $cpanalyzer_sorted_flags, function ( $cpanalyzer_flag, $cpanalyzer_url ) use($cpanalyzer_search_query) {
            return stripos( $cpanalyzer_url, $cpanalyzer_search_query ) !== false;
        }, ARRAY_FILTER_USE_BOTH );
    }
    $cpanalyzer_total_rows = count( $cpanalyzer_filtered_flags );
    // Pagination
    $per_page = 25;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe pagination parameter processing
    $cpanalyzer_current_page = ( isset( $_GET['paged'] ) ? max( 1, intval( wp_unslash( $_GET['paged'] ) ) ) : 1 );
    $cpanalyzer_total_pages = ceil( $cpanalyzer_total_rows / $per_page );
    $cpanalyzer_offset = ($cpanalyzer_current_page - 1) * $per_page;
    $cpanalyzer_paginated_flags = array_slice(
        $cpanalyzer_filtered_flags,
        $cpanalyzer_offset,
        $per_page,
        true
    );
    $cpanalyzer_row_count = 0;
    $cpanalyzer_active_batch_lock = get_transient( 'cpanalyzer_batch_running' );
    $cpanalyzer_hide_report_until_complete = !empty( $cpanalyzer_active_batch_lock ) || !empty( $cpanalyzer_pending_content_analysis ) || !empty( $cpanalyzer_pending_ai_processing );
    ?>
        
        <?php 
    // Count actually flagged pages (not 'none')
    $cpanalyzer_actual_flagged_count = 0;
    foreach ( $cpanalyzer_flags as $cpanalyzer_flag ) {
        if ( $cpanalyzer_flag !== 'none' ) {
            $cpanalyzer_actual_flagged_count++;
        }
    }
    ?>
        <p><strong><?php 
    echo esc_html( sprintf(
        /* translators: 1: total pages; 2: flagged pages; 3: content analyzed pages; 4: current page; 5: total pages */
        __( 'Total pages: %1$d | Flagged: %2$d | Content analyzed: %3$d | Showing page %4$d of %5$d', 'content-performance-analyzer' ),
        intval( $cpanalyzer_total_rows ),
        intval( $cpanalyzer_actual_flagged_count ),
        intval( $cpanalyzer_content_analyzed_count ),
        intval( $cpanalyzer_current_page ),
        intval( $cpanalyzer_total_pages )
    ) );
    ?></strong></p>

        <?php 
    if ( $cpanalyzer_hide_report_until_complete ) {
        ?>
            <div class="notice notice-info cpanalyzer-report-hold">
                <p><strong><?php 
        esc_html_e( 'Insights report is still being prepared.', 'content-performance-analyzer' );
        ?></strong></p>
                <p><?php 
        esc_html_e( 'The table stays hidden until the active analysis run finishes so you do not see partial rows or missing AI actions. Once processing completes, reload or sync to view the full report.', 'content-performance-analyzer' );
        ?></p>
            </div>
        <?php 
    } else {
        ?>
        <!-- Search Box -->
        <div class="cpanalyzer-search-box" style="margin-bottom: 20px;">
            <form method="get" action="">
                <!-- Preserve whitelisted query parameters -->
                <?php 
        // Whitelist of allowed query parameters to preserve
        $cpanalyzer_allowed_query_params = array('page');
        foreach ( $cpanalyzer_allowed_query_params as $cpanalyzer_allowed_key ) {
            if ( isset( $_GET[$cpanalyzer_allowed_key] ) ) {
                $cpanalyzer_sanitized_key = sanitize_key( $cpanalyzer_allowed_key );
                $cpanalyzer_sanitized_value = sanitize_text_field( wp_unslash( $_GET[$cpanalyzer_allowed_key] ) );
                ?>
                        <input type="hidden"
                               name="<?php 
                echo esc_attr( $cpanalyzer_sanitized_key );
                ?>"
                               value="<?php 
                echo esc_attr( $cpanalyzer_sanitized_value );
                ?>" />
                        <?php 
            }
        }
        ?>

                <?php 
        wp_nonce_field( 'cpanalyzer_insights_filter', 'cpanalyzer_insights_filter_nonce', false );
        ?>
                
                <div style="display: flex; align-items: center; gap: 10px; max-width: 500px;">
                    <label for="cpanalyzer-search-input" style="min-width: 120px; font-weight: 600;">
                        <?php 
        esc_html_e( 'Search Pages:', 'content-performance-analyzer' );
        ?>
                    </label>
                    <input type="text" 
                           id="cpanalyzer-search-input"
                           name="search" 
                           value="<?php 
        echo esc_attr( $cpanalyzer_search_query );
        ?>" 
                           placeholder="<?php 
        esc_attr_e( 'Enter URL or page path...', 'content-performance-analyzer' );
        ?>"
                           style="flex: 1; padding: 6px 10px; border: 1px solid #ddd; border-radius: 3px;" />
                    <button type="submit" class="button">
                        <?php 
        esc_html_e( 'Search', 'content-performance-analyzer' );
        ?>
                    </button>
                    <?php 
        if ( !empty( $cpanalyzer_search_query ) ) {
            ?>
                        <a href="<?php 
            echo esc_url( remove_query_arg( ['search', 'paged'] ) );
            ?>" class="button">
                            <?php 
            esc_html_e( 'Clear', 'content-performance-analyzer' );
            ?>
                        </a>
                    <?php 
        }
        ?>
                </div>
            </form>
        </div>

        <!-- Export Button -->
        <div style="margin: 15px 0; text-align: right;">
            <form method="post" action="" style="display: inline;">
                <?php 
        wp_nonce_field( 'cpanalyzer_export_csv', 'cpanalyzer_export_csv_nonce' );
        ?>
                <button type="submit" name="cpanalyzer_export_csv" class="button button-primary" style="background: #00a32a; border-color: #00a32a;">
                    📊 <?php 
        esc_html_e( 'Export All Data to CSV', 'content-performance-analyzer' );
        ?>
                </button>
                <p style="margin: 5px 0 0 0; font-size: 12px; color: #666; text-align: right;">
                    <?php 
        /* translators: %d: number of pages to be exported */
        /* translators: %d: total number of pages to export */
        echo esc_html( sprintf( __( 'Export all %d pages with GA4, GSC, content, and AI data', 'content-performance-analyzer' ), $cpanalyzer_total_rows ) );
        ?>
                </p>
            </form>
        </div>
        
        <?php 
        if ( !empty( $cpanalyzer_search_query ) ) {
            ?>
            <div class="notice notice-info" style="margin-bottom: 15px;">
                <p>
                    <?php 
            echo esc_html( sprintf( 
                /* translators: 1: search query; 2: number of pages found */
                __( 'Search results for "%1$s" - %2$d pages found', 'content-performance-analyzer' ),
                $cpanalyzer_search_query,
                $cpanalyzer_total_rows
             ) );
            ?>
                </p>
            </div>
        <?php 
        }
        ?>

        <div class="cpanalyzer-insights-table-wrap">
        <table id="cpanalyzer-insights-table" class="widefat striped">
            <thead>
                <tr>
                    <th><?php 
        esc_html_e( 'Flag', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Page', 'content-performance-analyzer' );
        ?></th>
                    <th title="<?php 
        esc_attr_e( 'Time since this page was last updated. Old pages on decaying topics are the first refresh candidates.', 'content-performance-analyzer' );
        ?>"><?php 
        esc_html_e( 'Age', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'AI Action', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Priority', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Primary Keyword', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Performance', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Views', 'content-performance-analyzer' );
        ?><br><small>Δ %</small></th>
                    <th><?php 
        esc_html_e( 'Engagement', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Impressions', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'CTR', 'content-performance-analyzer' );
        ?></th>
                    <th title="<?php 
        esc_attr_e( 'Answer-engine readiness: how well this page is structured to be quoted by AI search (question headings, direct answers, schema, freshness)', 'content-performance-analyzer' );
        ?>"><?php 
        esc_html_e( 'AEO', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Conversions', 'content-performance-analyzer' );
        ?></th>
                    <th><?php 
        esc_html_e( 'Actions', 'content-performance-analyzer' );
        ?></th>
                </tr>
            </thead>
            <tbody>
                <?php 
        foreach ( $cpanalyzer_paginated_flags as $cpanalyzer_url => $cpanalyzer_flag ) {
            ?>
                    <?php 
            // Ensure $cpanalyzer_url is string
            $cpanalyzer_url = (string) $cpanalyzer_url;
            // Flag badge
            $cpanalyzer_flag_badges = array(
                'decay'       => '🛑 ' . __( 'Decay', 'content-performance-analyzer' ),
                'seo'         => '🔎 ' . __( 'SEO', 'content-performance-analyzer' ),
                'conversion'  => '💰 ' . __( 'Conv', 'content-performance-analyzer' ),
                'performance' => '⚡ ' . __( 'Performance', 'content-performance-analyzer' ),
                'none'        => '✅ ' . __( 'Good', 'content-performance-analyzer' ),
            );
            $cpanalyzer_badge = $cpanalyzer_flag_badges[$cpanalyzer_flag] ?? '–';
            if ( !empty( $cpanalyzer_content_data[$cpanalyzer_url] ) ) {
                $cpanalyzer_badge .= ' 📄';
            }
            // Decay-type diagnosis — deterministic, computed from this
            // page's own period deltas at processing time.
            $cpanalyzer_decay_diagnosis = (array) ($cpanalyzer_gsc_rows[$cpanalyzer_url]['decay_diagnosis'] ?? array());
            $cpanalyzer_diagnosis_type = (string) ($cpanalyzer_decay_diagnosis['type'] ?? 'none');
            $cpanalyzer_diagnosis_label = '';
            if ( !in_array( $cpanalyzer_diagnosis_type, array('none', ''), true ) ) {
                $cpanalyzer_diagnosis_label = (string) ($cpanalyzer_decay_diagnosis['label'] ?? '');
            }
            // Severity color: expected patterns green, data-quality
            // suspicions amber, genuine decay red.
            $cpanalyzer_diagnosis_colors = array(
                'seasonal' => '#007017',
                'tracking' => '#996800',
            );
            $cpanalyzer_diagnosis_color = $cpanalyzer_diagnosis_colors[$cpanalyzer_diagnosis_type] ?? '#b32d2e';
            // Action data
            $cpanalyzer_action_text = '<em class="cpanalyzer-ai-action-status">' . esc_html__( 'N/A (awaiting AI run)', 'content-performance-analyzer' ) . '</em>';
            $cpanalyzer_action_headline = '';
            $cpanalyzer_primary_keyword = '';
            $cpanalyzer_ai_keyword = '';
            $cpanalyzer_suggested_keywords = array();
            $cpanalyzer_content_priority = '';
            $cpanalyzer_technical_issues = array();
            $cpanalyzer_issue_summary = '';
            $cpanalyzer_why_now = '';
            $cpanalyzer_seo_recommendation = '';
            $cpanalyzer_aeo_recommendation = '';
            $cpanalyzer_geo_recommendation = '';
            $cpanalyzer_engagement_recommendation = '';
            $cpanalyzer_is_expired = false;
            $cpanalyzer_action_payload = null;
            // Answer-engine readiness + question gaps — deterministic,
            // from scan and GSC data directly, never from AI output.
            $cpanalyzer_aeo_readiness = ( function_exists( 'cpanalyzer_aeo_readiness' ) && !empty( $cpanalyzer_content_data[$cpanalyzer_url] ) ? cpanalyzer_aeo_readiness( $cpanalyzer_content_data[$cpanalyzer_url] ) : null );
            $cpanalyzer_question_gaps = ( function_exists( 'cpanalyzer_get_question_gaps' ) ? cpanalyzer_get_question_gaps( $cpanalyzer_url, $cpanalyzer_gsc_rows, $cpanalyzer_content_data ) : array() );
            // Scraped list of images missing alt text — displayed from
            // scan data directly, never from AI output.
            $cpanalyzer_missing_alt_images = array();
            if ( !empty( $cpanalyzer_content_data[$cpanalyzer_url]['images_missing_alt_list'] ) && is_array( $cpanalyzer_content_data[$cpanalyzer_url]['images_missing_alt_list'] ) ) {
                $cpanalyzer_missing_alt_images = array_values( array_filter( array_map( 'esc_url_raw', (array) $cpanalyzer_content_data[$cpanalyzer_url]['images_missing_alt_list'] ) ) );
            }
            // Content issues summary (will be merged into AI Action)
            $cpanalyzer_content_issues = array();
            if ( !empty( $cpanalyzer_content_data[$cpanalyzer_url] ) && is_array( $cpanalyzer_content_data[$cpanalyzer_url] ) ) {
                $cpanalyzer_content = $cpanalyzer_content_data[$cpanalyzer_url];
                if ( !empty( $cpanalyzer_content['has_noindex'] ) ) {
                    $cpanalyzer_content_issues[] = __( '⚠ noindex tag — excluded from search', 'content-performance-analyzer' );
                }
                if ( !empty( $cpanalyzer_content['canonical_mismatch'] ) ) {
                    $cpanalyzer_content_issues[] = __( 'Canonical points to a different URL', 'content-performance-analyzer' );
                }
                if ( ($cpanalyzer_content['title']['length'] ?? 0) < 30 ) {
                    $cpanalyzer_content_issues[] = __( 'Short title', 'content-performance-analyzer' );
                }
                if ( ($cpanalyzer_content['meta_description']['length'] ?? 0) === 0 ) {
                    $cpanalyzer_content_issues[] = __( 'No meta desc', 'content-performance-analyzer' );
                }
                if ( ($cpanalyzer_content['word_count'] ?? 0) < 300 ) {
                    $cpanalyzer_content_issues[] = __( 'Thin content', 'content-performance-analyzer' );
                }
                if ( empty( $cpanalyzer_content['h1_tags'] ) ) {
                    $cpanalyzer_content_issues[] = __( 'No H1', 'content-performance-analyzer' );
                }
                if ( ($cpanalyzer_content['images_without_alt'] ?? 0) > 0 ) {
                    $cpanalyzer_content_issues[] = __( 'Missing alt text', 'content-performance-analyzer' );
                }
                if ( !empty( $cpanalyzer_content['stale_dates']['oldest_year'] ) ) {
                    $cpanalyzer_content_issues[] = sprintf( 
                        /* translators: %d: the oldest year still referenced in the page copy */
                        __( 'Dated copy (refers to %d)', 'content-performance-analyzer' ),
                        (int) $cpanalyzer_content['stale_dates']['oldest_year']
                     );
                }
                if ( ($cpanalyzer_content['has_cta_buttons']['count'] ?? 0) === 0 ) {
                    $cpanalyzer_content_issues[] = __( 'No CTAs', 'content-performance-analyzer' );
                }
            }
            // First, get AI keyword data
            foreach ( $cpanalyzer_actions as $cpanalyzer_action ) {
                if ( !empty( $cpanalyzer_action['url'] ) && $cpanalyzer_action['url'] === $cpanalyzer_url ) {
                    $cpanalyzer_timestamp = $cpanalyzer_action['timestamp'] ?? 0;
                    $cpanalyzer_is_expired = ( function_exists( 'cpanalyzer_is_suggestion_expired' ) ? cpanalyzer_is_suggestion_expired( $cpanalyzer_timestamp ) : false );
                    $cpanalyzer_action_headline = trim( (string) ($cpanalyzer_action['action'] ?? '') );
                    $cpanalyzer_ai_keyword = sanitize_text_field( $cpanalyzer_action['primary_keyword'] ?? '' );
                    $cpanalyzer_suggested_keywords = array_values( array_filter( array_map( 'sanitize_text_field', (array) ($cpanalyzer_action['suggested_keywords'] ?? array()) ) ) );
                    $cpanalyzer_content_priority = sanitize_key( $cpanalyzer_action['content_priority'] ?? '' );
                    $cpanalyzer_technical_issues = array_values( array_filter( array_map( 'sanitize_text_field', (array) ($cpanalyzer_action['technical_issues'] ?? array()) ) ) );
                    $cpanalyzer_issue_summary = trim( (string) ($cpanalyzer_action['issue_summary'] ?? '') );
                    $cpanalyzer_why_now = trim( (string) ($cpanalyzer_action['why_now'] ?? '') );
                    $cpanalyzer_seo_recommendation = trim( (string) ($cpanalyzer_action['seo_recommendation'] ?? '') );
                    $cpanalyzer_aeo_recommendation = trim( (string) ($cpanalyzer_action['aeo_recommendation'] ?? '') );
                    $cpanalyzer_geo_recommendation = trim( (string) ($cpanalyzer_action['geo_recommendation'] ?? '') );
                    $cpanalyzer_engagement_recommendation = trim( (string) ($cpanalyzer_action['engagement_recommendation'] ?? '') );
                    $cpanalyzer_pro_artifacts = null;
                    $cpanalyzer_action_payload = array(
                        'url'                      => $cpanalyzer_url,
                        'headline'                 => $cpanalyzer_action_headline,
                        'issueSummary'             => $cpanalyzer_issue_summary,
                        'whyNow'                   => $cpanalyzer_why_now,
                        'seoRecommendation'        => $cpanalyzer_seo_recommendation,
                        'aeoRecommendation'        => $cpanalyzer_aeo_recommendation,
                        'geoRecommendation'        => $cpanalyzer_geo_recommendation,
                        'engagementRecommendation' => $cpanalyzer_engagement_recommendation,
                        'primaryKeyword'           => $cpanalyzer_ai_keyword,
                        'suggestedKeywords'        => $cpanalyzer_suggested_keywords,
                        'contentPriority'          => $cpanalyzer_content_priority,
                        'technicalIssues'          => $cpanalyzer_technical_issues,
                        'contentIssues'            => $cpanalyzer_content_issues,
                        'modelUsed'                => sanitize_text_field( $cpanalyzer_action['model_used'] ?? '' ),
                        'proArtifacts'             => $cpanalyzer_pro_artifacts,
                        'missingAltImages'         => $cpanalyzer_missing_alt_images,
                        'aeoReadiness'             => $cpanalyzer_aeo_readiness,
                        'questionGaps'             => $cpanalyzer_question_gaps,
                        'decayDiagnosis'           => $cpanalyzer_decay_diagnosis,
                        'cannibalization'          => array_slice( (array) ($cpanalyzer_gsc_rows[$cpanalyzer_url]['cannibalization'] ?? array()), 0, 3 ),
                        'clickTrend'               => ( !empty( $cpanalyzer_gsc_rows[$cpanalyzer_url]['trend'] ) && function_exists( 'cpanalyzer_analyze_click_trend' ) ? cpanalyzer_analyze_click_trend( $cpanalyzer_gsc_rows[$cpanalyzer_url]['trend'] ) : null ),
                        'inboundLinks'             => ( isset( $cpanalyzer_content_data[$cpanalyzer_url]['inbound_internal_links'] ) ? (int) $cpanalyzer_content_data[$cpanalyzer_url]['inbound_internal_links'] : null ),
                        'isOrphan'                 => !empty( $cpanalyzer_content_data[$cpanalyzer_url]['is_orphan'] ),
                        'isExpired'                => $cpanalyzer_is_expired,
                    );
                    $cpanalyzer_preview_summary = ( $cpanalyzer_issue_summary !== '' ? $cpanalyzer_issue_summary : $cpanalyzer_why_now );
                    $cpanalyzer_action_label = ( $cpanalyzer_action_headline !== '' ? $cpanalyzer_action_headline : __( 'AI recommendation available', 'content-performance-analyzer' ) );
                    $cpanalyzer_action_text = '<div class="cpanalyzer-ai-action-preview">';
                    if ( $cpanalyzer_is_expired ) {
                        $cpanalyzer_action_text .= '<span class="cpanalyzer-ai-action-status is-expired">' . esc_html__( 'Expired - needs refresh', 'content-performance-analyzer' ) . '</span>';
                    } else {
                        $cpanalyzer_action_text .= '<strong class="cpanalyzer-ai-action-title">' . esc_html( $cpanalyzer_action_label ) . '</strong>';
                    }
                    if ( $cpanalyzer_preview_summary !== '' ) {
                        $cpanalyzer_action_text .= '<span class="cpanalyzer-ai-action-summary">' . esc_html( wp_trim_words( $cpanalyzer_preview_summary, 16, '...' ) ) . '</span>';
                    }
                    $cpanalyzer_action_text .= '<button type="button" class="button button-small cpanalyzer-view-ai-action" data-ai-payload="' . esc_attr( wp_json_encode( $cpanalyzer_action_payload, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT ) ) . '">' . esc_html__( 'View AI details', 'content-performance-analyzer' ) . '</button>';
                    $cpanalyzer_action_text .= '</div>';
                    break;
                }
            }
            // If no AI action yet, show content issues in action column
            if ( $cpanalyzer_action_payload === null && !empty( $cpanalyzer_content_issues ) ) {
                $cpanalyzer_issues_text = implode( ', ', array_slice( $cpanalyzer_content_issues, 0, 3 ) );
                $cpanalyzer_action_text = '<div class="cpanalyzer-ai-action-preview"><em class="cpanalyzer-ai-action-status">' . esc_html__( 'Awaiting AI analysis', 'content-performance-analyzer' ) . '</em><span class="cpanalyzer-ai-action-summary">' . esc_html( $cpanalyzer_issues_text ) . '</span></div>';
            }
            // Primary keyword selection via shared helper.
            $cpanalyzer_kw_context = array(
                'title'    => $cpanalyzer_content_data[$cpanalyzer_url]['title']['text'] ?? '',
                'url'      => $cpanalyzer_url,
                'headings' => array_merge( $cpanalyzer_content_data[$cpanalyzer_url]['h1_tags'] ?? array(), $cpanalyzer_content_data[$cpanalyzer_url]['h2_tags'] ?? array(), $cpanalyzer_content_data[$cpanalyzer_url]['h3_tags'] ?? array() ),
            );
            $cpanalyzer_kw_result = cpanalyzer_select_primary_keyword( $cpanalyzer_gsc_rows[$cpanalyzer_url]['keywords'] ?? array(), $cpanalyzer_ai_keyword, $cpanalyzer_kw_context );
            if ( $cpanalyzer_kw_result['source'] === 'GSC' ) {
                $cpanalyzer_primary_keyword = esc_html( $cpanalyzer_kw_result['keyword'] ) . ' <small style="color:#27ae60;" title="' . esc_attr__( 'Primary keyword from Google Search Console top query for this URL.', 'content-performance-analyzer' ) . '">(GSC &bull; pos: ' . number_format( $cpanalyzer_kw_result['position'], 1 ) . ')</small>';
            } elseif ( $cpanalyzer_kw_result['source'] === 'Derived' ) {
                $cpanalyzer_primary_keyword = esc_html( $cpanalyzer_kw_result['keyword'] ) . ' <small style="color:#3498db;" title="' . esc_attr__( 'Primary keyword derived from the AI recommendation and grounded by available GSC and Serper signals when present. Used when no direct Search Console keyword is available to display.', 'content-performance-analyzer' ) . '">(Derived)</small>';
            }
            // GA data
            $cpanalyzer_views = intval( $cpanalyzer_ga_rows[$cpanalyzer_url]['views'] ?? 0 );
            $cpanalyzer_views_prev = intval( $cpanalyzer_ga_rows[$cpanalyzer_url]['views_prev'] ?? 0 );
            $cpanalyzer_view_change = ( $cpanalyzer_views_prev > 0 ? round( 100 * ($cpanalyzer_views - $cpanalyzer_views_prev) / $cpanalyzer_views_prev, 1 ) : 0 );
            $cpanalyzer_view_indicator = ( function_exists( 'cpanalyzer_get_change_indicator' ) ? cpanalyzer_get_change_indicator( $cpanalyzer_view_change ) : [
                'color' => '#000',
                'arrow' => '',
            ] );
            $cpanalyzer_engagement = ( isset( $cpanalyzer_ga_rows[$cpanalyzer_url]['engagement'] ) && is_numeric( $cpanalyzer_ga_rows[$cpanalyzer_url]['engagement'] ) ? number_format( $cpanalyzer_ga_rows[$cpanalyzer_url]['engagement'] * 100, 1 ) . '%' : '' );
            // GSC data
            $cpanalyzer_impressions = intval( $cpanalyzer_gsc_rows[$cpanalyzer_url]['impressions'] ?? 0 );
            $cpanalyzer_ctr = ( isset( $cpanalyzer_gsc_rows[$cpanalyzer_url]['ctr'] ) && is_numeric( $cpanalyzer_gsc_rows[$cpanalyzer_url]['ctr'] ) ? number_format( floatval( $cpanalyzer_gsc_rows[$cpanalyzer_url]['ctr'] ), 1 ) . '%' : '' );
            // PSI Performance data
            $cpanalyzer_psi_display = '';
            $cpanalyzer_psi_score = null;
            $cpanalyzer_cwv_status = '';
            $cpanalyzer_psi_error = '';
            $cpanalyzer_has_psi_data = !empty( $cpanalyzer_content_data[$cpanalyzer_url]['psi'] );
            if ( !empty( $cpanalyzer_content_data[$cpanalyzer_url]['psi_error'] ) ) {
                $cpanalyzer_psi_error = sanitize_text_field( $cpanalyzer_content_data[$cpanalyzer_url]['psi_error'] );
            }
            if ( $cpanalyzer_has_psi_data ) {
                $cpanalyzer_psi_data = $cpanalyzer_content_data[$cpanalyzer_url]['psi'];
                $cpanalyzer_primary_strategy = $cpanalyzer_psi_data['primary_strategy'] ?? 'mobile';
                $cpanalyzer_strategy_data = $cpanalyzer_psi_data[$cpanalyzer_primary_strategy] ?? null;
                if ( $cpanalyzer_strategy_data ) {
                    $cpanalyzer_psi_score = $cpanalyzer_strategy_data['score'] ?? null;
                    $cpanalyzer_cwv_pass = $cpanalyzer_strategy_data['core_web_vitals_pass'] ?? true;
                    $cpanalyzer_metrics = $cpanalyzer_strategy_data['metrics'] ?? array();
                    // Score badge with color
                    if ( $cpanalyzer_psi_score !== null ) {
                        if ( $cpanalyzer_psi_score >= 90 ) {
                            $cpanalyzer_badge_color = '#00a32a';
                        } elseif ( $cpanalyzer_psi_score >= 50 ) {
                            $cpanalyzer_badge_color = '#dba617';
                        } else {
                            $cpanalyzer_badge_color = '#d63638';
                        }
                        // Red
                        $cpanalyzer_psi_display .= '<span style="background: ' . $cpanalyzer_badge_color . '; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px;">' . $cpanalyzer_psi_score . '</span>';
                    }
                    // Core Web Vitals indicators
                    if ( !empty( $cpanalyzer_metrics ) ) {
                        $cpanalyzer_psi_display .= '<div style="font-size: 10px; margin-top: 2px;">';
                        // LCP
                        if ( isset( $cpanalyzer_metrics['LCP_ms'] ) ) {
                            $cpanalyzer_lcp_formatted = ( $cpanalyzer_metrics['LCP_ms'] > 1000 ? round( $cpanalyzer_metrics['LCP_ms'] / 1000, 1 ) . 's' : $cpanalyzer_metrics['LCP_ms'] . 'ms' );
                            $cpanalyzer_psi_display .= '<span title="LCP: ' . $cpanalyzer_metrics['LCP_ms'] . 'ms">LCP: ' . $cpanalyzer_lcp_formatted . '</span>';
                        }
                        // INP
                        if ( isset( $cpanalyzer_metrics['INP_ms'] ) ) {
                            if ( isset( $cpanalyzer_metrics['LCP_ms'] ) ) {
                                $cpanalyzer_psi_display .= ' | ';
                            }
                            $cpanalyzer_psi_display .= '<span title="INP: ' . $cpanalyzer_metrics['INP_ms'] . 'ms">INP: ' . $cpanalyzer_metrics['INP_ms'] . 'ms</span>';
                        }
                        // CLS
                        if ( isset( $cpanalyzer_metrics['CLS'] ) ) {
                            if ( isset( $cpanalyzer_metrics['LCP_ms'] ) || isset( $cpanalyzer_metrics['INP_ms'] ) ) {
                                $cpanalyzer_psi_display .= ' | ';
                            }
                            $cpanalyzer_psi_display .= '<span title="CLS: ' . $cpanalyzer_metrics['CLS'] . '">CLS: ' . $cpanalyzer_metrics['CLS'] . '</span>';
                        }
                        $cpanalyzer_psi_display .= '</div>';
                    }
                    // Performance flag indicator
                    if ( !$cpanalyzer_cwv_pass || $cpanalyzer_psi_score !== null && $cpanalyzer_psi_score < 50 ) {
                        $cpanalyzer_psi_display .= '<div style="color: #d63638; font-size: 10px;">⚡ Issues</div>';
                    }
                }
            }
            // Default display if no PSI data
            if ( empty( $cpanalyzer_psi_display ) ) {
                if ( $cpanalyzer_psi_error !== '' ) {
                    $cpanalyzer_psi_display = '<span style="color: #d63638; font-size: 11px;" title="' . esc_attr( $cpanalyzer_psi_error ) . '">' . esc_html__( 'PSI failed', 'content-performance-analyzer' ) . '</span>';
                } else {
                    $cpanalyzer_psi_display = '<span style="color: #666; font-size: 11px;">' . esc_html__( 'No data', 'content-performance-analyzer' ) . '</span>';
                }
            }
            // Form fills
            $cpanalyzer_form_fills = intval( $cpanalyzer_ga_rows[$cpanalyzer_url]['form_fills'] ?? 0 );
            // Priority color
            $cpanalyzer_priority_colors = array(
                'high'   => '#d63638',
                'medium' => '#dba617',
                'low'    => '#00a32a',
            );
            $cpanalyzer_priority_color = $cpanalyzer_priority_colors[$cpanalyzer_content_priority] ?? '#888';
            // Links
            $post_id = ( function_exists( 'url_to_postid' ) ? url_to_postid( $cpanalyzer_url ) : 0 );
            if ( !$post_id && '/' === $cpanalyzer_url && 'page' === get_option( 'show_on_front' ) ) {
                $post_id = (int) get_option( 'page_on_front' );
            }
            $cpanalyzer_edit_link = ( $post_id ? '<a href="' . esc_url( admin_url( 'post.php?post=' . $post_id . '&action=edit' ) ) . '" target="_blank">' . esc_html__( 'Edit', 'content-performance-analyzer' ) . '</a>' : '' );
            // Page age since the last content update.
            $cpanalyzer_modified_ts = 0;
            if ( $post_id ) {
                $cpanalyzer_modified_gmt = (string) get_post_field( 'post_modified_gmt', $post_id );
                if ( '' !== $cpanalyzer_modified_gmt && '0000-00-00 00:00:00' !== $cpanalyzer_modified_gmt ) {
                    $cpanalyzer_modified_ts = (int) strtotime( $cpanalyzer_modified_gmt . ' UTC' );
                }
            }
            $cpanalyzer_page_age = ( function_exists( 'cpanalyzer_page_age_display' ) ? cpanalyzer_page_age_display( $cpanalyzer_modified_ts ) : array(
                'label' => '',
                'stale' => false,
            ) );
            // Recovery status for pages the user marked as fixed.
            // Post-fix averages come from the weekly snapshot history
            // when available; the live row is the fallback until the
            // first post-fix snapshot lands.
            $cpanalyzer_recovery_chip = '';
            $cpanalyzer_is_marked_fixed = isset( $cpanalyzer_refreshed_map[$cpanalyzer_url] ) && is_array( $cpanalyzer_refreshed_map[$cpanalyzer_url] );
            if ( $cpanalyzer_is_marked_fixed && function_exists( 'cpanalyzer_recovery_status_for' ) ) {
                $cpanalyzer_rec_status = cpanalyzer_recovery_status_for(
                    $cpanalyzer_url,
                    $cpanalyzer_refreshed_map[$cpanalyzer_url],
                    $cpanalyzer_gsc_rows,
                    $cpanalyzer_ga_rows
                );
                if ( !empty( $cpanalyzer_rec_status['label'] ) ) {
                    $cpanalyzer_recovery_chip = '<br><small style="color:' . esc_attr( $cpanalyzer_rec_status['color'] ) . ';font-weight:600;">✓ ' . esc_html( $cpanalyzer_rec_status['label'] ) . '</small>';
                }
            }
            // Row actions: mark fixed / undo, and one-click refresh draft.
            $cpanalyzer_mark_link = '<a href="#" class="cpanalyzer-mark-fixed" data-url="' . esc_attr( $cpanalyzer_url ) . '" data-mode="' . (( $cpanalyzer_is_marked_fixed ? 'unmark' : 'mark' )) . '">' . (( $cpanalyzer_is_marked_fixed ? esc_html__( 'Unmark fixed', 'content-performance-analyzer' ) : esc_html__( 'Mark fixed', 'content-performance-analyzer' ) )) . '</a>';
            $cpanalyzer_draft_link = ( $post_id ? '<a href="#" class="cpanalyzer-create-refresh-draft" data-url="' . esc_attr( $cpanalyzer_url ) . '">' . esc_html__( 'Refresh draft', 'content-performance-analyzer' ) . '</a>' : '' );
            $cpanalyzer_view_link = '<a href="' . esc_url( home_url( $cpanalyzer_url ) ) . '" target="_blank">' . esc_html__( 'View', 'content-performance-analyzer' ) . '</a>';
            $cpanalyzer_retry_scan_link = '';
            $cpanalyzer_has_processed_context = !empty( $cpanalyzer_content_data[$cpanalyzer_url] ) || !empty( $cpanalyzer_ga_rows[$cpanalyzer_url] ) || !empty( $cpanalyzer_gsc_rows[$cpanalyzer_url] ) || $cpanalyzer_action_payload !== null;
            $cpanalyzer_can_retry_scan = $cpanalyzer_can_retry_psi && $cpanalyzer_has_processed_context && (!$cpanalyzer_has_psi_data || $cpanalyzer_psi_error !== '');
            if ( $cpanalyzer_can_retry_scan ) {
                $cpanalyzer_retry_scan_link = '<button type="button" class="button button-small cpanalyzer-retry-url-scan" data-url="' . esc_attr( $cpanalyzer_url ) . '">' . esc_html__( 'Retry Scan', 'content-performance-analyzer' ) . '</button>';
            }
            // Tooltips
            $cpanalyzer_keyword_tooltip = ( !empty( $cpanalyzer_suggested_keywords ) ? 'title="' . esc_attr( __( 'Suggested keywords: ', 'content-performance-analyzer' ) . implode( ', ', $cpanalyzer_suggested_keywords ) ) . '"' : '' );
            $cpanalyzer_issues_tooltip = ( !empty( $cpanalyzer_content_data[$cpanalyzer_url] ) && is_array( $cpanalyzer_content_data[$cpanalyzer_url] ) ? 'title="' . esc_attr( implode( ' | ', [
                'Words: ' . ($cpanalyzer_content_data[$cpanalyzer_url]['word_count'] ?? 0),
                'Title: ' . ($cpanalyzer_content_data[$cpanalyzer_url]['title']['length'] ?? 0) . ' chars',
                'H1s: ' . count( $cpanalyzer_content_data[$cpanalyzer_url]['h1_tags'] ?? array() ),
                'Links: ' . ($cpanalyzer_content_data[$cpanalyzer_url]['internal_links'] ?? 0)
            ] ) ) . '"' : '' );
            $cpanalyzer_row_class = 'cpanalyzer-row';
            ?>
                    
                    <tr class="<?php 
            echo esc_attr( $cpanalyzer_row_class );
            ?>" data-row-index="<?php 
            echo esc_attr( $cpanalyzer_row_count );
            ?>">
                        <td><span title="<?php 
            echo esc_attr( ( function_exists( 'cpanalyzer_get_flag_tooltip' ) ? cpanalyzer_get_flag_tooltip( $cpanalyzer_flag ) : '' ) );
            ?>"><?php 
            echo wp_kses_post( $cpanalyzer_badge );
            ?></span><?php 
            if ( '' !== $cpanalyzer_diagnosis_label ) {
                ?><br><small style="color:<?php 
                echo esc_attr( $cpanalyzer_diagnosis_color );
                ?>;" title="<?php 
                echo esc_attr( trim( ($cpanalyzer_decay_diagnosis['evidence'] ?? '') . ' ' . ($cpanalyzer_decay_diagnosis['trend_note'] ?? '') ) );
                ?>"><?php 
                echo esc_html( $cpanalyzer_diagnosis_label );
                ?></small><?php 
            }
            echo wp_kses_post( $cpanalyzer_recovery_chip );
            ?></td>
                        <td><?php 
            echo esc_html( $cpanalyzer_url );
            ?></td>
                        <td style="text-align:center;<?php 
            echo ( $cpanalyzer_page_age['stale'] ? 'color:#d63638;' : '' );
            ?>" <?php 
            if ( $cpanalyzer_modified_ts ) {
                ?>title="<?php 
                echo esc_attr( gmdate( 'Y-m-d', $cpanalyzer_modified_ts ) );
                ?>"<?php 
            }
            ?>><?php 
            echo ( '' !== $cpanalyzer_page_age['label'] ? esc_html( $cpanalyzer_page_age['label'] ) : '–' );
            ?></td>
                        <td class="cpanalyzer-ai-action-cell"><?php 
            echo wp_kses_post( $cpanalyzer_action_text );
            ?></td>
                        <td style="text-align:center;"><?php 
            echo ( !empty( $cpanalyzer_content_priority ) ? '<span style="color:' . esc_attr( $cpanalyzer_priority_color ) . '; font-weight:bold;">' . esc_html( strtoupper( $cpanalyzer_content_priority ) ) . '</span>' : '–' );
            ?></td>
                        <td <?php 
            echo wp_kses_post( $cpanalyzer_keyword_tooltip );
            ?>><?php 
            echo wp_kses_post( $cpanalyzer_primary_keyword );
            ?></td>
                        <td style="text-align:center;"><?php 
            echo wp_kses_post( $cpanalyzer_psi_display );
            ?></td>
                        <td style="text-align:center;"><span style="color:<?php 
            echo esc_attr( $cpanalyzer_view_indicator['color'] );
            ?>;"><?php 
            echo esc_html( cpanalyzer_format_number( $cpanalyzer_views ) );
            ?> <?php 
            echo esc_html( $cpanalyzer_view_indicator['arrow'] );
            ?> (<?php 
            echo esc_html( $cpanalyzer_view_change );
            ?>%)</span><?php 
            $cpanalyzer_ai_sessions = intval( $cpanalyzer_ga_rows[$cpanalyzer_url]['ai_sessions'] ?? 0 );
            if ( $cpanalyzer_ai_sessions > 0 ) {
                ?><br><small style="color:#7c3aed;" title="<?php 
                esc_attr_e( 'Sessions arriving from AI assistants (ChatGPT, Perplexity, Copilot, Gemini) in the last 30 days', 'content-performance-analyzer' );
                ?>">🤖 <?php 
                echo esc_html( cpanalyzer_format_number( $cpanalyzer_ai_sessions ) );
                ?></small><?php 
            }
            ?></td>
                        <td style="text-align:center;"><?php 
            echo esc_html( $cpanalyzer_engagement );
            ?></td>
                        <td style="text-align:center;"><?php 
            echo esc_html( cpanalyzer_format_number( $cpanalyzer_impressions ) );
            ?></td>
                        <td style="text-align:center;"><?php 
            echo esc_html( $cpanalyzer_ctr );
            ?></td>
                        <td style="text-align:center;">
                            <?php 
            if ( is_array( $cpanalyzer_aeo_readiness ) ) {
                ?>
                                <?php 
                $cpanalyzer_aeo_score = (int) $cpanalyzer_aeo_readiness['score'];
                $cpanalyzer_aeo_color = ( $cpanalyzer_aeo_score >= 70 ? '#00a32a' : (( $cpanalyzer_aeo_score >= 40 ? '#dba617' : '#d63638' )) );
                ?>
                                <span style="color: <?php 
                echo esc_attr( $cpanalyzer_aeo_color );
                ?>; font-weight: 600;"><?php 
                echo esc_html( $cpanalyzer_aeo_score );
                ?></span>
                                <?php 
                if ( !empty( $cpanalyzer_question_gaps ) ) {
                    ?>
                                    <br><small style="color:#0073aa;" title="<?php 
                    echo esc_attr( implode( ' | ', wp_list_pluck( $cpanalyzer_question_gaps, 'query' ) ) );
                    ?>"><?php 
                    /* translators: %d: number of unanswered question queries */
                    echo esc_html( sprintf( _n(
                        '%d question gap',
                        '%d question gaps',
                        count( $cpanalyzer_question_gaps ),
                        'content-performance-analyzer'
                    ), count( $cpanalyzer_question_gaps ) ) );
                    ?></small>
                                <?php 
                }
                ?>
                            <?php 
            } else {
                ?>
                                –
                            <?php 
            }
            ?>
                        </td>
                        <td style="text-align:center;"><?php 
            echo esc_html( $cpanalyzer_form_fills );
            ?></td>
                        <td style="text-align:center;"><?php 
            echo wp_kses_post( $cpanalyzer_edit_link );
            if ( $cpanalyzer_edit_link && $cpanalyzer_view_link ) {
                echo ' | ';
            }
            echo wp_kses_post( $cpanalyzer_view_link );
            if ( ($cpanalyzer_edit_link || $cpanalyzer_view_link) && $cpanalyzer_retry_scan_link ) {
                echo ' | ';
            }
            echo wp_kses_post( $cpanalyzer_retry_scan_link );
            ?><br><?php 
            echo wp_kses( $cpanalyzer_mark_link, array(
                'a' => array(
                    'href'      => true,
                    'class'     => true,
                    'data-url'  => true,
                    'data-mode' => true,
                ),
            ) );
            if ( $cpanalyzer_draft_link ) {
                ?> | <?php 
                echo wp_kses( $cpanalyzer_draft_link, array(
                    'a' => array(
                        'href'     => true,
                        'class'    => true,
                        'data-url' => true,
                    ),
                ) );
            }
            ?></td>
                    </tr>
                    
                    <?php 
            $cpanalyzer_row_count++;
            ?>
                <?php 
        }
        ?>
            </tbody>
        </table>
        </div>
        
        <?php 
        if ( $cpanalyzer_total_pages > 1 ) {
            ?>
            <div class="tablenav bottom">
                <div class="tablenav-pages">
                    <span class="displaying-num">
                        <?php 
            /* translators: %d: number of items being displayed */
            /* translators: %d: number of items */
            echo esc_html( sprintf( __( '%d items', 'content-performance-analyzer' ), $cpanalyzer_total_rows ) );
            ?>
                    </span>
                    <span class="pagination-links">
                        <?php 
            if ( $cpanalyzer_current_page > 1 ) {
                ?>
                            <a class="first-page button" href="<?php 
                echo esc_url( add_query_arg( [
                    'paged'  => 1,
                    'search' => $cpanalyzer_search_query,
                ] ) );
                ?>">
                                <span class="screen-reader-text"><?php 
                esc_html_e( 'First page', 'content-performance-analyzer' );
                ?></span>
                                <span aria-hidden="true">«</span>
                            </a>
                            <a class="prev-page button" href="<?php 
                echo esc_url( add_query_arg( [
                    'paged'  => $cpanalyzer_current_page - 1,
                    'search' => $cpanalyzer_search_query,
                ] ) );
                ?>">
                                <span class="screen-reader-text"><?php 
                esc_html_e( 'Previous page', 'content-performance-analyzer' );
                ?></span>
                                <span aria-hidden="true">‹</span>
                            </a>
                        <?php 
            }
            ?>
                        
                        <span class="paging-input">
                            <label for="current-page-selector" class="screen-reader-text"><?php 
            esc_html_e( 'Current Page', 'content-performance-analyzer' );
            ?></label>
                            <input class="current-page" id="current-page-selector" type="text" name="paged" value="<?php 
            echo esc_attr( $cpanalyzer_current_page );
            ?>" size="2" aria-describedby="table-paging" 
                                   onkeypress="if(event.keyCode==13) { window.location.href='<?php 
            echo esc_js( add_query_arg( [
                'search' => $cpanalyzer_search_query,
            ], remove_query_arg( 'paged' ) ) );
            ?>&paged=' + this.value; return false; }">
                            <span class="tablenav-paging-text"> <?php 
            esc_html_e( 'of', 'content-performance-analyzer' );
            ?> 
                                <span class="total-pages"><?php 
            echo esc_html( $cpanalyzer_total_pages );
            ?></span>
                            </span>
                        </span>
                        
                        <?php 
            if ( $cpanalyzer_current_page < $cpanalyzer_total_pages ) {
                ?>
                            <a class="next-page button" href="<?php 
                echo esc_url( add_query_arg( [
                    'paged'  => $cpanalyzer_current_page + 1,
                    'search' => $cpanalyzer_search_query,
                ] ) );
                ?>">
                                <span class="screen-reader-text"><?php 
                esc_html_e( 'Next page', 'content-performance-analyzer' );
                ?></span>
                                <span aria-hidden="true">›</span>
                            </a>
                            <a class="last-page button" href="<?php 
                echo esc_url( add_query_arg( [
                    'paged'  => $cpanalyzer_total_pages,
                    'search' => $cpanalyzer_search_query,
                ] ) );
                ?>">
                                <span class="screen-reader-text"><?php 
                esc_html_e( 'Last page', 'content-performance-analyzer' );
                ?></span>
                                <span aria-hidden="true">»</span>
                            </a>
                        <?php 
            }
            ?>
                    </span>
                </div>
            </div>
        <?php 
        }
        ?>
        <?php 
    }
    ?>

        <div id="cpanalyzer-ai-action-modal" class="cpanalyzer-ai-modal" aria-hidden="true" hidden>
            <div class="cpanalyzer-ai-modal__overlay" data-modal-close="1"></div>
            <div class="cpanalyzer-ai-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="cpanalyzer-ai-modal-title">
                <button type="button" class="cpanalyzer-ai-modal__close" aria-label="<?php 
    esc_attr_e( 'Close AI action details', 'content-performance-analyzer' );
    ?>">
                    <span aria-hidden="true">&times;</span>
                </button>
                <div class="cpanalyzer-ai-modal__header">
                    <p class="cpanalyzer-ai-modal__eyebrow"><?php 
    esc_html_e( 'AI Action Details', 'content-performance-analyzer' );
    ?></p>
                    <h2 id="cpanalyzer-ai-modal-title"></h2>
                    <p id="cpanalyzer-ai-modal-url" class="cpanalyzer-ai-modal__url"></p>
                    <p id="cpanalyzer-ai-modal-status" class="cpanalyzer-ai-modal__status" hidden></p>
                </div>

                <div class="cpanalyzer-ai-modal__meta">
                    <div class="cpanalyzer-ai-modal__meta-item" data-meta="priority" hidden>
                        <span class="cpanalyzer-ai-modal__meta-label"><?php 
    esc_html_e( 'Priority', 'content-performance-analyzer' );
    ?></span>
                        <span id="cpanalyzer-ai-modal-priority" class="cpanalyzer-ai-modal__meta-value"></span>
                    </div>
                    <div class="cpanalyzer-ai-modal__meta-item" data-meta="keyword" hidden>
                        <span class="cpanalyzer-ai-modal__meta-label"><?php 
    esc_html_e( 'Primary keyword', 'content-performance-analyzer' );
    ?></span>
                        <span id="cpanalyzer-ai-modal-keyword" class="cpanalyzer-ai-modal__meta-value"></span>
                    </div>
                    <div class="cpanalyzer-ai-modal__meta-item" data-meta="model" hidden>
                        <span class="cpanalyzer-ai-modal__meta-label"><?php 
    esc_html_e( 'Model', 'content-performance-analyzer' );
    ?></span>
                        <span id="cpanalyzer-ai-modal-model" class="cpanalyzer-ai-modal__meta-value"></span>
                    </div>
                </div>

                <nav class="cpanalyzer-ai-modal__tabs" role="tablist">
                    <button type="button" class="cpanalyzer-ai-modal__tab is-active" role="tab" data-tab="overview"><?php 
    esc_html_e( 'Overview', 'content-performance-analyzer' );
    ?></button>
                    <button type="button" class="cpanalyzer-ai-modal__tab" role="tab" data-tab="fixes"><?php 
    esc_html_e( 'Fix plan', 'content-performance-analyzer' );
    ?></button>
                    <?php 
    ?>
                    <button type="button" class="cpanalyzer-ai-modal__tab" role="tab" data-tab="checks"><?php 
    esc_html_e( 'Checks', 'content-performance-analyzer' );
    ?></button>
                </nav>

                <div class="cpanalyzer-ai-modal__body">
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="overview" data-section="decayDiagnosis" hidden>
                        <h3><?php 
    esc_html_e( 'Decay diagnosis', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-decayType" style="font-weight:600;"></p>
                        <p id="cpanalyzer-ai-modal-decayEvidence"></p>
                        <p id="cpanalyzer-ai-modal-decayTrend" style="color:#b32d2e;" hidden></p>
                        <p id="cpanalyzer-ai-modal-decayFix" style="background:#f0f6fc;border-left:4px solid #0073aa;padding:8px 12px;" hidden></p>
                        <p class="description"><?php 
    esc_html_e( 'Computed from this page\'s own Search Console and GA4 period deltas — not AI output. Different decay types need different fixes: a content refresh only helps ranking decay.', 'content-performance-analyzer' );
    ?></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="overview" data-section="cannibalization" hidden>
                        <h3><?php 
    esc_html_e( 'Keyword cannibalization', 'content-performance-analyzer' );
    ?></h3>
                        <p class="description"><?php 
    esc_html_e( 'Queries where this page splits clicks with other pages on your own site over the last 90 days. Consider consolidating the weaker page into the stronger one.', 'content-performance-analyzer' );
    ?></p>
                        <ul id="cpanalyzer-ai-modal-cannibalization" class="cpanalyzer-ai-modal__list"></ul>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="overview" data-section="inboundLinks" hidden>
                        <h3><?php 
    esc_html_e( 'Internal links pointing here', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-inboundLinks"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="overview" data-section="issueSummary" hidden>
                        <h3><?php 
    esc_html_e( 'Why it is underperforming', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-issueSummary"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="overview" data-section="whyNow" hidden>
                        <h3><?php 
    esc_html_e( 'Why now', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-whyNow"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="fixes" data-section="seoRecommendation" hidden>
                        <h3><?php 
    esc_html_e( 'SEO recommendation', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-seoRecommendation"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="fixes" data-section="aeoRecommendation" hidden>
                        <h3><?php 
    esc_html_e( 'AEO recommendation', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-aeoRecommendation"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="fixes" data-section="geoRecommendation" hidden>
                        <h3><?php 
    esc_html_e( 'GEO recommendation', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-geoRecommendation"></p>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="fixes" data-section="engagementRecommendation" hidden>
                        <h3><?php 
    esc_html_e( 'Engagement recommendation', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-engagementRecommendation"></p>
                    </section>
                    <?php 
    ?>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="fixes" data-section="suggestedKeywords" hidden>
                        <h3><?php 
    esc_html_e( 'Suggested keywords', 'content-performance-analyzer' );
    ?></h3>
                        <div id="cpanalyzer-ai-modal-suggestedKeywords" class="cpanalyzer-ai-modal__chips"></div>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="checks" data-section="issues" hidden>
                        <h3><?php 
    esc_html_e( 'Supporting issues', 'content-performance-analyzer' );
    ?></h3>
                        <ul id="cpanalyzer-ai-modal-issues" class="cpanalyzer-ai-modal__list"></ul>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="checks" data-section="aeoReadiness" hidden>
                        <h3><?php 
    esc_html_e( 'Answer-engine readiness', 'content-performance-analyzer' );
    ?></h3>
                        <p id="cpanalyzer-ai-modal-aeoScore" style="font-weight:600;"></p>
                        <ul id="cpanalyzer-ai-modal-aeoChecks" class="cpanalyzer-ai-modal__list"></ul>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="checks" data-section="questionGaps" hidden>
                        <h3><?php 
    esc_html_e( 'Unanswered questions you already rank for', 'content-performance-analyzer' );
    ?></h3>
                        <p class="description"><?php 
    esc_html_e( 'Real searches from Search Console where this page appears (positions 2-20) but no heading answers the question. Adding a question heading with a concise answer targets featured snippets and AI answers at once.', 'content-performance-analyzer' );
    ?></p>
                        <ul id="cpanalyzer-ai-modal-questionGaps" class="cpanalyzer-ai-modal__list"></ul>
                    </section>
                    <section class="cpanalyzer-ai-modal__section" data-tab-panel="checks" data-section="missingAltImages" hidden>
                        <h3><?php 
    esc_html_e( 'Images missing alt text', 'content-performance-analyzer' );
    ?></h3>
                        <ul id="cpanalyzer-ai-modal-missingAltImages" class="cpanalyzer-ai-modal__list"></ul>
                        <p>
                            <button type="button" class="button button-primary" id="cpanalyzer-fix-alt-text">
                                <?php 
    esc_html_e( 'Generate and apply alt text with AI', 'content-performance-analyzer' );
    ?>
                            </button>
                            <span id="cpanalyzer-fix-alt-status" role="status" aria-live="polite"></span>
                        </p>
                        <p class="description">
                            <?php 
    esc_html_e( 'Writes alt text to the Media Library, and into the page content when the image sits in an editable post. Images from themes or external sources are listed but must be fixed where they are defined. Existing alt text is never overwritten.', 'content-performance-analyzer' );
    ?>
                        </p>
                    </section>
                </div>
            </div>
        </div>
    <?php 
}
?>
</div>
