/**
 * Enhanced Core Web Vitals Component with 2025 Features
 * 
 * Features:
 * - Real-time monitoring with web-vitals library
 * - Historical charts with Chart.js
 * - CrUX field data integration
 * - Performance budgets and alerts
 * - Multi-page monitoring
 * - Export functionality
 * - Automated recommendations
 * 
 * @package ProRank\SEO
 * @since   2.0.0
 */

import { useState, useEffect, useRef } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Line, Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js';
import ProrankButton from '../../../components/ProrankButton';
import { ProrankCard, ProrankCardBody, ProrankCardHeader } from '../../../components/ProrankCard';
import { ProrankSpinner } from '../../../components/ProrankSpinner';
import { ProrankProgressBar } from '../../../components/ProrankProgressBar';
import { ProrankNotice } from '../../../components/ProrankNotice';
import ProrankToggleSlider from '../../../components/ProrankToggleSlider';
import { Flex, FlexItem, FlexBlock } from '../../../components/design-system/Flex';
import { useNotification } from '../../../contexts/NotificationContext';
import * as React from 'react';

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

interface WebVitalMetric {
  name: string;
  value: number;
  rating: 'good' | 'needs-improvement' | 'poor';
  delta?: number;
  entries?: any[];
  id?: string;
  navigationType?: string;
}

interface CoreWebVitalsData {
  lcp: number | null;
  inp: number | null;
  cls: number | null;
  fcp: number | null;
  ttfb: number | null;
  score?: number;
  timestamp: string;
  url: string;
  device?: string;
  diagnostics?: {
    psi_configured?: boolean;
    gsc_connected?: boolean;
    crux_available?: boolean;
    has_history?: boolean;
    history_count?: number;
    has_current?: boolean;
    current_source?: string;
    messages?: string[];
  };
}

interface VitalThresholds {
  good: number;
  poor: number;
}

interface PerformanceBudget {
  metric: string;
  threshold: number;
  enabled: boolean;
}

interface CrUXData {
  available: boolean;
  metrics?: {
    [key: string]: {
      p75: number | null;
      good: number;
      needs_improvement: number;
      poor: number;
    };
  };
  summary?: {
    has_data?: boolean;
    insights?: string[];
  };
  source_device?: string;
}

interface AuditRunSummary {
  status: 'info' | 'success' | 'warning' | 'error';
  message: string;
  audited: number;
  withMetrics: number;
  withoutMetrics: number;
  errors: number;
}

const DEFAULT_PERFORMANCE_BUDGETS: PerformanceBudget[] = [
  { metric: 'lcp', threshold: 2500, enabled: true },
  { metric: 'inp', threshold: 200, enabled: true },
  { metric: 'cls', threshold: 0.1, enabled: true },
  { metric: 'fcp', threshold: 1800, enabled: false },
  { metric: 'ttfb', threshold: 800, enabled: false }
];

const VITAL_THRESHOLDS: { [key: string]: VitalThresholds } = {
  lcp: { good: 2500, poor: 4000 },
  inp: { good: 200, poor: 500 },
  cls: { good: 0.1, poor: 0.25 },
  fcp: { good: 1800, poor: 3000 },
  ttfb: { good: 800, poor: 1800 }
};

