<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class SEO_Fury_Page_Speed {

    private $api_base = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
    private $cache_ttl = 3600; // 1 hour

    public function __construct() {
        add_action( 'wp_ajax_seo_fury_page_speed_check', array( $this, 'ajax_check_speed' ) );
        add_action( 'wp_ajax_seo_fury_page_speed_batch', array( $this, 'ajax_batch_check' ) );
        add_action( 'wp_ajax_seo_fury_page_speed_save_key', array( $this, 'ajax_save_api_key' ) );
        add_action( 'wp_ajax_seo_fury_page_speed_save_result', array( $this, 'ajax_save_result' ) );
    }

    /**
     * AJAX: Save PageSpeed result for a post (persistent storage).
     */
    public function ajax_save_result() {
        check_ajax_referer( 'seo_fury_page_speed_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $post_id  = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
        $strategy = isset( $_POST['strategy'] ) ? sanitize_text_field( wp_unslash( $_POST['strategy'] ) ) : 'mobile';
        $score    = isset( $_POST['score'] ) ? absint( $_POST['score'] ) : 0;
        $data     = isset( $_POST['result'] ) ? wp_unslash( $_POST['result'] ) : '';

        if ( $post_id ) {
            $meta_key = '_seo_fury_speed_' . $strategy;
            $new_entry = array(
                'score'      => $score,
                'checked_at' => current_time( 'mysql' ),
            );

            // Get existing history
            $history = get_post_meta( $post_id, $meta_key, true );

            // Backward compat: if old format (single result), convert to array
            if ( is_array( $history ) && isset( $history['score'] ) && ! isset( $history[0] ) ) {
                $history = array( $history );
            }
            if ( ! is_array( $history ) ) {
                $history = array();
            }

            // Prepend new entry (newest first), keep max 10
            array_unshift( $history, $new_entry );
            $history = array_slice( $history, 0, 10 );

            update_post_meta( $post_id, $meta_key, $history );
            wp_send_json_success( array( 'message' => __( 'Result saved', 'seo-fury' ) ) );
        } else {
            // Save for a URL (admin tab single check)
            $url = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : '';
            if ( $url ) {
                $saved = get_option( 'seo_fury_speed_results', array() );
                $key = md5( $url . $strategy );
                // The result blob comes from the browser, not re-derived
                // server-side, so sanitize every string leaf before storing —
                // it is later rendered in the admin (defense against stored XSS).
                $decoded = is_string( $data ) ? json_decode( $data, true ) : $data;
                $decoded = is_array( $decoded ) ? map_deep( $decoded, 'sanitize_text_field' ) : array();
                $saved[ $key ] = array(
                    'url'        => $url,
                    'strategy'   => $strategy,
                    'score'      => $score,
                    'checked_at' => current_time( 'mysql' ),
                    'data'       => $decoded,
                );
                // Keep the 50 most RECENT results. Re-checking an existing URL
                // updates its entry in place, so slicing by array position could
                // evict a just-refreshed entry — sort by checked_at first.
                if ( count( $saved ) > 50 ) {
                    uasort( $saved, function ( $a, $b ) {
                        return strcmp( (string) ( isset( $b['checked_at'] ) ? $b['checked_at'] : '' ), (string) ( isset( $a['checked_at'] ) ? $a['checked_at'] : '' ) );
                    } );
                    $saved = array_slice( $saved, 0, 50, true );
                }
                update_option( 'seo_fury_speed_results', $saved, false );
                wp_send_json_success( array( 'message' => __( 'Result saved', 'seo-fury' ) ) );
            }
        }

        wp_send_json_error( array( 'message' => __( 'Invalid request', 'seo-fury' ) ) );
    }

    /**
     * AJAX: Save Google PageSpeed API Key.
     */
    public function ajax_save_api_key() {
        check_ajax_referer( 'seo_fury_page_speed_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
        update_option( 'seo_fury_pagespeed_api_key', $api_key );
        wp_send_json_success( array( 'message' => __( 'API key saved', 'seo-fury' ) ) );
    }

    /**
     * AJAX: Check speed for a single URL.
     */
    public function ajax_check_speed() {
        check_ajax_referer( 'seo_fury_page_speed_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $url      = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : '';
        $strategy = isset( $_POST['strategy'] ) ? sanitize_text_field( wp_unslash( $_POST['strategy'] ) ) : 'mobile';

        if ( empty( $url ) ) {
            wp_send_json_error( array( 'message' => __( 'URL is required', 'seo-fury' ) ) );
        }

        if ( ! in_array( $strategy, array( 'mobile', 'desktop' ), true ) ) {
            $strategy = 'mobile';
        }

        // Check cache
        $cache_key = 'sf_psi_' . md5( $url . $strategy );
        $cached = get_transient( $cache_key );
        if ( false !== $cached ) {
            $cached['cached'] = true;
            wp_send_json_success( $cached );
        }

        $result = $this->run_pagespeed_check( $url, $strategy );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        }

        // Cache result
        set_transient( $cache_key, $result, $this->cache_ttl );

        wp_send_json_success( $result );
    }

    /**
     * AJAX: Batch check speeds for overview table.
     */
    public function ajax_batch_check() {
        check_ajax_referer( 'seo_fury_page_speed_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $post_id  = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
        $strategy = isset( $_POST['strategy'] ) ? sanitize_text_field( wp_unslash( $_POST['strategy'] ) ) : 'mobile';

        if ( ! $post_id ) {
            wp_send_json_error( array( 'message' => __( 'Invalid post', 'seo-fury' ) ) );
        }

        $url = get_permalink( $post_id );
        if ( ! $url ) {
            wp_send_json_error( array( 'message' => __( 'Could not get URL', 'seo-fury' ) ) );
        }

        $cache_key = 'sf_psi_' . md5( $url . $strategy );
        $cached = get_transient( $cache_key );
        if ( false !== $cached ) {
            $cached['cached']  = true;
            $cached['post_id'] = $post_id;
            wp_send_json_success( $cached );
        }

        $result = $this->run_pagespeed_check( $url, $strategy );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array(
                'message' => $result->get_error_message(),
                'post_id' => $post_id,
            ) );
        }

        set_transient( $cache_key, $result, $this->cache_ttl );
        $result['post_id'] = $post_id;

        wp_send_json_success( $result );
    }

    /**
     * Run PageSpeed Insights API check.
     *
     * @param string $url      URL to check.
     * @param string $strategy 'mobile' or 'desktop'.
     * @return array|WP_Error
     */
    private function run_pagespeed_check( $url, $strategy ) {
        $args = array(
            'url'      => $url,
            'strategy' => $strategy,
            'category' => 'PERFORMANCE',
        );

        $api_key = get_option( 'seo_fury_pagespeed_api_key', '' );
        if ( ! empty( $api_key ) ) {
            $args['key'] = $api_key;
        }

        $api_url = add_query_arg( $args, $this->api_base );

        $response = wp_remote_get( $api_url, array(
            'timeout' => 60,
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $code !== 200 ) {
            $raw_msg = isset( $body['error']['message'] ) ? $body['error']['message'] : '';

            // Detect quota / rate-limit errors and show user-friendly message
            if ( $code === 429 || stripos( $raw_msg, 'quota' ) !== false || stripos( $raw_msg, 'rate' ) !== false ) {
                $api_key = get_option( 'seo_fury_pagespeed_api_key', '' );
                if ( empty( $api_key ) ) {
                    $msg = __( 'Daily API quota exceeded. Please add your own Google PageSpeed API key in SEO Fury → Speed settings to increase the limit.', 'seo-fury' );
                } else {
                    $msg = __( 'API quota exceeded. Please try again later or check your Google Cloud Console quota limits.', 'seo-fury' );
                }
            } else {
                $msg = ! empty( $raw_msg ) ? $raw_msg : __( 'API error', 'seo-fury' );
            }

            return new WP_Error( 'api_error', $msg );
        }

        if ( ! isset( $body['lighthouseResult'] ) ) {
            return new WP_Error( 'no_data', __( 'No data returned from API', 'seo-fury' ) );
        }

        $lh = $body['lighthouseResult'];
        $categories = isset( $lh['categories']['performance'] ) ? $lh['categories']['performance'] : array();
        $audits = isset( $lh['audits'] ) ? $lh['audits'] : array();

        // Core Web Vitals
        $metrics = array(
            'score' => isset( $categories['score'] ) ? round( $categories['score'] * 100 ) : 0,
            'fcp'   => $this->extract_metric( $audits, 'first-contentful-paint' ),
            'lcp'   => $this->extract_metric( $audits, 'largest-contentful-paint' ),
            'tbt'   => $this->extract_metric( $audits, 'total-blocking-time' ),
            'cls'   => $this->extract_metric( $audits, 'cumulative-layout-shift' ),
            'si'    => $this->extract_metric( $audits, 'speed-index' ),
            'tti'   => $this->extract_metric( $audits, 'interactive' ),
        );

        // Key opportunities
        $opportunities = array();
        $opp_keys = array(
            'render-blocking-resources',
            'unused-css-rules',
            'unused-javascript',
            'modern-image-formats',
            'uses-optimized-images',
            'efficiently-encode-images',
            'uses-text-compression',
            'server-response-time',
            'uses-responsive-images',
            'offscreen-images',
        );

        foreach ( $opp_keys as $key ) {
            if ( isset( $audits[ $key ] ) && isset( $audits[ $key ]['score'] ) && $audits[ $key ]['score'] < 1 ) {
                $opportunities[] = array(
                    'id'          => $key,
                    'title'       => $audits[ $key ]['title'],
                    'description' => isset( $audits[ $key ]['description'] ) ? $audits[ $key ]['description'] : '',
                    'savings'     => isset( $audits[ $key ]['details']['overallSavingsMs'] )
                        ? round( $audits[ $key ]['details']['overallSavingsMs'] ) . ' ms'
                        : '',
                    'score'       => $audits[ $key ]['score'],
                );
            }
        }

        return array(
            'url'           => $url,
            'strategy'      => $strategy,
            'score'         => $metrics['score'],
            'metrics'       => $metrics,
            'opportunities' => $opportunities,
            'checked_at'    => current_time( 'mysql' ),
            'cached'        => false,
        );
    }

    /**
     * Extract a metric value from audits.
     *
     * @param array  $audits Lighthouse audits.
     * @param string $key    Audit key.
     * @return array
     */
    private function extract_metric( $audits, $key ) {
        if ( ! isset( $audits[ $key ] ) ) {
            return array( 'value' => 0, 'display' => 'N/A', 'score' => 0 );
        }

        $audit = $audits[ $key ];

        return array(
            'value'   => isset( $audit['numericValue'] ) ? round( $audit['numericValue'] ) : 0,
            'display' => isset( $audit['displayValue'] ) ? $audit['displayValue'] : 'N/A',
            'score'   => isset( $audit['score'] ) ? $audit['score'] : 0,
        );
    }

    /**
     * Render the Page Speed admin tab.
     */
    public function render_admin_tab() {
        ?>
        <div class="seo-fury-page-speed-wrap">

            <!-- Single URL Check -->
            <div class="seo-card" style="margin-bottom: 20px;">
                <h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">
                    <span style="font-size: 20px;">🔍</span>
                    <?php esc_html_e( 'Check Page Speed', 'seo-fury' ); ?>
                </h3>
                <div style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
                    <div style="flex: 1; min-width: 250px;">
                        <label for="sf-speed-url" style="display: block; font-weight: 600; margin-bottom: 4px;">
                            <?php esc_html_e( 'URL', 'seo-fury' ); ?>
                        </label>
                        <input type="url" id="sf-speed-url" class="regular-text" style="width: 100%;"
                               value="<?php echo esc_attr( home_url( '/' ) ); ?>"
                               placeholder="https://example.com">
                    </div>
                    <div>
                        <label style="display: block; font-weight: 600; margin-bottom: 4px;">
                            <?php esc_html_e( 'Device', 'seo-fury' ); ?>
                        </label>
                        <div class="sf-speed-strategy-toggle" style="display: flex; border: 1px solid var(--sf-gray-300,#CBD5E1); border-radius: 6px; overflow: hidden;">
                            <button type="button" class="sf-speed-strategy active" data-strategy="mobile"
                                    style="padding: 6px 14px; border: none; background: #3B82F6; color: #fff; cursor: pointer; font-size: 13px;">
                                <span class="dashicons dashicons-smartphone" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle;"></span>
                                <?php esc_html_e( 'Mobile', 'seo-fury' ); ?>
                            </button>
                            <button type="button" class="sf-speed-strategy" data-strategy="desktop"
                                    style="padding: 6px 14px; border: none; background: var(--sf-white,#fff); color: var(--sf-gray-700,#334155); cursor: pointer; font-size: 13px;">
                                <span class="dashicons dashicons-desktop" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle;"></span>
                                <?php esc_html_e( 'Desktop', 'seo-fury' ); ?>
                            </button>
                        </div>
                    </div>
                    <button type="button" class="button button-primary" id="sf-speed-check-btn" style="height: 36px;">
                        <span class="dashicons dashicons-performance" style="margin-top: 4px;"></span>
                        <?php esc_html_e( 'Analyze', 'seo-fury' ); ?>
                    </button>
                </div>
            </div>

            <!-- Results -->
            <div id="sf-speed-results" style="display: none;">
                <!-- Score circle -->
                <div class="seo-card" style="margin-bottom: 20px;">
                    <div style="display: flex; align-items: center; gap: 30px; flex-wrap: wrap;">
                        <div style="text-align: center;">
                            <div id="sf-speed-gauge" class="sf-speed-gauge">
                                <svg viewBox="0 0 120 120" width="120" height="120">
                                    <circle cx="60" cy="60" r="54" fill="none" stroke="#E2E8F0" stroke-width="8"/>
                                    <circle id="sf-speed-circle" cx="60" cy="60" r="54" fill="none"
                                            stroke="#22C55E" stroke-width="8" stroke-linecap="round"
                                            stroke-dasharray="339.3" stroke-dashoffset="339.3"
                                            transform="rotate(-90 60 60)"/>
                                    <text id="sf-speed-score" x="60" y="60" text-anchor="middle"
                                          dominant-baseline="central" font-size="28" font-weight="700" fill="#1E293B">
                                        0
                                    </text>
                                </svg>
                            </div>
                            <div id="sf-speed-label" style="font-weight: 600; font-size: 14px; margin-top: 4px;"></div>
                        </div>

                        <!-- Core Web Vitals -->
                        <div style="flex: 1; display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px;">
                            <div class="sf-metric-card" id="sf-metric-fcp">
                                <div class="sf-metric-label"><?php esc_html_e( 'FCP', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'First Contentful Paint', 'seo-fury' ); ?></div>
                            </div>
                            <div class="sf-metric-card" id="sf-metric-lcp">
                                <div class="sf-metric-label"><?php esc_html_e( 'LCP', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'Largest Contentful Paint', 'seo-fury' ); ?></div>
                            </div>
                            <div class="sf-metric-card" id="sf-metric-tbt">
                                <div class="sf-metric-label"><?php esc_html_e( 'TBT', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'Total Blocking Time', 'seo-fury' ); ?></div>
                            </div>
                            <div class="sf-metric-card" id="sf-metric-cls">
                                <div class="sf-metric-label"><?php esc_html_e( 'CLS', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'Cumulative Layout Shift', 'seo-fury' ); ?></div>
                            </div>
                            <div class="sf-metric-card" id="sf-metric-si">
                                <div class="sf-metric-label"><?php esc_html_e( 'SI', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'Speed Index', 'seo-fury' ); ?></div>
                            </div>
                            <div class="sf-metric-card" id="sf-metric-tti">
                                <div class="sf-metric-label"><?php esc_html_e( 'TTI', 'seo-fury' ); ?></div>
                                <div class="sf-metric-value">-</div>
                                <div class="sf-metric-desc"><?php esc_html_e( 'Time to Interactive', 'seo-fury' ); ?></div>
                            </div>
                        </div>
                    </div>
                    <div id="sf-speed-checked-at" style="margin-top: 12px; font-size: 12px; color: var(--sf-gray-400, #94a3b8);"></div>
                </div>

                <!-- Opportunities -->
                <div class="seo-card" id="sf-speed-opportunities" style="display: none;">
                    <h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">
                        <span style="font-size: 20px;">💡</span>
                        <?php esc_html_e( 'Opportunities', 'seo-fury' ); ?>
                    </h3>
                    <div id="sf-speed-opp-list"></div>
                </div>
            </div>

            <!-- Loading state -->
            <div id="sf-speed-loading" style="display: none;">
                <div class="seo-card" style="text-align: center; padding: 40px;">
                    <div class="sf-speed-spinner"></div>
                    <p style="font-size: 14px; color: var(--sf-gray-500, #64748b); margin-top: 16px;">
                        <?php esc_html_e( 'Analyzing page speed... This may take 15-30 seconds.', 'seo-fury' ); ?>
                    </p>
                </div>
            </div>

            <!-- Pages Overview -->
            <div class="seo-card" style="margin-top: 20px;">
                <h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">
                    <span style="font-size: 20px;">📊</span>
                    <?php esc_html_e( 'Pages Overview', 'seo-fury' ); ?>
                </h3>
                <p class="description" style="margin-bottom: 12px;">
                    <?php esc_html_e( 'Quick speed check for your most recent published pages.', 'seo-fury' ); ?>
                </p>

                <?php
                $pages = get_posts( array(
                    'post_type'      => array( 'post', 'page' ),
                    'post_status'    => 'publish',
                    'posts_per_page' => 10,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                ) );
                ?>

                <?php if ( ! empty( $pages ) ) : ?>
                    <table class="widefat striped" style="margin-top: 10px;">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Page', 'seo-fury' ); ?></th>
                                <th style="width: 100px; text-align: center;"><?php esc_html_e( 'Mobile', 'seo-fury' ); ?></th>
                                <th style="width: 100px; text-align: center;"><?php esc_html_e( 'Desktop', 'seo-fury' ); ?></th>
                                <th style="width: 160px; text-align: center;"><?php esc_html_e( 'Last Check', 'seo-fury' ); ?></th>
                                <th style="width: 100px; text-align: center;"><?php esc_html_e( 'Action', 'seo-fury' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $pages as $page ) :
                                $saved_mobile  = get_post_meta( $page->ID, '_seo_fury_speed_mobile', true );
                                $saved_desktop = get_post_meta( $page->ID, '_seo_fury_speed_desktop', true );

                                // Support new array format (history) and old single-object format
                                if ( is_array( $saved_mobile ) && isset( $saved_mobile[0]['score'] ) ) {
                                    $mobile_score = (int) $saved_mobile[0]['score'];
                                } elseif ( is_array( $saved_mobile ) && isset( $saved_mobile['score'] ) ) {
                                    $mobile_score = (int) $saved_mobile['score'];
                                } else {
                                    $mobile_score = 0;
                                }
                                if ( is_array( $saved_desktop ) && isset( $saved_desktop[0]['score'] ) ) {
                                    $desktop_score = (int) $saved_desktop[0]['score'];
                                } elseif ( is_array( $saved_desktop ) && isset( $saved_desktop['score'] ) ) {
                                    $desktop_score = (int) $saved_desktop['score'];
                                } else {
                                    $desktop_score = 0;
                                }

                                $mobile_cls    = $mobile_score > 0 ? ( $mobile_score >= 90 ? 'sf-score-good' : ( $mobile_score >= 50 ? 'sf-score-avg' : 'sf-score-bad' ) ) : 'sf-score-na';
                                $desktop_cls   = $desktop_score > 0 ? ( $desktop_score >= 90 ? 'sf-score-good' : ( $desktop_score >= 50 ? 'sf-score-avg' : 'sf-score-bad' ) ) : 'sf-score-na';
                                $last_check    = '';
                                // Extract last check from new array format or old format
                                $m_checked = '';
                                if ( is_array( $saved_mobile ) && isset( $saved_mobile[0]['checked_at'] ) ) {
                                    $m_checked = $saved_mobile[0]['checked_at'];
                                } elseif ( is_array( $saved_mobile ) && ! empty( $saved_mobile['checked_at'] ) ) {
                                    $m_checked = $saved_mobile['checked_at'];
                                }
                                $d_checked = '';
                                if ( is_array( $saved_desktop ) && isset( $saved_desktop[0]['checked_at'] ) ) {
                                    $d_checked = $saved_desktop[0]['checked_at'];
                                } elseif ( is_array( $saved_desktop ) && ! empty( $saved_desktop['checked_at'] ) ) {
                                    $d_checked = $saved_desktop['checked_at'];
                                }
                                $last_check = $m_checked;
                                if ( ! empty( $d_checked ) && ( empty( $last_check ) || strtotime( $d_checked ) > strtotime( $last_check ) ) ) {
                                    $last_check = $d_checked;
                                }
                            ?>
                                <tr data-post-id="<?php echo esc_attr( $page->ID ); ?>">
                                    <td>
                                        <strong><?php echo esc_html( $page->post_title ); ?></strong>
                                        <br><small style="color: var(--sf-gray-400, #94a3b8);"><?php echo esc_html( get_permalink( $page->ID ) ); ?></small>
                                    </td>
                                    <td style="text-align: center;" class="sf-overview-mobile">
                                        <span class="sf-score-badge <?php echo esc_attr( $mobile_cls ); ?>"><?php echo $mobile_score > 0 ? esc_html( $mobile_score ) : '—'; ?></span>
                                    </td>
                                    <td style="text-align: center;" class="sf-overview-desktop">
                                        <span class="sf-score-badge <?php echo esc_attr( $desktop_cls ); ?>"><?php echo $desktop_score > 0 ? esc_html( $desktop_score ) : '—'; ?></span>
                                    </td>
                                    <td style="text-align: center;" class="sf-overview-last-check">
                                        <?php if ( $last_check ) : ?>
                                            <small style="color: var(--sf-gray-500, #64748b);"><?php echo esc_html( $last_check ); ?></small>
                                        <?php else : ?>
                                            <small style="color: var(--sf-gray-400, #cbd5e1);">—</small>
                                        <?php endif; ?>
                                    </td>
                                    <td style="text-align: center;">
                                        <button type="button" class="button sf-overview-check-btn" data-post-id="<?php echo esc_attr( $page->ID ); ?>">
                                            <?php esc_html_e( 'Check', 'seo-fury' ); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p><?php esc_html_e( 'No published pages found.', 'seo-fury' ); ?></p>
                <?php endif; ?>
            </div>

            <!-- Page Speed Settings (collapsible) -->
            <div class="seo-card" style="margin-top:25px;padding:20px;">
                <details>
                    <summary style="cursor:pointer;font-weight:600;font-size:13px;color:var(--sf-gray-900, #23282d);">
                        <span class="dashicons dashicons-admin-generic" style="vertical-align:middle;margin-right:4px;font-size:16px;width:16px;height:16px;"></span>
                        <?php esc_html_e( 'Page Speed Settings', 'seo-fury' ); ?>
                    </summary>
                    <div style="margin-top:12px;">
                        <h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 20px;">🔑</span>
                            <?php esc_html_e( 'Google API Key', 'seo-fury' ); ?>
                        </h3>
                        <p class="description" style="margin-bottom: 10px;">
                            <?php esc_html_e( 'Add a free Google API key to increase the request limit from ~25/day to 25,000/day.', 'seo-fury' ); ?>
                            <a href="https://developers.google.com/speed/docs/insights/v5/get-started#key" target="_blank" rel="noopener"><?php esc_html_e( 'Get a free key', 'seo-fury' ); ?> &rarr;</a>
                        </p>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <input type="text" id="sf-speed-api-key" class="regular-text" style="flex: 1; max-width: 400px;"
                                   value="<?php echo esc_attr( get_option( 'seo_fury_pagespeed_api_key', '' ) ); ?>"
                                   placeholder="AIza...">
                            <button type="button" class="button" id="sf-speed-save-key">
                                <?php esc_html_e( 'Save Key', 'seo-fury' ); ?>
                            </button>
                            <span id="sf-speed-key-status" style="font-size: 13px;"></span>
                        </div>
                    </div>
                </details>
            </div>
        </div>
        <?php
    }

    /**
     * Render a compact speed widget for post editor meta box.
     */
    public function render_post_meta_tab( $post ) {
        $url = get_permalink( $post->ID );
        ?>
        <div class="seo-fury-speed-meta-wrap">
            <p class="description" style="margin-bottom: 12px;">
                <?php esc_html_e( 'Check the loading speed of this page using Google PageSpeed Insights.', 'seo-fury' ); ?>
            </p>
            <div style="display: flex; gap: 8px; margin-bottom: 16px;">
                <button type="button" class="button button-primary sf-meta-speed-check" data-strategy="mobile" data-url="<?php echo esc_attr( $url ); ?>">
                    <span class="dashicons dashicons-smartphone" style="margin-top: 4px;"></span>
                    <?php esc_html_e( 'Mobile', 'seo-fury' ); ?>
                </button>
                <button type="button" class="button sf-meta-speed-check" data-strategy="desktop" data-url="<?php echo esc_attr( $url ); ?>">
                    <span class="dashicons dashicons-desktop" style="margin-top: 4px;"></span>
                    <?php esc_html_e( 'Desktop', 'seo-fury' ); ?>
                </button>
            </div>
            <div id="sf-meta-speed-loading" style="display: none; text-align: center; padding: 20px;">
                <div class="sf-speed-spinner"></div>
                <p style="font-size: 13px; color: var(--sf-gray-400, #94a3b8);"><?php esc_html_e( 'Analyzing...', 'seo-fury' ); ?></p>
            </div>
            <div id="sf-meta-speed-results" style="display: none;">
                <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 12px;">
                    <div style="text-align: center;">
                        <svg id="sf-meta-gauge" viewBox="0 0 80 80" width="80" height="80">
                            <circle cx="40" cy="40" r="36" fill="none" stroke="#E2E8F0" stroke-width="6"/>
                            <circle id="sf-meta-circle" cx="40" cy="40" r="36" fill="none"
                                    stroke="#22C55E" stroke-width="6" stroke-linecap="round"
                                    stroke-dasharray="226.2" stroke-dashoffset="226.2"
                                    transform="rotate(-90 40 40)"/>
                            <text id="sf-meta-score" x="40" y="40" text-anchor="middle"
                                  dominant-baseline="central" font-size="20" font-weight="700" fill="#1E293B">0</text>
                        </svg>
                    </div>
                    <div style="flex: 1;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
                            <div class="sf-meta-metric"><strong>FCP:</strong> <span id="sf-meta-fcp">-</span></div>
                            <div class="sf-meta-metric"><strong>LCP:</strong> <span id="sf-meta-lcp">-</span></div>
                            <div class="sf-meta-metric"><strong>TBT:</strong> <span id="sf-meta-tbt">-</span></div>
                            <div class="sf-meta-metric"><strong>CLS:</strong> <span id="sf-meta-cls">-</span></div>
                        </div>
                    </div>
                </div>
                <div id="sf-meta-speed-opps" style="font-size: 12px;"></div>
            </div>
            <div id="sf-meta-speed-error" style="display: none; color: #d63638;"></div>

            <?php
            // Speed History
            $mobile_history = get_post_meta( $post->ID, '_seo_fury_speed_mobile', true );
            $desktop_history = get_post_meta( $post->ID, '_seo_fury_speed_desktop', true );

            // Backward compat: convert old single-object format
            if ( is_array( $mobile_history ) && isset( $mobile_history['score'] ) && ! isset( $mobile_history[0] ) ) {
                $mobile_history = array( $mobile_history );
            }
            if ( is_array( $desktop_history ) && isset( $desktop_history['score'] ) && ! isset( $desktop_history[0] ) ) {
                $desktop_history = array( $desktop_history );
            }

            $all_entries = array();
            if ( is_array( $mobile_history ) ) {
                foreach ( $mobile_history as $entry ) {
                    if ( ! is_array( $entry ) || ! isset( $entry['score'] ) ) continue;
                    $entry['strategy'] = 'mobile';
                    $all_entries[] = $entry;
                }
            }
            if ( is_array( $desktop_history ) ) {
                foreach ( $desktop_history as $entry ) {
                    if ( ! is_array( $entry ) || ! isset( $entry['score'] ) ) continue;
                    $entry['strategy'] = 'desktop';
                    $all_entries[] = $entry;
                }
            }

            if ( ! empty( $all_entries ) ) :
                usort( $all_entries, function( $a, $b ) {
                    return strtotime( $b['checked_at'] ?? '0' ) - strtotime( $a['checked_at'] ?? '0' );
                });
                $all_entries = array_slice( $all_entries, 0, 10 );
            ?>
            <div id="sf-meta-speed-history" style="margin-top: 16px; border-top: 1px solid var(--sf-gray-200, #e2e8f0); padding-top: 12px;">
                <h5 style="margin: 0 0 8px; font-size: 12px; font-weight: 600; color: var(--sf-gray-700, #475569);">
                    <?php esc_html_e( 'Speed History', 'seo-fury' ); ?>
                </h5>
                <table style="width: 100%; font-size: 11px; border-collapse: collapse;">
                    <thead>
                        <tr style="border-bottom: 1px solid var(--sf-gray-200, #e2e8f0);">
                            <th style="text-align:left;padding:4px 6px;color:var(--sf-gray-500, #64748b);font-weight:600;"><?php esc_html_e( 'Date', 'seo-fury' ); ?></th>
                            <th style="text-align:center;padding:4px 6px;color:var(--sf-gray-500, #64748b);font-weight:600;"><?php esc_html_e( 'Device', 'seo-fury' ); ?></th>
                            <th style="text-align:center;padding:4px 6px;color:var(--sf-gray-500, #64748b);font-weight:600;"><?php esc_html_e( 'Score', 'seo-fury' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $all_entries as $entry ) :
                            $s = intval( $entry['score'] );
                            $color = $s >= 90 ? '#22C55E' : ( $s >= 50 ? '#F59E0B' : '#EF4444' );
                            $icon = $entry['strategy'] === 'mobile' ? 'smartphone' : 'desktop';
                        ?>
                        <tr style="border-bottom: 1px solid var(--sf-gray-200, #f1f5f9);">
                            <td style="padding:4px 6px;color:var(--sf-gray-700, #475569);"><?php echo esc_html( $entry['checked_at'] ?? '' ); ?></td>
                            <td style="text-align:center;padding:4px 6px;">
                                <span class="dashicons dashicons-<?php echo esc_attr( $icon ); ?>" style="font-size:14px;width:14px;height:14px;color:var(--sf-gray-500, #64748b);"></span>
                            </td>
                            <td style="text-align:center;padding:4px 6px;">
                                <span style="color:<?php echo esc_attr( $color ); ?>;font-weight:700;"><?php echo esc_html( $s ); ?></span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }
}
