/**
 * Internal Linking Dashboard
 * 
 * Enhanced dashboard with graphs, metrics, and comprehensive link analysis
 */

import { useState, useEffect, useMemo, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert } from '../../components/ui';
import LoadingState from '../../components/LoadingState';
import {
  loadWorkflowState,
  markWorkflowAction,
  resetWorkflowState,
  buildWorkflowModel,
} from './workflowState';

const LinkingDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [scanProgress, setScanProgress] = useState(0);
  const [scanRuntimeMessage, setScanRuntimeMessage] = useState('');
  const [showWorkflowPanel, setShowWorkflowPanel] = useState(false);
  const [showEcosystemPanel, setShowEcosystemPanel] = useState(false);
  const [lastScan, setLastScan] = useState(null);
  const [scanMeta, setScanMeta] = useState({
    last_scan: null,
    stats: {
      total_posts: 0,
      internal_links: 0,
      orphaned_posts: 0,
      broken_links: 0,
      suggestions: 0,
    },
  });
  const [schemaStatus, setSchemaStatus] = useState({
    ready: true,
    version_mismatch: false,
    expected_version: '',
    current_version: '',
    missing_tables: [],
  });
  const [repairingSchema, setRepairingSchema] = useState(false);
  const [linkingSettings, setLinkingSettings] = useState({
    enabled: true,
    ai_suggestions: false,
    gsc_integration: false,
    auto_linking: false,
  });
  const [operations, setOperations] = useState({
    state: {
      enabled: false,
      frequency: 'weekly',
      email_enabled: false,
      email_recipients: '',
      last_run_at: '',
      last_run_status: 'idle',
      last_run_message: '',
    },
    runs: [],
    next_run_at: null,
    next_run_label: '',
    frequencies: [],
  });
  const [operationsLoading, setOperationsLoading] = useState(false);
  const [operationsSaving, setOperationsSaving] = useState(false);
  const [operationsRunning, setOperationsRunning] = useState(false);
  const [operationsNotice, setOperationsNotice] = useState('');
  const [workflowState, setWorkflowState] = useState(() => loadWorkflowState());
  const [stats, setStats] = useState({
    posts_crawled: 0,
    link_clicks_tracked: 0,
    link_clicks_change: 0,
    orphaned_posts: 0,
    broken_links: 0,
    link_coverage: 0,
    link_quality_score: 0,
    external_site_focus: 0,
    anchor_length_score: 0,
    most_linked_domains: [],
    link_health_details: {
      total_internal: 0,
      total_external: 0,
      avg_links_per_post: 0,
      posts_without_links: 0,
    },
    link_distribution: [],
    recent_changes: [],
    scan_history: [],
    scan_trends: {
      has_previous: false,
      deltas: {},
    },
  });

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

  const toPercent = (value, fallback = 0) => {
    const numeric = toFiniteNumber(value, fallback);
    return Math.min(100, Math.max(0, numeric));
  };

  useEffect(() => {
    loadDashboardData();
    loadScanMeta();
    loadLinkingSettings();
    loadSchemaStatus();
    loadOperationsState();
  }, []);

  const loadDashboardData = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/dashboard',
      });
      
      if (response && response.data) {
        const totalPosts = toFiniteNumber(response.data.total_posts);
        const totalInternalLinks = toFiniteNumber(response.data.total_internal_links);
        const totalExternalLinks = toFiniteNumber(response.data.total_external_links);
        const totalLinks = totalInternalLinks + totalExternalLinks;
        const resolvedExternalFocus = response.data.external_percentage !== undefined && response.data.external_percentage !== null
          ? toPercent(response.data.external_percentage)
          : (totalLinks > 0 ? toPercent((totalExternalLinks / totalLinks) * 100) : 0);
        const resolvedAnchorScore = response.data.anchor_score !== undefined && response.data.anchor_score !== null
          ? toPercent(response.data.anchor_score)
          : 0;

        // Process and enhance the data
        const enhancedStats = {
          posts_crawled: totalPosts,
          link_clicks_tracked: toFiniteNumber(response.data.link_clicks),
          link_clicks_change: toFiniteNumber(response.data.link_clicks_change),
          orphaned_posts: toFiniteNumber(response.data.orphan_count),
          broken_links: toFiniteNumber(response.data.broken_links),
          link_coverage: toPercent(response.data.link_coverage),
          link_quality_score: calculateQualityScore(response.data),
          external_site_focus: resolvedExternalFocus,
          anchor_length_score: resolvedAnchorScore,
          most_linked_domains: response.data.top_domains || [],
          link_health_details: {
            total_internal: totalInternalLinks,
            total_external: totalExternalLinks,
            avg_links_per_post: toFiniteNumber(response.data.avg_links),
            posts_without_links: toFiniteNumber(response.data.posts_without_links),
          },
          link_distribution: response.data.link_distribution || [],
          recent_changes: response.data.recent_changes || [],
          scan_history: response.data.scan_history || [],
          scan_trends: response.data.scan_trends || {
            has_previous: false,
            deltas: {},
          },
        };
        setStats(enhancedStats);

        if (response.data.last_scan) {
          setLastScan(new Date(response.data.last_scan));
        }
      }
    } catch (error) {
      // Error loading dashboard data
    } finally {
      setLoading(false);
    }
  };

  const calculateQualityScore = (data) => {
    // Calculate quality score based on multiple factors
    let score = 0;
    const coverage = toPercent(data?.link_coverage);
    const totalPosts = toFiniteNumber(data?.total_posts);
    const orphanCount = toFiniteNumber(data?.orphan_count);
    const totalInternalLinks = toFiniteNumber(data?.total_internal_links);
    const brokenLinks = toFiniteNumber(data?.broken_links);
    
    // Coverage contributes 40%
    if (coverage > 0) {
      score += (coverage / 100) * 40;
    }
    
    // Orphan rate contributes 30% (inverse)
    const orphanRate = totalPosts > 0 ?
      (orphanCount / totalPosts) : 1;
    score += (1 - orphanRate) * 30;
    
    // Broken links contribute 30% (inverse)
    const brokenRate = totalInternalLinks > 0 ?
      (brokenLinks / totalInternalLinks) : 0;
    score += (1 - Math.min(brokenRate, 1)) * 30;
    
    return Math.min(100, Math.max(0, Math.round(score)));
  };

  const loadScanMeta = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/scan-info',
      });

      const payload = response?.data || {};
      const resolvedLastScan = payload.last_scan || response?.last_scan || null;

      if (resolvedLastScan) {
        setLastScan(new Date(resolvedLastScan));
      }

      setScanMeta({
        last_scan: resolvedLastScan,
        stats: {
          total_posts: payload?.stats?.total_posts || 0,
          internal_links: payload?.stats?.internal_links || 0,
          orphaned_posts: payload?.stats?.orphaned_posts || 0,
          broken_links: payload?.stats?.broken_links || 0,
          suggestions: payload?.stats?.suggestions || 0,
        },
      });
    } catch (error) {
      // Error checking scan info
    }
  };

  const loadLinkingSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/internal-linking',
      });

      const data = response?.data || response || {};
      if (data && typeof data === 'object') {
        setLinkingSettings((prev) => ({
          ...prev,
          ...data,
        }));
      }
    } catch (error) {
      // Silent fail: workflow panel degrades gracefully.
    }
  };

  const loadSchemaStatus = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/table-readiness',
      });

      const data = response?.data || {};
      setSchemaStatus({
        ready: Boolean(data?.ready),
        version_mismatch: Boolean(data?.version_mismatch),
        expected_version: data?.expected_version || '',
        current_version: data?.current_version || '',
        missing_tables: Array.isArray(data?.missing_tables) ? data.missing_tables : [],
      });
    } catch (error) {
      // Keep default optimistic state; endpoint requires manage_options.
    }
  };

  const normalizeOperationsPayload = (payload) => {
    const state = payload?.state && typeof payload.state === 'object' ? payload.state : {};
    return {
      state: {
        enabled: Boolean(state.enabled),
        frequency: state.frequency || 'weekly',
        email_enabled: Boolean(state.email_enabled),
        email_recipients: state.email_recipients || '',
        last_run_at: state.last_run_at || '',
        last_run_status: state.last_run_status || 'idle',
        last_run_message: state.last_run_message || '',
      },
      runs: Array.isArray(payload?.runs) ? payload.runs : [],
      next_run_at: payload?.next_run_at || null,
      next_run_label: payload?.next_run_label || '',
      frequencies: Array.isArray(payload?.frequencies) ? payload.frequencies : [],
    };
  };

  const loadOperationsState = async () => {
    setOperationsLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/operations-state',
      });
      const payload = response?.data || {};
      setOperations(normalizeOperationsPayload(payload));
    } catch (error) {
      // Endpoint requires elevated role; dashboard should stay usable without it.
    } finally {
      setOperationsLoading(false);
    }
  };

  const updateOperationsField = (key, value) => {
    setOperations((prev) => ({
      ...prev,
      state: {
        ...prev.state,
        [key]: value,
      },
    }));
  };

  const saveOperationsState = async () => {
    setOperationsSaving(true);
    setOperationsNotice('');
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/operations-state',
        method: 'POST',
        data: operations.state,
      });
      const payload = response?.data || {};
      setOperations(normalizeOperationsPayload(payload));
      setOperationsNotice(__('Automation settings saved.', 'prorank-seo'));
    } catch (error) {
      setOperationsNotice(__('Failed to save automation settings.', 'prorank-seo'));
    } finally {
      setOperationsSaving(false);
    }
  };

  const runOperationsCycle = async () => {
    setOperationsRunning(true);
    setOperationsNotice(__('Running operational cycle...', 'prorank-seo'));
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/operations-run',
        method: 'POST',
      });

      const payload = response?.data?.operations || {};
      if (payload && typeof payload === 'object') {
        setOperations(normalizeOperationsPayload(payload));
      }

      setOperationsNotice(
        response?.message || __('Operational cycle completed.', 'prorank-seo')
      );
      loadDashboardData();
      loadScanMeta();
    } catch (error) {
      setOperationsNotice(__('Operational cycle failed. Please retry.', 'prorank-seo'));
    } finally {
      setOperationsRunning(false);
    }
  };

  const repairSchema = async () => {
    setRepairingSchema(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/table-readiness?repair=1',
      });
      const data = response?.data || {};
      setSchemaStatus({
        ready: Boolean(data?.ready),
        version_mismatch: Boolean(data?.version_mismatch),
        expected_version: data?.expected_version || '',
        current_version: data?.current_version || '',
        missing_tables: Array.isArray(data?.missing_tables) ? data.missing_tables : [],
      });
    } catch (error) {
      // Repair failures surface through existing UI/logs.
    } finally {
      setRepairingSchema(false);
    }
  };

  const runLinkScan = async () => {
    setScanning(true);
    setScanProgress(0);
    setScanRuntimeMessage(__('Starting link scan...', 'prorank-seo'));

    try {
      // Start the scan
      await apiFetch({
        path: '/prorank-seo/v1/linking/start-scan',
        method: 'POST',
      });

      // Poll for real progress with exponential backoff on errors
      let pollDelay = 1000;
      let consecutiveErrors = 0;
      const maxErrors = 5;

      const pollProgress = async () => {
        if (consecutiveErrors >= maxErrors) {
          setScanning(false);
          setScanProgress(100);
          setScanRuntimeMessage(__('Scan finished with partial results. Refreshing dashboard data...', 'prorank-seo'));
          loadDashboardData();
          loadScanMeta();
          return;
        }

        try {
          const response = await apiFetch({
            path: '/prorank-seo/v1/linking/scan-progress',
          });

          // Reset error count on success
          consecutiveErrors = 0;
          pollDelay = 1000;

          if (response) {
            const progress = response.progress || 0;
            setScanProgress(progress);
            if (response.message) {
              setScanRuntimeMessage(response.message);
            }

            if (response.status === 'complete' || progress >= 100) {
              setScanning(false);
              setScanRuntimeMessage(__('Scan complete. Dashboard updated.', 'prorank-seo'));
              loadDashboardData();
              loadScanMeta();
              return;
            }

            // Continue polling
            setTimeout(pollProgress, pollDelay);
          } else {
            // No response, continue polling
            setTimeout(pollProgress, pollDelay);
          }
        } catch (error) {
          // On error, use exponential backoff
          consecutiveErrors++;
          pollDelay = Math.min(pollDelay * 2, 10000); // Max 10 seconds
          setTimeout(pollProgress, pollDelay);
        }
      };

      // Start polling after a short delay
      setTimeout(pollProgress, 500);

    } catch (error) {
      setScanning(false);
      setScanRuntimeMessage(__('Scan failed. Please try again.', 'prorank-seo'));
    }
  };

  const getHealthScoreColor = (score) => {
    if (score >= 70) return '#10b981';
    if (score >= 40) return '#f59e0b';
    return '#ef4444';
  };

  const getChangeIndicator = (value) => {
    if (value > 0) {
      return <span className="pr:text-green-500 pr:text-[11px] pr:transition-all pr:duration-300">+{value}%</span>;
    } else if (value < 0) {
      return <span className="pr:text-red-500 pr:text-[11px] pr:transition-all pr:duration-300">{value}%</span>;
    }
    return <span className="pr:text-gray-500 pr:text-[11px] pr:transition-all pr:duration-300">0%</span>;
  };

  const renderProgressCircle = (value, max = 100, color = '#3b82f6') => {
    const safeValue = toFiniteNumber(value);
    const safeMax = toFiniteNumber(max);
    const percentage = safeMax > 0 ? Math.min(100, Math.max(0, (safeValue / safeMax) * 100)) : 0;
    const radius = 30;
    const circumference = 2 * Math.PI * radius;
    const offset = circumference - (percentage / 100) * circumference;
    
    return (
      <div className="pr:relative pr:w-[70px] pr:h-[70px]">
        <svg width="70" height="70" className="pr:transform pr:-rotate-90">
          <circle
            cx="35"
            cy="35"
            r={radius}
            stroke="#e5e7eb"
            strokeWidth="4"
            fill="none"
          />
          <circle
            cx="35"
            cy="35"
            r={radius}
            stroke={color}
            strokeWidth="4"
            fill="none"
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            className="pr:transition-all pr:duration-500"
          />
        </svg>
        <div className="pr:absolute pr:top-1/2 pr:left-1/2 pr:transform pr:-translate-x-1/2 pr:-translate-y-1/2 pr:text-sm pr:font-semibold pr:text-gray-900">
          {Math.round(percentage)}%
        </div>
      </div>
    );
  };

  const goToInternalTab = (tab, extra = {}) => {
    const currentHash = window.location.hash || '#';
    const baseHash = currentHash.split('?')[0] || '#';
    const params = new URLSearchParams({ tab });

    Object.entries(extra).forEach(([key, value]) => {
      if (value !== undefined && value !== null && String(value) !== '') {
        params.set(key, String(value));
      }
    });

    window.location.hash = `${baseHash}?${params.toString()}`;
  };

  const openAdminModule = (tab, extra = {}) => {
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    params.set('page', 'prorank-seo');
    params.set('tab', tab);

    Object.entries(extra).forEach(([key, value]) => {
      if (value !== undefined && value !== null && String(value) !== '') {
        params.set(key, String(value));
      }
    });

    window.location.href = `${url.origin}${url.pathname}?${params.toString()}`;
  };

  const recordWorkflowAction = useCallback((stepId) => {
    setWorkflowState((prev) => markWorkflowAction(stepId, prev));
  }, []);

  const resetWorkflowProgress = useCallback(() => {
    setWorkflowState(resetWorkflowState());
  }, []);

  const openIssueCount = (stats.orphaned_posts || 0) + (stats.broken_links || 0);

  const workflow = useMemo(() => {
    const hasSettingsReview = Boolean(linkingSettings.enabled);
    const hasScan = Boolean(lastScan);
    const hasAutoLinking = Boolean(linkingSettings.auto_linking);
    const hasMeasurement = (stats.link_clicks_tracked || 0) > 0;
    const actionHistory = workflowState.actions || {};

    const baseSteps = [
      {
        id: 'connect_sources',
        title: __('Review Linking Settings', 'prorank-seo'),
        description: __('Confirm suggestions, exclusions, and auto-linking preferences before scanning.', 'prorank-seo'),
        complete: hasSettingsReview,
        actionLabel: __('Open Settings', 'prorank-seo'),
        action: () => {
          recordWorkflowAction('connect_sources');
          goToInternalTab('settings');
        },
      },
      {
        id: 'run_scan',
        title: __('Run Full Site Scan', 'prorank-seo'),
        description: __('Refresh orphan, broken, and coverage metrics before making changes.', 'prorank-seo'),
        complete: hasScan,
        prerequisites: ['connect_sources'],
        actionLabel: scanning ? __('Scanning...', 'prorank-seo') : __('Run Scan', 'prorank-seo'),
        action: () => {
          recordWorkflowAction('run_scan');
          runLinkScan();
        },
        disabled: scanning,
      },
      {
        id: 'review_issues',
        title: __('Review Priority Issues', 'prorank-seo'),
        description: openIssueCount > 0
          ? `${openIssueCount} ${__('issues need attention (orphans + broken links).', 'prorank-seo')}`
          : __('No critical linking issues detected.', 'prorank-seo'),
        complete: hasScan && openIssueCount === 0,
        prerequisites: ['run_scan'],
        actionLabel: __('Open Reports', 'prorank-seo'),
        action: () => {
          recordWorkflowAction('review_issues');
          goToInternalTab(openIssueCount > 0 ? 'broken-links' : 'links-report');
        },
      },
      {
        id: 'apply_changes',
        title: __('Apply Improvements', 'prorank-seo'),
        description: __('Use Auto Linking rules and map review to implement fixes at scale.', 'prorank-seo'),
        complete: hasAutoLinking,
        prerequisites: ['review_issues'],
        actionLabel: __('Configure Auto Linking', 'prorank-seo'),
        action: () => {
          recordWorkflowAction('apply_changes');
          goToInternalTab('auto-linking');
        },
      },
      {
        id: 'measure_impact',
        title: __('Measure Impact', 'prorank-seo'),
        description: __('Track click behavior and link distribution after each optimization cycle.', 'prorank-seo'),
        complete: hasMeasurement,
        prerequisites: ['apply_changes'],
        actionLabel: __('Open Links Report', 'prorank-seo'),
        action: () => {
          recordWorkflowAction('measure_impact');
          goToInternalTab('links-report');
        },
      },
    ];

    const model = buildWorkflowModel(baseSteps);
    const stepTitleById = baseSteps.reduce((acc, step) => {
      acc[step.id] = step.title;
      return acc;
    }, {});

    const steps = model.steps.map((step) => ({
      ...step,
      lastActionAt: actionHistory[step.id] || null,
      blockedReason: step.blockedBy
        ? sprintf(
            /* translators: %s: prerequisite step title */
            __('Complete "%s" first.', 'prorank-seo'),
            stepTitleById[step.blockedBy] || __('previous step', 'prorank-seo')
          )
        : '',
    }));

    return {
      ...model,
      steps,
      openIssueCount,
    };
  }, [linkingSettings, lastScan, openIssueCount, stats, scanning, workflowState.actions, recordWorkflowAction]);

  const trustSignals = useMemo(() => {
    const parseDate = (value) => {
      if (!value) return null;
      const parsed = new Date(value);
      return Number.isNaN(parsed.getTime()) ? null : parsed;
    };

    const scanDate = parseDate(lastScan || scanMeta.last_scan);
    const now = new Date();
    const ageHours = scanDate ? Math.max(0, (now.getTime() - scanDate.getTime()) / (1000 * 60 * 60)) : null;

    let freshnessLabel = __('Not Scanned', 'prorank-seo');
    let freshnessTone = 'pr:bg-gray-100 pr:text-gray-700';
    if (ageHours !== null && ageHours <= 24) {
      freshnessLabel = __('Fresh (<24h)', 'prorank-seo');
      freshnessTone = 'pr:bg-emerald-100 pr:text-emerald-800';
    } else if (ageHours !== null && ageHours <= 72) {
      freshnessLabel = __('Aging (1-3 days)', 'prorank-seo');
      freshnessTone = 'pr:bg-amber-100 pr:text-amber-800';
    } else if (ageHours !== null) {
      freshnessLabel = __('Stale (>3 days)', 'prorank-seo');
      freshnessTone = 'pr:bg-rose-100 pr:text-rose-800';
    }

    const sampleSize = scanMeta?.stats?.total_posts || stats.posts_crawled || 0;
    const coverage = Number(stats.link_coverage || 0);
    const recencyScore = ageHours === null ? 20 : Math.max(0, 100 - Math.min(ageHours * 2, 100));
    const sampleScore = sampleSize >= 200 ? 100 : Math.round((sampleSize / 200) * 100);
    const confidence = Math.round((recencyScore * 0.4) + (coverage * 0.35) + (sampleScore * 0.25));

    return {
      scanDate,
      freshnessLabel,
      freshnessTone,
      confidence,
      sampleSize,
      recencyHours: ageHours,
    };
  }, [lastScan, scanMeta, stats]);

  const scanHistory = useMemo(() => {
    if (!Array.isArray(stats.scan_history)) {
      return [];
    }

    return stats.scan_history.slice(0, 8);
  }, [stats.scan_history]);

  const changeByMetric = useMemo(() => {
    if (!Array.isArray(stats.recent_changes)) {
      return {};
    }

    return stats.recent_changes.reduce((acc, change) => {
      if (change?.metric) {
        acc[change.metric] = change;
      }
      return acc;
    }, {});
  }, [stats.recent_changes]);

  const trendCards = useMemo(() => {
    const cardDefs = [
      {
        id: 'internal',
        metric: 'total_internal_links',
        label: __('Internal Links', 'prorank-seo'),
        value: stats.link_health_details.total_internal || 0,
        precision: 0,
      },
      {
        id: 'orphans',
        metric: 'orphan_count',
        label: __('Orphan Pages', 'prorank-seo'),
        value: stats.orphaned_posts || 0,
        precision: 0,
      },
      {
        id: 'broken',
        metric: 'broken_links',
        label: __('Broken Links', 'prorank-seo'),
        value: stats.broken_links || 0,
        precision: 0,
      },
      {
        id: 'coverage',
        metric: 'link_coverage',
        label: __('Link Coverage', 'prorank-seo'),
        value: `${Number(stats.link_coverage || 0).toFixed(1)}%`,
        precision: 2,
      },
    ];

    return cardDefs.map((card) => {
      const change = changeByMetric[card.metric] || null;
      if (!change) {
        return {
          ...card,
          trendLabel: __('Baseline', 'prorank-seo'),
          trendTone: 'pr:bg-gray-100 pr:text-gray-700',
        };
      }

      const delta = Number(change.delta || 0);
      const hasChange = Math.abs(delta) > 0.0001;
      const unit = change.unit || '';
      const trendLabel = hasChange
        ? `${delta > 0 ? '+' : ''}${delta.toFixed(card.precision)}${unit}`
        : __('No change', 'prorank-seo');

      let trendTone = 'pr:bg-gray-100 pr:text-gray-700';
      if (change.status === 'improved') {
        trendTone = 'pr:bg-emerald-100 pr:text-emerald-700';
      } else if (change.status === 'declined') {
        trendTone = 'pr:bg-rose-100 pr:text-rose-700';
      }

      return {
        ...card,
        trendLabel,
        trendTone,
      };
    });
  }, [changeByMetric, stats]);

  const latestChanges = useMemo(() => {
    if (!Array.isArray(stats.recent_changes)) {
      return [];
    }

    return stats.recent_changes.slice(0, 5);
  }, [stats.recent_changes]);

  const operationsRuns = useMemo(() => {
    if (!Array.isArray(operations.runs)) {
      return [];
    }

    return operations.runs.slice(0, 6);
  }, [operations.runs]);

  const formatRuntimeDate = (value) => {
    if (!value) {
      return __('Never', 'prorank-seo');
    }

    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) {
      return value;
    }

    return parsed.toLocaleString();
  };

  const formatWorkflowActionDate = (value) => {
    if (!value) {
      return __('Not started', 'prorank-seo');
    }

    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) {
      return value;
    }

    return parsed.toLocaleString();
  };

  if (loading) {
    return (
      <Card className="pr:p-8">
        <LoadingState message={__('Loading dashboard...', 'prorank-seo')} />
      </Card>
    );
  }

  return (
    <div className="prorank-linking-dashboard">
      {/* Operational Signals */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:border pr:border-gray-200">
        <div className="pr:p-6">
          <div className="pr:flex pr:items-start pr:justify-between pr:gap-4 pr:flex-wrap">
            <div>
              <h3 className="pr:text-base pr:font-semibold pr:mb-1">
                {__('Operational Status', 'prorank-seo')}
              </h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Trust signals for scan freshness, dataset confidence, and readiness to ship internal-link changes.', 'prorank-seo')}
              </p>
            </div>
            <span className={`pr:inline-flex pr:items-center pr:px-3 pr:py-1 pr:rounded-full pr:text-xs pr:font-semibold ${trustSignals.freshnessTone}`}>
              {trustSignals.freshnessLabel}
            </span>
          </div>

          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-5 pr:gap-3 pr:mt-4">
            <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
              <div className="pr:text-xs pr:text-gray-500">{__('Confidence Score', 'prorank-seo')}</div>
              <div className="pr:text-xl pr:font-semibold pr:text-gray-900">{trustSignals.confidence}%</div>
            </div>
            <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
              <div className="pr:text-xs pr:text-gray-500">{__('Scanned Content', 'prorank-seo')}</div>
              <div className="pr:text-xl pr:font-semibold pr:text-gray-900">{trustSignals.sampleSize}</div>
            </div>
            <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
              <div className="pr:text-xs pr:text-gray-500">{__('Open Issue Backlog', 'prorank-seo')}</div>
              <div className="pr:text-xl pr:font-semibold pr:text-gray-900">{workflow.openIssueCount}</div>
            </div>
            <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
              <div className="pr:text-xs pr:text-gray-500">{__('Schema Readiness', 'prorank-seo')}</div>
              <div className={`pr:text-sm pr:font-semibold ${schemaStatus.ready ? 'pr:text-emerald-700' : 'pr:text-rose-700'}`}>
                {schemaStatus.ready ? __('Ready', 'prorank-seo') : __('Needs Repair', 'prorank-seo')}
              </div>
              {!schemaStatus.ready && (
                <div className="pr:text-[11px] pr:text-rose-700 pr:mt-1">
                  {schemaStatus.missing_tables.length > 0
                    ? `${schemaStatus.missing_tables.length} ${__('tables incomplete', 'prorank-seo')}`
                    : __('Schema mismatch detected', 'prorank-seo')}
                </div>
              )}
            </div>
            <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
              <div className="pr:text-xs pr:text-gray-500">{__('Last Scan', 'prorank-seo')}</div>
              <div className="pr:text-sm pr:font-semibold pr:text-gray-900">
                {trustSignals.scanDate ? trustSignals.scanDate.toLocaleString() : __('Never', 'prorank-seo')}
              </div>
            </div>
          </div>

          {(!schemaStatus.ready || schemaStatus.version_mismatch) && (
            <div className="pr:mt-3 pr:rounded-lg pr:border pr:border-amber-200 pr:bg-amber-50 pr:p-3">
              <div className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
                <div className="pr:text-sm pr:text-amber-900">
                  {__('Internal-linking schema is not fully aligned. Repair before running large scans.', 'prorank-seo')}
                  {(schemaStatus.current_version || schemaStatus.expected_version) && (
                    <span className="pr:block pr:text-xs pr:mt-1">
                      {__('Current:', 'prorank-seo')} {schemaStatus.current_version || '0'} · {__('Expected:', 'prorank-seo')} {schemaStatus.expected_version || 'n/a'}
                    </span>
                  )}
                </div>
                <Button
                  variant="secondary"
                  onClick={repairSchema}
                  disabled={repairingSchema}
                  className="pr:!text-xs"
                >
                  {repairingSchema ? __('Repairing...', 'prorank-seo') : __('Repair Schema', 'prorank-seo')}
                </Button>
              </div>
            </div>
          )}

          {(scanning || scanRuntimeMessage) && (
            <p className="pr:mt-3 pr:text-sm pr:text-gray-600">
              {scanRuntimeMessage || __('Scan in progress...', 'prorank-seo')}
            </p>
          )}
        </div>
      </Card>

      <div className="pr:grid pr:grid-cols-1 pr:xl:grid-cols-2 pr:gap-5 pr:mb-5">
        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:p-6">
            <div className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
              <h3 className="pr:text-base pr:font-semibold">
                {__('Trend Snapshot', 'prorank-seo')}
              </h3>
              <span className="pr:text-xs pr:text-gray-500">
                {stats.scan_trends?.has_previous
                  ? __('vs previous scan', 'prorank-seo')
                  : __('Awaiting baseline', 'prorank-seo')}
              </span>
            </div>

            <div className="pr:grid pr:grid-cols-1 pr:sm:grid-cols-2 pr:gap-3 pr:mt-4">
              {trendCards.map((card) => (
                <div key={card.id} className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
                  <div className="pr:text-xs pr:text-gray-500">{card.label}</div>
                  <div className="pr:text-xl pr:font-semibold pr:text-gray-900 pr:mt-1">{card.value}</div>
                  <span className={`pr:mt-2 pr:inline-flex pr:items-center pr:px-2 pr:py-0.5 pr:rounded-full pr:text-xs pr:font-semibold ${card.trendTone}`}>
                    {card.trendLabel}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:p-6">
            <h3 className="pr:text-base pr:font-semibold">
              {__('What Changed Since Last Scan', 'prorank-seo')}
            </h3>

            {latestChanges.length > 0 ? (
              <div className="pr:space-y-2 pr:mt-4">
                {latestChanges.map((change) => {
                  const delta = Number(change?.delta || 0);
                  const hasDelta = Math.abs(delta) > 0.0001;
                  const unit = change?.unit || '';
                  const displayDelta = hasDelta
                    ? `${delta > 0 ? '+' : ''}${Math.abs(delta % 1) < 0.0001 ? delta.toFixed(0) : delta.toFixed(2)}${unit}`
                    : __('No change', 'prorank-seo');

                  let tone = 'pr:bg-gray-100 pr:text-gray-700';
                  if (change.status === 'improved') {
                    tone = 'pr:bg-emerald-100 pr:text-emerald-700';
                  } else if (change.status === 'declined') {
                    tone = 'pr:bg-rose-100 pr:text-rose-700';
                  }

                  return (
                    <div key={change.metric} className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:rounded-lg pr:border pr:border-gray-200 pr:bg-white pr:px-3 pr:py-2">
                      <div>
                        <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{change.label}</div>
                        <div className="pr:text-xs pr:text-gray-500">
                          {__('Now:', 'prorank-seo')} {change.current} · {__('Prev:', 'prorank-seo')} {change.previous}
                        </div>
                      </div>
                      <span className={`pr:inline-flex pr:items-center pr:px-2 pr:py-0.5 pr:rounded-full pr:text-xs pr:font-semibold ${tone}`}>
                        {displayDelta}
                      </span>
                    </div>
                  );
                })}
              </div>
            ) : (
              <Alert variant="info" className="pr:mt-4">
                {__('Run at least two full scans to start change tracking.', 'prorank-seo')}
              </Alert>
            )}
          </div>
        </Card>
      </div>

      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:border pr:border-gray-200">
        <div className="pr:p-6">
          <h3 className="pr:text-base pr:font-semibold">
            {__('Scan History Timeline', 'prorank-seo')}
          </h3>
          <p className="pr:text-sm pr:text-gray-600 pr:mt-1">
            {__('Recent scan snapshots for progress tracking and audit confidence.', 'prorank-seo')}
          </p>

          {scanHistory.length > 0 ? (
            <div className="pr:space-y-3 pr:mt-4">
              {scanHistory.map((snapshot, index) => {
                const parsedDate = new Date(snapshot.scanned_at);
                const scanDate = Number.isNaN(parsedDate.getTime())
                  ? String(snapshot.scanned_at || '')
                  : parsedDate.toLocaleString();
                const previous = scanHistory[index + 1] || null;
                const internalDelta = previous
                  ? Number(snapshot.total_internal_links || 0) - Number(previous.total_internal_links || 0)
                  : null;

                return (
                  <div key={`${snapshot.scanned_at}-${index}`} className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-3">
                    <div className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
                      <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{scanDate}</div>
                      {index === 0 && (
                        <span className="pr:inline-flex pr:items-center pr:px-2 pr:py-0.5 pr:rounded-full pr:text-xs pr:font-semibold pr:bg-blue-100 pr:text-blue-700">
                          {__('Latest', 'prorank-seo')}
                        </span>
                      )}
                    </div>

                    <div className="pr:grid pr:grid-cols-2 pr:md:grid-cols-4 pr:gap-2 pr:mt-2">
                      <div className="pr:text-xs pr:text-gray-600">
                        <span className="pr:block pr:text-gray-500">{__('Internal', 'prorank-seo')}</span>
                        <span className="pr:text-sm pr:font-semibold pr:text-gray-900">{snapshot.total_internal_links || 0}</span>
                      </div>
                      <div className="pr:text-xs pr:text-gray-600">
                        <span className="pr:block pr:text-gray-500">{__('Orphans', 'prorank-seo')}</span>
                        <span className="pr:text-sm pr:font-semibold pr:text-gray-900">{snapshot.orphan_count || 0}</span>
                      </div>
                      <div className="pr:text-xs pr:text-gray-600">
                        <span className="pr:block pr:text-gray-500">{__('Broken', 'prorank-seo')}</span>
                        <span className="pr:text-sm pr:font-semibold pr:text-gray-900">{snapshot.broken_links || 0}</span>
                      </div>
                      <div className="pr:text-xs pr:text-gray-600">
                        <span className="pr:block pr:text-gray-500">{__('Coverage', 'prorank-seo')}</span>
                        <span className="pr:text-sm pr:font-semibold pr:text-gray-900">{Number(snapshot.link_coverage || 0).toFixed(1)}%</span>
                      </div>
                    </div>

                    {internalDelta !== null && (
                      <div className="pr:text-xs pr:text-gray-500 pr:mt-2">
                        {__('Internal links delta:', 'prorank-seo')} {internalDelta > 0 ? '+' : ''}{internalDelta}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          ) : (
            <Alert variant="info" className="pr:mt-4">
              {__('No scan history yet. Run your first full scan to build timeline data.', 'prorank-seo')}
            </Alert>
          )}
        </div>
      </Card>

      {/* Guided Workflow */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:border pr:border-blue-100 pr:bg-gradient-to-br pr:from-blue-50 pr:to-white">
        <div className="pr:p-6">
          <div className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
            <div>
              <h3 className="pr:text-base pr:font-semibold pr:mb-1">
                {__('Guided Workflow', 'prorank-seo')}
              </h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Wizard-style execution with prerequisites and completion gates.', 'prorank-seo')}
              </p>
            </div>
            <div className="pr:flex pr:items-center pr:gap-2">
              <span className="pr:text-sm pr:font-semibold pr:text-blue-700">
                {workflow.completeCount}/{workflow.steps.length} {__('complete', 'prorank-seo')}
              </span>
              <Button
                size="sm"
                variant="secondary"
                onClick={resetWorkflowProgress}
              >
                {__('Reset Progress', 'prorank-seo')}
              </Button>
            </div>
          </div>

          <div className="pr:mt-3 pr:flex pr:flex-wrap pr:items-center pr:gap-2">
            {workflow.isComplete ? (
              <span className="pr:inline-flex pr:items-center pr:px-2 pr:py-1 pr:rounded-full pr:text-xs pr:font-semibold pr:bg-emerald-100 pr:text-emerald-700">
                {__('Workflow complete. Start another optimization cycle any time.', 'prorank-seo')}
              </span>
            ) : workflow.nextReadyStep ? (
              <span className="pr:inline-flex pr:items-center pr:px-2 pr:py-1 pr:rounded-full pr:text-xs pr:font-semibold pr:bg-blue-100 pr:text-blue-700">
                {sprintf(__('Current stage: %s', 'prorank-seo'), workflow.nextReadyStep.title)}
              </span>
            ) : workflow.nextBlockedStep ? (
              <span className="pr:inline-flex pr:items-center pr:px-2 pr:py-1 pr:rounded-full pr:text-xs pr:font-semibold pr:bg-amber-100 pr:text-amber-700">
                {__('Workflow blocked until prerequisite steps are completed.', 'prorank-seo')}
              </span>
            ) : null}
          </div>

          <div className="pr:mt-3 pr:flex pr:items-center pr:justify-between pr:gap-3">
            <div className="pr:w-full pr:bg-blue-100 pr:rounded-full pr:h-2">
              <div
                className="pr:h-2 pr:rounded-full pr:bg-gradient-to-r pr:from-blue-600 pr:to-sky-500 pr:transition-all pr:duration-500"
                style={{ width: `${workflow.progress}%` }}
              />
            </div>
            <Button
              size="sm"
              variant="secondary"
              onClick={() => setShowWorkflowPanel((prev) => !prev)}
            >
              {showWorkflowPanel
                ? __('Hide Steps', 'prorank-seo')
                : __('Show Steps', 'prorank-seo')}
            </Button>
          </div>

          {showWorkflowPanel && (
            <div className="pr:mt-4 pr:space-y-3">
              {workflow.steps.map((step, index) => (
                <div key={step.id} className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:rounded-lg pr:border pr:border-gray-200 pr:bg-white pr:px-3 pr:py-2">
                  <div className="pr:flex pr:items-start pr:gap-3">
                    <div className={`pr:flex pr:items-center pr:justify-center pr:w-6 pr:h-6 pr:rounded-full pr:text-xs pr:font-semibold ${
                      step.status === 'complete'
                        ? 'pr:bg-emerald-100 pr:text-emerald-700'
                        : step.status === 'ready'
                          ? 'pr:bg-blue-100 pr:text-blue-700'
                          : 'pr:bg-amber-100 pr:text-amber-700'
                    }`}>
                      {step.complete ? '✓' : (index + 1)}
                    </div>
                    <div>
                      <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{step.title}</div>
                      <div className="pr:text-xs pr:text-gray-600">{step.description}</div>
                      {step.blockedReason && (
                        <div className="pr:text-xs pr:text-amber-700 pr:mt-1">{step.blockedReason}</div>
                      )}
                      <div className="pr:text-[11px] pr:text-gray-500 pr:mt-1">
                        {__('Last action:', 'prorank-seo')} {formatWorkflowActionDate(step.lastActionAt)}
                      </div>
                    </div>
                  </div>
                  <div className="pr:flex pr:flex-col pr:items-end pr:gap-1">
                    <span className={`pr:inline-flex pr:items-center pr:px-2 pr:py-0.5 pr:rounded-full pr:text-[11px] pr:font-semibold ${
                      step.status === 'complete'
                        ? 'pr:bg-emerald-100 pr:text-emerald-700'
                        : step.status === 'ready'
                          ? 'pr:bg-blue-100 pr:text-blue-700'
                          : 'pr:bg-amber-100 pr:text-amber-700'
                    }`}>
                      {step.status === 'complete'
                        ? __('Complete', 'prorank-seo')
                        : step.status === 'ready'
                          ? __('Ready', 'prorank-seo')
                          : __('Blocked', 'prorank-seo')}
                    </span>
                  <Button
                    variant={step.complete ? 'secondary' : (step.status === 'blocked' ? 'ghost' : 'primary')}
                    size="sm"
                    onClick={step.action}
                    disabled={!step.canAct}
                  >
                    {step.status === 'blocked'
                      ? __('Complete Previous Step', 'prorank-seo')
                      : step.actionLabel}
                  </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </Card>

      {/* Operations Automation */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:border pr:border-indigo-100 pr:bg-gradient-to-br pr:from-indigo-50 pr:to-white">
        <div className="pr:p-6">
          <div className="pr:flex pr:items-start pr:justify-between pr:gap-3 pr:flex-wrap">
            <div>
              <h3 className="pr:text-base pr:font-semibold">
                {__('Operations Automation', 'prorank-seo')}
              </h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Schedule repeatable internal-linking cycles with run history and optional summary emails.', 'prorank-seo')}
              </p>
            </div>
            <Button
              variant="primary"
              size="sm"
              onClick={runOperationsCycle}
              disabled={operationsRunning || scanning}
            >
              {operationsRunning
                ? __('Running Cycle...', 'prorank-seo')
                : __('Run Cycle Now', 'prorank-seo')}
            </Button>
          </div>

          {operationsNotice && (
            <p className="pr:mt-3 pr:text-sm pr:text-gray-700">{operationsNotice}</p>
          )}

          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-4 pr:mt-4">
            <label className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
              <input
                type="checkbox"
                checked={Boolean(operations.state.enabled)}
                onChange={(event) => updateOperationsField('enabled', event.target.checked)}
                disabled={operationsLoading}
              />
              {__('Enable Scheduled Cycles', 'prorank-seo')}
            </label>

            <label className="pr:flex pr:flex-col pr:gap-1 pr:text-sm pr:text-gray-700">
              <span>{__('Frequency', 'prorank-seo')}</span>
              <select
                value={operations.state.frequency || 'weekly'}
                onChange={(event) => updateOperationsField('frequency', event.target.value)}
                disabled={operationsLoading}
                className="pr:h-9 pr:rounded-md pr:border pr:border-gray-300 pr:bg-white pr:px-2"
              >
                {(operations.frequencies.length > 0
                  ? operations.frequencies
                  : [
                      { value: 'daily', label: __('Daily', 'prorank-seo') },
                      { value: 'weekly', label: __('Weekly', 'prorank-seo') },
                      { value: 'monthly', label: __('Monthly', 'prorank-seo') },
                    ]
                ).map((frequency) => (
                  <option key={frequency.value} value={frequency.value}>
                    {frequency.label}
                  </option>
                ))}
              </select>
            </label>

            <label className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
              <input
                type="checkbox"
                checked={Boolean(operations.state.email_enabled)}
                onChange={(event) => updateOperationsField('email_enabled', event.target.checked)}
                disabled={operationsLoading}
              />
              {__('Send Summary Email', 'prorank-seo')}
            </label>

            <label className="pr:flex pr:flex-col pr:gap-1 pr:text-sm pr:text-gray-700">
              <span>{__('Email Recipients', 'prorank-seo')}</span>
              <input
                type="text"
                value={operations.state.email_recipients || ''}
                placeholder={__('owner@example.com, seo@example.com', 'prorank-seo')}
                onChange={(event) => updateOperationsField('email_recipients', event.target.value)}
                disabled={operationsLoading}
                className="pr:h-9 pr:rounded-md pr:border pr:border-gray-300 pr:bg-white pr:px-2"
              />
            </label>
          </div>

          <div className="pr:mt-4 pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
            <div className="pr:text-xs pr:text-gray-600">
              {__('Next scheduled run:', 'prorank-seo')}{' '}
              <span className="pr:font-semibold pr:text-gray-800">
                {operations.next_run_label || __('Not scheduled', 'prorank-seo')}
              </span>
              {' · '}
              {__('Last run:', 'prorank-seo')}{' '}
              <span className="pr:font-semibold pr:text-gray-800">
                {formatRuntimeDate(operations.state.last_run_at)}
              </span>
            </div>
            <Button
              variant="secondary"
              size="sm"
              onClick={saveOperationsState}
              disabled={operationsSaving || operationsLoading}
            >
              {operationsSaving
                ? __('Saving...', 'prorank-seo')
                : __('Save Automation', 'prorank-seo')}
            </Button>
          </div>

          {operationsRuns.length > 0 ? (
            <div className="pr:mt-4 pr:space-y-2">
              {operationsRuns.map((run) => {
                const metrics = run.metrics || {};
                const statusTone = run.status === 'success'
                  ? 'pr:bg-emerald-100 pr:text-emerald-700'
                  : 'pr:bg-rose-100 pr:text-rose-700';

                return (
                  <div key={run.run_id} className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-white pr:p-3">
                    <div className="pr:flex pr:items-center pr:justify-between pr:gap-3 pr:flex-wrap">
                      <div className="pr:text-sm pr:font-semibold pr:text-gray-900">
                        {formatRuntimeDate(run.completed_at || run.started_at)}
                      </div>
                      <span className={`pr:inline-flex pr:items-center pr:px-2 pr:py-0.5 pr:rounded-full pr:text-xs pr:font-semibold ${statusTone}`}>
                        {run.status === 'success'
                          ? __('Success', 'prorank-seo')
                          : __('Failed', 'prorank-seo')}
                      </span>
                    </div>
                    <div className="pr:text-xs pr:text-gray-600 pr:mt-1">{run.message}</div>
                    <div className="pr:grid pr:grid-cols-2 pr:md:grid-cols-4 pr:gap-2 pr:mt-2 pr:text-xs pr:text-gray-600">
                      <span>{__('Posts', 'prorank-seo')}: {metrics.total_posts || 0}</span>
                      <span>{__('Internal', 'prorank-seo')}: {metrics.total_internal_links || 0}</span>
                      <span>{__('Orphans', 'prorank-seo')}: {metrics.orphan_count || 0}</span>
                      <span>{__('Broken', 'prorank-seo')}: {metrics.broken_links || 0}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <Alert variant="info" className="pr:mt-4">
              {__('No operational runs yet. Trigger "Run Cycle Now" to create baseline history.', 'prorank-seo')}
            </Alert>
          )}
        </div>
      </Card>

      {/* Scan Section */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:bg-gradient-to-br pr:from-gray-100 pr:to-white">
        <div className="pr:p-6">
          <div className="pr:flex pr:items-center pr:justify-between">
            <div>
              <h3 className="pr:text-base pr:font-semibold pr:mb-2">
                {__('Link Scan', 'prorank-seo')}
              </h3>
              {lastScan && (
                <span className="pr:text-sm pr:text-gray-500">
                  {__('Last scan:', 'prorank-seo')} {lastScan.toLocaleDateString()} {lastScan.toLocaleTimeString()}
                </span>
              )}
            </div>
            <Button
              variant="primary"
              onClick={runLinkScan}
              disabled={scanning}
              className="pr:transition-all pr:duration-300 pr:border-none pr:text-white pr:px-5 pr:py-2 pr:text-sm pr:font-medium pr:rounded-md pr:shadow-xs"
              style={{
                background: scanning ? '#9ca3af' : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
                transition: 'all 0.3s ease',
              }}
            >
              {scanning ? __('Scanning...', 'prorank-seo') : __('Run Link Scan', 'prorank-seo')}
            </Button>
          </div>
          {scanning && (
            <div className="pr:mt-4 pr:transition-all pr:duration-300">
              <div className="pr:w-full pr:bg-gray-200 pr:rounded-full pr:h-2 pr:overflow-hidden">
                <div
                  className="pr:bg-gradient-to-r pr:from-purple-600 pr:to-purple-800 pr:h-full pr:transition-all pr:duration-300"
                  style={{ width: `${scanProgress}%` }}
                />
              </div>
              <span className="pr:text-sm pr:text-gray-500 pr:mt-2 pr:block">
                {__('Scanning posts...', 'prorank-seo')} {scanProgress}%
              </span>
            </div>
          )}
        </div>
      </Card>

      {/* Link Insights */}
      <div className="pr:bg-white pr:rounded-lg pr:p-5 pr:mb-5 pr:shadow-xs pr:transition-all pr:duration-300">
        <h3 className="pr:text-base pr:font-semibold pr:mb-4">
          {__('Link Insights', 'prorank-seo')}
        </h3>

        <div className="pr:grid pr:grid-cols-4 pr:gap-5">
          <div
            className="pr:text-center pr:cursor-pointer pr:p-2.5 pr:rounded-md pr:transition-all pr:duration-200 pr:hover:bg-gray-100"
            onClick={() => goToInternalTab('links-report')}
          >
            <div className="pr:text-2xl pr:font-semibold pr:text-gray-900">
              {stats.posts_crawled}
            </div>
            <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
              {__('Posts Crawled', 'prorank-seo')}
            </div>
          </div>

          <div
            className="pr:text-center pr:cursor-pointer pr:p-2.5 pr:rounded-md pr:transition-all pr:duration-200 pr:hover:bg-gray-100"
            onClick={() => goToInternalTab('links-report')}
          >
            <div className="pr:text-2xl pr:font-semibold pr:text-gray-900">
              {stats.link_clicks_tracked}
            </div>
            <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
              {__('Link Clicks Tracked', 'prorank-seo')}
            </div>
            {getChangeIndicator(stats.link_clicks_change)}
          </div>

          <div
            className="pr:text-center pr:cursor-pointer pr:p-2.5 pr:rounded-md pr:transition-all pr:duration-200 pr:hover:bg-gray-100"
            onClick={() => goToInternalTab('links-report')}
          >
            <div className="pr:text-2xl pr:font-semibold pr:text-red-500">
              {stats.orphaned_posts}
            </div>
            <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
              {__('Orphaned Posts', 'prorank-seo')}
            </div>
          </div>

          <div
            className="pr:text-center pr:cursor-pointer pr:p-2.5 pr:rounded-md pr:transition-all pr:duration-200 pr:hover:bg-gray-100"
            onClick={() => goToInternalTab('links-report')}
          >
            <div className="pr:text-2xl pr:font-semibold pr:text-amber-500">
              {stats.broken_links}
            </div>
            <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
              {__('Broken Links', 'prorank-seo')}
            </div>
          </div>
        </div>
      </div>

      {/* Link Health Metrics */}
      <div className="pr:grid pr:grid-cols-2 pr:gap-5 pr:mb-5">
        {/* Link Health Scores */}
        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:p-6">
            <h3 className="pr:text-base pr:font-semibold pr:mb-4">{__('Link Health', 'prorank-seo')}</h3>
            <div className="pr:grid pr:grid-cols-2 pr:gap-4">
              <div>
                <div className="pr:flex pr:items-center pr:justify-between pr:mb-3">
                  <span className="pr:text-sm">{__('Link Coverage', 'prorank-seo')}</span>
                  <span className="pr:text-sm pr:font-semibold">{stats.link_coverage.toFixed(2)}%</span>
                </div>
                <div className="pr:bg-gray-200 pr:h-2 pr:rounded-xs pr:overflow-hidden">
                  <div
                    className="pr:h-full pr:transition-all pr:duration-300"
                    style={{
                      width: `${stats.link_coverage}%`,
                      background: getHealthScoreColor(stats.link_coverage),
                    }}
                  />
                </div>
              </div>

              <div>
                <div className="pr:flex pr:items-center pr:justify-between pr:mb-3">
                  <span className="pr:text-sm">{__('Link Quality Score', 'prorank-seo')}</span>
                  <span className="pr:text-sm pr:font-semibold">{stats.link_quality_score}%</span>
                </div>
                <div className="pr:bg-gray-200 pr:h-2 pr:rounded-xs pr:overflow-hidden">
                  <div
                    className="pr:h-full pr:transition-all pr:duration-300"
                    style={{
                      width: `${stats.link_quality_score}%`,
                      background: getHealthScoreColor(stats.link_quality_score),
                    }}
                  />
                </div>
              </div>

              <div>
                <div className="pr:flex pr:items-center pr:justify-between pr:mb-3">
                  <span className="pr:text-sm">{__('External Site Focus', 'prorank-seo')}</span>
                  <span className="pr:text-sm pr:font-semibold">{stats.external_site_focus}%</span>
                </div>
                <div className="pr:bg-gray-200 pr:h-2 pr:rounded-xs pr:overflow-hidden">
                  <div
                    className="pr:h-full pr:transition-all pr:duration-300"
                    style={{
                      width: `${stats.external_site_focus}%`,
                      background: stats.external_site_focus > 70 ? '#ef4444' : getHealthScoreColor(100 - stats.external_site_focus),
                    }}
                  />
                </div>
              </div>

              <div>
                <div className="pr:flex pr:items-center pr:justify-between pr:mb-3">
                  <span className="pr:text-sm">{__('Anchor Length Score', 'prorank-seo')}</span>
                  <span className="pr:text-sm pr:font-semibold">{stats.anchor_length_score}%</span>
                  <button
                    className="pr:text-xs pr:text-purple-600 pr:underline pr:ml-2 pr:transition-all pr:duration-300 pr:hover:text-purple-700"
                    onClick={() => goToInternalTab('links-report')}
                  >
                    {__('Fix', 'prorank-seo')}
                  </button>
                </div>
                <div className="pr:bg-gray-200 pr:h-2 pr:rounded-xs pr:overflow-hidden">
                  <div
                    className="pr:h-full pr:transition-all pr:duration-300"
                    style={{
                      width: `${stats.anchor_length_score}%`,
                      background: getHealthScoreColor(stats.anchor_length_score),
                    }}
                  />
                </div>
              </div>
            </div>
          </div>
        </Card>

        {/* Most Linked To Domains */}
        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:p-6">
            <h3 className="pr:text-base pr:font-semibold pr:mb-4">{__('Most Linked To Domains', 'prorank-seo')}</h3>
            {stats.most_linked_domains.length > 0 ? (
              <div className="pr:space-y-2">
                {stats.most_linked_domains.map((domain, index) => (
                  <div
                    key={index}
                    className="pr:flex pr:items-center pr:justify-between pr:w-full pr:p-3 pr:rounded-xs pr:transition-all pr:duration-300"
                    style={{ background: index % 2 === 0 ? '#f9fafb' : '#fff' }}
                  >
                    <span className="pr:text-sm pr:font-mono">
                      {domain.domain || domain}
                    </span>
                    <span className="pr:text-sm pr:font-semibold pr:text-gray-500">
                      {domain.count || 0} links
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <Alert variant="info">
                {__('No external domains found. Run a scan to populate this data.', 'prorank-seo')}
              </Alert>
            )}
          </div>
        </Card>
      </div>

      {/* Link Distribution Chart */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300">
        <div className="pr:p-6">
          <h3 className="pr:text-base pr:font-semibold pr:mb-4">{__('Link Distribution', 'prorank-seo')}</h3>
          <div className="pr:flex pr:items-center pr:justify-around pr:py-5">
            <div className="pr:text-center">
              {renderProgressCircle(stats.link_health_details.total_internal,
                stats.link_health_details.total_internal + stats.link_health_details.total_external,
                '#10b981')}
              <span className="pr:text-sm pr:mt-2 pr:block">
                {__('Internal Links', 'prorank-seo')}
              </span>
              <span className="pr:text-sm pr:font-semibold pr:block">
                {stats.link_health_details.total_internal}
              </span>
            </div>

            <div className="pr:text-center">
              {renderProgressCircle(stats.link_health_details.total_external,
                stats.link_health_details.total_internal + stats.link_health_details.total_external,
                '#f59e0b')}
              <span className="pr:text-sm pr:mt-2 pr:block">
                {__('External Links', 'prorank-seo')}
              </span>
              <span className="pr:text-sm pr:font-semibold pr:block">
                {stats.link_health_details.total_external}
              </span>
            </div>

            <div className="pr:text-center">
              <div className="pr:w-[70px] pr:h-[70px] pr:rounded-full pr:flex pr:items-center pr:justify-center pr:text-xl pr:font-semibold pr:text-indigo-700 pr:transition-all pr:duration-300"
                style={{ background: 'linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%)' }}>
                {stats.link_health_details.avg_links_per_post.toFixed(1)}
              </div>
              <span className="pr:text-sm pr:mt-2 pr:block">
                {__('Avg Links/Post', 'prorank-seo')}
              </span>
            </div>
          </div>
        </div>
      </Card>

      {/* Ecosystem Integrations */}
      <Card className="pr:mb-5 pr:transition-all pr:duration-300 pr:border pr:border-gray-200">
        <div className="pr:p-6">
          <div className="pr:flex pr:items-start pr:justify-between pr:gap-4 pr:flex-wrap">
            <div>
              <h3 className="pr:text-base pr:font-semibold pr:mb-1">
                {__('Ecosystem Integrations', 'prorank-seo')}
              </h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Use adjacent ProRank modules to scale and validate internal-linking outcomes.', 'prorank-seo')}
              </p>
            </div>
            <Button
              size="sm"
              variant="secondary"
              onClick={() => setShowEcosystemPanel((prev) => !prev)}
            >
              {showEcosystemPanel
                ? __('Hide Integrations', 'prorank-seo')
                : __('Show Integrations', 'prorank-seo')}
            </Button>
          </div>

          {showEcosystemPanel && (
            <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:xl:grid-cols-4 pr:gap-3 pr:mt-4">
              <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:p-3 pr:bg-gray-50">
                <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{__('Internal Linking Settings', 'prorank-seo')}</div>
                <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {linkingSettings.enabled
                    ? __('Suggestion engine is enabled and ready for manual review.', 'prorank-seo')
                    : __('Enable internal linking suggestions before running scans.', 'prorank-seo')}
                </div>
                <Button size="sm" variant="secondary" className="pr:mt-3" onClick={() => goToInternalTab('settings')}>
                  {__('Open Settings', 'prorank-seo')}
                </Button>
              </div>

              <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:p-3 pr:bg-gray-50">
                <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{__('Suggestions Workflow', 'prorank-seo')}</div>
                <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {lastScan
                    ? __('Latest scan data is available for review and action.', 'prorank-seo')
                    : __('Run a fresh scan to populate orphan and broken-link opportunities.', 'prorank-seo')}
                </div>
                <Button size="sm" variant="secondary" className="pr:mt-3" onClick={() => goToInternalTab('links-report')}>
                  {__('Open Links Report', 'prorank-seo')}
                </Button>
              </div>

              <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:p-3 pr:bg-gray-50">
                <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{__('Site Audit', 'prorank-seo')}</div>
                <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {lastScan
                    ? __('Audit is ready for cross-checking link issues.', 'prorank-seo')
                    : __('Run a scan first to align with audit priorities.', 'prorank-seo')}
                </div>
                <Button size="sm" variant="secondary" className="pr:mt-3" onClick={() => openAdminModule('site-audit')}>
                  {__('Open Site Audit', 'prorank-seo')}
                </Button>
              </div>

              <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:p-3 pr:bg-gray-50">
                <div className="pr:text-sm pr:font-semibold pr:text-gray-900">{__('On-Page SEO', 'prorank-seo')}</div>
                <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {__('Align titles, schema, and content intent with your linking strategy.', 'prorank-seo')}
                </div>
                <Button size="sm" variant="secondary" className="pr:mt-3" onClick={() => openAdminModule('on-page-seo')}>
                  {__('Open On-Page SEO', 'prorank-seo')}
                </Button>
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* Quick Actions */}
      <div className="pr:grid pr:grid-cols-4 pr:gap-4">
        <button
          onClick={() => goToInternalTab('links-report', { filter: 'orphans' })}
          className="pr:p-3 pr:text-center pr:border pr:border-gray-200 pr:rounded-lg pr:bg-white pr:transition-all pr:duration-300 pr:hover:shadow-md pr:hover:border-purple-200"
        >
          <div className="pr:space-y-2">
            <svg className="pr:w-6 pr:h-6 pr:mx-auto pr:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span className="pr:text-sm">{__('Fix Orphans', 'prorank-seo')}</span>
          </div>
        </button>

        <button
          onClick={() => goToInternalTab('broken-links')}
          className="pr:p-3 pr:text-center pr:border pr:border-gray-200 pr:rounded-lg pr:bg-white pr:transition-all pr:duration-300 pr:hover:shadow-md pr:hover:border-purple-200"
        >
          <div className="pr:space-y-2">
            <svg className="pr:w-6 pr:h-6 pr:mx-auto pr:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <span className="pr:text-sm">{__('Fix Broken', 'prorank-seo')}</span>
          </div>
        </button>

        <button
          onClick={() => goToInternalTab('auto-linking')}
          className="pr:p-3 pr:text-center pr:border pr:border-gray-200 pr:rounded-lg pr:bg-white pr:transition-all pr:duration-300 pr:hover:shadow-md pr:hover:border-purple-200"
        >
          <div className="pr:space-y-2">
            <svg className="pr:w-6 pr:h-6 pr:mx-auto pr:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            <span className="pr:text-sm">{__('Auto Link', 'prorank-seo')}</span>
          </div>
        </button>

        <button
          onClick={() => goToInternalTab('links-report')}
          className="pr:p-3 pr:text-center pr:border pr:border-gray-200 pr:rounded-lg pr:bg-white pr:transition-all pr:duration-300 pr:hover:shadow-md pr:hover:border-purple-200"
        >
          <div className="pr:space-y-2">
            <svg className="pr:w-6 pr:h-6 pr:mx-auto pr:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
            </svg>
            <span className="pr:text-sm">{__('Analyze', 'prorank-seo')}</span>
          </div>
        </button>
      </div>
    </div>
  );
};

export default LinkingDashboard;