const CoreWebVitalsEnhanced: React.FC = () => {
  const [vitalsData, setVitalsData] = useState<CoreWebVitalsData | null>(null);
  const [historicalData, setHistoricalData] = useState<CoreWebVitalsData[]>([]);
  const [cruxData, setCruxData] = useState<CrUXData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [measuring, setMeasuring] = useState<boolean>(false);
  const [selectedMetric, setSelectedMetric] = useState<string>('lcp');
  const [selectedPeriod, setSelectedPeriod] = useState<number>(30);
  const [performanceBudgets, setPerformanceBudgets] = useState<PerformanceBudget[]>([]);
  const [budgetAlerts, setBudgetAlerts] = useState<string[]>([]);
  const [recommendations, setRecommendations] = useState<any[]>([]);
  const [multiPageData, setMultiPageData] = useState<any[]>([]);
  const [auditSummary, setAuditSummary] = useState<AuditRunSummary | null>(null);
  const [showExport, setShowExport] = useState<boolean>(false);
  const { showNotification } = useNotification();
  const chartRef = useRef<any>(null);

  const hasCurrentMetricData = (data?: Partial<CoreWebVitalsData> | null): boolean => {
    if (!data) {
      return false;
    }

    return ['lcp', 'inp', 'cls', 'fcp', 'ttfb'].some((metric) => {
      const value = (data as any)[metric];
      return value !== null && value !== undefined && !Number.isNaN(value);
    });
  };

  const getRecommendationText = (recommendation: any): string => {
    if (typeof recommendation === 'object' && recommendation !== null) {
      return recommendation.message || JSON.stringify(recommendation);
    }

    return String(recommendation || '');
  };

  const getPagePath = (url?: string): string => {
    if (!url) {
      return '—';
    }

    try {
      return new URL(url).pathname || '/';
    } catch (error) {
      return url;
    }
  };

  useEffect(() => {
    loadVitalsData();
  }, [selectedPeriod]);

  useEffect(() => {
    measureCurrentPageVitals();
  }, []);

  const loadVitalsData = async () => {
    try {
      setLoading(true);
      const [vitalsResponse, historyResponse, cruxResponse, budgetResponse] = await Promise.all([
        apiFetch({ path: '/prorank-seo/v1/core-web-vitals' }),
        apiFetch({ path: `/prorank-seo/v1/core-web-vitals/history?days=${selectedPeriod}` }),
        apiFetch({ path: '/prorank-seo/v1/core-web-vitals/crux' }),
        apiFetch({ path: '/prorank-seo/v1/core-web-vitals/budget' })
      ]);

      setVitalsData(vitalsResponse as any);
      setHistoricalData((historyResponse as any).data || []);
      setCruxData(cruxResponse as any);
      
      const budgetData = budgetResponse as any;
      setPerformanceBudgets(budgetData.budgets || DEFAULT_PERFORMANCE_BUDGETS);
      if (budgetData.alerts && budgetData.alerts.length > 0) {
        setBudgetAlerts(budgetData.alerts);
      } else {
        setBudgetAlerts([]);
      }
      
      // Load recommendations
      if ((vitalsResponse as any).recommendations) {
        setRecommendations((vitalsResponse as any).recommendations);
      } else {
        setRecommendations([]);
      }
    } catch (error) {
      console.error('Failed to load Core Web Vitals data:', error);
      showNotification(__('Failed to load Core Web Vitals data', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const savePerformanceBudgets = async (budgets: PerformanceBudget[]) => {
    setPerformanceBudgets(budgets);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/core-web-vitals/budget',
        method: 'POST',
        data: {
          budgets
        }
      }) as any;

      if (response.budgets) {
        setPerformanceBudgets(response.budgets);
      }
    } catch (error) {
      showNotification(__('Failed to save performance budgets', 'prorank-seo'), 'error');
    }
  };

  const measureCurrentPageVitals = () => {
    if (typeof window !== 'undefined') {
      const path = window.location.pathname || '';
      if (path.startsWith('/wp-admin') || path.startsWith('/wp-login.php') || path.startsWith('/wp-json')) {
        return;
      }
    }

    if (typeof window !== 'undefined' && 'PerformanceObserver' in window) {
      try {
        import(/* webpackMode: "eager" */ 'web-vitals').then(({ onLCP, onINP, onCLS, onFCP, onTTFB }) => {
          const vitals: Partial<CoreWebVitalsData> = {
            url: window.location.href,
            timestamp: new Date().toISOString(),
          };

          onLCP((metric) => {
            vitals.lcp = metric.value;
            updateVitalsDisplay(vitals);
            checkBudget('lcp', metric.value);
          });

          onINP((metric) => {
            vitals.inp = metric.value;
            updateVitalsDisplay(vitals);
            checkBudget('inp', metric.value);
          });

          onCLS((metric) => {
            vitals.cls = metric.value;
            updateVitalsDisplay(vitals);
            checkBudget('cls', metric.value);
          });

          onFCP((metric) => {
            vitals.fcp = metric.value;
            updateVitalsDisplay(vitals);
          });

          onTTFB((metric) => {
            vitals.ttfb = metric.value;
            updateVitalsDisplay(vitals);
          });
          
          // Save measurement to backend
          setTimeout(() => {
            if (hasCurrentMetricData(vitals)) {
              saveVitalsMeasurement(vitals);
            }
          }, 5000);
        }).catch(error => {
          console.warn('Web Vitals library not available:', error);
        });
      } catch (error) {
        console.error('Error measuring Core Web Vitals:', error);
      }
    }
  };

  const updateVitalsDisplay = (vitals: Partial<CoreWebVitalsData>) => {
    setVitalsData(prev => ({
      ...prev,
      ...vitals,
    } as CoreWebVitalsData));
  };

  const saveVitalsMeasurement = async (vitals: Partial<CoreWebVitalsData>) => {
    try {
      await apiFetch({
        path: '/prorank-seo/v1/core-web-vitals/save',
        method: 'POST',
        data: vitals
      });
    } catch (error) {
      console.error('Failed to save vitals measurement:', error);
    }
  };

  const checkBudget = (metric: string, value: number) => {
    const budget = performanceBudgets.find(b => b.metric === metric && b.enabled);
    if (budget && value > budget.threshold) {
      const alert = sprintf(
        __('%s exceeded budget: %s (threshold: %s)', 'prorank-seo'),
        metric.toUpperCase(),
        formatMetricValue(metric, value),
        formatMetricValue(metric, budget.threshold)
      );
      
      setBudgetAlerts(prev => (prev.includes(alert) ? prev : [...prev, alert]));
      showNotification(alert, 'warning');
    }
  };

  const runFullAudit = async () => {
    setMeasuring(true);
    setAuditSummary({
      status: 'info',
      message: __('Running Core Web Vitals audit across your homepage and published pages…', 'prorank-seo'),
      audited: 0,
      withMetrics: 0,
      withoutMetrics: 0,
      errors: 0,
    });
    showNotification(__('Starting comprehensive Core Web Vitals audit...', 'prorank-seo'), 'info');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/core-web-vitals/audit',
        method: 'POST',
        data: {
          url: window.location.origin,
          pages: 10,
        }
      });

      const result = response as any;
      const results = Array.isArray(result.results) ? result.results : [];
      const withMetrics = results.filter((page) => hasCurrentMetricData(page)).length;
      const errors = results.filter((page) => !!page?.error).length;
      const withoutMetrics = results.filter((page) => !page?.error && !hasCurrentMetricData(page)).length;
      const audited = Number(result.audited) || results.length;
      const status: AuditRunSummary['status'] =
        withMetrics > 0 ? 'success' : errors > 0 ? 'error' : 'warning';

      const message =
        withMetrics > 0
          ? sprintf(
              __('Audit completed. %1$d of %2$d pages returned usable Core Web Vitals metrics.', 'prorank-seo'),
              withMetrics,
              audited
            )
          : __(
              'Audit finished, but the scanned pages did not return usable Core Web Vitals metrics yet. Configure PageSpeed Insights or try again later.',
              'prorank-seo'
            );

      setAuditSummary({
        status,
        message,
        audited,
        withMetrics,
        withoutMetrics,
        errors,
      });

      showNotification(message, withMetrics > 0 ? 'success' : 'warning');

      setMultiPageData(results);
      await loadVitalsData();
    } catch (error: any) {
      setAuditSummary({
        status: 'error',
        message: error?.message || __('Core Web Vitals audit failed to complete. Check the diagnostics below and try again.', 'prorank-seo'),
        audited: 0,
        withMetrics: 0,
        withoutMetrics: 0,
        errors: 1,
      });
      showNotification(error?.message || __('Failed to run Core Web Vitals audit', 'prorank-seo'), 'error');
    } finally {
      setMeasuring(false);
    }
  };

  const exportData = (format: 'csv' | 'pdf' | 'json') => {
    const data = {
      current: vitalsData,
      history: historicalData,
      budgets: performanceBudgets,
      recommendations: recommendations,
      crux: cruxData
    };

    switch (format) {
      case 'json':
        downloadJSON(data);
        break;
      case 'csv':
        downloadCSV(historicalData);
        break;
      case 'pdf':
        generatePDFReport(data);
        break;
    }
    
    showNotification(sprintf(__('Data exported as %s', 'prorank-seo'), format.toUpperCase()), 'success');
  };

  const downloadJSON = (data: any) => {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `core-web-vitals-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
  };

  const downloadCSV = (data: CoreWebVitalsData[]) => {
    const headers = ['Timestamp', 'URL', 'LCP', 'INP', 'CLS', 'FCP', 'TTFB', 'Score'];
    const rows = data.map(row => [
      row.timestamp,
      row.url,
      row.lcp,
      row.inp,
      row.cls,
      row.fcp,
      row.ttfb,
      row.score || ''
    ]);
    
    const csv = [headers, ...rows].map(row => row.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `core-web-vitals-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
  };

  const generatePDFReport = async (data: any) => {
    // This would typically use a library like jsPDF
    // For now, we'll create a simple HTML report that can be printed to PDF
    const reportWindow = window.open('', '_blank');
    if (reportWindow) {
      reportWindow.document.write(`
        <html>
          <head>
            <title>Core Web Vitals Report</title>
            <style>
              body { font-family: Arial, sans-serif; padding: 20px; }
              h1 { color: #2563eb; }
              .metric { margin: 20px 0; padding: 15px; border: 1px solid #e5e7eb; }
              .good { color: #10b981; }
              .needs-improvement { color: #f59e0b; }
              .poor { color: #ef4444; }
            </style>
          </head>
          <body>
            <h1>Core Web Vitals Report</h1>
            <p>Generated: ${new Date().toLocaleString()}</p>
            <div class="metric">
              <h2>Current Metrics</h2>
              <p>LCP: ${data.current?.lcp || 'N/A'}</p>
              <p>INP: ${data.current?.inp || 'N/A'}</p>
              <p>CLS: ${data.current?.cls || 'N/A'}</p>
            </div>
            <div class="metric">
              <h2>Recommendations</h2>
              ${data.recommendations.map((r: any) => `<p>• ${r.message || r}</p>`).join('')}
            </div>
          </body>
        </html>
      `);
      reportWindow.document.close();
      reportWindow.print();
    }
  };

  const getRating = (metric: string, value: number): 'good' | 'needs-improvement' | 'poor' => {
    const thresholds = VITAL_THRESHOLDS[metric];
    if (!thresholds) return 'poor';
    
    if (value <= thresholds.good) return 'good';
    if (value <= thresholds.poor) return 'needs-improvement';
    return 'poor';
  };

  const formatMetricValue = (metric: string, value: number | null | undefined): string => {
    if (value === null || value === undefined || Number.isNaN(value)) {
      return '—';
    }
    if (metric === 'cls') {
      return value.toFixed(3);
    }
    if (metric === 'lcp' || metric === 'inp' || metric === 'fcp' || metric === 'ttfb') {
      if (value >= 1000) {
        return `${(value / 1000).toFixed(2)}s`;
      }
      return `${Math.round(value)}ms`;
    }
    return value.toString();
  };

  const getChartData = () => {
    const labels = historicalData.map(d => 
      new Date(d.timestamp).toLocaleDateString()
    );
    
    const datasets = [
      {
        label: selectedMetric.toUpperCase(),
        data: historicalData.map(d => (d as any)[selectedMetric] || 0),
        borderColor: '#2563eb',
        backgroundColor: 'rgba(37, 99, 235, 0.1)',
        tension: 0.4,
        fill: true
      }
    ];
    
    // Add threshold lines
    const threshold = VITAL_THRESHOLDS[selectedMetric];
    if (threshold) {
      datasets.push({
        label: __('Good Threshold', 'prorank-seo'),
        data: new Array(labels.length).fill(threshold.good),
        borderColor: '#10b981',
        borderDash: [5, 5],
        pointRadius: 0,
        fill: false
      } as any);
      
      datasets.push({
        label: __('Poor Threshold', 'prorank-seo'),
        data: new Array(labels.length).fill(threshold.poor),
        borderColor: '#ef4444',
        borderDash: [5, 5],
        pointRadius: 0,
        fill: false
      } as any);
    }
    
    return { labels, datasets };
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'top' as const,
      },
      title: {
        display: true,
        text: sprintf(__('%s Trend', 'prorank-seo'), selectedMetric.toUpperCase()),
      },
      tooltip: {
        callbacks: {
          label: (context: any) => {
            const value = context.parsed.y;
            return `${context.dataset.label}: ${formatMetricValue(selectedMetric, value)}`;
          }
        }
      }
    },
    scales: {
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: selectedMetric === 'cls' ? 'Score' : 'Time (ms)'
        }
      }
    }
  };

  const currentHasMetrics = hasCurrentMetricData(vitalsData);
  const multiPageMetricCount = multiPageData.filter((page) => hasCurrentMetricData(page)).length;
  const multiPageErrorCount = multiPageData.filter((page) => !!page?.error).length;
  const hasUsableCwvData =
    currentHasMetrics ||
    historicalData.length > 0 ||
    Boolean(cruxData?.available) ||
    multiPageMetricCount > 0;
  const visibleRecommendations = recommendations.filter((recommendation) => {
    const text = getRecommendationText(recommendation).toLowerCase();
    if (!hasUsableCwvData && text.includes('looking good')) {
      return false;
    }
    if (!hasUsableCwvData && text.includes('keep monitoring')) {
      return false;
    }
    return Boolean(text.trim());
  });

  if (loading) {
    return (
      <div className="prorank-loading-container">
        <ProrankSpinner size="large" />
        <p>{__('Loading Core Web Vitals...', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-page prorank-core-web-vitals-enhanced">
      {/* Performance Budget Alerts */}
      {budgetAlerts.length > 0 && (
        <ProrankNotice status="warning" isDismissible onDismiss={() => setBudgetAlerts([])}>
          <strong>{__('Performance Budget Alerts', 'prorank-seo')}</strong>
          <ul>
            {budgetAlerts.map((alert, index) => (
              <li key={index}>{alert}</li>
            ))}
          </ul>
        </ProrankNotice>
      )}

      {/* Main Dashboard Card */}
      <ProrankCard>
        <ProrankCardHeader>
          <div className="prorank-cwv-header">
            <div className="prorank-cwv-header-main">
              <h3>{__('Core Web Vitals Dashboard', 'prorank-seo')}</h3>
              <p className="prorank-text-secondary">
                {__('Live monitoring with INP and PageSpeed/CrUX data when available', 'prorank-seo')}
              </p>
            </div>
            <div className="prorank-cwv-actions">
              <div className="prorank-cwv-buttons">
                <ProrankButton
                  variant="secondary"
                  onClick={() => setShowExport(!showExport)}
                >
                  {__('Export', 'prorank-seo')}
                </ProrankButton>
                <ProrankButton
                  variant="primary"
                  onClick={runFullAudit}
                  disabled={measuring || !vitalsData?.diagnostics?.psi_configured}
                >
                  {measuring && <ProrankSpinner size="small" />}
                  {__('Run Audit', 'prorank-seo')}
                </ProrankButton>
              </div>
            </div>
          </div>
        </ProrankCardHeader>
        <ProrankCardBody>
          {/* Export Options */}
          {showExport && (
            <div className="prorank-export-options prorank-cwv-export-options prorank-mb-4">
              <Flex gap={2}>
                <ProrankButton size="small" onClick={() => exportData('json')}>
                  {__('Export JSON', 'prorank-seo')}
                </ProrankButton>
                <ProrankButton size="small" onClick={() => exportData('csv')}>
                  {__('Export CSV', 'prorank-seo')}
                </ProrankButton>
                <ProrankButton size="small" onClick={() => exportData('pdf')}>
                  {__('Generate PDF Report', 'prorank-seo')}
                </ProrankButton>
              </Flex>
            </div>
          )}

          {measuring && (
            <ProrankNotice status="info" isDismissible={false}>
              <strong>{__('Audit in progress', 'prorank-seo')}</strong>
              <p>
                {__('Checking your homepage and a sample of published URLs. Results will appear here when the run finishes.', 'prorank-seo')}
              </p>
            </ProrankNotice>
          )}

          {!measuring && auditSummary && (
            <ProrankNotice status={auditSummary.status} isDismissible={false}>
              <strong>{__('Latest audit run', 'prorank-seo')}</strong>
              <p>{auditSummary.message}</p>
              <p>
                {sprintf(
                  __('Pages audited: %1$d. With metrics: %2$d. No metrics yet: %3$d. Errors: %4$d.', 'prorank-seo'),
                  auditSummary.audited,
                  auditSummary.withMetrics,
                  auditSummary.withoutMetrics,
                  auditSummary.errors
                )}
              </p>
            </ProrankNotice>
          )}

          {/* Current Metrics Grid */}
          <div className="prorank-vitals-grid prorank-grid-auto">
            {/* LCP Card */}
            <div className="prorank-vital-card prorank-metric-card">
              <h4>{__('LCP', 'prorank-seo')}</h4>
              <p className="prorank-text-secondary prorank-text-sm">
                {__('Largest Contentful Paint', 'prorank-seo')}
              </p>
              <div className="prorank-metric-value">
                {vitalsData?.lcp !== null && vitalsData?.lcp !== undefined ? formatMetricValue('lcp', vitalsData.lcp) : '--'}
              </div>
              {vitalsData?.lcp !== null && vitalsData?.lcp !== undefined && (
                <span className={`prorank-badge prorank-badge-${getRating('lcp', vitalsData.lcp)}`}>
                  {getRating('lcp', vitalsData.lcp)}
                </span>
              )}
            </div>

            {/* INP Card */}
            <div className="prorank-vital-card prorank-metric-card prorank-metric-card-highlighted">
              <h4>
                {__('INP', 'prorank-seo')}
                <span className="prorank-badge prorank-badge-new">
                  {__('Current', 'prorank-seo')}
                </span>
              </h4>
              <p className="prorank-text-secondary prorank-text-sm">
                {__('Interaction to Next Paint', 'prorank-seo')}
              </p>
              <div className="prorank-metric-value">
                {vitalsData?.inp !== null && vitalsData?.inp !== undefined ? formatMetricValue('inp', vitalsData.inp) : '--'}
              </div>
              {vitalsData?.inp !== null && vitalsData?.inp !== undefined && (
                <span className={`prorank-badge prorank-badge-${getRating('inp', vitalsData.inp)}`}>
                  {getRating('inp', vitalsData.inp)}
                </span>
              )}
            </div>

            {/* CLS Card */}
            <div className="prorank-vital-card prorank-metric-card">
              <h4>{__('CLS', 'prorank-seo')}</h4>
              <p className="prorank-text-secondary prorank-text-sm">
                {__('Cumulative Layout Shift', 'prorank-seo')}
              </p>
              <div className="prorank-metric-value">
                {vitalsData?.cls !== null && vitalsData?.cls !== undefined ? formatMetricValue('cls', vitalsData.cls) : '--'}
              </div>
              {vitalsData?.cls !== null && vitalsData?.cls !== undefined && (
                <span className={`prorank-badge prorank-badge-${getRating('cls', vitalsData.cls)}`}>
                  {getRating('cls', vitalsData.cls)}
                </span>
              )}
            </div>

            {/* Performance Score */}
            {vitalsData?.score !== null && vitalsData?.score !== undefined && (
              <div className="prorank-vital-card prorank-metric-card">
                <h4>{__('Performance Score', 'prorank-seo')}</h4>
                <p className="prorank-text-secondary prorank-text-sm">
                  {__('Overall PageSpeed Score', 'prorank-seo')}
                </p>
                <div className="prorank-metric-value">
                  {vitalsData.score}
                </div>
                <ProrankProgressBar 
                  value={vitalsData.score} 
                  max={100}
                  variant={vitalsData.score >= 90 ? 'success' : vitalsData.score >= 50 ? 'warning' : 'error'}
                />
              </div>
            )}
          </div>

          {vitalsData?.diagnostics?.current_source && (
            <p className="prorank-text-secondary prorank-text-sm prorank-mt-2">
              {sprintf(__('Current source: %s', 'prorank-seo'), vitalsData.diagnostics.current_source)}
            </p>
          )}

          {vitalsData?.diagnostics?.messages && vitalsData.diagnostics.messages.length > 0 && (
            <ProrankNotice status="info" isDismissible={false}>
              <strong>{__('CWV Data Status', 'prorank-seo')}</strong>
              <ul>
                {vitalsData.diagnostics.messages.map((message, index) => (
                  <li key={index}>{message}</li>
                ))}
              </ul>
            </ProrankNotice>
          )}

          {!measuring && !hasUsableCwvData && (
            <ProrankNotice status="warning" isDismissible={false}>
              <strong>{__('No usable Core Web Vitals data yet', 'prorank-seo')}</strong>
              <p>
                {__('This page is functional, but the site does not currently have usable CWV metrics to show. Add a PageSpeed Insights API key to populate lab data sooner, or wait for history/CrUX data to build up.', 'prorank-seo')}
              </p>
            </ProrankNotice>
          )}

          {/* Historical Chart */}
          {historicalData.length > 0 && (
            <ProrankCard className="prorank-mt-4">
              <ProrankCardHeader>
                <Flex align="center" justify="space-between">
                  <h4>{__('Historical Trends', 'prorank-seo')}</h4>
                  <Flex gap={2}>
                    <select 
                      value={selectedMetric}
                      onChange={(e) => setSelectedMetric(e.target.value)}
                      className="prorank-select"
                    >
                      <option value="lcp">LCP</option>
                      <option value="inp">INP</option>
                      <option value="cls">CLS</option>
                      <option value="fcp">FCP</option>
                      <option value="ttfb">TTFB</option>
                    </select>
                    <select
                      value={selectedPeriod}
                      onChange={(e) => setSelectedPeriod(parseInt(e.target.value))}
                      className="prorank-select"
                    >
                      <option value={7}>{__('Last 7 days', 'prorank-seo')}</option>
                      <option value={30}>{__('Last 30 days', 'prorank-seo')}</option>
                      <option value={90}>{__('Last 90 days', 'prorank-seo')}</option>
                    </select>
                  </Flex>
                </Flex>
              </ProrankCardHeader>
              <ProrankCardBody>
                <div style={{ height: '300px' }}>
                  <Line ref={chartRef} data={getChartData()} options={chartOptions} />
                </div>
              </ProrankCardBody>
            </ProrankCard>
          )}

          {/* CrUX Field Data */}
          {cruxData?.available && (
            <ProrankCard className="prorank-mt-4">
              <ProrankCardHeader>
                <h4>{__('Chrome User Experience Report (Field Data)', 'prorank-seo')}</h4>
              </ProrankCardHeader>
              <ProrankCardBody>
                {cruxData.source_device && cruxData.source_device !== 'none' && (
                  <p className="prorank-text-secondary prorank-text-sm">
                    {sprintf(__('Source: %s', 'prorank-seo'), cruxData.source_device)}
                  </p>
                )}
                <div className="prorank-grid-3">
                  {Object.entries(cruxData.metrics || {}).map(([metric, data]) => (
                    <div key={metric} className="prorank-crux-metric">
                      <h5>{metric.toUpperCase()}</h5>
                      <div className="prorank-crux-bars">
                        <div className="prorank-crux-bar good" style={{ width: `${data.good * 100}%` }}>
                          {Math.round(data.good * 100)}%
                        </div>
                        <div className="prorank-crux-bar needs-improvement" style={{ width: `${data.needs_improvement * 100}%` }}>
                          {Math.round(data.needs_improvement * 100)}%
                        </div>
                        <div className="prorank-crux-bar poor" style={{ width: `${data.poor * 100}%` }}>
                          {Math.round(data.poor * 100)}%
                        </div>
                      </div>
                      <p className="prorank-text-sm prorank-text-secondary">
                        P75: {data.p75 !== null ? formatMetricValue(metric, data.p75) : '—'}
                      </p>
                    </div>
                  ))}
                </div>
                {cruxData.summary?.insights && cruxData.summary.insights.length > 0 && (
                  <ProrankNotice status="info" isDismissible={false}>
                    {cruxData.summary.insights[0]}
                  </ProrankNotice>
                )}
              </ProrankCardBody>
            </ProrankCard>
          )}

          {cruxData && !cruxData.available && (
            <ProrankCard className="prorank-mt-4">
              <ProrankCardHeader>
                <h4>{__('Chrome User Experience Report (Field Data)', 'prorank-seo')}</h4>
              </ProrankCardHeader>
              <ProrankCardBody>
                <ProrankNotice status="info" isDismissible={false}>
                  {(cruxData.summary?.insights && cruxData.summary.insights[0]) || __('No CrUX field data is available for this site yet.', 'prorank-seo')}
                </ProrankNotice>
              </ProrankCardBody>
            </ProrankCard>
          )}

          {/* Multi-Page Analysis */}
          {multiPageData.length > 0 && (
            <ProrankCard className="prorank-mt-4">
              <ProrankCardHeader>
                <h4>{__('Multi-Page Analysis', 'prorank-seo')}</h4>
              </ProrankCardHeader>
              <ProrankCardBody>
                {multiPageMetricCount === 0 && (
                  <ProrankNotice status="warning" isDismissible={false}>
                    <strong>{__('URLs were scanned, but no CWV metrics were returned', 'prorank-seo')}</strong>
                    <p>
                      {__('This usually means PageSpeed data is not available for these URLs yet, or the PageSpeed Insights API key is not configured.', 'prorank-seo')}
                    </p>
                  </ProrankNotice>
                )}
                {multiPageErrorCount > 0 && (
                  <ProrankNotice status="error" isDismissible={false}>
                    <strong>{__('Some scanned pages could not be measured', 'prorank-seo')}</strong>
                    <p>
                      {getRecommendationText(multiPageData.find((page) => page?.error)?.error || __('The audit returned one or more page-level measurement errors.', 'prorank-seo'))}
                    </p>
                  </ProrankNotice>
                )}
                <table className="prorank-table">
                  <thead>
                    <tr>
                      <th>{__('Page', 'prorank-seo')}</th>
                      <th>LCP</th>
                      <th>INP</th>
                      <th>CLS</th>
                      <th>{__('Score', 'prorank-seo')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {multiPageData.map((page, index) => (
                      <tr key={index}>
                        <td>{getPagePath(page.url)}</td>
                        <td className={page.lcp !== null && page.lcp !== undefined ? `prorank-badge-${getRating('lcp', page.lcp)}` : ''}>
                          {page.lcp !== null && page.lcp !== undefined ? formatMetricValue('lcp', page.lcp) : '--'}
                        </td>
                        <td className={page.inp !== null && page.inp !== undefined ? `prorank-badge-${getRating('inp', page.inp)}` : ''}>
                          {page.inp !== null && page.inp !== undefined ? formatMetricValue('inp', page.inp) : '--'}
                        </td>
                        <td className={page.cls !== null && page.cls !== undefined ? `prorank-badge-${getRating('cls', page.cls)}` : ''}>
                          {page.cls !== null && page.cls !== undefined ? formatMetricValue('cls', page.cls) : '--'}
                        </td>
                        <td>{page.score !== null && page.score !== undefined ? page.score : '--'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </ProrankCardBody>
            </ProrankCard>
          )}

          {/* Recommendations */}
          {visibleRecommendations.length > 0 && (
            <ProrankCard className="prorank-mt-4">
              <ProrankCardHeader>
                <h4>{__('Automated Recommendations', 'prorank-seo')}</h4>
              </ProrankCardHeader>
              <ProrankCardBody>
                {visibleRecommendations.map((rec, index) => (
                  <ProrankNotice 
                    key={index}
                    status={typeof rec === 'object' && rec.severity === 'high' ? 'error' : typeof rec === 'object' && rec.severity === 'medium' ? 'warning' : 'info'}
                    isDismissible={false}
                  >
                    {typeof rec === 'object' && rec.metric ? <strong>{rec.metric}</strong> : null}
                    {typeof rec === 'object' && rec.metric ? ': ' : ''}
                    {getRecommendationText(rec)}
                  </ProrankNotice>
                ))}
              </ProrankCardBody>
            </ProrankCard>
          )}

          {/* Performance Budgets */}
          <ProrankCard className="prorank-mt-4">
            <ProrankCardHeader>
              <h4>{__('Performance Budgets', 'prorank-seo')}</h4>
            </ProrankCardHeader>
            <ProrankCardBody>
              <div className="prorank-budgets-grid">
                {performanceBudgets.map((budget, index) => (
                  <div key={index} className="prorank-budget-item">
                    <Flex align="center" justify="space-between">
                      <FlexBlock>
                        <strong>{budget.metric.toUpperCase()}</strong>
                        <input
                          type="number"
                          value={budget.threshold}
                          onChange={(e) => {
                            const newBudgets = [...performanceBudgets];
                            newBudgets[index].threshold = e.target.value === '' ? 0 : parseFloat(e.target.value);
                            savePerformanceBudgets(newBudgets);
                          }}
                          className="prorank-input prorank-ml-2"
                          style={{ width: '100px' }}
                        />
                      </FlexBlock>
                      <ProrankToggleSlider
                        checked={budget.enabled}
                        onChange={(checked) => {
                          const newBudgets = [...performanceBudgets];
                          newBudgets[index].enabled = checked;
                          savePerformanceBudgets(newBudgets);
                        }}
                      />
                    </Flex>
                  </div>
                ))}
              </div>
            </ProrankCardBody>
          </ProrankCard>
        </ProrankCardBody>
      </ProrankCard>
    </div>
  );
};

export default CoreWebVitalsEnhanced;
