/**
 * Site Audit Dashboard Component - Simplified Version
 *
 * Simplified dashboard without chart dependencies
 *
 * @package
 * @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,
  Modal,
  CheckboxControl,
  __experimentalHeading as Heading,
  __experimentalText as Text,
  Flex,
  FlexItem,
  FlexBlock,
  Icon,
} from '@wordpress/components';
import ProrankProgressBar from '../../components/ProrankProgressBar';
import { Toggle } from '../../components/ui';
import { check, warning, info, closeSmall, arrowRight, external } from '@wordpress/icons';
import { useNotification } from '../../contexts/NotificationContext';
import ProrankHeader from '../../components/ProrankHeader';
import headerBadges from '../../utils/headerBadges';

const DEFAULT_AUDIT_TAB = 'dashboard';

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 [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') || '';
    };

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

    return 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 - free version defaults
  const [settings, setSettings] = useState({
    max_urls: 50,  // Free version: 1-100 pages (default 50)
    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: '',
  });
  
  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()}` : '#';
    if (window.location.hash !== nextHash) {
      window.location.hash = nextHash;
    }
  }, []);

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

  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 statusState = auditStatus?.state || 'idle';
  const statusTone = statusState === 'completed'
    ? 'done'
    : (statusState === 'checking' || statusState === 'crawling')
      ? 'running'
      : (statusState === 'failed' ? 'error' : 'idle');

  const statusLabelMap = {
    idle: __('Idle', 'prorank-seo'),
    crawling: __('Discovering URLs', 'prorank-seo'),
    checking: __('Running', 'prorank-seo'),
    completed: __('Completed', 'prorank-seo'),
    failed: __('Failed', 'prorank-seo'),
  };

  const statusLabel = statusLabelMap[statusState] || __('Idle', 'prorank-seo');

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

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

  // 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'),
    },
  ];
  
  // Add report details tab if viewing a report
  if (selectedReport) {
    tabs.push({
      name: 'report-details',
      title: __('Report Details', 'prorank-seo'),
    });
  }

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

  // Load saved settings from API
  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit-settings',
        method: 'GET',
      });
      if (response.success && response.settings) {
        setSettings(prev => ({
          ...prev,
          ...response.settings,
        }));
      }
    } catch (error) {
      console.error('Failed to load audit settings:', error);
    }
  };

  // Auto-refresh when audit is running
  useEffect(() => {
    if (auditStatus?.state === 'crawling' || auditStatus?.state === 'checking') {
      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: `/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: `/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 = async (modeOverride) => {
    const mode = modeOverride || auditMode;
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/audit/history?mode=${encodeURIComponent(mode)}`,
        method: 'GET',
      });
      setAuditHistory(response?.audits || response || []);
    } catch (error) {
      console.error('Failed to load audit history:', error);
    }
  };

  const startNewAudit = async () => {
    try {
      setStartingAudit(true);
      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);
      showNotification(error?.message || __('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/audit-settings',
        method: 'POST',
        data: settings,
      });
      
      if (response.success) {
        if (!silent) {
          showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
        }
      }
    } catch (error) {
      console.error('Failed to save settings:', error);
      if (!silent) {
        showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
      }
    }
  };

  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 = async (reportId) => {
    setLoadingReport(true);
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/audit/report/${reportId}`,
        method: 'GET',
      });
      setReportDetails(response);
      setSelectedReport(reportId);
      selectAuditTab('report-details');
    } catch (error) {
      console.error('Failed to load report details:', error);
      showNotification(__('Failed to load report details', 'prorank-seo'), 'error');
    } finally {
      setLoadingReport(false);
    }
  };

  const downloadPDFReport = async (reportId) => {
    try {
      const ajaxUrl = window?.prorankSeo?.ajaxUrl || window?.ajaxurl || '';
      const nonce = window?.prorankSeo?.nonce || (window?.wpApiSettings?.nonce || '');
      if (!ajaxUrl) {
        throw new Error('Missing admin-ajax URL');
      }
      const url = `${ajaxUrl}?action=prorank_audit_report&report_id=${encodeURIComponent(reportId)}${nonce ? `&_wpnonce=${encodeURIComponent(nonce)}` : ''}`;
      window.open(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));
  };

  // 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);
    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;
  };

  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">
      <ProrankHeader
        title={__('Site Audit', 'prorank-seo')}
        subtitle={__('Analyze your site for SEO issues and get actionable recommendations.', 'prorank-seo')}
        badges={headerBadges['site-audit']}
      />

      <div className={`prorank-audit-status-line status-${statusTone}`}>
        <div className="prorank-audit-status-left">
          <span className="prorank-audit-status-label">{__('Status', 'prorank-seo')}:</span>
          <span className="prorank-audit-status-value">{statusLabel}</span>
          {(statusState === 'checking' || statusState === 'crawling') && (
            <span className="prorank-audit-status-progress">
              {sprintf(__('Progress: %d%%', 'prorank-seo'), Math.round(auditProgress))}
            </span>
          )}
        </div>
        <div className="prorank-audit-status-right">
          <span className="prorank-audit-status-label">{__('Last scan', 'prorank-seo')}:</span>
          <span>{auditStatus?.completed_at ? formatDateTime(auditStatus.completed_at) : __('—', 'prorank-seo')}</span>
        </div>
      </div>

      {/* Premium Audit Banner */}

      {/* Show progress if audit is running */}
      {(auditStatus?.state === 'crawling' || auditStatus?.state === 'checking') && (
        <Notice status="info" isDismissible={false}>
          <strong>{__('Audit in Progress', 'prorank-seo')}</strong>
          <p>
            {auditStatus.state === 'crawling'
              ? __('Crawling your site to discover all pages...', 'prorank-seo')
              : __('Analyzing pages for SEO issues...', 'prorank-seo')
            }
          </p>
          <ProrankProgressBar value={auditProgress} />
          <Button
            variant="secondary"
            size="small"
            onClick={stopAudit}
            style={{ marginTop: '10px' }}
          >
            {__('Stop Audit', 'prorank-seo')}
          </Button>
        </Notice>
      )}

      <TabPanel
        className="prorank-audit-tabs"
        activeClass="is-active"
        tabs={tabs}
        initialTabName="dashboard"
        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(totalChecks) &&
                totalChecks > 0 &&
                (!Number.isFinite(passedChecks) || passedChecks <= 0)
              ) {
                passedChecks = Math.max(0, totalChecks - uniqueIssuesTotal);
              }
              if (!Number.isFinite(passedChecks)) {
                passedChecks = 0;
              }

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

              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 },
                };

                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);
              }

              const 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 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));
                return parts.join(' • ');
              };

              return (
                <div className="prorank-audit-dashboard-content">
                  {auditStatus?.state === 'completed' ? (
                    <div className="prorank-audit-results">
                      {/* Overall Score Card */}
                      <Card className="prorank-overall-score-card">
                        <CardHeader>
                          <Heading level={3}>{__('Overall Site Health', 'prorank-seo')}</Heading>
                        </CardHeader>
                        <CardBody>
                          <div className="prorank-score-display">
                            <div className={`score-circle ${overallScoreClass}`}>
                              <div className="score-value">{overallScore}</div>
                              <div className="score-label">%</div>
                            </div>
                            <div className="score-details">
                              <p>{__('Your site health score is based on:', 'prorank-seo')}</p>
                              <ul>
                                <li>{sprintf(__('%d issues found', 'prorank-seo'), uniqueIssuesTotal)}</li>
                                {showInstanceCounts && (
                                  <li>
                                    {sprintf(
                                      __('%d issue instances across pages', 'prorank-seo'),
                                      issueInstancesTotal
                                    )}
                                  </li>
                                )}
                                <li>{sprintf(__('%d pages scanned', 'prorank-seo'), totalUrls)}</li>
                                <li>{sprintf(__('%d critical issues', 'prorank-seo'), Number(stats?.critical_issues || 0))}</li>
                                {totalChecks > 0 && (
                                  <li>{sprintf(__('%d passed checks', 'prorank-seo'), passedChecks)}</li>
                                )}
                              </ul>
                              {auditStatus.completed_at && (
                                <p className="last-scan">
                                  {sprintf(__('Last scan: %s', 'prorank-seo'), formatDateTime(auditStatus.completed_at))}
                                </p>
                              )}
                            </div>
                          </div>
                        </CardBody>
                      </Card>

                      {/* Quick Stats */}
                      <div
                        style={{
                          display: 'grid',
                          gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
                          gap: '12px',
                          marginBottom: '16px',
                        }}
                      >
                        <Card>
                          <CardBody>
                            <Flex align="center" gap={2}>
                              <Icon icon={closeSmall} size={20} />
                              <div>
                                <div style={{ fontSize: '20px', fontWeight: 600 }}>
                                  {Number(stats?.critical_issues || 0)}
                                </div>
                                <div style={{ color: '#555' }}>{__('Critical', 'prorank-seo')}</div>
                              </div>
                            </Flex>
                          </CardBody>
                        </Card>
                        <Card>
                          <CardBody>
                            <Flex align="center" gap={2}>
                              <Icon icon={warning} size={20} />
                              <div>
                                <div style={{ fontSize: '20px', fontWeight: 600 }}>
                                  {Number(stats?.high_issues || 0)}
                                </div>
                                <div style={{ color: '#555' }}>{__('High', 'prorank-seo')}</div>
                              </div>
                            </Flex>
                          </CardBody>
                        </Card>
                        <Card>
                          <CardBody>
                            <Flex align="center" gap={2}>
                              <Icon icon={info} size={20} />
                              <div>
                                <div style={{ fontSize: '20px', fontWeight: 600 }}>
                                  {Number(stats?.medium_issues || 0)}
                                </div>
                                <div style={{ color: '#555' }}>{__('Medium', 'prorank-seo')}</div>
                              </div>
                            </Flex>
                          </CardBody>
                        </Card>
                        <Card>
                          <CardBody>
                            <Flex align="center" gap={2}>
                              <Icon icon={check} size={20} />
                              <div>
                                <div style={{ fontSize: '20px', fontWeight: 600 }}>
                                  {passedChecks}
                                </div>
                                <div style={{ color: '#555' }}>{__('Passed Checks', 'prorank-seo')}</div>
                              </div>
                            </Flex>
                          </CardBody>
                        </Card>
                      </div>

                      {/* Category Results */}
                      <Card className="prorank-category-results">
                        <CardHeader>
                          <Heading level={3}>{__('Category Breakdown', 'prorank-seo')}</Heading>
                        </CardHeader>
                        <CardBody>
                          {categoryRows.length ? (
                            <div className="category-breakdown">
                              {categoryRows.map((category) => (
                                <div key={category.key} className="category-item">
                                  <Flex justify="space-between" align="center">
                                    <Text weight="semibold">{category.label}</Text>
                                    <Text>
                                      {sprintf(__('%d%%', 'prorank-seo'), category.score)} •{' '}
                                      {sprintf(__('%d issues', 'prorank-seo'), category.unique)}
                                      {showInstanceCounts && category.instances !== category.unique
                                        ? sprintf(__(' (%d instances)', 'prorank-seo'), category.instances)
                                        : ''}
                                    </Text>
                                  </Flex>
                                  <ProrankProgressBar value={category.score} />
                                  <Text variant="muted" size="small">
                                    {renderSeveritySummary(category.severities)}
                                  </Text>
                                </div>
                              ))}
                            </div>
                          ) : (
                            <Notice status="success" isDismissible={false}>
                              <p>{__('No issues detected in this audit.', 'prorank-seo')}</p>
                            </Notice>
                          )}
                        </CardBody>
                      </Card>

                      {/* Quick Fixes Panel */}
                      {auditStatus.quick_fixes && auditStatus.quick_fixes.length > 0 && (
                        <Card className="prorank-quick-fixes">
                          <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>
                      )}

                      <Button
                        variant="primary"
                        type="button"
                        onClick={() => startNewAudit()}
                        style={{ marginTop: '20px' }}
                      >
                        {__('Run Audit', 'prorank-seo')}
                      </Button>
                    </div>
                  ) : (
                    <Card className="prorank-empty-state">
                      <CardBody>
                        <div className="empty-state-content" style={{ textAlign: 'center', padding: '48px 24px' }}>
                          <div className="empty-icon" style={{ fontSize: '64px', marginBottom: '16px' }}>🔍</div>
                          <Heading level={3} style={{ marginBottom: '12px' }}>{__('No Recent Audit', 'prorank-seo')}</Heading>
                          <Text style={{ color: '#6b7280', marginBottom: '24px', display: 'block' }}>
                            {__('Start a comprehensive site audit to check for SEO issues.', 'prorank-seo')}
                          </Text>
                          <button
                            type="button"
                            onClick={() => startNewAudit()}
                            disabled={startingAudit}
                            style={{
                              background: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 50%, #1d4ed8 100%)',
                              color: 'white',
                              border: 'none',
                              padding: '14px 32px',
                              fontSize: '15px',
                              fontWeight: '600',
                              borderRadius: '10px',
                              cursor: startingAudit ? 'not-allowed' : 'pointer',
                              boxShadow: '0 4px 14px -3px rgba(59, 130, 246, 0.5)',
                              transition: 'all 0.2s ease',
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '8px',
                              opacity: startingAudit ? 0.7 : 1,
                            }}
                            onMouseOver={(e) => {
                              if (!startingAudit) {
                                e.currentTarget.style.transform = 'translateY(-2px)';
                                e.currentTarget.style.boxShadow = '0 6px 20px -3px rgba(59, 130, 246, 0.6)';
                              }
                            }}
                            onMouseOut={(e) => {
                              e.currentTarget.style.transform = 'translateY(0)';
                              e.currentTarget.style.boxShadow = '0 4px 14px -3px rgba(59, 130, 246, 0.5)';
                            }}
                          >
                            {startingAudit ? (
                              <>
                                <Spinner style={{ width: '16px', height: '16px' }} />
                                {__('Starting...', 'prorank-seo')}
                              </>
                            ) : (
                              <>
                                <span style={{ fontSize: '18px' }}>🚀</span>
                                {__('Run Site Audit', 'prorank-seo')}
                              </>
                            )}
                          </button>
                        </div>
                      </CardBody>
                    </Card>
                  )}
                </div>
              );
              }

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

              const categoryValues = Array.from(
                new Set(issuesList.map((issue) => String(getIssueCategoryKey(issue))))
              ).filter((key) => key && key !== 'other');

              const categoryOptions = [
                { label: __('All Categories', 'prorank-seo'), value: 'all' },
                ...categoryValues.map((key) => ({ label: formatCategoryLabel(key), value: key })),
              ];

              const filteredIssues = issuesList.filter((issue) => {
                const severity = String(issue?.severity || 'low');
                const category = String(getIssueCategoryKey(issue));

                const matchesSeverity = selectedSeverity === 'all' || severity === selectedSeverity;
                const matchesCategory = selectedCategory === 'all' || category === selectedCategory;

                return matchesSeverity && matchesCategory;
              });

              return (
                <div className="prorank-audit-issues-content">
                  {auditStatus?.state === 'completed' ? (
                    <>
                      {/* Filters */}
                      <Card style={{ marginBottom: '20px' }}>
                        <CardBody>
                          <Flex gap={4}>
                            <SelectControl
                              label={__('Severity', 'prorank-seo')}
                              value={selectedSeverity}
                              options={[
                                { label: __('All Severities', 'prorank-seo'), value: 'all' },
                                { label: __('Critical', 'prorank-seo'), value: 'critical' },
                                { label: __('High', 'prorank-seo'), value: 'high' },
                                { label: __('Medium', 'prorank-seo'), value: 'medium' },
                                { label: __('Low', 'prorank-seo'), value: 'low' },
                              ]}
                              onChange={(value) => {
                                setSelectedSeverity(value);
                              }}
                            />
                            <SelectControl
                              label={__('Category', 'prorank-seo')}
                              value={selectedCategory}
                              options={categoryOptions}
                              onChange={(value) => {
                                setSelectedCategory(value);
                              }}
                            />
                          </Flex>
                        </CardBody>
                      </Card>

                      {/* Issues List */}
                      {loadingIssues ? (
                        <Card>
                          <CardBody>
                            <Spinner />
                          </CardBody>
                        </Card>
                      ) : filteredIssues.length > 0 ? (
                        <Card>
                          <CardHeader>
                            <Heading level={3}>
                              {sprintf(__('%d Issues Found', 'prorank-seo'), filteredIssues.length)}
                            </Heading>
                          </CardHeader>
                          <CardBody>
                            <div className="prorank-issues-list">
                              {filteredIssues.map((issue, index) => {
                                const issueKey = String(issue?.id || issue?.issue_id || `${issue?.severity || 'low'}-${issue?.type || 'issue'}-${index}`);
                                const urls = getIssueUrls(issue);

                                return (
                                <div key={issueKey} className="issue-item">
                                  <div className="issue-header">
                                    <Icon
                                      icon={getSeverityIcon(issue.severity)}
                                      style={{ color: getSeverityColor(issue.severity) }}
                                    />
                                    <span className="issue-title">{getIssueTitle(issue)}</span>
                                    <span className="issue-count">({issue.count || 1} {__('issues', 'prorank-seo')})</span>
                                    <Button
                                      variant="link"
                                      onClick={() => toggleRowExpansion(issueKey)}
                                    >
                                      {expandedRows[issueKey] ? __('Hide', 'prorank-seo') : __('Details', 'prorank-seo')}
                                    </Button>
                                  </div>
                                  {expandedRows[issueKey] && (
                                    <div className="issue-details">
                                      <p><strong>{__('Category:', 'prorank-seo')}</strong> {formatCategoryLabel(getIssueCategoryKey(issue))}</p>
                                      {getIssueDescription(issue) && (
                                        <p className="issue-description">{getIssueDescription(issue)}</p>
                                      )}
                                      {issue?.how_to_fix && (
                                        <p><strong>{__('How to fix:', 'prorank-seo')}</strong> {issue.how_to_fix}</p>
                                      )}
                                      {urls.length > 0 && (
                                        <>
                                          <p><strong>{__('Affected URLs:', 'prorank-seo')}</strong></p>
                                          <ul>
                                            {urls.map((url, urlIndex) => (
                                              <li key={urlIndex}>
                                                <a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
                                              </li>
                                            ))}
                                          </ul>
                                        </>
                                      )}
                                    </div>
                                  )}
                                </div>
                              );
                              })}
                            </div>
                          </CardBody>
                        </Card>
                      ) : (
                        <Card>
                          <CardBody>
                            <Notice status="success" isDismissible={false}>
                              <p>{__('No issues found! Your site is in great shape.', 'prorank-seo')}</p>
                            </Notice>
                          </CardBody>
                        </Card>
                      )}
                    </>
                  ) : (
                    <Card>
                      <CardBody>
                        <Text>{__('Run an audit to see issues.', 'prorank-seo')}</Text>
                      </CardBody>
                    </Card>
                  )}
                </div>
              );
            }

            case 'history':
              return (
                <div className="prorank-audit-history-content">
                  <Card>
                    <CardHeader>
                      <Heading level={3}>{__('Audit History', 'prorank-seo')}</Heading>
                    </CardHeader>
                    <CardBody>
                      {auditHistory.length > 0 ? (
                        <table className="prorank-history-table wp-list-table widefat fixed striped">
                          <thead>
                            <tr>
                              <th>{__('Date', '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) => (
                              <tr key={audit.id || index}>
                                <td>{new Date(audit.date).toLocaleDateString()}</td>
                                <td>
                                  <span className={`score-badge score-${audit.score >= 80 ? 'good' : audit.score >= 60 ? 'medium' : 'poor'}`}>
                                    {audit.score}%
                                  </span>
                                </td>
                                <td>{audit.totalUrls || audit.stats?.total_urls || 0}</td>
                                <td>{audit.total_issues || audit.stats?.total_issues || 0}</td>
                                <td>{audit.critical || audit.stats?.critical_issues || 0}</td>
                                <td>{audit.duration ? `${audit.duration}s` : '-'}</td>
                                <td>
                                  <Button
                                    variant="secondary"
                                    size="small"
                                    onClick={() => viewReportDetails(audit.id)}
                                  >
                                    {__('View Details', 'prorank-seo')}
                                  </Button>
                                  {' '}
                                  <Button
                                    variant="link"
                                    size="small"
                                    onClick={() => downloadPDFReport(audit.id)}
                                  >
                                    {__('Download HTML', 'prorank-seo')}
                                  </Button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      ) : (
                        <Notice status="info" isDismissible={false}>
                          <p>{__('No audit history available yet.', 'prorank-seo')}</p>
                        </Notice>
                      )}
                    </CardBody>
                  </Card>
                </div>
              );
              
            case 'report-details':
              return (
                <div className="prorank-audit-report-details">
                  <div className="report-header">
                    <Button
                      icon="arrow-left-alt2"
                      onClick={() => selectAuditTab('history')}
                    >
                      {__('Back to History', 'prorank-seo')}
                    </Button>
                    <h2>{sprintf(__('Audit Report - %s', 'prorank-seo'), reportDetails?.date ? new Date(reportDetails.date).toLocaleDateString() : '')}</h2>
                  </div>
                  
                  {loadingReport ? (
                    <Card>
                      <CardBody>
                        <Spinner />
                      </CardBody>
                    </Card>
                  ) : reportDetails ? (
                    <>
                      {/* Report Summary */}
                      <Card>
                        <CardHeader>
                          <Heading level={3}>{__('Report Summary', 'prorank-seo')}</Heading>
                        </CardHeader>
                        <CardBody>
                          <div className="report-summary-grid">
                            <div className="summary-item">
                              <strong>{__('Overall Score:', 'prorank-seo')}</strong>
                              <span className={`score-badge score-${reportDetails.score >= 80 ? 'good' : reportDetails.score >= 60 ? 'medium' : 'poor'}`}>
                                {reportDetails.score}%
                              </span>
                            </div>
                            <div className="summary-item">
                              <strong>{__('Pages Scanned:', 'prorank-seo')}</strong>
                              <span>{reportDetails.stats?.total_urls || 0}</span>
                            </div>
                            <div className="summary-item">
                              <strong>{__('Total Issues:', 'prorank-seo')}</strong>
                              <span>{reportDetails.stats?.total_issues || 0}</span>
                            </div>
                            <div className="summary-item">
                              <strong>{__('Critical Issues:', 'prorank-seo')}</strong>
                              <span style={{ color: '#dc2626' }}>{reportDetails.stats?.critical_issues || 0}</span>
                            </div>
                          </div>
                        </CardBody>
                      </Card>
                      
                      {/* Category Breakdown */}
                      {reportDetails.category_breakdown && (
                        <Card>
                          <CardHeader>
                            <Heading level={3}>{__('Category Breakdown', 'prorank-seo')}</Heading>
                          </CardHeader>
                          <CardBody>
                            <div className="category-breakdown">
                              {Object.entries(reportDetails.category_breakdown).map(([category, data]) => (
                                <div key={category} className="category-item">
                                  <Flex justify="space-between" align="center">
                                    <span>{category}</span>
                                    <span>{data.score}% ({data.issues} issues)</span>
                                  </Flex>
                                  <ProrankProgressBar value={data.score} />
                                </div>
                              ))}
                            </div>
                          </CardBody>
                        </Card>
                      )}
                    </>
                  ) : (
                    <Card>
                      <CardBody>
                        <Notice status="error" isDismissible={false}>
                          {__('Failed to load report details.', 'prorank-seo')}
                        </Notice>
                      </CardBody>
                    </Card>
                  )}
                </div>
              );

            case 'settings':
              return (
                <div className="prorank-audit-settings-content">
                  <Card>
                    <CardHeader>
                      <Heading level={3}>{__('Audit Settings', 'prorank-seo')}</Heading>
                    </CardHeader>
                    <CardBody>
                      <form className="prorank-audit-settings-form" onSubmit={(e) => { e.preventDefault(); saveSettings(); }}>
                        <fieldset>
                          <legend>{__('Crawl Settings', 'prorank-seo')}</legend>
                          
                          <TextControl
                            label={__('Maximum URLs to Scan', 'prorank-seo')}
                            type="number"
                            min="1"
                            max="100"
                            value={settings.max_urls}
                            onChange={(value) => {
                              const num = Math.max(1, Math.min(100, parseInt(value) || 1));
                              setSettings({ ...settings, max_urls: num });
                            }}
                            help={__('Number of pages to scan (1-100 in free version)', 'prorank-seo')}
                          />

                          <TextControl
                            label={__('Maximum Crawl Depth', 'prorank-seo')}
                            type="number"
                            min="1"
                            max="10"
                            value={settings.max_depth}
                            onChange={(value) => setSettings({ ...settings, max_depth: parseInt(value) })}
                            help={__('How many levels deep to follow links', 'prorank-seo')}
                          />
                        </fieldset>

                        <fieldset>
                          <legend>{__('Check Types', 'prorank-seo')}</legend>
                          
                          <div className="checkbox-group">
                            <h4>{__('SEO Essentials', 'prorank-seo')}</h4>
                            {Object.entries({
                              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'),
                              robots_txt: __('Robots Meta Tags', 'prorank-seo'),
                              xml_sitemap: __('XML Sitemap Validation', 'prorank-seo'),
                            }).map(([key, label]) => (
                              <Toggle
                                key={key}
                                label={label}
                                checked={settings.check_types[key]}
                                onChange={(value) => setSettings({
                                  ...settings,
                                  check_types: { ...settings.check_types, [key]: value }
                                })}
                              />
                            ))}

                            <h4>{__('Content & Links', 'prorank-seo')}</h4>
                            {Object.entries({
                              content_quality: __('Content Quality Score', 'prorank-seo'),
                              thin_content: __('Thin Content Detection', 'prorank-seo'),
                              duplicate_content: __('Duplicate Content', 'prorank-seo'),
                              broken_links: __('Broken Links', 'prorank-seo'),
                              internal_linking: __('Internal Linking', 'prorank-seo'),
                              external_links: __('External Links', 'prorank-seo'),
                              orphaned_pages: __('Orphaned Pages', 'prorank-seo'),
                            }).map(([key, label]) => (
                              <Toggle
                                key={key}
                                label={label}
                                checked={settings.check_types[key]}
                                onChange={(value) => setSettings({
                                  ...settings,
                                  check_types: { ...settings.check_types, [key]: value }
                                })}
                              />
                            ))}

                            <h4>{__('Performance & Technical', 'prorank-seo')}</h4>
                            {Object.entries({
                              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'),
                            }).map(([key, label]) => (
                              <Toggle
                                key={key}
                                label={label}
                                checked={settings.check_types[key]}
                                onChange={(value) => setSettings({
                                  ...settings,
                                  check_types: { ...settings.check_types, [key]: value }
                                })}
                              />
                            ))}

                            <h4>{__('Security', 'prorank-seo')}</h4>
                            {Object.entries({
                              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'),
                            }).map(([key, label]) => (
                              <Toggle
                                key={key}
                                label={label}
                                checked={settings.check_types[key]}
                                onChange={(value) => setSettings({
                                  ...settings,
                                  check_types: { ...settings.check_types, [key]: value }
                                })}
                              />
                            ))}

                            <h4>{__('WordPress Health', 'prorank-seo')}</h4>
                            {Object.entries({
                              wordpress_health: __('WordPress Version & PHP', 'prorank-seo'),
                              plugin_conflicts: __('Plugin Conflicts', 'prorank-seo'),
                              database_optimization: __('Database Optimization', 'prorank-seo'),
                            }).map(([key, label]) => (
                              <Toggle
                                key={key}
                                label={label}
                                checked={settings.check_types[key]}
                                onChange={(value) => setSettings({
                                  ...settings,
                                  check_types: { ...settings.check_types, [key]: value }
                                })}
                              />
                            ))}
                          </div>
                        </fieldset>

                        <fieldset>
                          <legend>{__('Schedule & Automation', 'prorank-seo')}</legend>

                          <Toggle
                            label={__('Enable Scheduled Audits', 'prorank-seo')}
                            checked={settings.schedule_enabled}
                            onChange={(value) => setSettings({ ...settings, schedule_enabled: value })}
                          />

                          {settings.schedule_enabled && (
                            <>
                              <SelectControl
                                label={__('Audit Frequency', 'prorank-seo')}
                                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 })}
                              />

                              <TextControl
                                label={__('Preferred Time', 'prorank-seo')}
                                type="time"
                                value={settings.schedule_time}
                                onChange={(value) => setSettings({ ...settings, schedule_time: value })}
                                help={__('Schedule audits during low-traffic periods', 'prorank-seo')}
                              />
                            </>
                          )}

                          <h4>{__('Email Notifications', 'prorank-seo')}</h4>

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

                          <Toggle
                            label={__('Only notify for critical issues', 'prorank-seo')}
                            checked={settings.email_critical_only}
                            onChange={(value) => setSettings({ ...settings, email_critical_only: value })}
                          />

                          <TextControl
                            label={__('Notification Recipients', 'prorank-seo')}
                            placeholder={__('email@example.com, another@example.com', 'prorank-seo')}
                            value={settings.notification_emails}
                            onChange={(value) => setSettings({ ...settings, notification_emails: value })}
                            help={__('Comma-separated list of email addresses', 'prorank-seo')}
                          />
                        </fieldset>

                        <div className="form-actions">
                          <Button variant="primary" type="submit">
                            {__('Save Settings', 'prorank-seo')}
                          </Button>
                        </div>
                      </form>
                    </CardBody>
                  </Card>
                </div>
              );

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

export default SiteAuditDashboard;
