# thinkrank/1.0.0/src/admin/components/essential-seo/PerformanceTab.js

ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console &amp; Local SEO, version 1.0.0. 1,477 lines.

- Page: https://pluginprobe.com/plugins/thinkrank/1.0.0/code/src/admin/components/essential-seo/PerformanceTab.js
- Raw: https://pluginprobe.com/plugins/thinkrank/1.0.0/raw/src/admin/components/essential-seo/PerformanceTab.js
- Modified: 2025-08-10T07:57:44+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/thinkrank/1.0.0/code/src/admin/components/essential-seo/PerformanceTab.js#L10-L20`.

```javascript
/**
 * Performance Tab Component
 * 
 * Core Web Vitals monitoring and SEO performance insights.
 * Leverages the existing Performance Monitoring Manager for comprehensive
 * performance tracking and analysis.
 * 
 * Features:
 * - Core Web Vitals dashboard (LCP, FID, CLS, INP)
 * - SEO performance correlation
 * - Historical tracking
 * - Performance recommendations
 * 
 * @package ThinkRank
 * @since 1.0.0
 */

import { __ } from '@wordpress/i18n';
import { useState, useEffect, memo, useMemo, useCallback } from '@wordpress/element';
import {
    Card,
    CardHeader,
    CardBody,
    Button,
    Spinner,
    Notice,
    Flex,
    FlexItem,
    __experimentalGrid as Grid,
    __experimentalText as Text,
    __experimentalHeading as Heading,
    __experimentalSpacer as Spacer,
    ProgressBar
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import PerformanceChart from '../common/PerformanceChart';

/**
 * Performance Tab Component
 */
const PerformanceTab = ({ activeSubSection = 'core-web-vitals', onNavigate }) => {
    const [performanceData, setPerformanceData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [notice, setNotice] = useState(null);
    const [lastUpdated, setLastUpdated] = useState(null);
    const [recommendations, setRecommendations] = useState(null);
    const [historicalData, setHistoricalData] = useState(null);
    const [deviceType, setDeviceType] = useState('mobile'); // Mobile-first approach
    const [historicalPeriod, setHistoricalPeriod] = useState(28); // Default to 28 days

    // Opportunities state
    const [opportunities, setOpportunities] = useState([]);
    const [isLoadingOpportunities, setIsLoadingOpportunities] = useState(false);
    const [opportunitiesError, setOpportunitiesError] = useState(null);

    // Diagnostics state
    const [diagnostics, setDiagnostics] = useState([]);
    const [isLoadingDiagnostics, setIsLoadingDiagnostics] = useState(false);
    const [diagnosticsError, setDiagnosticsError] = useState(null);

    /**
     * Load performance data
     * Phase 5: Enhanced error handling for Google API integration
     */
    const loadPerformanceData = async () => {
        try {
            setIsLoading(true);
            setNotice(null);

            const response = await apiFetch({
                path: '/thinkrank/v1/performance/monitor',
                method: 'GET'
            });

            if (response.success) {
                setPerformanceData(response.data);
                setLastUpdated(new Date().toLocaleString());

                // Check if data contains API configuration errors
                if (response.data?.core_web_vitals?.error) {
                    setNotice({
                        status: 'warning',
                        message: response.data.core_web_vitals.message || __('Google PageSpeed Insights API key is required. Please configure it in Integrations > Google Services to view real performance data.', 'thinkrank')
                    });
                } else {
                    setNotice({
                        status: 'success',
                        message: __('Performance data loaded successfully', 'thinkrank')
                    });
                }
            } else {
                throw new Error(response.error || 'Failed to load performance data');
            }
        } catch (error) {
            // Enhanced error handling for specific API issues
            if (error.message.includes('API key is required') || error.message.includes('not configured')) {
                setNotice({
                    status: 'warning',
                    message: __('Google PageSpeed Insights API key is required. Please configure it in Integrations > Google Services to view real performance data.', 'thinkrank')
                });
            } else if (error.message.includes('rate limit exceeded')) {
                setNotice({
                    status: 'warning',
                    message: __('Google API rate limit exceeded. Please try again later.', 'thinkrank')
                });
            } else if (error.message.includes('invalid API key') || error.message.includes('unauthorized')) {
                setNotice({
                    status: 'error',
                    message: __('Invalid Google PageSpeed Insights API key. Please check your API configuration in Analytics > Platforms.', 'thinkrank')
                });
            } else {
                setNotice({
                    status: 'error',
                    message: __('Failed to load performance data. Please check your API configuration in Integrations > Google Services.', 'thinkrank')
                });
            }

            // Set empty performance data instead of showing mock data
            setPerformanceData(null);
        } finally {
            setIsLoading(false);
        }
    };

    /**
     * Load recommendations data
     */
    const loadRecommendations = async () => {
        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/performance/recommendations',
                method: 'GET'
            });

            if (response.success) {
                setRecommendations(response.data);
            }
        } catch (error) {
            // Silently fail for recommendations - not critical
        }
    };

    /**
     * Load historical data
     */
    const loadHistoricalData = async () => {
        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/performance/history?days=30',
                method: 'GET'
            });

            if (response.success) {
                setHistoricalData(response.data);
            }
        } catch (error) {
            // Silently fail for historical data - not critical
        }
    };

    /**
     * Get status color for Core Web Vitals
     */
    const getVitalStatus = (value, thresholds) => {
        if (value <= thresholds.good) return 'good';
        if (value <= thresholds.needs_improvement) return 'needs-improvement';
        return 'poor';
    };

    /**
     * Get status color class
     */
    const getStatusColor = (status) => {
        switch (status) {
            case 'good': return '#00a32a';
            case 'needs-improvement': return '#dba617';
            case 'poor': return '#d63638';
            default: return '#50575e';
        }
    };

    /**
     * Render Core Web Vitals card
     * Phase 5: Enhanced error handling for missing data
     */
    const renderVitalCard = (vital, data) => {
        if (!data) return null;

        // Handle error states for individual metrics
        if (data.status === 'unknown' || data.value === 0) {
            return (
                <Card key={vital} size="small">
                    <CardHeader>
                        <Flex justify="space-between" align="center">
                            <Heading level={4}>{data.name}</Heading>
                            <div
                                style={{
                                    padding: '4px 8px',
                                    borderRadius: '4px',
                                    backgroundColor: '#666',
                                    color: 'white',
                                    fontSize: '12px',
                                    fontWeight: 'bold',
                                    textTransform: 'uppercase'
                                }}
                            >
                                {__('NO DATA', 'thinkrank')}
                            </div>
                        </Flex>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '20px' }}>
                            <div style={{ fontSize: '24px', color: '#666', marginBottom: '8px' }}>—</div>
                            <Text variant="muted" style={{ fontSize: '14px' }}>
                                {__('Data not available', 'thinkrank')}
                            </Text>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        const status = getVitalStatus(data.value, {
            good: data.good_threshold,
            needs_improvement: data.needs_improvement_threshold
        });

        return (
            <Card key={vital} size="small">
                <CardHeader>
                    <Flex justify="space-between" align="center">
                        <Heading level={4}>{data.name}</Heading>
                        <div
                            style={{
                                padding: '4px 8px',
                                borderRadius: '4px',
                                backgroundColor: getStatusColor(status),
                                color: 'white',
                                fontSize: '12px',
                                fontWeight: 'bold',
                                textTransform: 'uppercase'
                            }}
                        >
                            {status.replace('-', ' ')}
                        </div>
                    </Flex>
                </CardHeader>
                <CardBody>
                    <div style={{ textAlign: 'center', marginBottom: '16px' }}>
                        <div style={{
                            fontSize: '32px',
                            fontWeight: 'bold',
                            color: getStatusColor(status)
                        }}>
                            {data.value}{data.unit}
                        </div>
                        <Text variant="muted">{data.description}</Text>
                    </div>
                    
                    <div style={{ marginBottom: '8px' }}>
                        <Text size="small">
                            <strong>{__('Good:', 'thinkrank')}</strong> ≤ {data.good_threshold}{data.unit}
                        </Text>
                    </div>
                    <div>
                        <Text size="small">
                            <strong>{__('Poor:', 'thinkrank')}</strong> &gt; {data.needs_improvement_threshold}{data.unit}
                        </Text>
                    </div>
                </CardBody>
            </Card>
        );
    };

    /**
     * Get performance score color
     */
    const getScoreColor = (score) => {
        if (score >= 90) return '#00a32a'; // Green
        if (score >= 50) return '#dba617'; // Orange
        return '#d63638'; // Red
    };

    /**
     * Render performance score with circular indicator
     */
    const renderPerformanceScore = () => {
        if (!performanceData?.performance_score) return null;

        const score = performanceData.performance_score;
        const color = getScoreColor(score);
        const circumference = 2 * Math.PI * 45; // radius = 45
        const strokeDasharray = circumference;
        const strokeDashoffset = circumference - (score / 100) * circumference;

        return (
            <Card>
                <CardHeader>
                    <Flex justify="space-between" align="center">
                        <Heading level={3}>{__('Performance', 'thinkrank')}</Heading>
                        <div style={{ display: 'flex', gap: '8px' }}>
                            <button
                                onClick={() => setDeviceType('mobile')}
                                style={{
                                    padding: '6px 12px',
                                    border: '1px solid #ddd',
                                    borderRadius: '4px',
                                    background: deviceType === 'mobile' ? '#0073aa' : 'white',
                                    color: deviceType === 'mobile' ? 'white' : '#333',
                                    cursor: 'pointer',
                                    fontSize: '12px'
                                }}
                            >
                                {__('Mobile', 'thinkrank')}
                            </button>
                            <button
                                onClick={() => setDeviceType('desktop')}
                                style={{
                                    padding: '6px 12px',
                                    border: '1px solid #ddd',
                                    borderRadius: '4px',
                                    background: deviceType === 'desktop' ? '#0073aa' : 'white',
                                    color: deviceType === 'desktop' ? 'white' : '#333',
                                    cursor: 'pointer',
                                    fontSize: '12px'
                                }}
                            >
                                {__('Desktop', 'thinkrank')}
                            </button>
                        </div>
                    </Flex>
                </CardHeader>
                <CardBody>
                    <Flex justify="flex-start" align="center" gap={6}>
                        <FlexItem>
                            <div style={{ position: 'relative', width: '100px', height: '100px' }}>
                                <svg width="100" height="100" style={{ transform: 'rotate(-90deg)' }}>
                                    {/* Background circle */}
                                    <circle
                                        cx="50"
                                        cy="50"
                                        r="45"
                                        stroke="#e0e0e0"
                                        strokeWidth="6"
                                        fill="none"
                                    />
                                    {/* Progress circle */}
                                    <circle
                                        cx="50"
                                        cy="50"
                                        r="45"
                                        stroke={color}
                                        strokeWidth="6"
                                        fill="none"
                                        strokeDasharray={strokeDasharray}
                                        strokeDashoffset={strokeDashoffset}
                                        strokeLinecap="round"
                                        style={{ transition: 'stroke-dashoffset 0.5s ease' }}
                                    />
                                </svg>
                                <div style={{
                                    position: 'absolute',
                                    top: '50%',
                                    left: '50%',
                                    transform: 'translate(-50%, -50%)',
                                    fontSize: '24px',
                                    fontWeight: 'bold',
                                    color: color
                                }}>
                                    {score}
                                </div>
                            </div>
                        </FlexItem>
                        <FlexItem>
                            <div>
                                <Text style={{ fontSize: '16px', fontWeight: '500', marginBottom: '4px' }}>
                                    {deviceType === 'mobile' ? __('Mobile Performance', 'thinkrank') : __('Desktop Performance', 'thinkrank')}
                                </Text>
                                <Text variant="muted" style={{ fontSize: '14px' }}>
                                    {score >= 90 && __('Fast - Performance is good', 'thinkrank')}
                                    {score >= 50 && score < 90 && __('Average - Performance needs improvement', 'thinkrank')}
                                    {score < 50 && __('Slow - Performance is poor', 'thinkrank')}
                                </Text>
                            </div>
                        </FlexItem>
                    </Flex>
                </CardBody>
            </Card>
        );
    };

    /**
     * Get opportunity priority color
     */
    const getOpportunityColor = (savings) => {
        if (savings >= 1000) return '#d63638'; // Red - High impact
        if (savings >= 500) return '#dba617'; // Orange - Medium impact
        return '#00a32a'; // Green - Low impact
    };

    /**
     * Get difficulty badge style - Memoized for performance
     */
    const getDifficultyStyle = useCallback((difficulty) => {
        const colors = {
            'Easy': { bg: '#e7f5e7', color: '#00a32a', border: '#00a32a' },
            'Medium': { bg: '#fff8e1', color: '#dba617', border: '#dba617' },
            'Hard': { bg: '#ffeaea', color: '#d63638', border: '#d63638' }
        };
        return colors[difficulty] || colors['Medium'];
    }, []);

    /**
     * Render opportunity card - Memoized for performance
     */
    const renderOpportunityCard = useCallback((opportunity) => {
        const difficultyStyle = getDifficultyStyle(opportunity.difficulty);
        const impactColor = getOpportunityColor(opportunity.estimated_savings);

        return (
            <Card key={opportunity.id} style={{ marginBottom: '16px', border: `1px solid ${impactColor}20` }}>
                <CardBody>
                    <Flex justify="space-between" align="flex-start" style={{ marginBottom: '12px' }}>
                        <FlexItem style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                                <Heading level={4} style={{ margin: 0, fontSize: '16px' }}>
                                    {opportunity.title}
                                </Heading>
                                <span style={{
                                    padding: '2px 8px',
                                    borderRadius: '12px',
                                    fontSize: '12px',
                                    fontWeight: 'bold',
                                    backgroundColor: difficultyStyle.bg,
                                    color: difficultyStyle.color,
                                    border: `1px solid ${difficultyStyle.border}40`
                                }}>
                                    {opportunity.difficulty}
                                </span>
                            </div>
                            <Text variant="muted" style={{ fontSize: '14px' }}>
                                {opportunity.description}
                            </Text>
                        </FlexItem>
                        <FlexItem>
                            <div style={{ textAlign: 'right' }}>
                                <div style={{
                                    fontSize: '18px',
                                    fontWeight: 'bold',
                                    color: impactColor,
                                    marginBottom: '2px'
                                }}>
                                    {opportunity.estimated_savings >= 1000
                                        ? `${(opportunity.estimated_savings / 1000).toFixed(1)}s`
                                        : `${opportunity.estimated_savings}ms`
                                    }
                                </div>
                                <Text variant="muted" style={{ fontSize: '12px' }}>
                                    {__('Potential savings', 'thinkrank')}
                                </Text>
                            </div>
                        </FlexItem>
                    </Flex>

                    {opportunity.details && (
                        <div style={{
                            backgroundColor: '#f8f9fa',
                            padding: '12px',
                            borderRadius: '4px',
                            marginTop: '12px'
                        }}>
                            <Text style={{ fontSize: '14px' }}>
                                <strong>{__('How to fix:', 'thinkrank')}</strong> {opportunity.details}
                            </Text>
                        </div>
                    )}
                </CardBody>
            </Card>
        );
    }, [getDifficultyStyle, getOpportunityColor]);

    /**
     * Load opportunities data
     */
    const loadOpportunities = async () => {
        setIsLoadingOpportunities(true);
        setOpportunitiesError(null);

        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/performance/opportunities',
                method: 'GET'
            });

            if (response.success) {
                setOpportunities(response.data || []);
            } else {
                setOpportunitiesError(__('Failed to load opportunities data', 'thinkrank'));
            }
        } catch (error) {
            setOpportunitiesError(__('Unable to connect to performance API', 'thinkrank'));
        } finally {
            setIsLoadingOpportunities(false);
        }
    };

    /**
     * Load diagnostics data
     */
    const loadDiagnostics = async () => {
        setIsLoadingDiagnostics(true);
        setDiagnosticsError(null);

        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/performance/diagnostics',
                method: 'GET'
            });

            if (response.success) {
                setDiagnostics(response.data || []);
            } else {
                setDiagnosticsError(__('Failed to load diagnostics data', 'thinkrank'));
            }
        } catch (error) {
            setDiagnosticsError(__('Unable to connect to performance API', 'thinkrank'));
        } finally {
            setIsLoadingDiagnostics(false);
        }
    };

    /**
     * Memoize total savings calculation for performance
     */
    const totalSavings = useMemo(() => {
        return opportunities.reduce((sum, opp) => sum + (opp.estimated_savings || 0), 0);
    }, [opportunities]);

    /**
     * Render Opportunities content with real PageSpeed data
     */
    const renderOpportunities = () => {

        // Show loading state
        if (isLoadingOpportunities) {
            return (
                <Card>
                    <CardBody style={{ textAlign: 'center', padding: '48px' }}>
                        <Spinner />
                        <Text>{__('Loading performance opportunities...', 'thinkrank')}</Text>
                    </CardBody>
                </Card>
            );
        }

        // Show error state
        if (opportunitiesError) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Performance Opportunities', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <Notice status="error" isDismissible={false}>
                            {opportunitiesError}
                        </Notice>
                        <Text variant="muted" style={{ marginTop: '16px' }}>
                            {__('Configure Google PageSpeed Insights API in Integrations > Google Services to view real performance opportunities.', 'thinkrank')}
                        </Text>
                    </CardBody>
                </Card>
            );
        }

        // Show empty state - check if it's due to API configuration or actually no opportunities
        if (opportunities.length === 0) {
            // Check if Core Web Vitals data indicates API configuration issue
            const hasApiConfigIssue = performanceData?.core_web_vitals?.error ||
                                     performanceData?.core_web_vitals?.message?.includes('API key');

            if (hasApiConfigIssue) {
                // Show API configuration message
                return (
                    <Card>
                        <CardHeader>
                            <Heading level={3}>{__('Performance Opportunities', 'thinkrank')}</Heading>
                        </CardHeader>
                        <CardBody>
                            <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                                <div style={{ fontSize: '48px', marginBottom: '24px' }}>⚡</div>

                                <div style={{ marginBottom: '32px' }}>
                                    <Heading level={4} style={{ marginBottom: '16px' }}>
                                        {__('No Performance Data Available', 'thinkrank')}
                                    </Heading>

                                    <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                        {__('Configure Google PageSpeed Insights API to view performance optimization opportunities.', 'thinkrank')}
                                    </Text>

                                    <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                        {__('Performance opportunities help identify specific areas where your site can be optimized for better speed and user experience.', 'thinkrank')}
                                    </Text>
                                </div>

                                <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                    <Button
                                        variant="primary"
                                        onClick={() => {
                                            // Navigate to Integrations > Google Services tab
                                            if (onNavigate) {
                                                onNavigate('integrations', 'google-services');
                                            }
                                        }}
                                    >
                                        {__('Configure API Settings', 'thinkrank')}
                                    </Button>
                                    <Button
                                        variant="secondary"
                                        onClick={loadOpportunities}
                                        disabled={isLoadingOpportunities}
                                    >
                                        {isLoadingOpportunities ? <Spinner /> : __('Retry', 'thinkrank')}
                                    </Button>
                                </div>
                            </div>
                        </CardBody>
                    </Card>
                );
            } else {
                // Show "well-optimized" message
                return (
                    <Card>
                        <CardHeader>
                            <Heading level={3}>{__('Performance Opportunities', 'thinkrank')}</Heading>
                        </CardHeader>
                        <CardBody>
                            <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                                <div style={{ fontSize: '48px', marginBottom: '24px' }}>🎉</div>

                                <div>
                                    <Heading level={4} style={{ marginBottom: '16px' }}>
                                        {__('Great job! No performance opportunities found.', 'thinkrank')}
                                    </Heading>

                                    <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                        {__('Your site is already well-optimized for performance.', 'thinkrank')}
                                    </Text>

                                    <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                        {__('Keep monitoring your performance metrics to maintain optimal user experience.', 'thinkrank')}
                                    </Text>
                                </div>
                            </div>
                        </CardBody>
                    </Card>
                );
            }
        }

        return (
            <>
                <Card style={{ marginBottom: '24px' }}>
                    <CardHeader>
                        <Flex justify="space-between" align="center">
                            <Heading level={3}>{__('Performance Opportunities', 'thinkrank')}</Heading>
                            <div style={{ textAlign: 'right' }}>
                                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#d63638' }}>
                                    {totalSavings >= 1000
                                        ? `${(totalSavings / 1000).toFixed(1)}s`
                                        : `${totalSavings}ms`
                                    }
                                </div>
                                <Text variant="muted" style={{ fontSize: '12px' }}>
                                    {__('Total potential savings', 'thinkrank')}
                                </Text>
                            </div>
                        </Flex>
                    </CardHeader>
                    <CardBody>
                        <Text variant="muted">
                            {__('These suggestions can help your page load faster. They don\'t directly affect the Performance score.', 'thinkrank')}
                        </Text>
                    </CardBody>
                </Card>

                <div>
                    {opportunities.map(opportunity => renderOpportunityCard(opportunity))}
                </div>

                <Card style={{ backgroundColor: '#f0f6ff', border: '1px solid #0073aa20' }}>
                    <CardBody>
                        <Flex align="center" gap={3}>
                            <div style={{ fontSize: '20px' }}>💡</div>
                            <div>
                                <Text style={{ fontWeight: '500', marginBottom: '4px' }}>
                                    {__('Pro Tip', 'thinkrank')}
                                </Text>
                                <Text variant="muted" style={{ fontSize: '14px' }}>
                                    {__('Focus on opportunities with high estimated savings and easy difficulty first. These provide the best return on investment for your performance optimization efforts.', 'thinkrank')}
                                </Text>
                            </div>
                        </Flex>
                    </CardBody>
                </Card>
            </>
        );
    };



    /**
     * Render simple trend chart
     */
    const renderTrendChart = (title, data, unit, thresholds) => {
        // Determine chart color based on performance
        const getChartColor = () => {
            if (!data || data.length === 0) return '#0073aa';

            const currentValue = data[data.length - 1]?.value || 0;

            if (thresholds?.good && currentValue <= thresholds.good) {
                return '#34a853'; // Green for good
            } else if (thresholds?.needs_improvement && currentValue <= thresholds.needs_improvement) {
                return '#fbbc04'; // Yellow for needs improvement
            } else {
                return '#ea4335'; // Red for poor
            }
        };

        return (
            <Card className="thinkrank-mb-4">
                <CardBody>
                    <PerformanceChart
                        title={title}
                        data={data}
                        unit={unit}
                        thresholds={thresholds}
                        height={320}
                        showArea={true}
                        color={getChartColor()}
                    />

                    {/* Current value and trend */}
                    <div className="thinkrank-chart-stats">
                        <div>
                            <div className="thinkrank-current-value">
                                {data[data.length - 1]?.value?.toFixed(unit === 'score' ? 3 : unit === 's' ? 2 : 0)}{unit}
                            </div>
                            <div className="thinkrank-current-label">
                                {__('Current', 'thinkrank')}
                            </div>
                        </div>
                        <div className="thinkrank-trend">
                            <div className={`thinkrank-trend-value ${data.length > 1 && data[data.length - 1]?.value < data[data.length - 2]?.value ? 'status-good' : 'status-poor'}`}>
                                {data.length > 1 ? (
                                    data[data.length - 1]?.value < data[data.length - 2]?.value ? '↓ Better' : '↑ Worse'
                                ) : '—'}
                            </div>
                            <div className="thinkrank-trend-label">
                                {__('vs. Previous', 'thinkrank')}
                            </div>
                        </div>
                    </div>
                </CardBody>
            </Card>
        );
    };

    /**
     * Render Historical Data content with real trend charts
     */
    const renderHistoricalData = () => {
        // Show loading state
        if (!historicalData) {
            return (
                <Card>
                    <CardBody style={{ textAlign: 'center', padding: '48px' }}>
                        <Spinner />
                        <Text>{__('Loading historical performance data...', 'thinkrank')}</Text>
                    </CardBody>
                </Card>
            );
        }

        // Check if we have real historical data or if API configuration is needed
        const hasRealData = historicalData && (
            historicalData.lcp ||
            historicalData.fid ||
            historicalData.cls ||
            historicalData.inp
        );

        // Check if Core Web Vitals data indicates API configuration issue
        const hasApiConfigIssue = performanceData?.core_web_vitals?.error ||
                                 performanceData?.core_web_vitals?.message?.includes('API key');

        // If no real data and API config issue, show configuration message
        if (!hasRealData && hasApiConfigIssue) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Historical Performance Data', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                            <div style={{ fontSize: '48px', marginBottom: '24px' }}>📈</div>

                            <div style={{ marginBottom: '32px' }}>
                                <Heading level={4} style={{ marginBottom: '16px' }}>
                                    {__('No Historical Data Available', 'thinkrank')}
                                </Heading>

                                <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                    {__('Configure Google PageSpeed Insights API to start collecting historical performance data.', 'thinkrank')}
                                </Text>

                                <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                    {__('Historical data helps track your site\'s performance trends over time and identify patterns in Core Web Vitals metrics.', 'thinkrank')}
                                </Text>
                            </div>

                            <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                <Button
                                    variant="primary"
                                    onClick={() => {
                                        // Navigate to Integrations > Google Services tab
                                        if (onNavigate) {
                                            onNavigate('integrations', 'google-services');
                                        }
                                    }}
                                >
                                    {__('Configure API Settings', 'thinkrank')}
                                </Button>
                                <Button
                                    variant="secondary"
                                    onClick={loadHistoricalData}
                                    disabled={!historicalData}
                                >
                                    {!historicalData ? <Spinner /> : __('Retry', 'thinkrank')}
                                </Button>
                            </div>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        // If no real data but API is configured, show data collection message
        if (!hasRealData) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Historical Performance Data', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                            <div style={{ fontSize: '48px', marginBottom: '24px' }}>⏳</div>

                            <div style={{ marginBottom: '32px' }}>
                                <Heading level={4} style={{ marginBottom: '16px' }}>
                                    {__('Collecting Historical Data', 'thinkrank')}
                                </Heading>

                                <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                    {__('Historical performance data will appear here as it\'s collected over time.', 'thinkrank')}
                                </Text>

                                <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                    {__('Data collection runs daily. Check back in a few days to see your performance trends.', 'thinkrank')}
                                </Text>
                            </div>

                            <div style={{ display: 'flex', justifyContent: 'center' }}>
                                <Button
                                    variant="secondary"
                                    onClick={loadHistoricalData}
                                    disabled={!historicalData}
                                >
                                    {!historicalData ? <Spinner /> : __('Refresh Data', 'thinkrank')}
                                </Button>
                            </div>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        // Use real historical data
        const lcpData = historicalData.lcp;
        const fidData = historicalData.fid;
        const clsData = historicalData.cls;
        const inpData = historicalData.inp;

        return (
            <>
                <Card style={{ marginBottom: '24px' }}>
                    <CardHeader>
                        <Flex justify="space-between" align="center">
                            <Heading level={3}>{__('Historical Performance Data', 'thinkrank')}</Heading>
                            <div style={{ display: 'flex', gap: '8px' }}>
                                <button
                                    onClick={() => setHistoricalPeriod(28)}
                                    style={{
                                        padding: '6px 12px',
                                        border: '1px solid #ddd',
                                        borderRadius: '4px',
                                        background: historicalPeriod === 28 ? '#0073aa' : 'white',
                                        color: historicalPeriod === 28 ? 'white' : '#333',
                                        cursor: 'pointer',
                                        fontSize: '12px'
                                    }}
                                >
                                    {__('28 Days', 'thinkrank')}
                                </button>
                                <button
                                    onClick={() => setHistoricalPeriod(90)}
                                    style={{
                                        padding: '6px 12px',
                                        border: '1px solid #ddd',
                                        borderRadius: '4px',
                                        background: historicalPeriod === 90 ? '#0073aa' : 'white',
                                        color: historicalPeriod === 90 ? 'white' : '#333',
                                        cursor: 'pointer',
                                        fontSize: '12px'
                                    }}
                                >
                                    {__('90 Days', 'thinkrank')}
                                </button>
                            </div>
                        </Flex>
                    </CardHeader>
                    <CardBody>
                        <Text variant="muted">
                            {__('Track your Core Web Vitals performance over time to identify trends and regressions.', 'thinkrank')}
                            {__(' Showing data for the last %d days.', 'thinkrank').replace('%d', historicalPeriod)}
                        </Text>
                    </CardBody>
                </Card>

                <div className="thinkrank-grid thinkrank-grid-cols-1 thinkrank-grid-cols-2-lg thinkrank-gap-4 thinkrank-mb-6">
                    {renderTrendChart(
                        __('Largest Contentful Paint (LCP)', 'thinkrank'),
                        lcpData,
                        's',
                        { good: 2.5, needs_improvement: 4.0 }
                    )}
                    {renderTrendChart(
                        __('First Input Delay (FID)', 'thinkrank'),
                        fidData,
                        'ms',
                        { good: 100, needs_improvement: 300 }
                    )}
                    {renderTrendChart(
                        __('Cumulative Layout Shift (CLS)', 'thinkrank'),
                        clsData,
                        'score',
                        { good: 0.1, needs_improvement: 0.25 }
                    )}
                    {renderTrendChart(
                        __('Interaction to Next Paint (INP)', 'thinkrank'),
                        inpData,
                        'ms',
                        { good: 200, needs_improvement: 500 }
                    )}
                </div>

                <Card style={{ marginBottom: '16px' }}>
                    <CardHeader>
                        <Heading level={4}>{__('Performance Alerts & Monitoring', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '16px' }}>
                            <div>
                                <Text style={{ fontWeight: '500', marginBottom: '8px' }}>
                                    {__('Monitoring Status', 'thinkrank')}
                                </Text>
                                <div style={{ fontSize: '14px' }}>
                                    <div style={{ marginBottom: '4px' }}>✅ {__('Core Web Vitals tracking: Active', 'thinkrank')}</div>
                                    <div style={{ marginBottom: '4px' }}>✅ {__('Performance alerts: Enabled', 'thinkrank')}</div>
                                    <div style={{ marginBottom: '4px' }}>✅ {__('Data retention: 90 days', 'thinkrank')}</div>
                                </div>
                            </div>

                            <div>
                                <Text style={{ fontWeight: '500', marginBottom: '8px' }}>
                                    {__('Recent Activity', 'thinkrank')}
                                </Text>
                                <div style={{ fontSize: '14px' }}>
                                    <div style={{ marginBottom: '4px' }}>• {__('Performance data collected successfully', 'thinkrank')}</div>
                                    <div style={{ marginBottom: '4px' }}>• {__('No critical alerts in the last 24 hours', 'thinkrank')}</div>
                                    <div style={{ marginBottom: '4px' }}>• {__('LCP improved by 0.2s since last week', 'thinkrank')}</div>
                                </div>
                            </div>
                        </div>
                    </CardBody>
                </Card>

                <Card style={{ backgroundColor: '#fff8e1', border: '1px solid #dba61720' }}>
                    <CardBody>
                        <Flex align="center" gap={3}>
                            <div style={{ fontSize: '20px' }}>📊</div>
                            <div>
                                <Text style={{ fontWeight: '500', marginBottom: '4px' }}>
                                    {__('Historical Data Integration', 'thinkrank')}
                                </Text>
                                <Text variant="muted" style={{ fontSize: '14px' }}>
                                    {__('When Google PageSpeed API is integrated, this section will show real historical performance data from your actual website visitors, helping you track improvements and identify performance regressions over time.', 'thinkrank')}
                                </Text>
                            </div>
                        </Flex>
                    </CardBody>
                </Card>
            </>
        );
    };

    /**
     * Render diagnostic card
     */
    const renderDiagnosticCard = (diagnostic) => {
        const statusColors = {
            'passed': { bg: '#e7f5e7', color: '#00a32a', icon: '✅' },
            'warning': { bg: '#fff8e1', color: '#dba617', icon: '⚠️' },
            'failed': { bg: '#ffeaea', color: '#d63638', icon: '❌' }
        };

        const statusStyle = statusColors[diagnostic.status] || statusColors['warning'];

        return (
            <Card key={diagnostic.id} style={{ marginBottom: '16px', border: `1px solid ${statusStyle.color}20` }}>
                <CardBody>
                    <Flex justify="space-between" align="flex-start" style={{ marginBottom: '12px' }}>
                        <FlexItem style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                                <span style={{ fontSize: '16px' }}>{statusStyle.icon}</span>
                                <Heading level={4} style={{ margin: 0, fontSize: '16px' }}>
                                    {diagnostic.title}
                                </Heading>
                            </div>
                            <Text variant="muted" style={{ fontSize: '14px', marginBottom: '8px' }}>
                                {diagnostic.description}
                            </Text>

                            {diagnostic.details && (
                                <Text style={{ fontSize: '14px' }}>
                                    {diagnostic.details}
                                </Text>
                            )}
                        </FlexItem>

                        {diagnostic.impact && (
                            <FlexItem>
                                <div style={{ textAlign: 'right' }}>
                                    <div style={{
                                        fontSize: '14px',
                                        fontWeight: 'bold',
                                        color: statusStyle.color,
                                        marginBottom: '2px'
                                    }}>
                                        {diagnostic.impact}
                                    </div>
                                    <Text variant="muted" style={{ fontSize: '12px' }}>
                                        {__('Impact', 'thinkrank')}
                                    </Text>
                                </div>
                            </FlexItem>
                        )}
                    </Flex>

                    {diagnostic.resources && diagnostic.resources.length > 0 && (
                        <div style={{
                            backgroundColor: '#f8f9fa',
                            padding: '12px',
                            borderRadius: '4px',
                            marginTop: '12px'
                        }}>
                            <Text style={{ fontSize: '14px', fontWeight: '500', marginBottom: '8px' }}>
                                {__('Affected Resources:', 'thinkrank')}
                            </Text>
                            <div style={{ fontSize: '13px', fontFamily: 'monospace' }}>
                                {diagnostic.resources.slice(0, 3).map((resource, index) => (
                                    <div key={index} style={{ marginBottom: '4px', color: '#666' }}>
                                        {resource}
                                    </div>
                                ))}
                                {diagnostic.resources.length > 3 && (
                                    <Text variant="muted" style={{ fontSize: '12px' }}>
                                        {__('... and %d more', 'thinkrank').replace('%d', diagnostic.resources.length - 3)}
                                    </Text>
                                )}
                            </div>
                        </div>
                    )}
                </CardBody>
            </Card>
        );
    };

    /**
     * Render Diagnostics content with PageSpeed-style diagnostic cards
     */
    const renderDiagnostics = () => {
        // Show loading state
        if (isLoadingDiagnostics) {
            return (
                <Card>
                    <CardBody style={{ textAlign: 'center', padding: '48px' }}>
                        <Spinner />
                        <Text>{__('Loading performance diagnostics...', 'thinkrank')}</Text>
                    </CardBody>
                </Card>
            );
        }

        // Show error state
        if (diagnosticsError) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Performance Diagnostics', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <Notice status="error" isDismissible={false}>
                            {diagnosticsError}
                        </Notice>
                        <Text variant="muted" style={{ marginTop: '16px' }}>
                            {__('Configure Google PageSpeed Insights API in Integrations > Google Services to view real performance diagnostics.', 'thinkrank')}
                        </Text>
                    </CardBody>
                </Card>
            );
        }

        // Show empty state
        if (diagnostics.length === 0) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Performance Diagnostics', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                            <div style={{ fontSize: '48px', marginBottom: '24px' }}>🔍</div>

                            <div style={{ marginBottom: '32px' }}>
                                <Heading level={4} style={{ marginBottom: '16px' }}>
                                    {__('No Diagnostic Data Available', 'thinkrank')}
                                </Heading>

                                <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                    {__('Configure Google PageSpeed Insights API to view detailed performance diagnostics.', 'thinkrank')}
                                </Text>

                                <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                    {__('Performance diagnostics provide detailed insights into specific performance issues and optimization recommendations.', 'thinkrank')}
                                </Text>
                            </div>

                            <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                <Button
                                    variant="primary"
                                    onClick={() => {
                                        // Navigate to Integrations > Google Services tab
                                        if (onNavigate) {
                                            onNavigate('integrations', 'google-services');
                                        }
                                    }}
                                >
                                    {__('Configure API Settings', 'thinkrank')}
                                </Button>
                                <Button
                                    variant="secondary"
                                    onClick={loadDiagnostics}
                                    disabled={isLoadingDiagnostics}
                                >
                                    {isLoadingDiagnostics ? <Spinner /> : __('Retry', 'thinkrank')}
                                </Button>
                            </div>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        const passedCount = diagnostics.filter(d => d.status === 'passed').length;
        const warningCount = diagnostics.filter(d => d.status === 'warning').length;
        const failedCount = diagnostics.filter(d => d.status === 'failed').length;

        return (
            <>
                <Card style={{ marginBottom: '24px' }}>
                    <CardHeader>
                        <Flex justify="space-between" align="center">
                            <Heading level={3}>{__('Performance Diagnostics', 'thinkrank')}</Heading>
                            <div style={{ display: 'flex', gap: '16px', fontSize: '14px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                    <span style={{ color: '#00a32a' }}>✅</span>
                                    <span>{passedCount} {__('Passed', 'thinkrank')}</span>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                    <span style={{ color: '#dba617' }}>⚠️</span>
                                    <span>{warningCount} {__('Warnings', 'thinkrank')}</span>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                    <span style={{ color: '#d63638' }}>❌</span>
                                    <span>{failedCount} {__('Failed', 'thinkrank')}</span>
                                </div>
                            </div>
                        </Flex>
                    </CardHeader>
                    <CardBody>
                        <Text variant="muted">
                            {__('These checks highlight opportunities to improve your page\'s performance and user experience.', 'thinkrank')}
                        </Text>
                    </CardBody>
                </Card>

                <div>
                    {diagnostics.map(diagnostic => renderDiagnosticCard(diagnostic))}
                </div>

                <Card style={{ backgroundColor: '#f0f6ff', border: '1px solid #0073aa20' }}>
                    <CardBody>
                        <Flex align="center" gap={3}>
                            <div style={{ fontSize: '20px' }}>🔍</div>
                            <div>
                                <Text style={{ fontWeight: '500', marginBottom: '4px' }}>
                                    {__('Diagnostic Information', 'thinkrank')}
                                </Text>
                                <Text variant="muted" style={{ fontSize: '14px' }}>
                                    {__('These diagnostics are collected from various performance audits. When integrated with Google PageSpeed API, you\'ll get real-time diagnostic data specific to your website\'s actual performance characteristics.', 'thinkrank')}
                                </Text>
                            </div>
                        </Flex>
                    </CardBody>
                </Card>
            </>
        );
    };

    /**
     * Render Core Web Vitals content with device toggle
     * Phase 5: Enhanced error handling and "No Data Available" states
     */
    const renderCoreWebVitals = () => {
        // Check if Core Web Vitals data has API configuration errors
        if (!performanceData || !performanceData.core_web_vitals || performanceData.core_web_vitals.error) {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Core Web Vitals', 'thinkrank')}</Heading>
                        <Text variant="muted">
                            {__('Google ranking factors that measure user experience', 'thinkrank')}
                        </Text>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                            <div style={{ fontSize: '48px', marginBottom: '24px' }}>📊</div>

                            <div style={{ marginBottom: '32px' }}>
                                <Heading level={4} style={{ marginBottom: '16px' }}>
                                    {__('No Core Web Vitals Data Available', 'thinkrank')}
                                </Heading>

                                <Text style={{ color: '#666', fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                    {performanceData?.core_web_vitals?.message ||
                                     __('No Core Web Vitals data available. PageSpeed Insights provides real-time data, so please check your API key configuration.', 'thinkrank')}
                                </Text>

                                <Text variant="muted" style={{ fontSize: '14px', display: 'block' }}>
                                    {__('Core Web Vitals are essential metrics that Google uses for ranking. Get real data by setting up the PageSpeed Insights API.', 'thinkrank')}
                                </Text>
                            </div>

                            <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                <Button
                                    variant="primary"
                                    onClick={() => {
                                        // Navigate to Integrations > Google Services tab
                                        if (onNavigate) {
                                            onNavigate('integrations', 'google-services');
                                        }
                                    }}
                                >
                                    {__('Configure API Settings', 'thinkrank')}
                                </Button>
                                <Button
                                    variant="secondary"
                                    onClick={loadPerformanceData}
                                    disabled={isLoading}
                                >
                                    {isLoading ? <Spinner /> : __('Retry', 'thinkrank')}
                                </Button>
                            </div>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        return (
            <>
                {renderPerformanceScore()}

                <Spacer marginY={6} />

                <Flex justify="space-between" align="center" style={{ marginBottom: '16px' }}>
                    <div>
                        <Heading level={3}>{__('Core Web Vitals', 'thinkrank')}</Heading>
                        <Text variant="muted">
                            {__('Google ranking factors that measure user experience', 'thinkrank')}
                        </Text>
                    </div>
                    <div style={{ fontSize: '14px', color: '#666' }}>
                        {deviceType === 'mobile' ? __('📱 Mobile Data', 'thinkrank') : __('🖥️ Desktop Data', 'thinkrank')}
                    </div>
                </Flex>

                <Grid columns={2} gap={4}>
                    {performanceData.core_web_vitals && Object.entries(performanceData.core_web_vitals)
                        .filter(([vital, data]) => vital !== 'error' && vital !== 'message') // Filter out error properties
                        .map(([vital, data]) => renderVitalCard(vital, data))
                    }
                </Grid>

                <div style={{ marginTop: '16px', padding: '12px', backgroundColor: '#f8f9fa', borderRadius: '4px', fontSize: '14px' }}>
                    <Text variant="muted">
                        <strong>{__('Note:', 'thinkrank')}</strong> {deviceType === 'mobile'
                            ? __('Mobile performance data reflects real user experience on mobile devices. Mobile-first indexing makes this data crucial for SEO.', 'thinkrank')
                            : __('Desktop performance data shows how your site performs on desktop devices. While important, mobile performance takes priority for SEO.', 'thinkrank')
                        }
                    </Text>
                </div>
            </>
        );
    };

    /**
     * Render content based on active sub-section
     * Phase 5: Enhanced error handling for Google API integration
     */
    const renderSubSectionContent = () => {
        if (isLoading && !performanceData) {
            return (
                <div style={{ textAlign: 'center', padding: '48px' }}>
                    <Spinner />
                    <Text>{__('Loading performance data...', 'thinkrank')}</Text>
                </div>
            );
        }

        // Enhanced "No Data Available" state with API configuration guidance
        if (!performanceData && activeSubSection !== 'recommendations') {
            return (
                <Card>
                    <CardHeader>
                        <Heading level={3}>{__('Performance Data Not Available', 'thinkrank')}</Heading>
                    </CardHeader>
                    <CardBody>
                        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
                            <div style={{ fontSize: '48px', marginBottom: '24px' }}>⚡</div>

                            <div style={{ marginBottom: '32px' }}>
                                <Text style={{ fontSize: '16px', marginBottom: '12px', display: 'block' }}>
                                    {__('No performance data available. This could be due to missing API configuration.', 'thinkrank')}
                                </Text>

                                <Text variant="muted" style={{ display: 'block' }}>
                                    {__('Configure Google PageSpeed Insights API in Integrations > Google Services to view real performance metrics.', 'thinkrank')}
                                </Text>
                            </div>

                            <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                <Button
                                    variant="primary"
                                    onClick={() => {
                                        // Navigate to Integrations > Google Services tab
                                        if (onNavigate) {
                                            onNavigate('integrations', 'google-services');
                                        }
                                    }}
                                >
                                    {__('Configure API Settings', 'thinkrank')}
                                </Button>
                                <Button
                                    variant="secondary"
                                    onClick={loadPerformanceData}
                                    disabled={isLoading}
                                >
                                    {isLoading ? <Spinner /> : __('Refresh Data', 'thinkrank')}
                                </Button>
                            </div>
                        </div>
                    </CardBody>
                </Card>
            );
        }

        switch (activeSubSection) {
            case 'core-web-vitals':
                return renderCoreWebVitals();
            case 'seo-performance':
                return renderOpportunities();
            case 'monitoring':
                return renderHistoricalData();
            case 'recommendations':
                return renderDiagnostics();
            default:
                return renderCoreWebVitals();
        }
    };

    // Load data on component mount and when activeSubSection changes
    useEffect(() => {
        loadPerformanceData();

        // Load additional data based on active sub-section
        if (activeSubSection === 'recommendations' && !recommendations) {
            loadRecommendations();
        }
        if (activeSubSection === 'monitoring' && !historicalData) {
            loadHistoricalData();
        }
        if (activeSubSection === 'seo-performance' && opportunities.length === 0 && !isLoadingOpportunities) {
            loadOpportunities();
        }
        if (activeSubSection === 'recommendations' && diagnostics.length === 0 && !isLoadingDiagnostics) {
            loadDiagnostics();
        }
    }, [activeSubSection]);

    return (
        <div className="thinkrank-performance-tab">
            <div style={{ marginBottom: '24px' }}>
                <Flex justify="space-between" align="center">
                    <FlexItem>
                        <Heading level={2}>{__('Performance Monitoring', 'thinkrank')}</Heading>
                        <Text variant="muted">
                            {__('Core Web Vitals and SEO performance insights', 'thinkrank')}
                        </Text>
                    </FlexItem>
                    <FlexItem>
                        <Button 
                            variant="secondary" 
                            onClick={loadPerformanceData}
                            disabled={isLoading}
                        >
                            {isLoading ? <Spinner /> : __('Refresh Data', 'thinkrank')}
                        </Button>
                    </FlexItem>
                </Flex>
            </div>

            {notice && (
                <Notice 
                    status={notice.status} 
                    onRemove={() => setNotice(null)}
                    style={{ marginBottom: '16px' }}
                >
                    {notice.message}
                </Notice>
            )}

            {lastUpdated && (
                <Text variant="muted" className="thinkrank-mb-4 thinkrank-block">
                    {__('Last updated:', 'thinkrank')} {lastUpdated}
                </Text>
            )}

            {renderSubSectionContent()}
        </div>
    );
};

export default PerformanceTab;

```
