'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  CheckCircle2, AlertTriangle, XCircle, Activity, Shield, Zap,
  TestTube, Bug, Clock, TrendingUp, Download,
  ChevronDown, Eye, RefreshCw, Play, ArrowRight, BookOpen, BarChart3
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { normalizePerformanceMetrics, getLangBaseline } from '../lib/perf-metrics';

interface Props {
  projectId: string;
  onNavigate: (section: string, projectId?: string) => void;
  maxReachedStep?: number;
  project?: Project | null;
}

interface TestResult {
  id: string;
  name: string;
  type: 'unit' | 'integration' | 'e2e';
  status: 'passed' | 'failed' | 'skipped';
  duration: string;
  file: string;
  error?: string;
}

interface SecurityIssue {
  id: string;
  severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
  title: string;
  description: string;
  location: string;
  cwe?: string;
  recommendation?: string;
}

interface QualityGate {
  id: string;
  name: string;
  status: 'passed' | 'failed' | 'warning';
  value: string;
  threshold: string;
}

function langLabel(id: string) {
  const s = (id || '').toLowerCase().replace(/\s+/g, '-');
  const map: Record<string, string> = {
    cobol: 'COBOL', java: 'Java', python: 'Python', csharp: 'C#',
    'c#': 'C#', javascript: 'JavaScript', typescript: 'TypeScript', cpp: 'C++',
    fortran: 'Fortran', rpg: 'RPG', pl1: 'PL/I', 'pl/i': 'PL/I', ada: 'Ada',
    kotlin: 'Kotlin', scala: 'Scala', go: 'Go', rust: 'Rust', php: 'PHP',
    ruby: 'Ruby', swift: 'Swift', vb6: 'VB6', vbnet: 'VB.NET',
    'cobol-85': 'COBOL-85', 'java-22': 'Java 22',
  };
  return (map[s] ?? id) || '—';
}


