/**
 * Site Audit Dashboard Component
 *
 * Main dashboard for site audits with collapsible settings sections
 *
 * @package ProRank\SEO
 * @since   1.0.0
 */

import React, { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
  Card,
  CardBody,
  CardHeader,
  Button,
  Spinner,
  Notice,
  TabPanel,
  TextControl,
  SelectControl,
  __experimentalHeading as Heading,
  __experimentalText as Text,
  Flex,
  FlexItem,
  FlexBlock,
  Icon,
} from '@wordpress/components';
import ProrankProgressBar from '../../components/ProrankProgressBar';
import ProrankToggleSlider from '../../components/ProrankToggleSlider';
import { ProrankSelect } from '../../components/ProrankSelect';
import { ProrankInput } from '../../components/ProrankInput';
import ProrankButton from '../../components/ProrankButton';
import { check, warning, info, closeSmall, arrowRight, external } from '@wordpress/icons';
import { useNotification } from '../../contexts/NotificationContext';
import AdvancedAuditSettings from './components/AuditSettings';
import SettingsSection from './components/SettingsSection';
import SettingRow from './components/SettingRow';
import IssuesPage from './components/IssuesPage';
import ReportIssuesView from './components/ReportIssuesView';

const getDefaultSiteAuditSettings = () => ({
  max_urls: 500,
  max_depth: 5,
  check_types: {
    meta_tags: true,
    broken_links: true,
    image_optimization: true,
    page_speed: true,
    mobile_friendly: true,
    https_status: true,
    schema_validation: true,
    content_quality: true,
    accessibility: true,
    core_web_vitals: true,
    redirect_chains: true,
    canonical_tags: true,
    open_graph: true,
    twitter_cards: true,
    headings_structure: true,
    duplicate_content: true,
    thin_content: true,
    xml_sitemap: true,
    robots_txt: true,
    orphaned_pages: true,
    crawl_depth: true,
    internal_linking: true,
    external_links: true,
    ssl_certificate: true,
    mixed_content: true,
    security_headers: true,
    wordpress_health: true,
    plugin_conflicts: true,
    database_optimization: true,
  },
  schedule_enabled: false,
  schedule_frequency: 'weekly',
  schedule_time: '02:00',
  email_notifications: true,
  email_critical_only: true,
  notification_emails: '',
  enable_autofix: false,
  autofix_compression: true,
  autofix_caching: true,
  autofix_meta_descriptions: true,
  autofix_alt_texts: true,
});

const DEFAULT_AUDIT_TAB = 'dashboard';
const LEGACY_AUDIT_SUBTAB_ALIASES = {
  overview: 'dashboard',
  audit: 'dashboard',
  dashboard: 'dashboard',
  issues: 'issues',
  history: 'history',
  settings: 'settings',
};