export default function VerificationDashboard({ projectId, onNavigate, maxReachedStep = 0, project: propProject }: Props) {
  const [selectedTab, setSelectedTab] = useState('quality');
  const [expandedSection, setExpandedSection] = useState<string | null>(null);

  const project = propProject;
  const isDraft = !project || (project.status === 'draft' && maxReachedStep < 5);

  // Read results from project config
  const rootCfg = (project?.config as Record<string, unknown> | undefined) ?? {};
  const cfg = (rootCfg.analysisResults as Record<string, unknown> | undefined) ?? {};
  const vcfg = (rootCfg.verification as Record<string, unknown> | undefined) ?? {};
  const verificationCfg = (cfg.verification as { metrics?: { overallScore?: number; syntaxScore?: number } } | undefined) ?? {};
  const testsCfg = (cfg.tests as { metrics?: { tests?: number; passed?: number; failed?: number; skipped?: number } } | undefined) ?? {};
  const performanceCfg = (cfg.performance as { metrics?: unknown; legacy?: { throughput?: number; latency?: number; memoryMB?: number } } | undefined) ?? {};
  const securityCfg = (cfg.security as { metrics?: { score?: number; critical?: number; high?: number; medium?: number } } | undefined) ?? {};
  const testGenerationCfg = (cfg.testGeneration as { metrics?: { coverage?: number } } | undefined) ?? {};
  const documentationCfg = (cfg.documentation as { metrics?: { pages?: number; examples?: number; apis?: number } } | undefined) ?? {};

  const verifMetrics = verificationCfg.metrics;
  const testMetrics = testsCfg.metrics;
  const perfMetrics = performanceCfg.metrics;
  const perfM = normalizePerformanceMetrics(perfMetrics);
  const secMetrics = securityCfg.metrics;
  const testGenMetrics = testGenerationCfg.metrics;
  const docMetrics = documentationCfg.metrics;
  const translation = cfg?.translation as Record<string, unknown> | undefined;
  const artifacts = translation?.artifacts as Record<string, unknown> | undefined;
  const archStats = artifacts?.archStats as Record<string, number> | undefined;
  const srcLang = langLabel(project?.sourceLanguage ?? '');
  const tgtLang = langLabel(project?.targetLanguage ?? '');
  const totalTests = testMetrics?.tests ?? 0;
  const passedMetricTests = testMetrics?.passed ?? 0;
  const failedMetricTests = testMetrics?.failed ?? 0;
  const skippedMetricTests = testMetrics?.skipped ?? 0;

  // Score cards
  const overallScore = verifMetrics?.overallScore ?? 0;
  const functionalParity = totalTests > 0
    ? Math.round((passedMetricTests / totalTests) * 1000) / 10
    : 0;
  const performanceScore = perfM.throughput != null ? Math.min(100, Math.round(perfM.throughput / 15)) : 0;
  const securityScore = secMetrics?.score ?? 0;
  const testCoverage = testGenMetrics?.coverage ?? 0;

  const testResults: TestResult[] = Array.isArray(vcfg?.testResults) ? vcfg.testResults : [];

  const securityIssues: SecurityIssue[] = Array.isArray(vcfg?.securityIssues) ? vcfg.securityIssues : [];

  const qualityGates: QualityGate[] = Array.isArray(vcfg?.qualityGates) && vcfg.qualityGates.length > 0
    ? vcfg.qualityGates
    : [
        { id: 'qg1', name: 'Functional Parity', status: functionalParity >= 95 ? 'passed' : 'warning', value: `${functionalParity}%`, threshold: '≥ 95%' },
        { id: 'qg2', name: 'Test Coverage', status: testCoverage >= 80 ? 'passed' : 'warning', value: `${testCoverage}%`, threshold: '≥ 80%' },
        { id: 'qg3', name: 'Security Score', status: securityScore >= 90 ? 'passed' : 'warning', value: `${securityScore}/100`, threshold: '≥ 90' },
        { id: 'qg4', name: 'Zero Critical Vulnerabilities', status: (secMetrics?.critical ?? 0) === 0 ? 'passed' : 'failed', value: `${secMetrics?.critical ?? 0} found`, threshold: '= 0' },
        { id: 'qg5', name: 'Syntax Correctness', status: (verifMetrics?.syntaxScore ?? 0) >= 100 ? 'passed' : 'warning', value: `${verifMetrics?.syntaxScore ?? 0}%`, threshold: '= 100%' },
        { id: 'qg6', name: 'Business Rule Coverage', status: 'warning', value: '—', threshold: 'From analysis' },
        { id: 'qg7', name: 'Build / compile', status: 'warning', value: '—', threshold: 'No errors' },
        { id: 'qg8', name: 'Performance Baseline', status: performanceScore >= 80 ? 'passed' : 'warning', value: perfM.throughput != null ? `${perfM.throughput} tps` : '—', threshold: '≥ 1000 tps' },
      ];

  const passedTests = testResults.length > 0 ? testResults.filter(t => t.status === 'passed').length : passedMetricTests;
  const failedTests = testResults.length > 0 ? testResults.filter(t => t.status === 'failed').length : failedMetricTests;
  const skippedTests = testResults.length > 0 ? testResults.filter(t => t.status === 'skipped').length : skippedMetricTests;
  const passedGates = qualityGates.filter(g => g.status === 'passed').length;

  const countSev = (sev: SecurityIssue['severity']) => securityIssues.filter(i => i.severity === sev).length;
  type SecExt = { critical?: number; high?: number; medium?: number };
  const secM = secMetrics as SecExt | undefined;
  const criticalCount = secM?.critical ?? countSev('critical');
  const highCount = secM?.high ?? countSev('high');
  const mediumCount = secM?.medium ?? countSev('medium');

  const businessRules = Array.isArray(translation?.businessRules) ? translation.businessRules as unknown[] : [];
  const rulesDocCount = businessRules.length;

  const docCoveragePct =
    testGenMetrics?.coverage != null
      ? `${testGenMetrics.coverage}%`
      : project?.testCoverage != null && project.testCoverage > 0
        ? `${project.testCoverage}%`
        : '—';

  const vcfgRec = vcfg as Record<string, unknown> | undefined;
  const docToc: string[] = Array.isArray(vcfgRec?.documentationToc)
    ? (vcfgRec.documentationToc as string[])
    : [
        '1. Executive Summary',
        `2. Source system (${srcLang})`,
        `3. Target architecture (${tgtLang})`,
        '4. File-by-file translation mapping',
        '5. Business rules & validation',
        '6. Data type mapping',
        '7. Dependencies & integrations',
        '8. Test strategy & coverage',
        '9. Security assessment',
        '10. Performance comparison',
        '11. Known limitations & recommendations',
        '12. Appendix',
      ];

  const docCards = [
    {
      label: 'API doc coverage',
      value: docCoveragePct,
      desc: testGenMetrics?.coverage != null ? 'From generated test metrics' : 'From project test coverage when available',
    },
    {
      label: 'Migration report',
      value: docMetrics?.pages != null ? `${docMetrics.pages} pages` : '—',
      desc: 'Documentation metrics in analysis results',
    },
    {
      label: 'Code examples',
      value: docMetrics?.examples != null ? String(docMetrics.examples) : '—',
      desc: 'Examples referenced in generated docs',
    },
    {
      label: 'Business rules doc',
      value: rulesDocCount > 0 ? `${rulesDocCount} rules` : '—',
      desc: rulesDocCount > 0 ? 'Extracted from translation analysis' : 'Run migration to extract rules',
    },
    {
      label: 'API reference',
      value:
        archStats?.services != null
          ? `${archStats.services} services`
          : docMetrics?.apis != null
            ? `${docMetrics.apis} APIs`
            : '—',
      desc: 'From architecture stats or documentation metrics',
    },
    {
      label: 'Changelog',
      value: project?.completedAt
        ? `Completed ${new Date(project.completedAt).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}`
        : project?.updatedAt
          ? `Updated ${new Date(project.updatedAt).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}`
          : '—',
      desc: 'From project timeline',
    },
  ];

  const docSectionComplete =
    !!(docMetrics?.pages || docMetrics?.examples || artifacts?.documentation || translation?.documentation);

  const severityColor = (severity: string) => {
    switch (severity) {
      case 'critical': return 'text-red-400 bg-red-500/15 border-red-500/30';
      case 'high': return 'text-orange-400 bg-orange-500/15 border-orange-500/30';
      case 'medium': return 'text-amber-400 bg-amber-500/15 border-amber-500/30';
      case 'low': return 'text-blue-400 bg-blue-500/15 border-blue-500/30';
      case 'info': return 'text-muted bg-surface-light border-border';
      default: return 'text-muted bg-surface-light border-border';
    }
  };

  const statusIcon = (status: string) => {
    switch (status) {
      case 'passed': return <CheckCircle2 className="w-4 h-4 text-success" />;
      case 'failed': return <XCircle className="w-4 h-4 text-danger" />;
      case 'skipped': return <AlertTriangle className="w-4 h-4 text-amber-400" />;
      case 'warning': return <AlertTriangle className="w-4 h-4 text-amber-400" />;
      default: return <Activity className="w-4 h-4 text-muted" />;
    }
  };

  if (isDraft) {
    return (
      <div className="space-y-6">
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-foreground">Verification & Quality Assurance</h2>
            <p className="text-sm text-muted mt-1">Comprehensive verification of migrated code</p>
          </div>
        </motion.div>
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="glass-light rounded-lg p-12 text-center">
          <div className="w-20 h-20 rounded-full gradient-accent flex items-center justify-center mx-auto mb-6">
            <Play className="w-10 h-10 text-white" />
          </div>
          <h3 className="text-xl font-semibold text-foreground mb-3">Verification Not Started</h3>
          <p className="text-sm text-muted mb-8 max-w-md mx-auto">
            Connect a repository and run the migration process to see verification results, test coverage, and security analysis.
          </p>
          <button onClick={() => onNavigate('repository', projectId)} className="px-8 py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer mx-auto glow-accent">
            <Play className="w-5 h-5" /> Connect Repository
          </button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Verification & Quality Assurance</h2>
          <p className="text-sm text-muted mt-1">{passedGates}/{qualityGates.length} quality gates passed &middot; {passedTests + failedTests + skippedTests} tests executed</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => onNavigate('export', projectId)}
            className="px-3 py-1.5 rounded-lg border border-border text-xs font-semibold hover:bg-surface-light transition-colors flex items-center gap-1.5 cursor-pointer"
          >
            <Download className="w-3.5 h-3.5" /> Export
          </button>
          <button onClick={() => onNavigate('security', projectId)} className="px-4 py-1.5 rounded-lg gradient-accent text-white text-xs font-semibold hover:opacity-90 transition-opacity flex items-center gap-1.5 cursor-pointer">
            Security &amp; Compliance <ArrowRight className="w-3.5 h-3.5" />
          </button>
        </div>
      </motion.div>

      {/* Score Cards */}
      <div className="grid grid-cols-6 gap-3">
        {[
          { label: 'Overall Score', value: overallScore, suffix: '%', icon: Activity, color: 'text-accent-light', bg: 'bg-accent/10' },
          { label: 'Functional Parity', value: functionalParity, suffix: '%', icon: CheckCircle2, color: 'text-success', bg: 'bg-success/10' },
          { label: 'Test Coverage', value: testCoverage, suffix: '%', icon: TestTube, color: 'text-amber-400', bg: 'bg-amber-500/10' },
          { label: 'Security', value: securityScore, suffix: '/100', icon: Shield, color: 'text-pink-400', bg: 'bg-pink-500/10' },
          { label: 'Performance', value: performanceScore, suffix: '%', icon: Zap, color: 'text-cyan-400', bg: 'bg-cyan-500/10' },
          { label: 'Quality Gates', value: passedGates, suffix: `/${qualityGates.length}`, icon: BarChart3, color: 'text-purple-400', bg: 'bg-purple-500/10' },
        ].map((m) => (
          <motion.div key={m.label} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="glass rounded-xl p-3.5">
            <div className="flex items-center gap-2 mb-2">
              <div className={`w-7 h-7 rounded-lg ${m.bg} flex items-center justify-center`}>
                <m.icon className={`w-3.5 h-3.5 ${m.color}`} />
              </div>
              <span className="text-[10px] text-muted uppercase tracking-wider leading-tight">{m.label}</span>
            </div>
            <p className="text-xl font-bold text-foreground">{m.value}<span className="text-sm font-normal text-muted">{m.suffix}</span></p>
          </motion.div>
        ))}
      </div>

      {/* Tabs */}
      <div className="glass rounded-xl p-1.5">
        <div className="flex gap-1">
          {[
            { id: 'quality', label: 'Quality Gates', icon: BarChart3 },
            { id: 'functional', label: 'Test Results', icon: TestTube },
            { id: 'security', label: 'Security Scan', icon: Shield },
            { id: 'performance', label: 'Performance', icon: Zap },
            { id: 'documentation', label: 'Documentation', icon: BookOpen },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setSelectedTab(tab.id)}
              className={`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs transition-all cursor-pointer ${
                selectedTab === tab.id ? 'bg-accent/15 text-accent-light font-semibold' : 'text-muted hover:text-foreground hover:bg-surface-light'
              }`}
            >
              <tab.icon className="w-3.5 h-3.5" />
              <span>{tab.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Quality Gates Tab */}
      {selectedTab === 'quality' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="glass rounded-xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-accent-light" /> Quality Gate Results
            </h3>
            <span className={`text-xs font-bold px-2.5 py-1 rounded-full ${passedGates === qualityGates.length ? 'bg-success/15 text-success' : 'bg-amber-500/15 text-amber-400'}`}>
              {passedGates === qualityGates.length ? 'ALL PASSED' : `${passedGates}/${qualityGates.length} PASSED`}
            </span>
          </div>
          <div className="space-y-2">
            {qualityGates.map((gate) => (
              <div key={gate.id} className={`flex items-center gap-3 p-3 rounded-lg transition-all ${
                gate.status === 'passed' ? 'glass-light' : gate.status === 'warning' ? 'bg-amber-500/5 border border-amber-500/20' : 'bg-red-500/5 border border-red-500/20'
              }`}>
                {statusIcon(gate.status)}
                <span className="text-xs font-medium text-foreground flex-1">{gate.name}</span>
                <span className="text-xs font-mono text-foreground">{gate.value}</span>
                <span className="text-[10px] text-muted font-mono w-20 text-right">{gate.threshold}</span>
              </div>
            ))}
          </div>
        </motion.div>
      )}

      {/* Functional Tests Tab */}
      {selectedTab === 'functional' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          {/* Summary bar */}
          <div className="glass rounded-xl p-4">
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-success" />
                <span className="text-sm font-medium text-foreground">{passedTests} passed</span>
              </div>
              <div className="flex items-center gap-2">
                <XCircle className="w-4 h-4 text-danger" />
                <span className="text-sm font-medium text-foreground">{failedTests} failed</span>
              </div>
              {skippedTests > 0 && (
                <div className="flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4 text-amber-400" />
                  <span className="text-sm font-medium text-foreground">{skippedTests} skipped</span>
                </div>
              )}
              <div className="ml-auto flex items-center gap-2">
                {testResults.length > 0 ? (
                  <>
                    <div className="w-48 h-2 rounded-full bg-surface-light overflow-hidden flex">
                      <div className="h-full bg-success rounded-l-full" style={{ width: `${(passedTests / testResults.length) * 100}%` }} />
                      <div className="h-full bg-danger" style={{ width: `${(failedTests / testResults.length) * 100}%` }} />
                    </div>
                    <span className="text-[10px] text-muted font-mono">{Math.round((passedTests / testResults.length) * 100)}%</span>
                  </>
                ) : (
                  <span className="text-[10px] text-muted">No saved test results</span>
                )}
              </div>
            </div>
          </div>

          {/* Test list */}
          <div className="glass rounded-xl p-4">
            <div className="space-y-1.5">
              {testResults.length === 0 && (
                <p className="text-sm text-muted py-4 text-center">No test run data yet. Run a migration to populate verification results for this project.</p>
              )}
              {testResults.map((test) => (
                <div key={test.id}>
                  <div
                    className={`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer transition-all ${
                      test.status === 'failed' ? 'bg-red-500/5 hover:bg-red-500/10' : 'hover:bg-white/5'
                    }`}
                    onClick={() => setExpandedSection(expandedSection === test.id ? null : test.id)}
                  >
                    {statusIcon(test.status)}
                    <span className="text-xs text-foreground flex-1 truncate">{test.name}</span>
                    <span className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${
                      test.type === 'unit' ? 'bg-blue-500/15 text-blue-400' :
                      test.type === 'integration' ? 'bg-purple-500/15 text-purple-400' :
                      'bg-pink-500/15 text-pink-400'
                    }`}>{test.type}</span>
                    <span className="text-[10px] text-muted font-mono w-12 text-right">{test.duration}</span>
                    <ChevronDown className={`w-3.5 h-3.5 text-muted transition-transform ${expandedSection === test.id ? 'rotate-180' : ''}`} />
                  </div>
                  <AnimatePresence>
                    {expandedSection === test.id && (
                      <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }} className="overflow-hidden">
                        <div className="ml-7 p-3 text-xs text-muted space-y-1.5 border-l-2 border-border">
                          <p><span className="text-foreground">File:</span> <span className="font-mono">{test.file}</span></p>
                          {test.error && (
                            <>
                              <p><span className="text-danger">Error:</span> {test.error}</p>
                            </>
                          )}
                          {!test.error && <p className="text-success">Test passed successfully</p>}
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              ))}
            </div>
          </div>
        </motion.div>
      )}

      {/* Security Scan Tab */}
      {selectedTab === 'security' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          {/* Summary */}
          <div className="glass rounded-xl p-4">
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2">
                <Shield className="w-4 h-4 text-success" />
                <span className="text-sm font-medium text-foreground">Score: {securityScore}/100</span>
              </div>
              <div className="flex items-center gap-4 text-xs text-muted">
                <span className="text-red-400">{criticalCount} critical</span>
                <span className="text-orange-400">{highCount} high</span>
                <span className="text-amber-400">{mediumCount} medium</span>
                <span className="text-blue-400">{securityIssues.filter(i => i.severity === 'low').length} low</span>
                <span>{securityIssues.filter(i => i.severity === 'info').length} info</span>
              </div>
            </div>
          </div>

          {/* Issues */}
          <div className="glass rounded-xl p-4 space-y-3">
            {securityIssues.map((issue) => (
              <div key={issue.id} className={`p-4 rounded-lg border ${severityColor(issue.severity)}`}
                   onClick={() => setExpandedSection(expandedSection === issue.id ? null : issue.id)}>
                <div className="flex items-start gap-3 cursor-pointer">
                  <Bug className="w-4 h-4 mt-0.5 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className={`text-[10px] px-2 py-0.5 rounded font-medium uppercase ${severityColor(issue.severity)}`}>{issue.severity}</span>
                      {issue.cwe && <span className="text-[10px] text-muted font-mono">{issue.cwe}</span>}
                    </div>
                    <p className="text-xs font-medium text-foreground">{issue.title}</p>
                    <p className="text-[11px] text-muted mt-1">{issue.description}</p>
                    <p className="text-[10px] text-muted font-mono mt-1.5">{issue.location}</p>
                  </div>
                  <ChevronDown className={`w-3.5 h-3.5 text-muted shrink-0 transition-transform ${expandedSection === issue.id ? 'rotate-180' : ''}`} />
                </div>
                <AnimatePresence>
                  {expandedSection === issue.id && issue.recommendation && (
                    <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }} className="overflow-hidden">
                      <div className="mt-3 pt-3 border-t border-border">
                        <p className="text-[10px] text-muted uppercase tracking-wider mb-1">Recommendation</p>
                        <p className="text-xs text-foreground">{issue.recommendation}</p>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ))}
            {securityIssues.length === 0 && (
              <div className="text-center py-8">
                <Shield className="w-8 h-8 text-success mx-auto mb-2" />
                <p className="text-sm text-foreground font-medium">No security issues found</p>
              </div>
            )}
          </div>
        </motion.div>
      )}

      {/* Performance Tab */}
      {selectedTab === 'performance' && (() => {
        const srcKey = (project?.sourceLanguage ?? '').toLowerCase().replace(/\s+/g, '-');
        const tgtKey = (project?.targetLanguage ?? '').toLowerCase().replace(/\s+/g, '-');
        const srcB = getLangBaseline(srcKey);
        const tgtB = getLangBaseline(tgtKey);

        const throughputGain = srcB.throughput > 0 ? Math.round((tgtB.throughput / srcB.throughput - 1) * 100) : 0;
        const latencyDrop   = srcB.latency > 0    ? Math.round((1 - tgtB.latency / srcB.latency) * 100)    : 0;
        const memoryDrop    = srcB.memoryMB > 0   ? Math.round((1 - tgtB.memoryMB / srcB.memoryMB) * 100)  : 0;
        const startupDrop   = srcB.startupMs > 0  ? Math.round((1 - tgtB.startupMs / srcB.startupMs) * 100): 0;
        const p99Drop       = srcB.p99Latency > 0 ? Math.round((1 - tgtB.p99Latency / srcB.p99Latency) * 100): 0;

        const srcEfficiency = srcB.memoryMB > 0 ? Math.round((srcB.throughput / srcB.memoryMB) * 10) / 10 : 0;
        const tgtEfficiency = tgtB.memoryMB > 0 ? Math.round((tgtB.throughput / tgtB.memoryMB) * 10) / 10 : 0;
        const effGain = srcEfficiency > 0 ? Math.round((tgtEfficiency / srcEfficiency - 1) * 100) : 0;

        // Bar chart helper — returns width% for legacy and modern bars
        function barWidths(legacyVal: number, modernVal: number) {
          const max = Math.max(legacyVal, modernVal);
          if (max === 0) return { legacy: 0, modern: 0 };
          return { legacy: Math.round((legacyVal / max) * 100), modern: Math.round((modernVal / max) * 100) };
        }

        const tBars = barWidths(srcB.throughput, tgtB.throughput);
        const lBars = barWidths(srcB.latency, tgtB.latency);
        const mBars = barWidths(srcB.memoryMB, tgtB.memoryMB);

        const fmtNum = (n: number) => n >= 1_000 ? `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n);

        const improvementBadge = (pct: number, higherIsBetter = true) => {
          const good = higherIsBetter ? pct > 0 : pct > 0;
          const label = higherIsBetter
            ? `${pct > 0 ? '+' : ''}${pct}%`
            : pct >= 0 ? `-${pct}%` : `+${Math.abs(pct)}%`;
          return (
            <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${good ? 'bg-success/15 text-success' : 'bg-red-500/15 text-red-400'}`}>
              {label}
            </span>
          );
        };

        return (
          <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">

            {/* Summary banner */}
            <div className="glass rounded-xl p-5">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                  <Zap className="w-4 h-4 text-accent-light" /> Performance — {srcLang} vs {tgtLang}
                </h3>
                <span className="text-[10px] text-muted">Source: TechEmpower r22 · language-level baselines</span>
              </div>
              <div className="grid grid-cols-4 gap-3">
                {[
                  { label: 'Throughput gain', value: `+${throughputGain}%`, color: 'text-success', bg: 'bg-success/10' },
                  { label: 'Latency reduction', value: latencyDrop >= 0 ? `-${latencyDrop}%` : `+${Math.abs(latencyDrop)}%`, color: latencyDrop >= 0 ? 'text-success' : 'text-red-400', bg: latencyDrop >= 0 ? 'bg-success/10' : 'bg-red-500/10' },
                  { label: 'Memory reduction', value: memoryDrop >= 0 ? `-${memoryDrop}%` : `+${Math.abs(memoryDrop)}%`, color: memoryDrop >= 0 ? 'text-success' : 'text-red-400', bg: memoryDrop >= 0 ? 'bg-success/10' : 'bg-red-500/10' },
                  { label: 'Efficiency gain', value: `+${effGain}%`, color: 'text-cyan-400', bg: 'bg-cyan-500/10' },
                ].map(c => (
                  <div key={c.label} className={`${c.bg} rounded-lg p-3 text-center`}>
                    <p className={`text-xl font-bold ${c.color}`}>{c.value}</p>
                    <p className="text-[10px] text-muted mt-0.5">{c.label}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Bar chart comparisons */}
            <div className="glass rounded-xl p-5 space-y-5">
              <h4 className="text-xs font-semibold text-foreground flex items-center gap-2">
                <BarChart3 className="w-3.5 h-3.5 text-accent-light" /> Core Metrics
              </h4>

              {/* Throughput */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <TrendingUp className="w-3.5 h-3.5 text-accent-light" />
                    <span className="text-xs font-medium text-foreground">Throughput</span>
                  </div>
                  {improvementBadge(throughputGain, true)}
                </div>
                <div className="space-y-2">
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-muted">{srcLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{srcB.throughput.toLocaleString()} req/s</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-muted/40 transition-all" style={{ width: `${tBars.legacy}%` }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-success">{tgtLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{tgtB.throughput.toLocaleString()} req/s</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-success transition-all" style={{ width: `${tBars.modern}%` }} />
                    </div>
                  </div>
                </div>
              </div>

              <div className="border-t border-border" />

              {/* Latency */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <Clock className="w-3.5 h-3.5 text-accent-light" />
                    <span className="text-xs font-medium text-foreground">Response Latency (p50)</span>
                  </div>
                  {improvementBadge(latencyDrop, false)}
                </div>
                <div className="space-y-2">
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-muted">{srcLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{srcB.latency} ms</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-amber-500/60 transition-all" style={{ width: `${lBars.legacy}%` }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-success">{tgtLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{tgtB.latency} ms</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-success transition-all" style={{ width: `${lBars.modern}%` }} />
                    </div>
                  </div>
                </div>
              </div>

              <div className="border-t border-border" />

              {/* Memory */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <Activity className="w-3.5 h-3.5 text-accent-light" />
                    <span className="text-xs font-medium text-foreground">Memory Usage (idle RSS)</span>
                  </div>
                  {improvementBadge(memoryDrop, false)}
                </div>
                <div className="space-y-2">
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-muted">{srcLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{srcB.memoryMB} MB</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-pink-500/60 transition-all" style={{ width: `${mBars.legacy}%` }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] text-success">{tgtLang}</span>
                      <span className="text-[10px] font-mono text-foreground">{tgtB.memoryMB} MB</span>
                    </div>
                    <div className="h-2 rounded-full bg-surface-light overflow-hidden">
                      <div className="h-full rounded-full bg-success transition-all" style={{ width: `${mBars.modern}%` }} />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Additional metrics grid */}
            <div className="grid grid-cols-2 gap-4">

              {/* p99 Latency */}
              <div className="glass rounded-xl p-4">
                <h4 className="text-xs font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Clock className="w-3.5 h-3.5 text-purple-400" /> Tail Latency (p99)
                </h4>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted">{srcLang}</span>
                    <span className="text-xs font-mono text-foreground">{srcB.p99Latency} ms</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-success">{tgtLang}</span>
                    <span className="text-xs font-mono text-foreground">{tgtB.p99Latency} ms</span>
                  </div>
                  <div className="pt-2 border-t border-border flex items-center justify-between">
                    <span className="text-[10px] text-muted">Improvement</span>
                    {improvementBadge(p99Drop, false)}
                  </div>
                </div>
              </div>

              {/* Startup time */}
              <div className="glass rounded-xl p-4">
                <h4 className="text-xs font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Zap className="w-3.5 h-3.5 text-cyan-400" /> Cold Start
                </h4>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted">{srcLang}</span>
                    <span className="text-xs font-mono text-foreground">
                      {srcB.startupMs >= 1_000 ? `${(srcB.startupMs / 1_000).toFixed(1)}s` : `${srcB.startupMs}ms`}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-success">{tgtLang}</span>
                    <span className="text-xs font-mono text-foreground">
                      {tgtB.startupMs >= 1_000 ? `${(tgtB.startupMs / 1_000).toFixed(1)}s` : `${tgtB.startupMs}ms`}
                    </span>
                  </div>
                  <div className="pt-2 border-t border-border flex items-center justify-between">
                    <span className="text-[10px] text-muted">Improvement</span>
                    {improvementBadge(startupDrop, false)}
                  </div>
                </div>
              </div>

              {/* Concurrency */}
              <div className="glass rounded-xl p-4">
                <h4 className="text-xs font-semibold text-foreground mb-3 flex items-center gap-2">
                  <RefreshCw className="w-3.5 h-3.5 text-amber-400" /> Concurrency
                </h4>
                <div className="space-y-3">
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-muted">{srcLang}</span>
                      <span className="text-xs font-mono text-foreground">{fmtNum(srcB.concurrency)} conns</span>
                    </div>
                    <p className="text-[10px] text-muted">{srcB.concurrencyModel}</p>
                  </div>
                  <div className="border-t border-border pt-2">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-success">{tgtLang}</span>
                      <span className="text-xs font-mono text-foreground">{fmtNum(tgtB.concurrency)} conns</span>
                    </div>
                    <p className="text-[10px] text-muted">{tgtB.concurrencyModel}</p>
                  </div>
                </div>
              </div>

              {/* Efficiency */}
              <div className="glass rounded-xl p-4">
                <h4 className="text-xs font-semibold text-foreground mb-3 flex items-center gap-2">
                  <TrendingUp className="w-3.5 h-3.5 text-green-400" /> Throughput Efficiency
                </h4>
                <p className="text-[10px] text-muted mb-3">Requests per second per MB of RAM</p>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted">{srcLang}</span>
                    <span className="text-xs font-mono text-foreground">{srcEfficiency} req/s/MB</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-success">{tgtLang}</span>
                    <span className="text-xs font-mono text-foreground">{tgtEfficiency} req/s/MB</span>
                  </div>
                  <div className="pt-2 border-t border-border flex items-center justify-between">
                    <span className="text-[10px] text-muted">Improvement</span>
                    {improvementBadge(effGain, true)}
                  </div>
                </div>
              </div>
            </div>

            {/* Benchmark source */}
            <div className="glass-light rounded-lg px-4 py-3 flex items-start gap-3">
              <Eye className="w-3.5 h-3.5 text-muted shrink-0 mt-0.5" />
              <p className="text-[10px] text-muted leading-relaxed">
                Figures are language-level reference baselines from <span className="text-foreground font-medium">TechEmpower Framework Benchmarks r22</span> (JSON serialisation, physical hardware).
                Startup times sourced from vendor documentation and community benchmarks.
                Actual production numbers will vary based on hardware, framework version, query complexity, and tuning.
              </p>
            </div>

          </motion.div>
        );
      })()}

      {/* Documentation Tab */}
      {selectedTab === 'documentation' && (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          <div className="glass rounded-xl p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-accent-light" /> Auto-Generated Documentation
              </h3>
              <span className={`text-xs font-bold px-2.5 py-1 rounded-full ${docSectionComplete ? 'text-success bg-success/15' : 'text-amber-400 bg-amber-500/15'}`}>
                {docSectionComplete ? 'Available' : 'Partial'}
              </span>
            </div>
            <div className="grid grid-cols-3 gap-3 mb-5">
              {docCards.map((doc) => (
                <div key={doc.label} className="glass-light rounded-lg p-3">
                  <p className="text-[10px] text-muted uppercase tracking-wider">{doc.label}</p>
                  <p className="text-sm font-bold text-foreground mt-1">{doc.value}</p>
                  <p className="text-[10px] text-muted mt-0.5">{doc.desc}</p>
                </div>
              ))}
            </div>
            <div className="glass-light rounded-lg p-4">
              <h4 className="text-xs font-semibold text-foreground mb-2">Migration Report — Table of Contents</h4>
              <div className="space-y-1 text-[11px] text-muted">
                {docToc.map((item) => (
                  <p key={item} className="flex items-center gap-2">
                    <CheckCircle2 className="w-3 h-3 text-success shrink-0" /> {item}
                  </p>
                ))}
              </div>
            </div>
          </div>
        </motion.div>
      )}
    </div>
  );
}