const SiteAuditDashboard = () => {
  const [auditStatus, setAuditStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [startingAudit, setStartingAudit] = useState(false);
  const [auditMode, setAuditMode] = useState('local');
  const [auditProgress, setAuditProgress] = useState(0);
  const [expandedRows, setExpandedRows] = useState({});
  const [auditIssues, setAuditIssues] = useState([]);
  const [auditHistory, setAuditHistory] = useState([]);
  const [latestOverallAudit, setLatestOverallAudit] = useState(null);
  const [loadingIssues, setLoadingIssues] = useState(false);
  const [selectedSeverity, setSelectedSeverity] = useState('all');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [refreshInterval, setRefreshInterval] = useState(null);
  const getRequestedAuditTab = useCallback(() => {
    if (typeof window === 'undefined') {
      return DEFAULT_AUDIT_TAB;
    }

    const readTabFromValue = (value) => {
      if (!value) {
        return '';
      }

      const query = value.includes('?')
        ? value.split('?')[1]
        : value.replace(/^#\/?/, '');

      const params = new URLSearchParams(query);
      return params.get('audit_tab') || params.get('tab') || '';
    };

    const requestedTab =
      readTabFromValue(window.location.hash || '') ||
      new URLSearchParams(window.location.search).get('audit_tab') ||
      new URLSearchParams(window.location.search).get('tab') ||
      '';

    return LEGACY_AUDIT_SUBTAB_ALIASES[requestedTab] || DEFAULT_AUDIT_TAB;
  }, []);

  const [activeTab, setActiveTab] = useState(() => getRequestedAuditTab());
  const [selectedReport, setSelectedReport] = useState(null);
  const [reportDetails, setReportDetails] = useState(null);
  const [loadingReport, setLoadingReport] = useState(false);
  
  // Settings state
  const [settings, setSettings] = useState(getDefaultSiteAuditSettings);

  const [cloudSettings, setCloudSettings] = useState({});
  const [cloudSettingsLoaded, setCloudSettingsLoaded] = useState(false);
  const [cloudSettingsLoading, setCloudSettingsLoading] = useState(false);
  const [cloudSettingsError, setCloudSettingsError] = useState('');
  
  const { showNotification } = useNotification();

  const syncAuditTabHash = useCallback((tabName) => {
    if (typeof window === 'undefined') {
      return;
    }

    const currentHash = window.location.hash || '#';
    const query = currentHash.includes('?')
      ? currentHash.split('?')[1]
      : currentHash.replace(/^#\/?/, '');
    const params = new URLSearchParams(query);

    params.set('tab', 'audit');

    if (tabName && tabName !== DEFAULT_AUDIT_TAB) {
      params.set('audit_tab', tabName);
    } else {
      params.delete('audit_tab');
    }

    const nextHash = params.toString() ? `#?${params.toString()}` : '#';
    const url = new URL(window.location.href);
    url.searchParams.set('tab', 'audit');

    if (tabName && tabName !== DEFAULT_AUDIT_TAB) {
      url.searchParams.set('audit_tab', tabName);
    } else {
      url.searchParams.delete('audit_tab');
    }

    url.hash = nextHash === '#' ? '' : nextHash.replace(/^#/, '');

    const nextUrl = url.toString();
    if (window.location.href !== nextUrl) {
      window.history.replaceState(window.history.state, document.title, nextUrl);
    }
  }, []);

  const selectAuditTab = useCallback((tabName) => {
    setActiveTab(tabName);
    syncAuditTabHash(tabName);
  }, [syncAuditTabHash]);

  useEffect(() => {
    const handleHashChange = () => {
      const requestedTab = getRequestedAuditTab();
      if (requestedTab !== activeTab) {
        setActiveTab(requestedTab);
      }
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, [activeTab, getRequestedAuditTab]);

  const normalizeBoolean = useCallback((value, fallback = false) => {
    if (typeof value === 'boolean') return value;
    if (typeof value === 'number') return value !== 0;
    if (typeof value === 'string') {
      const normalized = value.trim().toLowerCase();
      if (['1', 'true', 'yes', 'on', 'enabled'].includes(normalized)) return true;
      if (['0', 'false', 'no', 'off', 'disabled'].includes(normalized)) return false;
    }
    return fallback;
  }, []);

  const normalizeAuditSettingsResponse = useCallback((response) => {
    const defaults = getDefaultSiteAuditSettings();
    const source = (response && typeof response.settings === 'object')
      ? response.settings
      : response;

    if (!source || typeof source !== 'object') {
      return defaults;
    }

    const rawChecks = (source.check_types && typeof source.check_types === 'object')
      ? source.check_types
      : (source.site_audit_check_types && typeof source.site_audit_check_types === 'object' ? source.site_audit_check_types : {});

    const check_types = { ...defaults.check_types };
    Object.keys(check_types).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(rawChecks, key)) {
        check_types[key] = normalizeBoolean(rawChecks[key], check_types[key]);
      }
    });

    const maxUrlsRaw = Number(source.max_urls ?? source.site_audit_max_urls ?? defaults.max_urls);
    const maxDepthRaw = Number(source.max_depth ?? source.site_audit_max_depth ?? defaults.max_depth);

    return {
      ...defaults,
      max_urls: Number.isFinite(maxUrlsRaw) ? Math.min(10000, Math.max(10, Math.round(maxUrlsRaw))) : defaults.max_urls,
      max_depth: Number.isFinite(maxDepthRaw) ? Math.min(10, Math.max(1, Math.round(maxDepthRaw))) : defaults.max_depth,
      check_types,
      schedule_enabled: normalizeBoolean(source.schedule_enabled ?? source.site_audit_schedule_enabled, defaults.schedule_enabled),
      schedule_frequency: String(source.schedule_frequency ?? source.site_audit_schedule_frequency ?? defaults.schedule_frequency),
      schedule_time: String(source.schedule_time ?? defaults.schedule_time),
      email_notifications: normalizeBoolean(source.email_notifications ?? source.site_audit_email_reports, defaults.email_notifications),
      email_critical_only: normalizeBoolean(source.email_critical_only, defaults.email_critical_only),
      notification_emails: String(source.notification_emails ?? source.site_audit_email_recipients ?? defaults.notification_emails),
      enable_autofix: normalizeBoolean(source.enable_autofix ?? source.site_audit_auto_fix_enabled, defaults.enable_autofix),
      autofix_compression: normalizeBoolean(source.autofix_compression, defaults.autofix_compression),
      autofix_caching: normalizeBoolean(source.autofix_caching, defaults.autofix_caching),
      autofix_meta_descriptions: normalizeBoolean(source.autofix_meta_descriptions, defaults.autofix_meta_descriptions),
      autofix_alt_texts: normalizeBoolean(source.autofix_alt_texts, defaults.autofix_alt_texts),
    };
  }, [normalizeBoolean]);

  const hasCloudAuditEntitlement = false;
  const canUseCloudAudit = false;
  const selectedAuditMode = 'local';
  const isCloudAuditSelected = selectedAuditMode === 'cloud';

  const normalizeHistoryPayload = useCallback((response) => {
    if (Array.isArray(response?.audits)) {
      return response.audits;
    }
    return Array.isArray(response) ? response : [];
  }, []);

  const withCacheBust = useCallback((path) => {
    const separator = path.includes('?') ? '&' : '?';
    return `${path}${separator}_=${Date.now()}`;
  }, []);

  const getAuditTimestamp = useCallback((audit) => {
    if (!audit || typeof audit !== 'object') {
      return 0;
    }

    const rawValue = audit.completed_at || audit.end_time || audit.created_at || audit.started_at || audit.start_time || audit.date || '';
    if (!rawValue) {
      return 0;
    }

    const normalized = String(rawValue).includes('T')
      ? String(rawValue)
      : String(rawValue).replace(' ', 'T');
    const parsed = new Date(normalized);

    return Number.isNaN(parsed.getTime()) ? 0 : parsed.getTime();
  }, []);

  const getCompletedAudit = useCallback((audits) => {
    if (!Array.isArray(audits)) {
      return null;
    }

    return audits.find((audit) => {
      const status = String(audit?.status || audit?.state || '').toLowerCase();
      return status === 'completed';
    }) || null;
  }, []);

  const loadLatestOverallAudit = useCallback(async () => {
    try {
      const [localHistoryResponse, cloudHistoryResponse] = await Promise.all([
        apiFetch({ path: withCacheBust('/prorank-seo/v1/audit/history?mode=local'), method: 'GET' }),
        canUseCloudAudit
          ? apiFetch({ path: withCacheBust('/prorank-seo/v1/audit/history?mode=cloud'), method: 'GET' })
          : Promise.resolve([]),
      ]);

      const allAudits = [
        ...normalizeHistoryPayload(localHistoryResponse).map((audit) => ({ ...audit, _prorank_source: 'local' })),
        ...normalizeHistoryPayload(cloudHistoryResponse).map((audit) => ({ ...audit, _prorank_source: 'cloud' })),
      ];

      const latest = allAudits
        .filter((audit) => String(audit?.status || audit?.state || '').toLowerCase() === 'completed')
        .sort((left, right) => getAuditTimestamp(right) - getAuditTimestamp(left))[0] || null;

      setLatestOverallAudit(latest);
      return latest;
    } catch (error) {
      console.error('Failed to load latest overall audit:', error);
      return null;
    }
  }, [canUseCloudAudit, getAuditTimestamp, normalizeHistoryPayload, withCacheBust]);

  const loadLocalSettings = useCallback(async () => {
    try {
      const response = await apiFetch({
        path: withCacheBust('/prorank-seo/v1/settings/site-audit'),
        method: 'GET',
      });
      setSettings(normalizeAuditSettingsResponse(response));
    } catch (error) {
      // Keep defaults when loading fails.
      console.warn('Failed to load site audit settings:', error);
    }
  }, [normalizeAuditSettingsResponse, withCacheBust]);

  // Tabs configuration
  const tabs = [
    {
      name: 'dashboard',
      title: __('Dashboard', 'prorank-seo'),
    },
    {
      name: 'issues',
      title: __('Issues', 'prorank-seo'),
      count: auditIssues.length,
    },
    {
      name: 'history',
      title: __('History', 'prorank-seo'),
    },
    {
      name: 'settings',
      title: __('Settings', 'prorank-seo'),
    },
  ];
  
  // Report details are shown inline within the History tab

  // Load initial data
  useEffect(() => {
    loadAuditStatus();
    loadAuditHistory();
    loadLatestOverallAudit();
  }, [auditMode, loadLatestOverallAudit]);

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

  useEffect(() => {
    if (!canUseCloudAudit && auditMode === 'cloud') {
      setAuditMode('local');
    }
  }, [canUseCloudAudit, auditMode]);

  // Auto-refresh when audit is running
  useEffect(() => {
    if (['crawling', 'checking', 'running', 'analyzing', 'pending', 'queued'].includes(auditStatus?.state)) {
      const interval = setInterval(() => {
        loadAuditStatus();
      }, 5000); // Check every 5 seconds
      setRefreshInterval(interval);
    } else if (refreshInterval) {
      clearInterval(refreshInterval);
      setRefreshInterval(null);
    }
    
    return () => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    };
  }, [auditStatus?.state]);


  const loadAuditStatus = async (modeOverride) => {
    const mode = modeOverride || auditMode;
    try {
      const response = await apiFetch({
        path: withCacheBust(`/prorank-seo/v1/audit/status?mode=${encodeURIComponent(mode)}`),
      });
      setAuditStatus(response);
      
      // Update progress
      if (response.progress) {
        const total = response.progress.total_urls || 1;
        const checked = response.progress.checked_urls || 0;
        setAuditProgress((checked / total) * 100);
      }
      
      // Load issues if completed
      if (response.state === 'completed' && response.audit_id) {
        loadAuditIssues(mode);
      }
    } catch (error) {
      console.error('Failed to load audit status:', error);
      setAuditStatus({ state: 'idle' });
    } finally {
      setLoading(false);
    }
  };

  const loadAuditIssues = async (modeOverride) => {
    const mode = modeOverride || auditMode;
    try {
      setLoadingIssues(true);
      const response = await apiFetch({
        path: withCacheBust(`/prorank-seo/v1/audit/issues?mode=${encodeURIComponent(mode)}`),
        method: 'GET',
      });
      setAuditIssues(response.issues || []);
    } catch (error) {
      console.error('Failed to load audit issues:', error);
    } finally {
      setLoadingIssues(false);
    }
  };

  const loadAuditHistory = useCallback(async (modeOverride) => {
    const mode = modeOverride || auditMode;
    try {
      const response = await apiFetch({
        path: withCacheBust(`/prorank-seo/v1/audit/history?mode=${encodeURIComponent(mode)}`),
        method: 'GET',
      });
      setAuditHistory(normalizeHistoryPayload(response));
    } catch (error) {
      console.error('Failed to load audit history:', error);
    }
  }, [auditMode, normalizeHistoryPayload, withCacheBust]);

  const startNewAudit = async () => {
    try {
      setStartingAudit(true);
      setAuditMode('local');
      await saveSettings(true);
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit/start',
        method: 'POST',
        data: {
          mode: 'local',
          settings,
        },
      });
      
      if (response.success) {
        showNotification(__('Audit started successfully', 'prorank-seo'), 'success');
        await loadAuditStatus('local');
      }
    } catch (error) {
      console.error('Failed to start audit:', error);
      const rawMessage = typeof error?.message === 'string' ? error.message.trim() : '';
      showNotification(rawMessage || __('Failed to start audit', 'prorank-seo'), 'error');
    } finally {
      setStartingAudit(false);
    }
  };

  const stopAudit = async () => {
    if (!confirm(__('Are you sure you want to stop the audit?', 'prorank-seo'))) {
      return;
    }
    
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/audit/stop?mode=${encodeURIComponent(auditMode)}`,
        method: 'POST',
      });
      
      if (response.success) {
        showNotification(__('Audit stopped', 'prorank-seo'), 'info');
        await loadAuditStatus();
      }
    } catch (error) {
      console.error('Failed to stop audit:', error);
    }
  };

  const saveSettings = async (silent = false) => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/site-audit',
        method: 'POST',
        data: settings,
      });
      
      if (response.success) {
        if (!silent) {
          showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
        }
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to save settings:', error);
      if (!silent) {
        showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
      }
      return false;
    }
  };

  const loadCloudSettings = useCallback(async () => {
    setCloudSettingsLoading(true);
    setCloudSettingsError('');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit-settings',
        method: 'GET',
      });
      const nextSettings = response?.settings || {};
      setCloudSettings(nextSettings);
      setCloudSettingsLoaded(true);
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('prorank_audit_settings_advanced', JSON.stringify(nextSettings));
      }
      return nextSettings;
    } catch (error) {
      let fallbackSettings = null;
      if (typeof localStorage !== 'undefined') {
        try {
          const cached = localStorage.getItem('prorank_audit_settings_advanced');
          if (cached) {
            fallbackSettings = JSON.parse(cached);
          }
        } catch (storageError) {
          // Ignore storage errors
        }
      }

      if (fallbackSettings && typeof fallbackSettings === 'object') {
        setCloudSettings(fallbackSettings);
        setCloudSettingsLoaded(true);
        return fallbackSettings;
      }

      setCloudSettingsError(error?.message || __('Failed to load audit settings.', 'prorank-seo'));
      return null;
    } finally {
      setCloudSettingsLoading(false);
    }
  }, []);

  const saveCloudSettings = useCallback(async (nextSettings = null, silent = false) => {
    const payload = nextSettings || cloudSettings || {};

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit-settings',
        method: 'POST',
        data: payload,
      });
      const savedSettings = response?.settings || payload;
      setCloudSettings(savedSettings);
      setCloudSettingsLoaded(true);
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('prorank_audit_settings_advanced', JSON.stringify(savedSettings));
      }
      if (!silent) {
        showNotification(__('Audit settings saved successfully', 'prorank-seo'), 'success');
      }
      return savedSettings;
    } catch (error) {
      if (!silent) {
        showNotification(__('Failed to save audit settings', 'prorank-seo'), 'error');
      }
      throw error;
    }
  }, [cloudSettings, showNotification]);

  const buildCloudPayload = useCallback(() => ({
    ...(cloudSettings || {}),
    max_pages: settings.max_urls,
    max_depth: settings.max_depth,
  }), [cloudSettings, settings.max_urls, settings.max_depth]);

  const handleSaveAllSettings = async () => {
    const localSaved = await saveSettings(true);
    let cloudSaved = true;

    if (canUseCloudAudit && cloudSettingsLoaded && !cloudSettingsLoading && !cloudSettingsError) {
      try {
        await saveCloudSettings(buildCloudPayload(), true);
      } catch (error) {
        cloudSaved = false;
      }
    }

    if (localSaved && cloudSaved) {
      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
    } else {
      showNotification(__('Some settings could not be saved. Please try again.', 'prorank-seo'), 'error');
    }
  };

  const ensureCloudSettings = useCallback(async () => {
    if (cloudSettingsLoaded) {
      return cloudSettings;
    }
    const loaded = await loadCloudSettings();
    return loaded || cloudSettings;
  }, [cloudSettings, cloudSettingsLoaded, loadCloudSettings]);

  useEffect(() => {
    if (!canUseCloudAudit) {
      return;
    }
    loadCloudSettings();
  }, [canUseCloudAudit, loadCloudSettings]);

  const applyQuickFix = async (fixId, fixType) => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit/quick-fix',
        method: 'POST',
        data: { fix_id: fixId, fix_type: fixType },
      });
      
      if (response.success) {
        showNotification(response.message || __('Fix applied successfully', 'prorank-seo'), 'success');
        await loadAuditStatus();
        await loadAuditIssues();
      }
    } catch (error) {
      console.error('Failed to apply quick fix:', error);
      showNotification(__('Failed to apply fix', 'prorank-seo'), 'error');
    }
  };

  const fixBrokenLink = async (issueId, action) => {
    if (action === 'update') {
      const newUrl = prompt(__('Enter the correct URL:', 'prorank-seo'));
      if (!newUrl) return;
      
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/audit/fix-broken-link',
          method: 'POST',
          data: { link_id: issueId, action, new_url: newUrl },
        });
        
        if (response.success) {
          showNotification(response.message, 'success');
          await loadAuditIssues();
        }
      } catch (error) {
        console.error('Failed to fix broken link:', error);
        showNotification(__('Failed to fix link', 'prorank-seo'), 'error');
      }
    } else if (action === 'remove') {
      if (!confirm(__('Are you sure you want to remove this link?', 'prorank-seo'))) return;
      
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/audit/fix-broken-link',
          method: 'POST',
          data: { link_id: issueId, action },
        });
        
        if (response.success) {
          showNotification(response.message, 'success');
          await loadAuditIssues();
        }
      } catch (error) {
        console.error('Failed to remove link:', error);
        showNotification(__('Failed to remove link', 'prorank-seo'), 'error');
      }
    }
  };

  const toggleRowExpansion = (issueId) => {
    setExpandedRows(prev => ({
      ...prev,
      [issueId]: !prev[issueId]
    }));
  };

  const viewReportDetails = useCallback(async (reportId) => {
    setLoadingReport(true);
    try {
      const response = await apiFetch({
        path: withCacheBust(`/prorank-seo/v1/audit/report/${reportId}`),
        method: 'GET',
      });
      setReportDetails(response);
      setSelectedReport(reportId);
    } catch (error) {
      console.error('Failed to load report details:', error);
      showNotification(__('Failed to load report details', 'prorank-seo'), 'error');
    } finally {
      setLoadingReport(false);
    }
  }, [showNotification]);

  const openHistoryTab = useCallback(() => {
    selectAuditTab('history');
  }, [selectAuditTab]);

  const openReportDetails = useCallback(async (reportId) => {
    selectAuditTab('history');
    await viewReportDetails(reportId);
  }, [selectAuditTab, viewReportDetails]);

  const downloadPDFReport = async (reportId) => {
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/audit/reports/${reportId}/download`,
        method: 'GET',
      });
      
      if (response.download_url) {
        window.open(response.download_url, '_blank');
      }
    } catch (error) {
      console.error('Failed to download report:', error);
      showNotification(__('Failed to download report', 'prorank-seo'), 'error');
    }
  };

  const getSeverityIcon = (severity) => {
    switch (severity) {
      case 'critical':
        return closeSmall;
      case 'high':
        return warning;
      default:
        return info;
    }
  };

  const getSeverityColor = (severity) => {
    const colors = {
      critical: '#dc2626',
      high: '#f59e0b',
      medium: '#3b82f6',
      low: '#10b981',
      info: '#6b7280',
    };
    return colors[severity] || colors.info;
  };

  const computeScoreFromStats = (stats) => {
    const critical = Number(stats?.critical_issues || 0);
    const high = Number(stats?.high_issues || 0);
    const medium = Number(stats?.medium_issues || 0);
    const low = Number(stats?.low_issues || 0);

    let score = 100;
    score -= Math.min(60, critical * 15);
    score -= Math.min(40, high * 8);
    score -= Math.min(25, medium * 4);
    score -= Math.min(15, low * 2);

    return Math.max(0, Math.min(100, score));
  };

  const getScannedUrlsCount = () => {
    const stats = auditStatus?.stats || {};
    const candidates = [
      stats?.total_urls,
      stats?.urls_checked,
      stats?.pages_scanned,
      auditStatus?.pages_scanned,
      auditStatus?.total_urls,
    ];

    for (const value of candidates) {
      const parsed = Number(value);
      if (Number.isFinite(parsed) && parsed >= 0) {
        return parsed;
      }
    }

    return 0;
  };

  // Calculate scores
  const calculateOverallScore = () => {
    const raw = auditStatus?.score ?? auditStatus?.overallScore ?? auditStatus?.overall_score;
    if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
    if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return Number(raw);

    const stats = auditStatus?.stats || {};
    const scannedUrls = getScannedUrlsCount();
    const hasIssueSignals = ['total_issues', 'critical_issues', 'high_issues', 'medium_issues', 'low_issues'].some((key) => {
      const value = Number(stats?.[key] ?? 0);
      return Number.isFinite(value) && value > 0;
    });

    // Avoid misleading "100/100" when no local scan data exists.
    if (scannedUrls <= 0 && !hasIssueSignals) {
      return 0;
    }

    return computeScoreFromStats(auditStatus?.stats);
  };

  const formatCategoryLabel = (key) => {
    const normalized = String(key || '').trim();
    if (!normalized) return __('Other', 'prorank-seo');

    const map = {
      on_page_seo: __('On-Page SEO', 'prorank-seo'),
      onpageseo: __('On-Page SEO', 'prorank-seo'),
      technical_seo: __('Technical SEO', 'prorank-seo'),
      technicalseo: __('Technical SEO', 'prorank-seo'),
      performance: __('Performance', 'prorank-seo'),
      security: __('Security', 'prorank-seo'),
      content: __('Content', 'prorank-seo'),
      content_quality: __('Content Quality', 'prorank-seo'),
      accessibility: __('Accessibility', 'prorank-seo'),
      wordpress: __('WordPress', 'prorank-seo'),
    };

    if (map[normalized]) return map[normalized];

    return normalized
      .replace(/[_-]+/g, ' ')
      .replace(/\b\w/g, (m) => m.toUpperCase());
  };

  const getIssueCategoryKey = (issue) => {
    return (
      issue?.display_category ||
      issue?.displayCategory ||
      issue?.category ||
      issue?.issue_category ||
      issue?.issueCategory ||
      'other'
    );
  };

  const getIssueTitle = (issue) => {
    return (
      issue?.title ||
      issue?.type ||
      issue?.issue_type ||
      issue?.message ||
      __('Issue', 'prorank-seo')
    );
  };

  const getIssueDescription = (issue) => {
    return (
      issue?.description ||
      issue?.message ||
      ''
    );
  };

  const getIssueUrls = (issue) => {
    if (Array.isArray(issue?.affected_urls) && issue.affected_urls.length) return issue.affected_urls;
    if (Array.isArray(issue?.urls) && issue.urls.length) return issue.urls;
    if (Array.isArray(issue?.pages) && issue.pages.length) {
      return issue.pages
        .map((page) => (typeof page === 'string' ? page : page?.url))
        .filter(Boolean);
    }
    if (typeof issue?.url === 'string' && issue.url) return [issue.url];
    return [];
  };

  const getIssueInstanceCount = (issue) => {
    const count = Number(issue?.count);
    if (Number.isFinite(count) && count > 0) return count;

    const urls = getIssueUrls(issue);
    if (Array.isArray(urls) && urls.length > 1) return urls.length;

    if (Array.isArray(issue?.pages) && issue.pages.length) return issue.pages.length;
    if (Array.isArray(issue?.affected_urls) && issue.affected_urls.length) return issue.affected_urls.length;
    if (Array.isArray(issue?.urls) && issue.urls.length) return issue.urls.length;

    return 1;
  };

  const toFiniteNumber = (value, fallback = null) => {
    const numeric = Number(value);
    return Number.isFinite(numeric) ? numeric : fallback;
  };

  const toCount = (value) => {
    if (Array.isArray(value)) return value.length;
    const numeric = Number(value);
    return Number.isFinite(numeric) ? numeric : 0;
  };

  const formatSigned = (value, suffix = '') => {
    const numeric = Number(value);
    if (!Number.isFinite(numeric)) return `0${suffix}`;
    if (numeric === 0) return `0${suffix}`;
    return `${numeric > 0 ? '+' : ''}${numeric}${suffix}`;
  };

  const normalizeComparisonData = (comparisonRaw, fallbackScore, fallbackIssueCount) => {
    if (!comparisonRaw || typeof comparisonRaw !== 'object') {
      return null;
    }

    const hasComparisonSignal = [
      'previous_score',
      'score_previous',
      'score_delta',
      'delta_score',
      'previous_total_issues',
      'previous_issues',
      'issues_delta',
      'delta_issues',
      'improved_checks',
      'regressed_checks',
      'new_issues',
      'fixed_issues',
      'previous_completed_at',
      'baseline_completed_at',
      'compared_completed_at',
    ].some((key) => comparisonRaw[key] !== undefined)
      || typeof comparisonRaw.previous === 'object'
      || typeof comparisonRaw.baseline === 'object'
      || typeof comparisonRaw.delta === 'object'
      || typeof comparisonRaw.score === 'object'
      || typeof comparisonRaw.issues === 'object';

    if (!hasComparisonSignal) {
      return null;
    }

    const currentScore = toFiniteNumber(
      comparisonRaw.current_score
      ?? comparisonRaw.score_current
      ?? comparisonRaw?.current?.score
      ?? comparisonRaw?.score?.current,
      toFiniteNumber(fallbackScore, null)
    );

    const previousScore = toFiniteNumber(
      comparisonRaw.previous_score
      ?? comparisonRaw.score_previous
      ?? comparisonRaw?.previous?.score
      ?? comparisonRaw?.score?.previous
    );

    const scoreDelta = toFiniteNumber(
      comparisonRaw.score_delta
      ?? comparisonRaw.delta_score
      ?? comparisonRaw?.delta?.score
      ?? comparisonRaw?.score?.delta,
      (currentScore !== null && previousScore !== null) ? (currentScore - previousScore) : null
    );

    const currentIssues = toFiniteNumber(
      comparisonRaw.current_total_issues
      ?? comparisonRaw.current_issues
      ?? comparisonRaw.issues_current
      ?? comparisonRaw?.current?.total_issues
      ?? comparisonRaw?.issues?.current,
      toFiniteNumber(fallbackIssueCount, null)
    );

    const previousIssues = toFiniteNumber(
      comparisonRaw.previous_total_issues
      ?? comparisonRaw.previous_issues
      ?? comparisonRaw.issues_previous
      ?? comparisonRaw?.previous?.total_issues
      ?? comparisonRaw?.issues?.previous
    );

    const issuesDelta = toFiniteNumber(
      comparisonRaw.issues_delta
      ?? comparisonRaw.delta_issues
      ?? comparisonRaw?.delta?.issues
      ?? comparisonRaw?.issues?.delta,
      (currentIssues !== null && previousIssues !== null) ? (currentIssues - previousIssues) : null
    );

    const improvedChecks = toCount(
      comparisonRaw.improved_checks
      ?? comparisonRaw.improvements
      ?? comparisonRaw.improved
      ?? comparisonRaw.checks_improved
    );

    const regressedChecks = toCount(
      comparisonRaw.regressed_checks
      ?? comparisonRaw.regressions
      ?? comparisonRaw.regressed
      ?? comparisonRaw.checks_regressed
    );

    const fixedIssues = toCount(
      comparisonRaw.fixed_issues
      ?? comparisonRaw.resolved_issues
      ?? comparisonRaw.issues_fixed
      ?? comparisonRaw.resolved
    );

    const newIssues = toCount(
      comparisonRaw.new_issues
      ?? comparisonRaw.added_issues
      ?? comparisonRaw.issues_new
      ?? comparisonRaw.added
    );

    const baselineDate = comparisonRaw.previous_completed_at
      ?? comparisonRaw.baseline_completed_at
      ?? comparisonRaw.compared_completed_at
      ?? comparisonRaw?.previous?.completed_at
      ?? comparisonRaw?.baseline?.completed_at
      ?? null;

    const comparedAuditId = comparisonRaw.previous_audit_id
      ?? comparisonRaw.baseline_audit_id
      ?? comparisonRaw.compared_audit_id
      ?? comparisonRaw?.previous?.audit_id
      ?? comparisonRaw?.baseline?.audit_id
      ?? null;

    return {
      currentScore,
      previousScore,
      scoreDelta,
      currentIssues,
      previousIssues,
      issuesDelta,
      improvedChecks,
      regressedChecks,
      fixedIssues,
      newIssues,
      baselineDate,
      comparedAuditId,
    };
  };

  const normalizeUrlSegments = (segmentsRaw) => {
    if (!segmentsRaw || typeof segmentsRaw !== 'object') {
      return [];
    }

    const rows = [];
    const flattenArray = (input, source = '') => {
      if (!Array.isArray(input)) return;
      input.forEach((entry, index) => {
        if (!entry || typeof entry !== 'object') return;
        const segmentKey = String(
          entry.segment
          ?? entry.pattern
          ?? entry.key
          ?? entry.path_prefix
          ?? entry.name
          ?? entry.label
          ?? `${source || 'segment'}-${index + 1}`
        );

        rows.push({
          key: `${source || 'segment'}:${segmentKey}:${index}`,
          label: String(entry.label ?? entry.segment_label ?? entry.pattern ?? entry.segment ?? segmentKey),
          type: String(entry.segment_type ?? entry.type ?? source ?? 'segment'),
          urlCount: toCount(
            entry.url_count
            ?? entry.urls
            ?? entry.total_urls
            ?? entry.pages
            ?? entry.page_count
            ?? entry.count
          ),
          issueCount: toCount(
            entry.issue_count
            ?? entry.issues
            ?? entry.total_issues
            ?? entry.problems
          ),
          avgScore: toFiniteNumber(
            entry.avg_score
            ?? entry.average_score
            ?? entry.score
            ?? entry.health_score
          ),
          tags: Array.isArray(entry.tags) ? entry.tags.map(String) : [],
        });
      });
    };

    if (Array.isArray(segmentsRaw)) {
      flattenArray(segmentsRaw, 'segment');
      return rows;
    }

    const knownArrays = [
      'primary_segments',
      'segments',
      'items',
      'groups',
      'tags',
      'tag_segments',
      'patterns',
    ];

    knownArrays.forEach((key) => {
      if (Array.isArray(segmentsRaw[key])) {
        flattenArray(segmentsRaw[key], key);
      }
    });

    if (rows.length === 0) {
      Object.entries(segmentsRaw).forEach(([key, value]) => {
        if (value && typeof value === 'object') {
          flattenArray([{ ...value, segment: value.segment ?? key }], key);
          return;
        }
        if (Number.isFinite(Number(value))) {
          rows.push({
            key: `map:${key}`,
            label: key,
            type: 'segment',
            urlCount: toCount(value),
            issueCount: 0,
            avgScore: null,
            tags: [],
          });
        }
      });
    }

    return rows
      .filter((row) => row.urlCount > 0 || row.issueCount > 0 || row.avgScore !== null)
      .sort((a, b) => b.urlCount - a.urlCount || b.issueCount - a.issueCount);
  };

  if (loading) {
    return (
      <div className="prorank-site-audit-dashboard">
        <Card>
          <CardBody>
            <Flex justify="center" align="center" style={{ minHeight: '200px' }}>
              <Spinner />
            </Flex>
          </CardBody>
        </Card>
      </div>
    );
  }

  return (
    <div className="prorank-site-audit-dashboard">
      <div className="prorank-audit-header">
        <Heading level={1}>{__('Site Audit', 'prorank-seo')}</Heading>
        <Text>
          {__('Basic audit runs locally on your site. No audit data is sent to ProRank.', 'prorank-seo')}
        </Text>
      </div>

      {/* Show progress if audit is running */}
      {['crawling', 'checking', 'running', 'analyzing', 'pending', 'queued'].includes(auditStatus?.state) && (
        <Card className="prorank-audit-progress-card" style={{ marginBottom: '16px' }}>
          <CardBody>
            <Flex align="center" gap={3} style={{ marginBottom: '12px' }}>
              <Spinner />
              <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                <Text weight="semibold" size="large" style={{ display: 'block' }}>
                  {['crawling', 'running'].includes(auditStatus.state)
                    ? __('Crawling Site', 'prorank-seo')
                    : ['pending', 'queued'].includes(auditStatus.state)
                      ? __('Starting Audit', 'prorank-seo')
                      : __('Analyzing Pages', 'prorank-seo')
                  }
                </Text>
                <Text variant="muted" size="small" style={{ display: 'block' }}>
                  {['crawling', 'running'].includes(auditStatus.state)
                    ? __('Discovering all pages on your site...', 'prorank-seo')
                    : ['pending', 'queued'].includes(auditStatus.state)
                      ? __('Preparing your audit...', 'prorank-seo')
                      : __('Checking pages for SEO issues...', 'prorank-seo')
                  }
                </Text>
              </div>
            </Flex>

            <ProrankProgressBar value={auditProgress} />

            {/* Detailed Progress Stats */}
            <div
              className="prorank-progress-metrics-grid"
              style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
              gap: '16px',
              marginTop: '16px',
              padding: '12px',
              background: '#f8fafc',
              borderRadius: '6px'
              }}
            >
              <div className="prorank-progress-metric" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 600, color: '#1e293b' }}>
                  {auditStatus?.progress?.checked_urls || 0}
                </div>
                <div style={{ fontSize: '12px', color: '#64748b' }}>
                  {__('Pages Checked', 'prorank-seo')}
                </div>
              </div>
              <div className="prorank-progress-metric" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 600, color: '#1e293b' }}>
                  {auditStatus?.progress?.total_urls || '—'}
                </div>
                <div style={{ fontSize: '12px', color: '#64748b' }}>
                  {__('Total Pages', 'prorank-seo')}
                </div>
              </div>
              <div className="prorank-progress-metric" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 600, color: '#1e293b' }}>
                  {auditStatus?.progress?.issues_found || 0}
                </div>
                <div style={{ fontSize: '12px', color: '#64748b' }}>
                  {__('Issues Found', 'prorank-seo')}
                </div>
              </div>
              <div className="prorank-progress-metric" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 600, color: '#1e293b' }}>
                  {auditStatus?.progress?.estimated_time_remaining || '—'}
                </div>
                <div style={{ fontSize: '12px', color: '#64748b' }}>
                  {__('Est. Time Left', 'prorank-seo')}
                </div>
              </div>
            </div>

            {/* Elapsed Time */}
            {auditStatus?.started_at && (
              <Text variant="muted" size="small" style={{ marginTop: '12px', display: 'block' }}>
                {sprintf(
                  __('Started: %s', 'prorank-seo'),
                  new Date(auditStatus.started_at).toLocaleTimeString()
                )}
              </Text>
            )}

            <Button
              variant="secondary"
              size="small"
              onClick={stopAudit}
              style={{ marginTop: '12px' }}
            >
              {__('Stop Audit', 'prorank-seo')}
            </Button>
          </CardBody>
        </Card>
      )}

      <TabPanel
        key={activeTab}
        className="prorank-audit-tabs"
        activeClass="is-active"
        tabs={tabs}
        initialTabName={activeTab}
        onSelect={(tabName) => selectAuditTab(tabName)}
      >
        {(tab) => {
          switch (tab.name) {
            case 'dashboard':
              {
              const stats = auditStatus?.stats || {};
              const issuesList = (Array.isArray(auditIssues) && auditIssues.length)
                ? auditIssues
                : (Array.isArray(auditStatus?.issues) ? auditStatus.issues : []);

              const overallScore = calculateOverallScore();
              const overallScoreClass =
                overallScore >= 90 ? 'score-excellent' :
                overallScore >= 75 ? 'score-good' :
                overallScore >= 60 ? 'score-needs-work' :
                'score-poor';

              const uniqueIssuesTotal = Number(stats?.total_issues ?? issuesList.length ?? 0);
              const totalUrls = Number(stats?.total_urls ?? 0);
              const totalChecks = Number(stats?.total_checks ?? 0);

              let passedChecks = Number(stats?.passed ?? 0);
              if (!Number.isFinite(passedChecks) || passedChecks < 0) {
                passedChecks = 0;
              }

              const issueInstancesTotal = issuesList.reduce(
                (sum, issue) => sum + getIssueInstanceCount(issue),
                0
              );
              const showInstanceCounts = issueInstancesTotal > uniqueIssuesTotal;

              // Use API-provided categories when available
              const apiCategories = auditStatus?.categories;
              let categoryRows;

              if (apiCategories && typeof apiCategories === 'object' && Object.keys(apiCategories).length > 0) {
                categoryRows = Object.entries(apiCategories)
                  .map(([key, cat]) => {
                    const totalChecks = Number(cat.total ?? 0);
                    const passed = Number(cat.passed ?? 0);
                    const issues = Math.max(0, totalChecks - passed);
                    return {
                      key,
                      label: cat.name || formatCategoryLabel(key),
                      score: Number(cat.score ?? 0),
                      unique: issues,
                      instances: issues,
                      passed,
                      totalChecks,
                      severities: {
                        critical: Number(cat.critical ?? 0),
                        high: Number(cat.high ?? 0),
                        medium: Number(cat.medium ?? 0),
                        low: Number(cat.low ?? 0),
                        warning: Number(cat.warning ?? cat.warnings ?? 0),
                      },
                      checks: cat.checks || [],
                    };
                  })
                  .sort((a, b) => a.score - b.score || b.unique - a.unique);

                // Recalculate passedChecks from API categories
                const apiPassedSum = categoryRows.reduce((s, c) => s + (c.passed || 0), 0);
                if (apiPassedSum > 0) {
                  passedChecks = apiPassedSum;
                }
              } else {
                // Fallback: compute from local issues list
                const categoryMap = new Map();
                for (const issue of issuesList) {
                  const key = getIssueCategoryKey(issue);
                  const bucket = categoryMap.get(key) || {
                    key,
                    label: formatCategoryLabel(key),
                    unique: 0,
                    instances: 0,
                    severities: { critical: 0, high: 0, medium: 0, low: 0, warning: 0 },
                  };
                  const severity = (issue?.severity && bucket.severities[issue.severity] !== undefined)
                    ? issue.severity
                    : 'low';
                  bucket.unique += 1;
                  bucket.instances += getIssueInstanceCount(issue);
                  bucket.severities[severity] = (bucket.severities[severity] || 0) + 1;
                  categoryMap.set(key, bucket);
                }
                categoryRows = Array.from(categoryMap.values())
                  .map((category) => ({
                    ...category,
                    score: computeScoreFromStats({
                      critical_issues: category.severities.critical,
                      high_issues: category.severities.high,
                      medium_issues: category.severities.medium,
                      low_issues: category.severities.low,
                    }),
                  }))
                  .sort((a, b) => a.score - b.score || b.unique - a.unique);
              }

              const formatDateTime = (value) => {
                if (!value) return '';
                const raw = String(value);
                const parsed = new Date(raw.includes('T') ? raw : raw.replace(' ', 'T'));
                return Number.isNaN(parsed.getTime()) ? raw : parsed.toLocaleString();
              };

              const renderSeveritySummary = (severities) => {
                const parts = [];
                if (severities.critical) parts.push(sprintf(__('Critical: %d', 'prorank-seo'), severities.critical));
                if (severities.high) parts.push(sprintf(__('High: %d', 'prorank-seo'), severities.high));
                if (severities.medium) parts.push(sprintf(__('Medium: %d', 'prorank-seo'), severities.medium));
                if (severities.low) parts.push(sprintf(__('Low: %d', 'prorank-seo'), severities.low));
                if (severities.warning) parts.push(sprintf(__('Warning: %d', 'prorank-seo'), severities.warning));
                return parts.join(' • ');
              };

              const comparisonData = normalizeComparisonData(
                auditStatus?.comparison || auditStatus?.comparison_data,
                overallScore,
                uniqueIssuesTotal
              );

              const segmentRows = normalizeUrlSegments(
                auditStatus?.url_segments || auditStatus?.urlSegments
              );

              const scoreUnavailable = totalUrls <= 0;
              const scoreColor = scoreUnavailable
                ? '#94a3b8'
                : overallScore >= 75
                  ? '#22c55e'
                  : overallScore >= 50
                    ? '#f59e0b'
                    : '#ef4444';
              const scoreLabel = scoreUnavailable
                ? __('Not Scanned', 'prorank-seo')
                : overallScore >= 90
                  ? __('Excellent', 'prorank-seo')
                  : overallScore >= 75
                    ? __('Good', 'prorank-seo')
                    : overallScore >= 50
                      ? __('Needs Work', 'prorank-seo')
                      : __('Poor', 'prorank-seo');
              const isAuditRunning = ['crawling', 'checking', 'running', 'analyzing', 'pending', 'queued'].includes(auditStatus?.state);
              const latestCompletedAudit = getCompletedAudit(auditHistory);
              const latestDisplayAudit = latestOverallAudit || latestCompletedAudit;
              const latestOverallSource = latestOverallAudit?._prorank_source || latestOverallAudit?.source || latestOverallAudit?.mode || null;
              const selectedModeLabel = __('Basic (Local)', 'prorank-seo');
              const latestOverallLabel = latestOverallSource === 'cloud'
                ? __('Earlier Audit', 'prorank-seo')
                : __('Basic (Local)', 'prorank-seo');
              const isViewingOlderMode = Boolean(
                latestOverallAudit
                && latestOverallSource
                && latestOverallSource !== selectedAuditMode
                && getAuditTimestamp(latestOverallAudit) > getAuditTimestamp(latestCompletedAudit)
              );

              const criticalCount = Number(stats?.critical_issues || 0);
              const highCount = Number(stats?.high_issues || 0);
              const warningCount = Number(stats?.warning_issues || stats?.medium_issues || 0) + Number(stats?.low_issues || 0);

              return (
                <div className="prorank-audit-dashboard-content">
                  {auditStatus?.state === 'completed' ? (
                    <div className="prorank-audit-results">
                      {isViewingOlderMode && (
                        <Notice status="warning" isDismissible={false} style={{ marginBottom: '16px' }}>
                          {sprintf(
                            __('You are viewing %1$s results. The latest completed audit is %2$s with score %3$d, scanned %4$s.', 'prorank-seo'),
                            selectedModeLabel,
                            latestOverallLabel,
                            Number(latestOverallAudit?.overall_score ?? latestOverallAudit?.score ?? latestOverallAudit?.overallScore ?? 0),
                            formatDateTime(latestOverallAudit?.completed_at || latestOverallAudit?.created_at || latestOverallAudit?.started_at || latestOverallAudit?.date)
                          )}
                        </Notice>
                      )}

                      {/* Hero: Score Ring + Summary Stats */}
                      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: '20px', alignItems: 'stretch', marginBottom: '24px' }}>
                        {/* Score Ring Card */}
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '32px 20px 24px', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '16px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
                          <div style={{ position: 'relative', width: '140px', height: '140px' }}>
                            <svg viewBox="0 0 120 120" style={{ width: '100%', height: '100%', display: 'block' }}>
                              <circle cx="60" cy="60" r="52" fill="none" stroke="#f1f5f9" strokeWidth="10" />
                              <circle
                                cx="60" cy="60" r="52" fill="none"
                                strokeWidth="10" strokeLinecap="round"
                                stroke={scoreColor}
                                strokeDasharray={`${(overallScore / 100) * 326.7} 326.7`}
                                transform="rotate(-90 60 60)"
                                style={{ transition: 'stroke-dasharray 0.8s ease' }}
                              />
                            </svg>
                            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                              <span style={{ fontSize: '40px', fontWeight: 800, letterSpacing: '-0.04em', color: '#0f172a', lineHeight: 1 }}>{overallScore}</span>
                              <span style={{ fontSize: '12px', fontWeight: 500, color: '#94a3b8', marginTop: '2px' }}>/100</span>
                            </div>
                          </div>
                          <div style={{ marginTop: '14px', fontSize: '15px', fontWeight: 700, color: scoreColor, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                            {scoreLabel}
                          </div>
                          {auditStatus.completed_at && (
                            <div style={{ marginTop: '6px', fontSize: '11px', color: '#94a3b8' }}>
                              {sprintf(__('Scanned %s', 'prorank-seo'), formatDateTime(auditStatus.completed_at))}
                            </div>
                          )}
                        </div>

                        {/* Summary Stats Grid */}
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gridTemplateRows: 'repeat(2, 1fr)', gap: '12px' }}>
                          {/* Pages Scanned */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '20px', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px' }}>
                            <div style={{ width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '12px', background: '#eff6ff', color: '#2563eb', flexShrink: 0 }}>
                              <svg width="22" height="22" viewBox="0 0 20 20" fill="none"><path d="M3 4a2 2 0 012-2h6l5 5v9a2 2 0 01-2 2H5a2 2 0 01-2-2V4z" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M11 2v5h5" stroke="currentColor" strokeWidth="1.5"/></svg>
                            </div>
                            <div>
                              <div style={{ fontSize: '28px', fontWeight: 800, color: '#0f172a', lineHeight: 1, letterSpacing: '-0.03em' }}>{totalUrls}</div>
                              <div style={{ fontSize: '12px', fontWeight: 500, color: '#64748b', marginTop: '4px', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{__('Pages Scanned', 'prorank-seo')}</div>
                            </div>
                          </div>
                          {/* Total Issues */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '20px', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px' }}>
                            <div style={{ width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '12px', background: '#fef3c7', color: '#d97706', flexShrink: 0 }}>
                              <svg width="22" height="22" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M10 6v5M10 13.5v.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                            </div>
                            <div>
                              <div style={{ fontSize: '28px', fontWeight: 800, color: '#0f172a', lineHeight: 1, letterSpacing: '-0.03em' }}>{uniqueIssuesTotal}</div>
                              <div style={{ fontSize: '12px', fontWeight: 500, color: '#64748b', marginTop: '4px', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{__('Total Issues', 'prorank-seo')}</div>
                            </div>
                          </div>
                          {/* Critical */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '20px', background: criticalCount > 0 ? '#fef2f2' : '#fff', border: `1px solid ${criticalCount > 0 ? '#fecaca' : '#e2e8f0'}`, borderRadius: '12px' }}>
                            <div style={{ width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '12px', background: '#fef2f2', color: '#dc2626', flexShrink: 0 }}>
                              <svg width="22" height="22" viewBox="0 0 20 20" fill="none"><path d="M10 2l8 14H2L10 2z" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinejoin="round"/><path d="M10 8v3M10 13.5v.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                            </div>
                            <div>
                              <div style={{ fontSize: '28px', fontWeight: 800, color: criticalCount > 0 ? '#dc2626' : '#0f172a', lineHeight: 1, letterSpacing: '-0.03em' }}>{criticalCount}</div>
                              <div style={{ fontSize: '12px', fontWeight: 500, color: '#64748b', marginTop: '4px', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{__('Critical', 'prorank-seo')}</div>
                            </div>
                          </div>
                          {/* Passed */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '20px', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px' }}>
                            <div style={{ width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '12px', background: '#f0fdf4', color: '#16a34a', flexShrink: 0 }}>
                              <svg width="22" height="22" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M6.5 10l2.5 2.5 5-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                            </div>
                            <div>
                              <div style={{ fontSize: '28px', fontWeight: 800, color: '#16a34a', lineHeight: 1, letterSpacing: '-0.03em' }}>{passedChecks}</div>
                              <div style={{ fontSize: '12px', fontWeight: 500, color: '#64748b', marginTop: '4px', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{__('Passed', 'prorank-seo')}</div>
                            </div>
                          </div>
                        </div>
                      </div>

                      {comparisonData && (
                        <Card className="prorank-audit-comparison-card" style={{ marginBottom: '16px' }}>
                          <CardHeader>
                            <Heading level={3}>{__('Since Last Audit', 'prorank-seo')}</Heading>
                          </CardHeader>
                          <CardBody>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: '12px' }}>
                              <div style={{ padding: '12px', border: '1px solid #e2e8f0', borderRadius: '8px', background: '#f8fbff' }}>
                                <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>{__('Score Delta', 'prorank-seo')}</div>
                                <div style={{ fontSize: '22px', fontWeight: 700, color: (comparisonData.scoreDelta ?? 0) > 0 ? '#059669' : (comparisonData.scoreDelta ?? 0) < 0 ? '#dc2626' : '#334155' }}>
                                  {formatSigned(comparisonData.scoreDelta, '%')}
                                </div>
                              </div>
                              <div style={{ padding: '12px', border: '1px solid #e2e8f0', borderRadius: '8px', background: '#f8fbff' }}>
                                <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>{__('Issue Delta', 'prorank-seo')}</div>
                                <div style={{ fontSize: '22px', fontWeight: 700, color: (comparisonData.issuesDelta ?? 0) < 0 ? '#059669' : (comparisonData.issuesDelta ?? 0) > 0 ? '#dc2626' : '#334155' }}>
                                  {formatSigned(comparisonData.issuesDelta)}
                                </div>
                              </div>
                              <div style={{ padding: '12px', border: '1px solid #e2e8f0', borderRadius: '8px', background: '#f8fbff' }}>
                                <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>{__('Fixed Issues', 'prorank-seo')}</div>
                                <div style={{ fontSize: '22px', fontWeight: 700, color: '#334155' }}>{comparisonData.fixedIssues}</div>
                              </div>
                              <div style={{ padding: '12px', border: '1px solid #e2e8f0', borderRadius: '8px', background: '#f8fbff' }}>
                                <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>{__('New Issues', 'prorank-seo')}</div>
                                <div style={{ fontSize: '22px', fontWeight: 700, color: '#334155' }}>{comparisonData.newIssues}</div>
                              </div>
                            </div>
                            {(comparisonData.baselineDate || comparisonData.comparedAuditId) && (
                              <Text variant="muted" size="small" style={{ display: 'block', marginTop: '10px' }}>
                                {comparisonData.baselineDate
                                  ? sprintf(__('Compared with audit from %s', 'prorank-seo'), formatDateTime(comparisonData.baselineDate))
                                  : sprintf(__('Compared with audit %s', 'prorank-seo'), comparisonData.comparedAuditId)
                                }
                              </Text>
                            )}
                          </CardBody>
                        </Card>
                      )}

                      {/* Category Breakdown */}
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '14px', marginBottom: '16px' }}>
                        {categoryRows.length > 0 ? categoryRows.map((category) => {
                          const catScoreColor = category.score >= 75 ? '#16a34a' : category.score >= 50 ? '#d97706' : '#dc2626';
                          return (
                            <div key={category.key} style={{ padding: '18px 20px 16px', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px', transition: 'box-shadow 0.15s', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
                              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '10px' }}>
                                <span style={{ fontSize: '14px', fontWeight: 600, color: '#1e293b' }}>{category.label}</span>
                                <span style={{ fontSize: '22px', fontWeight: 800, letterSpacing: '-0.03em', lineHeight: 1, color: catScoreColor }}>
                                  {category.score}%
                                </span>
                              </div>
                              <div style={{ height: '6px', background: '#f1f5f9', borderRadius: '3px', overflow: 'hidden', marginBottom: '10px' }}>
                                <div style={{ width: `${category.score}%`, height: '100%', borderRadius: '3px', background: catScoreColor, transition: 'width 0.6s ease' }} />
                              </div>
                              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                                {category.severities.critical > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#fef2f2', color: '#b91c1c' }}>
                                    {category.severities.critical} {__('critical', 'prorank-seo')}
                                  </span>
                                )}
                                {category.severities.high > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#fff7ed', color: '#c2410c' }}>
                                    {category.severities.high} {__('high', 'prorank-seo')}
                                  </span>
                                )}
                                {category.severities.medium > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#eff6ff', color: '#1d4ed8' }}>
                                    {category.severities.medium} {__('medium', 'prorank-seo')}
                                  </span>
                                )}
                                {category.severities.low > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#ecfdf5', color: '#047857' }}>
                                    {category.severities.low} {__('low', 'prorank-seo')}
                                  </span>
                                )}
                                {category.severities.warning > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#f8fafc', color: '#475569' }}>
                                    {category.severities.warning} {__('warning', 'prorank-seo')}
                                  </span>
                                )}
                                {(category.passed || 0) > 0 && (
                                  <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, background: '#f0fdf4', color: '#15803d' }}>
                                    {category.passed} {__('passed', 'prorank-seo')}
                                  </span>
                                )}
                              </div>
                            </div>
                          );
                        }) : (
                          <Notice status="success" isDismissible={false}>
                            <p>{__('No issues detected in this audit.', 'prorank-seo')}</p>
                          </Notice>
                        )}
                      </div>

                      {segmentRows.length > 0 && (
                        <Card className="prorank-audit-segments-card" style={{ marginTop: '16px' }}>
                          <CardHeader>
                            <Heading level={3}>{__('URL Segment Breakdown', 'prorank-seo')}</Heading>
                          </CardHeader>
                          <CardBody>
                            <div style={{ overflowX: 'auto' }}>
                              <table className="wp-list-table widefat striped">
                                <thead>
                                  <tr>
                                    <th>{__('Segment', 'prorank-seo')}</th>
                                    <th>{__('Type', 'prorank-seo')}</th>
                                    <th>{__('URLs', 'prorank-seo')}</th>
                                    <th>{__('Issues', 'prorank-seo')}</th>
                                    <th>{__('Avg. Score', 'prorank-seo')}</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {segmentRows.slice(0, 15).map((segment) => (
                                    <tr key={segment.key}>
                                      <td>
                                        <strong>{segment.label}</strong>
                                        {Array.isArray(segment.tags) && segment.tags.length > 0 && (
                                          <div style={{ color: '#64748b', fontSize: '12px', marginTop: '2px' }}>
                                            {segment.tags.join(', ')}
                                          </div>
                                        )}
                                      </td>
                                      <td>{segment.type}</td>
                                      <td>{segment.urlCount}</td>
                                      <td>{segment.issueCount}</td>
                                      <td>{segment.avgScore !== null ? `${Math.round(segment.avgScore)}%` : '—'}</td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </div>
                          </CardBody>
                        </Card>
                      )}

                      {/* Quick Fixes Panel */}
                      {auditStatus.quick_fixes && auditStatus.quick_fixes.length > 0 && (
                        <Card className="prorank-quick-fixes" style={{ marginTop: '16px' }}>
                          <CardHeader>
                            <Heading level={3}>{__('Quick Fixes Available', 'prorank-seo')}</Heading>
                          </CardHeader>
                          <CardBody>
                            <p>{__('One-click fixes for common issues:', 'prorank-seo')}</p>
                            {auditStatus.quick_fixes.map((fix, index) => (
                              <div key={fix.id || index} className="quick-fix-item">
                                <Icon icon={getSeverityIcon(fix.severity)} style={{ color: getSeverityColor(fix.severity) }} />
                                <div className="fix-content">
                                  <Text weight="semibold">{fix.title}</Text>
                                  <Text variant="muted" size="small">{fix.description}</Text>
                                  {fix.impact && (
                                    <Text size="small" style={{ color: '#059669' }}>{fix.impact}</Text>
                                  )}
                                </div>
                                <Button variant="secondary" size="small" onClick={() => applyQuickFix(fix.id, fix.type)}>
                                  {__('Fix Now', 'prorank-seo')}
                                </Button>
                              </div>
                            ))}
                          </CardBody>
                        </Card>
                      )}

                      <div className="prorank-audit-actions">
                        <Button variant="primary" onClick={() => startNewAudit()}>
                          {__('Run Basic Audit', 'prorank-seo')}
                        </Button>
                      </div>
                    </div>
                  ) : isAuditRunning ? (
                    latestDisplayAudit ? (
                      <Card className="prorank-empty-state">
                        <CardBody>
                          <div className="empty-state-content" style={{ maxWidth: '720px', margin: '0 auto' }}>
                            <div className="empty-icon">⏳</div>
                            <Heading level={3}>{__('Audit In Progress', 'prorank-seo')}</Heading>
                            <Text>
                              {__('Your audit is currently running. The previous completed audit is shown below while new results are still being collected.', 'prorank-seo')}
                            </Text>
                            <div style={{ marginTop: '20px', width: '100%', textAlign: 'left', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px', padding: '18px 20px' }}>
                              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '16px', marginBottom: '12px', flexWrap: 'wrap' }}>
                                <div>
                                  <div style={{ fontSize: '12px', fontWeight: 600, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                                    {__('Most Recent Completed Audit', 'prorank-seo')}
                                  </div>
                                  <div style={{ fontSize: '16px', fontWeight: 700, color: '#0f172a', marginTop: '4px' }}>
                                    {latestDisplayAudit.completed_at || latestDisplayAudit.created_at || latestDisplayAudit.started_at || latestDisplayAudit.date
                                      ? formatDateTime(latestDisplayAudit.completed_at || latestDisplayAudit.created_at || latestDisplayAudit.started_at || latestDisplayAudit.date)
                                      : '—'}
                                  </div>
                                </div>
                                <div style={{ fontSize: '28px', fontWeight: 800, color: Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0) >= 75 ? '#16a34a' : Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0) >= 50 ? '#d97706' : '#dc2626', lineHeight: 1 }}>
                                  {Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0)}%
                                </div>
                              </div>
                              <div className="prorank-audit-empty-actions" style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                                <Button variant="secondary" onClick={openHistoryTab}>
                                  {__('View Audit History', 'prorank-seo')}
                                </Button>
                                {latestDisplayAudit.id && (
                                  <Button variant="primary" onClick={() => openReportDetails(latestDisplayAudit.id)}>
                                    {__('View Last Report', 'prorank-seo')}
                                  </Button>
                                )}
                              </div>
                            </div>
                          </div>
                        </CardBody>
                      </Card>
                    ) : (
                      <Card className="prorank-empty-state">
                        <CardBody>
                          <div className="empty-state-content">
                            <div className="empty-icon">⏳</div>
                            <Heading level={3}>{__('Audit In Progress', 'prorank-seo')}</Heading>
                            <Text>
                              {__('Your audit is currently running. Live progress is shown above and the report will appear here when it completes.', 'prorank-seo')}
                            </Text>
                            <div className="prorank-audit-empty-actions" style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                              <Button
                                variant="secondary"
                                onClick={openHistoryTab}
                              >
                                {__('View Audit History', 'prorank-seo')}
                              </Button>
                            </div>
                          </div>
                        </CardBody>
                      </Card>
                    )
                  ) : latestDisplayAudit ? (
                    <Card className="prorank-empty-state">
                      <CardBody>
                        <div className="empty-state-content" style={{ maxWidth: '720px', margin: '0 auto' }}>
                          <div className="empty-icon">📊</div>
                          <Heading level={3}>{__('Viewing Older Mode Results', 'prorank-seo')}</Heading>
                          <Text>
                            {sprintf(
                              __('There is no recent %1$s audit here. The newest completed audit is %2$s and is summarized below.', 'prorank-seo'),
                              selectedModeLabel,
                              latestOverallLabel
                            )}
                          </Text>
                          <div style={{ marginTop: '20px', width: '100%', textAlign: 'left', background: '#fff', border: '1px solid #e2e8f0', borderRadius: '12px', padding: '18px 20px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '16px', marginBottom: '12px', flexWrap: 'wrap' }}>
                              <div>
                                <div style={{ fontSize: '12px', fontWeight: 600, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                                  {latestOverallLabel}
                                </div>
                                <div style={{ fontSize: '16px', fontWeight: 700, color: '#0f172a', marginTop: '4px' }}>
                                  {latestDisplayAudit.completed_at || latestDisplayAudit.created_at || latestDisplayAudit.started_at || latestDisplayAudit.date
                                    ? formatDateTime(latestDisplayAudit.completed_at || latestDisplayAudit.created_at || latestDisplayAudit.started_at || latestDisplayAudit.date)
                                    : '—'}
                                </div>
                              </div>
                              <div style={{ fontSize: '28px', fontWeight: 800, color: Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0) >= 75 ? '#16a34a' : Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0) >= 50 ? '#d97706' : '#dc2626', lineHeight: 1 }}>
                                {Number(latestDisplayAudit.overall_score ?? latestDisplayAudit.score ?? latestDisplayAudit.overallScore ?? 0)}%
                              </div>
                            </div>
                            <div className="prorank-audit-empty-actions" style={{ display: 'flex', gap: '8px', justifyContent: 'center', flexWrap: 'wrap' }}>
                              <Button
                                variant="primary"
                                onClick={() => startNewAudit()}
                                isBusy={startingAudit}
                                disabled={startingAudit}
                              >
                                {__('Run Basic Audit', 'prorank-seo')}
                              </Button>
                              <Button variant="secondary" onClick={openHistoryTab}>
                                {__('View Audit History', 'prorank-seo')}
                              </Button>
                              {latestDisplayAudit.id && (
                                <Button variant="primary" onClick={() => openReportDetails(latestDisplayAudit.id)}>
                                  {__('View Last Report', 'prorank-seo')}
                                </Button>
                              )}
                            </div>
                          </div>
                        </div>
                      </CardBody>
                    </Card>
                  ) : (
                    <Card className="prorank-empty-state">
                      <CardBody>
                        <div className="empty-state-content">
                          <div className="empty-icon">🔍</div>
                          <Heading level={3}>{__('No Recent Audit', 'prorank-seo')}</Heading>
                          <Text>{__('Start a comprehensive site audit to check for SEO issues.', 'prorank-seo')}</Text>
                          <div className="prorank-audit-empty-actions" style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                            <Button
                              variant="primary"
                              onClick={() => startNewAudit()}
                              isBusy={startingAudit}
                              disabled={startingAudit}
                            >
                              {__('Run Basic Audit (Local)', 'prorank-seo')}
                            </Button>
                          </div>
                        </div>
                      </CardBody>
                    </Card>
                  )}
                </div>
              );
              }

            case 'issues': {
              const issuesList = (Array.isArray(auditStatus?.issues) && auditStatus.issues.length)
                ? auditStatus.issues
                : (Array.isArray(auditIssues) ? auditIssues : []);

              return (
                <IssuesPage
                  issues={issuesList}
                  isLoading={loadingIssues}
                  auditStatus={auditStatus}
                />
              );
            }

            case 'history': {
              // If a report is selected, show report details inline
              if (selectedReport && reportDetails) {
                const reportScore = toFiniteNumber(
                  reportDetails?.overall_score ?? reportDetails?.score ?? reportDetails?.overallScore,
                  0
                );
                const reportPages = Number(reportDetails?.statistics?.total_urls ?? reportDetails?.statistics?.pages_crawled ?? reportDetails?.stats?.total_urls ?? 0);
                const reportTotalIssues = Number(reportDetails?.issue_counts?.total ?? reportDetails?.stats?.total_issues ?? 0);
                const reportCriticalIssues = Number(reportDetails?.issue_counts?.critical ?? reportDetails?.stats?.critical_issues ?? 0);
                const reportHighIssues = Number(reportDetails?.issue_counts?.high ?? 0);
                const reportDate = reportDetails?.completed_at || reportDetails?.created_at || reportDetails?.started_at;
                const reportComparison = normalizeComparisonData(
                  reportDetails?.comparison || reportDetails?.comparison_data,
                  reportScore,
                  reportTotalIssues
                );
                const reportSegments = normalizeUrlSegments(
                  reportDetails?.url_segments || reportDetails?.urlSegments
                );
                const fmtDateTime = (value) => {
                  if (!value) return '';
                  const raw = String(value);
                  const parsed = new Date(raw.includes('T') ? raw : raw.replace(' ', 'T'));
                  return Number.isNaN(parsed.getTime()) ? raw : parsed.toLocaleString();
                };
                const rScoreColor = reportScore >= 75 ? '#16a34a' : reportScore >= 50 ? '#d97706' : '#dc2626';
                const reportScoreBand = reportScore >= 75 ? 'healthy' : reportScore >= 50 ? 'watch' : 'risk';
                const reportScoreLabel = reportScore >= 75
                  ? __('Healthy', 'prorank-seo')
                  : reportScore >= 50
                    ? __('Needs Attention', 'prorank-seo')
                    : __('At Risk', 'prorank-seo');
                const reportIssueTypes = Array.isArray(reportDetails?.issues) ? reportDetails.issues.length : 0;

                return (
                  <div className="prorank-audit-report-shell">
                    <div className="prorank-audit-report-topbar">
                      <Button
                        variant="secondary"
                        className="prorank-audit-report-topbar__back"
                        onClick={() => { setSelectedReport(null); setReportDetails(null); }}
                      >
                        ← {__('Back to History', 'prorank-seo')}
                      </Button>
                      <div className="prorank-audit-report-topbar__meta">
                        <span className="prorank-audit-report-pill">
                          {__('Local Audit', 'prorank-seo')}
                        </span>
                        <span className="prorank-audit-report-pill">
                          {fmtDateTime(reportDate)}
                        </span>
                      </div>
                    </div>

                    {loadingReport ? (
                      <Card><CardBody><Spinner /></CardBody></Card>
                    ) : (
                      <>
                        <div className="prorank-audit-report-head" data-band={reportScoreBand}>
                          <div className="prorank-audit-report-head__copy">
                            <span className="prorank-audit-report-head__eyebrow">
                              {__('Audit Report', 'prorank-seo')}
                            </span>
                            <Heading level={2} className="prorank-audit-report-head__title" style={{ margin: 0 }}>
                              {fmtDateTime(reportDate)}
                            </Heading>
                            <Text className="prorank-audit-report-head__description">
                              {__('Review the overall score, issue pressure, category health, and grouped remediation paths in one pass.', 'prorank-seo')}
                            </Text>
                            <div className="prorank-audit-report-head__chips">
                              <span className="prorank-audit-report-head__chip">
                                {sprintf(__('%d pages scanned', 'prorank-seo'), reportPages)}
                              </span>
                              <span className="prorank-audit-report-head__chip">
                                {sprintf(__('%d issue types', 'prorank-seo'), reportIssueTypes)}
                              </span>
                              <span className="prorank-audit-report-head__chip">
                                {sprintf(__('%d total findings', 'prorank-seo'), reportTotalIssues)}
                              </span>
                            </div>
                          </div>
                          <div className="prorank-audit-report-score-card" data-band={reportScoreBand}>
                            <div className="prorank-audit-report-score-card__label">
                              {__('Overall Score', 'prorank-seo')}
                            </div>
                            <div className="prorank-audit-report-score-card__value" style={{ color: rScoreColor }}>
                              {Math.round(reportScore)}%
                            </div>
                            <div className="prorank-audit-report-score-card__tone">
                              {reportScoreLabel}
                            </div>
                          </div>
                        </div>

                        <div className="prorank-audit-report-stat-grid">
                          <div className="prorank-audit-report-stat" data-tone="pages">
                            <div className="prorank-audit-report-stat__label">{__('Pages Scanned', 'prorank-seo')}</div>
                            <div className="prorank-audit-report-stat__value">{reportPages}</div>
                            <div className="prorank-audit-report-stat__hint">
                              {__('Crawled URLs included in this report.', 'prorank-seo')}
                            </div>
                          </div>
                          <div className="prorank-audit-report-stat" data-tone="issues">
                            <div className="prorank-audit-report-stat__label">{__('Total Findings', 'prorank-seo')}</div>
                            <div className="prorank-audit-report-stat__value">{reportTotalIssues}</div>
                            <div className="prorank-audit-report-stat__hint">
                              {__('Issue instances recorded across the crawl.', 'prorank-seo')}
                            </div>
                          </div>
                          <div className="prorank-audit-report-stat" data-tone="critical">
                            <div className="prorank-audit-report-stat__label">{__('Critical', 'prorank-seo')}</div>
                            <div className="prorank-audit-report-stat__value" style={{ color: reportCriticalIssues > 0 ? '#dc2626' : '#0f172a' }}>
                              {reportCriticalIssues}
                            </div>
                            <div className="prorank-audit-report-stat__hint">
                              {reportCriticalIssues > 0
                                ? __('Immediate blockers that need fixing first.', 'prorank-seo')
                                : __('No critical blockers were detected.', 'prorank-seo')}
                            </div>
                          </div>
                          <div className="prorank-audit-report-stat" data-tone="high">
                            <div className="prorank-audit-report-stat__label">{__('High Priority', 'prorank-seo')}</div>
                            <div className="prorank-audit-report-stat__value" style={{ color: reportHighIssues > 0 ? '#ea580c' : '#0f172a' }}>
                              {reportHighIssues}
                            </div>
                            <div className="prorank-audit-report-stat__hint">
                              {__('Important fixes that should be scheduled next.', 'prorank-seo')}
                            </div>
                          </div>
                        </div>

                        {/* Comparison */}
                        {reportComparison && (
                          <Card className="prorank-audit-report-panel">
                            <CardHeader className="prorank-audit-report-panel__header">
                              <Heading level={3} style={{ margin: 0 }}>{__('Since Previous Audit', 'prorank-seo')}</Heading>
                              <Text className="prorank-audit-report-panel__header-copy">
                                {__('Trend indicators show whether this audit is moving in the right direction.', 'prorank-seo')}
                              </Text>
                            </CardHeader>
                            <CardBody className="prorank-audit-report-panel__body">
                              <div className="prorank-audit-report-kpi-grid">
                                <div className="prorank-audit-report-kpi" data-trend={(reportComparison.scoreDelta ?? 0) > 0 ? 'positive' : (reportComparison.scoreDelta ?? 0) < 0 ? 'negative' : 'neutral'}>
                                  <div className="prorank-audit-report-kpi__label">{__('Score Delta', 'prorank-seo')}</div>
                                  <div className="prorank-audit-report-kpi__value">
                                    {formatSigned(reportComparison.scoreDelta, '%')}
                                  </div>
                                </div>
                                <div className="prorank-audit-report-kpi" data-trend={(reportComparison.issuesDelta ?? 0) < 0 ? 'positive' : (reportComparison.issuesDelta ?? 0) > 0 ? 'negative' : 'neutral'}>
                                  <div className="prorank-audit-report-kpi__label">{__('Issue Delta', 'prorank-seo')}</div>
                                  <div className="prorank-audit-report-kpi__value">
                                    {formatSigned(reportComparison.issuesDelta)}
                                  </div>
                                </div>
                                <div className="prorank-audit-report-kpi" data-trend="positive">
                                  <div className="prorank-audit-report-kpi__label">{__('Fixed Issues', 'prorank-seo')}</div>
                                  <div className="prorank-audit-report-kpi__value">{reportComparison.fixedIssues}</div>
                                </div>
                                <div className="prorank-audit-report-kpi" data-trend={reportComparison.newIssues > 0 ? 'negative' : 'neutral'}>
                                  <div className="prorank-audit-report-kpi__label">{__('New Issues', 'prorank-seo')}</div>
                                  <div className="prorank-audit-report-kpi__value">{reportComparison.newIssues}</div>
                                </div>
                              </div>
                              {(reportComparison.baselineDate || reportComparison.comparedAuditId) && (
                                <Text variant="muted" size="small" style={{ display: 'block', marginTop: '10px' }}>
                                  {reportComparison.baselineDate
                                    ? sprintf(__('Compared with audit from %s', 'prorank-seo'), fmtDateTime(reportComparison.baselineDate))
                                    : sprintf(__('Compared with audit %s', 'prorank-seo'), reportComparison.comparedAuditId)
                                  }
                                </Text>
                              )}
                            </CardBody>
                          </Card>
                        )}

                        {/* Category Breakdown */}
                        {reportDetails.category_breakdown && Object.keys(reportDetails.category_breakdown).length > 0 && (
                          <Card className="prorank-audit-report-panel">
                            <CardHeader className="prorank-audit-report-panel__header">
                              <Heading level={3} style={{ margin: 0 }}>{__('Category Breakdown', 'prorank-seo')}</Heading>
                              <Text className="prorank-audit-report-panel__header-copy">
                                {__('Category scoring keeps the report anchored to the main remediation areas in ProRank.', 'prorank-seo')}
                              </Text>
                            </CardHeader>
                            <CardBody className="prorank-audit-report-panel__body">
                              <div className="prorank-audit-breakdown-grid">
                                {Object.entries(reportDetails.category_breakdown).map(([catKey, catData]) => {
                                  const catScore = Number(catData.score ?? 0);
                                  const catColor = catScore >= 75 ? '#16a34a' : catScore >= 50 ? '#d97706' : '#dc2626';
                                  const catLabel = catData.name || formatCategoryLabel(catKey);
                                  const catIssues = Number(catData.total_issues ?? 0);
                                  return (
                                    <div key={catKey} className="prorank-audit-breakdown-card">
                                      <div className="prorank-audit-breakdown-card__top">
                                        <span className="prorank-audit-breakdown-card__label">{catLabel}</span>
                                        <span className="prorank-audit-breakdown-card__score" style={{ color: catColor }}>{catScore}%</span>
                                      </div>
                                      <div className="prorank-audit-breakdown-card__bar">
                                        <div className="prorank-audit-breakdown-card__bar-fill" style={{ width: `${catScore}%`, background: catColor }} />
                                      </div>
                                      <div className="prorank-audit-breakdown-card__chips">
                                        {Number(catData.critical ?? 0) > 0 && (
                                          <span className="prorank-audit-breakdown-card__chip" style={{ background: '#fef2f2', color: '#b91c1c' }}>{catData.critical} critical</span>
                                        )}
                                        {Number(catData.warnings ?? 0) > 0 && (
                                          <span className="prorank-audit-breakdown-card__chip" style={{ background: '#fff7ed', color: '#c2410c' }}>{catData.warnings} warnings</span>
                                        )}
                                        {Number(catData.passed ?? 0) > 0 && (
                                          <span className="prorank-audit-breakdown-card__chip" style={{ background: '#f0fdf4', color: '#15803d' }}>{catData.passed} passed</span>
                                        )}
                                        {catIssues > 0 && (
                                          <span className="prorank-audit-breakdown-card__chip" style={{ background: '#f8fafc', color: '#475569' }}>{catIssues} total</span>
                                        )}
                                      </div>
                                      {Array.isArray(catData.checks) && catData.checks.length > 0 && (
                                        <div className="prorank-audit-breakdown-card__checks">
                                          {catData.checks.join(' · ')}
                                        </div>
                                      )}
                                    </div>
                                  );
                                })}
                              </div>
                            </CardBody>
                          </Card>
                        )}

                        {/* URL Segments */}
                        {reportSegments.length > 0 && (
                          <Card className="prorank-audit-report-panel">
                            <CardHeader className="prorank-audit-report-panel__header">
                              <Heading level={3} style={{ margin: 0 }}>{__('URL Segment Breakdown', 'prorank-seo')}</Heading>
                              <Text className="prorank-audit-report-panel__header-copy">
                                {__('Segment reporting helps show where issues cluster across the crawl.', 'prorank-seo')}
                              </Text>
                            </CardHeader>
                            <CardBody className="prorank-audit-report-panel__body">
                              <div className="prorank-audit-segment-table">
                                <table className="wp-list-table widefat striped">
                                  <thead>
                                    <tr>
                                      <th>{__('Segment', 'prorank-seo')}</th>
                                      <th>{__('Type', 'prorank-seo')}</th>
                                      <th>{__('URLs', 'prorank-seo')}</th>
                                      <th>{__('Issues', 'prorank-seo')}</th>
                                      <th>{__('Avg. Score', 'prorank-seo')}</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {reportSegments.slice(0, 20).map((segment) => (
                                      <tr key={segment.key}>
                                        <td><strong>{segment.label}</strong></td>
                                        <td>{segment.type}</td>
                                        <td>{segment.urlCount}</td>
                                        <td>{segment.issueCount}</td>
                                        <td>{segment.avgScore !== null ? `${Math.round(segment.avgScore)}%` : '—'}</td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </CardBody>
                          </Card>
                        )}

                        {/* All Issues — Grouped by Type */}
                        {Array.isArray(reportDetails.issues) && reportDetails.issues.length > 0 && (
                          <ReportIssuesView issues={reportDetails.issues} embedded />
                        )}

                      </>
                    )}
                  </div>
                );
              }

              // History table
              return (
                <div className="prorank-audit-history-content">
                  <Card className="prorank-audit-history-card">
                    <CardHeader className="prorank-audit-history-card__header">
                      <div className="prorank-audit-history-card__copy">
                        <Heading level={3}>{__('Audit History', 'prorank-seo')}</Heading>
                        <Text className="prorank-audit-history-card__subtitle">
                          {__('Completed scans with direct report access and enough context to compare what changed.', 'prorank-seo')}
                        </Text>
                      </div>
                      <div className="prorank-audit-history-card__meta">
                        <span className="prorank-audit-history-pill">
                          {sprintf(__('%d reports', 'prorank-seo'), auditHistory.length)}
                        </span>
                        <span className="prorank-audit-history-pill is-muted">
                          {__('Local mode', 'prorank-seo')}
                        </span>
                      </div>
                    </CardHeader>
                    <CardBody className="prorank-audit-history-card__body">
                      {auditHistory.length > 0 ? (
                        <div className="prorank-audit-history-table-wrap">
                          <table className="prorank-history-table wp-list-table widefat striped" style={{ tableLayout: 'auto' }}>
                            <thead>
                              <tr>
                                <th>{__('Date', 'prorank-seo')}</th>
                                <th>{__('Status', 'prorank-seo')}</th>
                                <th>{__('Score', 'prorank-seo')}</th>
                                <th>{__('Pages', 'prorank-seo')}</th>
                                <th>{__('Issues', 'prorank-seo')}</th>
                                <th>{__('Critical', 'prorank-seo')}</th>
                                <th>{__('Duration', 'prorank-seo')}</th>
                                <th>{__('Actions', 'prorank-seo')}</th>
                              </tr>
                            </thead>
                            <tbody>
                              {auditHistory.map((audit, index) => {
                                const auditDate = audit.completed_at || audit.created_at || audit.started_at || audit.date;
                                const auditScore = Number(audit.overall_score ?? audit.score ?? audit.overallScore ?? 0);
                                const auditPages = Number(audit.total_urls ?? audit.totalUrls ?? audit.stats?.total_urls ?? 0);
                                const auditIssues = Number(audit.issues?.total ?? audit.total_issues ?? audit.stats?.total_issues ?? 0);
                                const auditCritical = Number(audit.issues?.critical ?? audit.critical ?? audit.stats?.critical_issues ?? 0);
                                const auditDuration = Number(audit.duration ?? 0);
                                const auditStatus = audit.status || audit.state || 'unknown';
                                const isCompleted = auditStatus === 'completed';
                                const isFailed = auditStatus === 'failed' || auditStatus === 'error';
                                const scoreTone = auditScore >= 75 ? 'is-good' : auditScore >= 50 ? 'is-warn' : 'is-bad';
                                const statusClass = isCompleted ? 'is-completed' : isFailed ? 'is-failed' : 'is-running';

                                return (
                                  <tr key={audit.id || index}>
                                    <td className="prorank-history-table__date">
                                      {auditDate ? new Date(auditDate).toLocaleString() : '—'}
                                    </td>
                                    <td>
                                      <span className={`prorank-history-status ${statusClass}`}>
                                        {isCompleted ? __('Completed', 'prorank-seo') : isFailed ? __('Failed', 'prorank-seo') : auditStatus}
                                      </span>
                                    </td>
                                    <td>
                                      {isCompleted ? (
                                        <span className={`prorank-history-score ${scoreTone}`}>{auditScore}%</span>
                                      ) : <span className="prorank-history-empty">—</span>}
                                    </td>
                                    <td>{auditPages || <span className="prorank-history-empty">—</span>}</td>
                                    <td>{isCompleted ? auditIssues : <span className="prorank-history-empty">—</span>}</td>
                                    <td>{isCompleted ? auditCritical : <span className="prorank-history-empty">—</span>}</td>
                                    <td>{auditDuration ? `${auditDuration}s` : <span className="prorank-history-empty">—</span>}</td>
                                    <td>
                                      {isCompleted && (
                                        <Button
                                          variant="secondary"
                                          size="small"
                                          className="prorank-history-action"
                                          onClick={() => viewReportDetails(audit.id)}
                                        >
                                          {__('View Details', 'prorank-seo')}
                                        </Button>
                                      )}
                                    </td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>
                        </div>
                      ) : (
                        <Notice status="info" isDismissible={false}>
                          <p>{__('No audit history available yet.', 'prorank-seo')}</p>
                        </Notice>
                      )}
                    </CardBody>
                  </Card>
                </div>
              );
            }

            case 'settings':
              // Helper to count enabled checks in a category
              const countEnabled = (keys) => keys.filter(k => settings.check_types[k]).length;

              // Check type categories
              const seoEssentials = {
                meta_tags: __('Meta Tags & Titles', 'prorank-seo'),
                headings_structure: __('Heading Structure (H1-H6)', 'prorank-seo'),
                canonical_tags: __('Canonical Tags', 'prorank-seo'),
                open_graph: __('Open Graph Tags', 'prorank-seo'),
                twitter_cards: __('Twitter Cards', 'prorank-seo'),
                schema_validation: __('Schema Markup', 'prorank-seo'),
                xml_sitemap: __('XML Sitemap', 'prorank-seo'),
                robots_txt: __('Robots.txt', 'prorank-seo'),
              };

              const contentQuality = {
                content_quality: __('Content Quality Score', 'prorank-seo'),
                duplicate_content: __('Duplicate Content', 'prorank-seo'),
                thin_content: __('Thin Content Detection', 'prorank-seo'),
                broken_links: __('Broken Links', 'prorank-seo'),
                orphaned_pages: __('Orphaned Pages', 'prorank-seo'),
                internal_linking: __('Internal Linking', 'prorank-seo'),
                external_links: __('External Links', 'prorank-seo'),
              };

              const performanceTechnical = {
                page_speed: __('Page Speed', 'prorank-seo'),
                core_web_vitals: __('Core Web Vitals', 'prorank-seo'),
                mobile_friendly: __('Mobile Friendliness', 'prorank-seo'),
                image_optimization: __('Image Optimization', 'prorank-seo'),
                redirect_chains: __('Redirect Chains', 'prorank-seo'),
                crawl_depth: __('Crawl Depth Analysis', 'prorank-seo'),
                accessibility: __('Accessibility (WCAG)', 'prorank-seo'),
              };

              const securityWordPress = {
                https_status: __('HTTPS/SSL Status', 'prorank-seo'),
                ssl_certificate: __('SSL Certificate Validation', 'prorank-seo'),
                mixed_content: __('Mixed Content Detection', 'prorank-seo'),
                security_headers: __('Security Headers', 'prorank-seo'),
                wordpress_health: __('WordPress Health Check', 'prorank-seo'),
                plugin_conflicts: __('Plugin Conflict Detection', 'prorank-seo'),
                database_optimization: __('Database Optimization', 'prorank-seo'),
              };

              const toggleAllInCategory = (category, enabled) => {
                const updates = {};
                Object.keys(category).forEach(key => {
                  updates[key] = enabled;
                });
                setSettings({
                  ...settings,
                  check_types: { ...settings.check_types, ...updates }
                });
              };

              return (
                <div className="prorank-audit-settings-content">
                  {/* Crawl Configuration */}
                  <SettingsSection
                    title={__('Crawl Configuration', 'prorank-seo')}
                    defaultExpanded={true}
                  >
                    <SettingRow
                      label={__('Maximum URLs to Scan', 'prorank-seo')}
                      description={__('Limit the number of pages to scan during audit', 'prorank-seo')}
                    >
                      <TextControl
                        type="number"
                        min="10"
                        max="10000"
                        value={settings.max_urls}
                        onChange={(value) => setSettings({ ...settings, max_urls: parseInt(value) || 500 })}
                        __nextHasNoMarginBottom
                      />
                    </SettingRow>
                    <SettingRow
                      label={__('Maximum Crawl Depth', 'prorank-seo')}
                      description={__('How many levels deep to follow links', 'prorank-seo')}
                    >
                      <TextControl
                        type="number"
                        min="1"
                        max="10"
                        value={settings.max_depth}
                        onChange={(value) => setSettings({ ...settings, max_depth: parseInt(value) || 5 })}
                        __nextHasNoMarginBottom
                      />
                    </SettingRow>
                  </SettingsSection>

                  {/* SEO Essentials */}
                  <SettingsSection
                    title={__('SEO Essentials', 'prorank-seo')}
                    badge={sprintf(__('%d enabled', 'prorank-seo'), countEnabled(Object.keys(seoEssentials)))}
                    enabledCount={countEnabled(Object.keys(seoEssentials))}
                    totalCount={Object.keys(seoEssentials).length}
                    onToggleAll={(enabled) => toggleAllInCategory(seoEssentials, enabled)}
                  >
                    <div className="prorank-check-grid">
                      {Object.entries(seoEssentials).map(([key, label]) => (
                        <SettingRow key={key} label={label}>
                          <ProrankToggleSlider
                            checked={settings.check_types[key]}
                            onChange={(value) => setSettings({
                              ...settings,
                              check_types: { ...settings.check_types, [key]: value }
                            })}
                          />
                        </SettingRow>
                      ))}
                    </div>
                  </SettingsSection>

                  {/* Content Quality */}
                  <SettingsSection
                    title={__('Content Quality', 'prorank-seo')}
                    badge={sprintf(__('%d enabled', 'prorank-seo'), countEnabled(Object.keys(contentQuality)))}
                    enabledCount={countEnabled(Object.keys(contentQuality))}
                    totalCount={Object.keys(contentQuality).length}
                    onToggleAll={(enabled) => toggleAllInCategory(contentQuality, enabled)}
                  >
                    <div className="prorank-check-grid">
                      {Object.entries(contentQuality).map(([key, label]) => (
                        <SettingRow key={key} label={label}>
                          <ProrankToggleSlider
                            checked={settings.check_types[key]}
                            onChange={(value) => setSettings({
                              ...settings,
                              check_types: { ...settings.check_types, [key]: value }
                            })}
                          />
                        </SettingRow>
                      ))}
                    </div>
                  </SettingsSection>

                  {/* Performance & Technical */}
                  <SettingsSection
                    title={__('Performance & Technical', 'prorank-seo')}
                    badge={sprintf(__('%d enabled', 'prorank-seo'), countEnabled(Object.keys(performanceTechnical)))}
                    enabledCount={countEnabled(Object.keys(performanceTechnical))}
                    totalCount={Object.keys(performanceTechnical).length}
                    onToggleAll={(enabled) => toggleAllInCategory(performanceTechnical, enabled)}
                  >
                    <div className="prorank-check-grid">
                      {Object.entries(performanceTechnical).map(([key, label]) => (
                        <SettingRow key={key} label={label}>
                          <ProrankToggleSlider
                            checked={settings.check_types[key]}
                            onChange={(value) => setSettings({
                              ...settings,
                              check_types: { ...settings.check_types, [key]: value }
                            })}
                          />
                        </SettingRow>
                      ))}
                    </div>
                  </SettingsSection>

                  {/* Security & WordPress */}
                  <SettingsSection
                    title={__('Security & WordPress', 'prorank-seo')}
                    badge={sprintf(__('%d enabled', 'prorank-seo'), countEnabled(Object.keys(securityWordPress)))}
                    enabledCount={countEnabled(Object.keys(securityWordPress))}
                    totalCount={Object.keys(securityWordPress).length}
                    onToggleAll={(enabled) => toggleAllInCategory(securityWordPress, enabled)}
                  >
                    <div className="prorank-check-grid">
                      {Object.entries(securityWordPress).map(([key, label]) => (
                        <SettingRow key={key} label={label}>
                          <ProrankToggleSlider
                            checked={settings.check_types[key]}
                            onChange={(value) => setSettings({
                              ...settings,
                              check_types: { ...settings.check_types, [key]: value }
                            })}
                          />
                        </SettingRow>
                      ))}
                    </div>
                  </SettingsSection>

                  {/* Schedule & Notifications */}
                  <SettingsSection
                    title={__('Schedule & Notifications', 'prorank-seo')}
                    defaultExpanded={false}
                  >
                    <SettingRow
                      label={__('Enable Scheduled Audits', 'prorank-seo')}
                      description={__('Run audits automatically on a schedule', 'prorank-seo')}
                    >
                      <ProrankToggleSlider
                        checked={settings.schedule_enabled}
                        onChange={(value) => setSettings({ ...settings, schedule_enabled: value })}
                      />
                    </SettingRow>

                    {settings.schedule_enabled && (
                      <>
                        <SettingRow
                          label={__('Audit Frequency', 'prorank-seo')}
                          description={__('How often to run scheduled audits', 'prorank-seo')}
                        >
                          <SelectControl
                            value={settings.schedule_frequency}
                            options={[
                              { label: __('Daily', 'prorank-seo'), value: 'daily' },
                              { label: __('Weekly', 'prorank-seo'), value: 'weekly' },
                              { label: __('Bi-weekly', 'prorank-seo'), value: 'biweekly' },
                              { label: __('Monthly', 'prorank-seo'), value: 'monthly' },
                            ]}
                            onChange={(value) => setSettings({ ...settings, schedule_frequency: value })}
                            __next40pxDefaultSize
                            __nextHasNoMarginBottom
                          />
                        </SettingRow>
                        <SettingRow
                          label={__('Preferred Time', 'prorank-seo')}
                          description={__('Schedule audits during low-traffic periods', 'prorank-seo')}
                        >
                          <TextControl
                            type="time"
                            value={settings.schedule_time}
                            onChange={(value) => setSettings({ ...settings, schedule_time: value })}
                            __nextHasNoMarginBottom
                          />
                        </SettingRow>
                      </>
                    )}

                    <SettingRow
                      label={__('Email Notifications', 'prorank-seo')}
                      description={__('Send email when audit completes', 'prorank-seo')}
                    >
                      <ProrankToggleSlider
                        checked={settings.email_notifications}
                        onChange={(value) => setSettings({ ...settings, email_notifications: value })}
                      />
                    </SettingRow>

                    {settings.email_notifications && (
                      <>
                        <SettingRow
                          label={__('Critical Issues Only', 'prorank-seo')}
                          description={__('Only notify for critical issues', 'prorank-seo')}
                        >
                          <ProrankToggleSlider
                            checked={settings.email_critical_only}
                            onChange={(value) => setSettings({ ...settings, email_critical_only: value })}
                          />
                        </SettingRow>
                        <SettingRow
                          label={__('Notification Recipients', 'prorank-seo')}
                          description={__('Comma-separated list of email addresses', 'prorank-seo')}
                        >
                          <TextControl
                            placeholder="email@example.com"
                            value={settings.notification_emails}
                            onChange={(value) => setSettings({ ...settings, notification_emails: value })}
                            __nextHasNoMarginBottom
                          />
                        </SettingRow>
                      </>
                    )}
                  </SettingsSection>

                  {/* Auto-Fix Settings */}
                  <SettingsSection
                    title={__('Auto-Fix Settings', 'prorank-seo')}
                    defaultExpanded={false}
                  >
                    <SettingRow
                      label={__('Enable Auto-Fix', 'prorank-seo')}
                      description={__('Automatically fix issues that are safe to resolve without manual review', 'prorank-seo')}
                    >
                      <ProrankToggleSlider
                        checked={settings.enable_autofix}
                        onChange={(value) => setSettings({ ...settings, enable_autofix: value })}
                      />
                    </SettingRow>

                    {settings.enable_autofix && (
                      <div className="prorank-check-grid">
                        <SettingRow label={__('Fix compression issues', 'prorank-seo')}>
                          <ProrankToggleSlider
                            checked={settings.autofix_compression}
                            onChange={(value) => setSettings({ ...settings, autofix_compression: value })}
                          />
                        </SettingRow>
                        <SettingRow label={__('Fix caching headers', 'prorank-seo')}>
                          <ProrankToggleSlider
                            checked={settings.autofix_caching}
                            onChange={(value) => setSettings({ ...settings, autofix_caching: value })}
                          />
                        </SettingRow>
                        <SettingRow label={__('Generate meta descriptions', 'prorank-seo')}>
                          <ProrankToggleSlider
                            checked={settings.autofix_meta_descriptions}
                            onChange={(value) => setSettings({ ...settings, autofix_meta_descriptions: value })}
                          />
                        </SettingRow>
                        <SettingRow label={__('Generate image alt texts', 'prorank-seo')}>
                          <ProrankToggleSlider
                            checked={settings.autofix_alt_texts}
                            onChange={(value) => setSettings({ ...settings, autofix_alt_texts: value })}
                          />
                        </SettingRow>
                      </div>
                    )}
                  </SettingsSection>

                  {/* Advanced Crawl Settings */}
                  {canUseCloudAudit && isCloudAuditSelected ? (
                    <SettingsSection
                      title={__('Advanced Crawl Settings', 'prorank-seo')}
                      premiumBadge={true}
                      defaultExpanded={false}
                    >
                      {cloudSettingsLoading ? (
                        <Flex justify="center" align="center" style={{ minHeight: '100px' }}>
                          <Spinner />
                        </Flex>
                      ) : cloudSettingsError ? (
                        <Notice status="error" isDismissible={false}>
                          {cloudSettingsError}
                        </Notice>
                      ) : (
                        <>
                          <Notice status="info" isDismissible={false}>
                            {__('Audits use the Crawl Configuration limits set above (Maximum URLs to Scan and Maximum Crawl Depth).', 'prorank-seo')}
                          </Notice>
                          <AdvancedAuditSettings
                            settings={cloudSettings}
                            onSave={saveCloudSettings}
                            onSettingsChange={setCloudSettings}
                            showSaveButton={false}
                          />
                        </>
                      )}
                    </SettingsSection>
                  ) : null}

                  {/* Save Button */}
                  <div className="prorank-settings-actions" style={{ marginTop: '20px' }}>
                    <ProrankButton variant="primary" onClick={handleSaveAllSettings}>
                      {__('Save Settings', 'prorank-seo')}
                    </ProrankButton>
                  </div>
                </div>
              );

            default:
              return null;
          }
        }}
      </TabPanel>
    </div>
  );
};

export default SiteAuditDashboard;
