'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSession } from '../lib/session-context';
import { getPlanCapabilities } from '../lib/plan-access';
import {
  Download, GitBranch, Rocket, Package, FileCode2,
  CheckCircle2, Loader2, ExternalLink, FolderArchive,
  Shield, Clock, BarChart3, Play, TestTube, BookOpen,
  Settings, Database, Folder, ChevronRight, ArrowRight, AlertCircle
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { normalizeProjectLang } from '../lib/cicd-workflow';

export default function Export({ projectId, onNavigate, maxReachedStep = 0, project: propProject }: { projectId?: string; onNavigate?: (s: string, pid?: string) => void; maxReachedStep?: number; project?: import('../data/projectsData').Project | null }) {
  const { user: sessionUser } = useSession();
  const capabilities = getPlanCapabilities(sessionUser?.tier);
  const [downloading, setDownloading] = useState(false);
  const [pushing, setPushing] = useState(false);
  const [deploying, setDeploying] = useState(false);
  const [downloaded, setDownloaded] = useState(false);
  const [pushed, setPushed] = useState(false);
  const [deployed, setDeployed] = useState(false);
  const [prUrl, setPrUrl] = useState<string | null>(null);
  const [deployPrUrl, setDeployPrUrl] = useState<string | null>(null);
  const [pushError, setPushError] = useState<string | null>(null);
  const [deployError, setDeployError] = useState<string | null>(null);

  const project = propProject;
  const projConfig = (project?.config ?? {}) as Record<string, unknown>;
  const wizardAddCI = projConfig.addCI !== false;
  const wizardAddTests = projConfig.addTests !== false;
  const wizardAddDocs = projConfig.addDocs !== false;
  const wizardAddLinter = projConfig.addLinter !== false;
  const wizardAddFormatter = projConfig.addFormatter !== false;
  const wizardAddTypeScript = projConfig.addTypeScript === true;
  const wizardAddDocker = projConfig.addDocker !== false;
  const wizardAddK8s = projConfig.addKubernetes === true;
  const wizardOpenAPI = projConfig.enableOpenAPISpec !== false;
  const analysisResults = ((projConfig.analysisResults ?? {}) as Record<string, any>);
  const translation = analysisResults?.translation;
  const conversionResult = (projConfig.conversionResult ?? {}) as Record<string, any>;
  const convTimeSec = Number((conversionResult?.metadata as any)?.conversionTime ?? 0);
  const convTimeDisplay = convTimeSec > 0
    ? convTimeSec >= 60
      ? `${Math.floor(convTimeSec / 60)}m ${Math.round(convTimeSec % 60)}s`
      : `${Math.round(convTimeSec)}s`
    : '—';
  const files = translation?.files || [];
  const artifacts = translation?.artifacts || {};
  const unitTestStats = artifacts?.unitTestStats || {};
  const integrationTestStats = artifacts?.integrationTestStats || {};
  const archStats = artifacts?.archStats || {};
  const docStats = artifacts?.docStats || {};

  const repoUrl = project?.repoUrl || '';
  const repoDisplay = repoUrl.replace(/^https?:\/\//, '');
  const sourceLang = project?.sourceLanguage || '';
  const targetLangRaw = project?.targetLanguage || '';
  const targetLang = normalizeProjectLang(targetLangRaw);
  const projectName = project?.name || 'project';
  const isDraft = project ? project.status === 'draft' && maxReachedStep < 7 : false;

  // Compute stats from translation data
  const sourceFileCount = files.length || (project?.totalFiles ?? 0);
  const targetFileCount = files.length || (project?.convertedFiles ?? 0);
  const totalSourceLines = files.reduce((s: number, f: any) => s + (f.linesSource || 0), 0) || (project?.totalLines ?? 0);
  const totalTargetLines = files.reduce((s: number, f: any) => s + (f.linesTarget || 0), 0) || (project?.totalLines ?? 0);
  const avgConfidence = files.length ? Math.round(files.reduce((s: number, f: any) => s + (f.confidence || 0), 0) / files.length * 10) / 10 : (project?.accuracy ?? 0);
  const totalUnitTests = Number(unitTestStats.cases) || 0;
  const totalIntTests = Number(integrationTestStats.cases) || 0;
  const coverage = Number(unitTestStats.coverage) || Number(project?.testCoverage) || 0;
  const serviceCount = Number(archStats.services) || files.length || 0;
  const repoCount = Number(archStats.repositories) || 0;
  const configCount = Number(archStats.configurations) || 0;
  const docPages = Number(docStats.pages) || 0;
  const qualityReportEligible = capabilities.hasQualityReport;

  const unitArtifactFiles = Array.isArray(artifacts.unitTestFiles) ? artifacts.unitTestFiles : [];
  const intArtifactFiles = Array.isArray(artifacts.integrationTestFiles) ? artifacts.integrationTestFiles : [];
  const docArtifactFiles = Array.isArray(artifacts.docFiles) ? artifacts.docFiles : [];
  const projArtifactFiles = Array.isArray(artifacts.projectFiles) ? artifacts.projectFiles : [];
  const toolingArtifactFiles = Array.isArray(artifacts.toolingFiles) ? artifacts.toolingFiles : [];
  const generatedFileCount =
    targetFileCount +
    unitArtifactFiles.length +
    intArtifactFiles.length +
    docArtifactFiles.length +
    projArtifactFiles.length +
    toolingArtifactFiles.length;
  const displayGenFiles = generatedFileCount > 0 ? generatedFileCount : targetFileCount;
  const estZipKb =
    totalSourceLines + totalTargetLines > 0
      ? Math.max(1, Math.round(((totalSourceLines + totalTargetLines) * 48) / 1024))
      : null;

  if (isDraft) {
    return (
      <div className="space-y-6">
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Download className="w-6 h-6 text-accent-light" /> Export & Deploy
          </h2>
          <p className="text-sm text-muted mt-1">Download, push to Git, or deploy your converted project</p>
        </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">Conversion Not Ready for Export</h3>
          <p className="text-sm text-muted mb-8 max-w-md mx-auto">Complete the migration to export and deploy the converted project.</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>
    );
  }

  const handleDownload = async () => {
    if (!projectId) return;
    setDownloading(true);
    try {
      const res = await fetch(`/api/export/${projectId}/download`);
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        console.error('Download failed:', err.error);
        setDownloading(false);
        return;
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${projectName.toLowerCase().replace(/\s+/g, '-')}-${targetLang || 'export'}.zip`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
      setDownloaded(true);
    } catch (e) {
      console.error('Download error:', e);
    }
    setDownloading(false);
  };

  const handlePush = async () => {
    if (!projectId) return;
    setPushing(true);
    setPushError(null);
    try {
      const res = await fetch(`/api/export/${projectId}/push`, { method: 'POST' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setPushError(data.error ?? 'Push failed');
      } else {
        setPrUrl(data.prUrl ?? null);
        setPushed(true);
      }
    } catch (e) {
      setPushError('Network error — please try again');
    }
    setPushing(false);
  };

  const handleDeploy = async () => {
    if (!projectId) return;
    setDeploying(true);
    setDeployError(null);
    try {
      const deployQs = '?withCicd=true';
      const res = await fetch(`/api/export/${projectId}/push${deployQs}`, { method: 'POST' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setDeployError(data.error ?? 'Deploy setup failed');
      } else {
        setDeployPrUrl(data.prUrl ?? null);
        setDeployed(true);
      }
    } catch (e) {
      setDeployError('Network error — please try again');
    }
    setDeploying(false);
  };

  // Package contents tree — paths derived from this project's target language only
  const pkgBase = targetLang === 'python'
    ? `src/${projectName.toLowerCase().replace(/\s+/g, '_')}/`
    : targetLang === 'typescript' || targetLang === 'javascript'
    ? 'src/'
    : targetLang === 'php'
    ? 'src/'
    : targetLang === 'csharp' || targetLang === 'cs'
    ? 'src/'
    : targetLang === 'java' || targetLang === 'kotlin'
    ? `src/main/java/${projectName.toLowerCase().replace(/\s+/g, '')}/`
    : 'converted/';
  const testBase = targetLang === 'java' || targetLang === 'kotlin'
    ? `src/test/java/${projectName.toLowerCase().replace(/\s+/g, '')}/`
    : 'tests/';
  const buildFile = targetLang === 'python' ? 'requirements.txt'
    : (targetLang === 'typescript' || targetLang === 'javascript') ? 'package.json'
    : targetLang === 'php' ? 'composer.json'
    : targetLang === 'csharp' || targetLang === 'cs' ? '*.csproj'
    : targetLang === 'java' || targetLang === 'kotlin' ? 'pom.xml / build.gradle*'
    : 'README.md';
  const buildFileDesc = targetLang === 'python' ? 'Python dependencies'
    : (targetLang === 'typescript' || targetLang === 'javascript') ? 'Node.js dependencies'
    : targetLang === 'php' ? 'Composer / PHP dependencies'
    : targetLang === 'csharp' || targetLang === 'cs' ? '.NET project file'
    : targetLang === 'java' || targetLang === 'kotlin' ? 'Build manifest (Maven or Gradle)'
    : 'Add a manifest for your target stack';

  const packageTree = [
    { icon: Folder, name: pkgBase, files: `${serviceCount} services, ${repoCount - 2} entities, ${configCount} configs`, color: 'text-accent-light' },
    ...(wizardAddTests
      ? [{ icon: Folder, name: testBase, files: `${totalUnitTests + totalIntTests} test cases (from migration)`, color: 'text-success' }]
      : []),
    ...(wizardAddDocs
      ? [{ icon: Folder, name: 'docs/', files: `SCRIBA-MIGRATION.md (migration report, ${docPages} pages)`, color: 'text-amber-400' }]
      : []),
    ...(wizardAddCI
      ? [{ icon: Folder, name: '.github/workflows/', files: 'scriba-deploy.yml (CI/CD pipeline)', color: 'text-purple-400' }]
      : []),
    ...(wizardAddLinter
      ? [{ icon: FileCode2, name: '.eslintrc.json', files: 'ESLint (wizard)', color: 'text-muted' }]
      : []),
    ...(wizardAddFormatter
      ? [{ icon: FileCode2, name: '.prettierrc', files: 'Prettier (wizard)', color: 'text-muted' }]
      : []),
    ...(wizardAddTypeScript
      ? [{ icon: FileCode2, name: 'tsconfig.scriba.json', files: 'TypeScript (wizard)', color: 'text-muted' }]
      : []),
    ...(wizardAddDocker
      ? [{ icon: FileCode2, name: 'Dockerfile', files: 'Container (wizard)', color: 'text-muted' }]
      : []),
    ...(wizardAddK8s
      ? [{ icon: Folder, name: 'k8s/', files: 'deployment.yaml (wizard)', color: 'text-muted' }]
      : []),
    ...(wizardOpenAPI
      ? [{ icon: FileCode2, name: 'openapi.yaml', files: 'API spec (wizard)', color: 'text-muted' }]
      : []),
    { icon: FileCode2, name: buildFile, files: buildFileDesc, color: 'text-pink-400' },
    { icon: BookOpen, name: 'SCRIBA-MIGRATION.md', files: 'Architecture, quickstart, migration metrics', color: 'text-cyan-400' },
  ];

  return (
    <div className="space-y-5">
      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
        <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
          <Download className="w-6 h-6 text-accent-light" /> Export & Deploy
        </h2>
        <p className="text-sm text-muted mt-1">
          {sourceLang.toUpperCase()} → {targetLang} migration complete &middot; {sourceFileCount} source files → {displayGenFiles} generated files
        </p>
      </motion.div>

      {/* Migration Summary Cards */}
      <div className="grid grid-cols-7 gap-2">
        {[
          { icon: FileCode2, label: 'Source Files', value: String(sourceFileCount), sub: `${totalSourceLines} lines`, color: 'text-pink-400', bg: 'bg-pink-500/10' },
          { icon: ArrowRight, label: 'Target Files', value: String(displayGenFiles), sub: `${totalTargetLines} lines`, color: 'text-accent-light', bg: 'bg-accent/10' },
          { icon: Shield, label: 'Confidence', value: `${avgConfidence}%`, sub: 'Avg parity', color: 'text-cyan-400', bg: 'bg-cyan-500/10' },
          { icon: TestTube, label: 'Tests', value: String(totalUnitTests + totalIntTests), sub: `${coverage}% coverage`, color: 'text-success', bg: 'bg-success/10' },
          { icon: Database, label: 'Services', value: String(serviceCount), sub: `${repoCount} repos`, color: 'text-purple-400', bg: 'bg-purple-500/10' },
          { icon: BookOpen, label: 'Docs', value: `${docPages}`, sub: 'pages', color: 'text-amber-400', bg: 'bg-amber-500/10' },
          { icon: Clock, label: 'Time', value: convTimeDisplay, sub: 'total', color: 'text-muted', bg: 'bg-surface-light' },
        ].map((m) => (
          <div key={m.label} className="glass rounded-xl p-2.5 text-center">
            <div className={`w-6 h-6 rounded-md ${m.bg} flex items-center justify-center mx-auto mb-1.5`}><m.icon className={`w-3 h-3 ${m.color}`} /></div>
            <p className="text-base font-bold text-foreground leading-tight">{m.value}</p>
            <p className="text-[9px] text-muted uppercase tracking-wider">{m.label}</p>
          </div>
        ))}
      </div>

      {/* Package Contents */}
      <div className="glass rounded-xl p-4">
        <h3 className="text-xs font-semibold text-foreground mb-3 flex items-center gap-2">
          <Package className="w-3.5 h-3.5 text-accent-light" /> Package Contents — {projectName.toLowerCase().replace(/\s+/g, '-')}-{targetLang.toLowerCase()}.zip
        </h3>
        <div className="space-y-1">
          {packageTree.map((item) => (
            <div key={item.name} className="flex items-center gap-2 glass-light rounded-lg px-3 py-2">
              <item.icon className={`w-3.5 h-3.5 ${item.color} shrink-0`} />
              <span className="text-[11px] text-foreground font-mono">{item.name}</span>
              <span className="text-[10px] text-muted ml-auto">{item.files}</span>
            </div>
          ))}
        </div>
        <div className="flex items-center justify-between mt-3 pt-3 border-t border-border text-[10px] text-muted">
          <span>{displayGenFiles} tracked outputs</span>
          <span>{estZipKb != null ? `~${estZipKb} KB estimated` : '—'}</span>
        </div>
      </div>

      {/* Action Cards */}
      <div className={`grid gap-4 ${qualityReportEligible ? 'grid-cols-4' : 'grid-cols-3'}`}>
        {/* Download */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className={`glass rounded-xl p-5 transition-all ${downloaded ? 'border border-success/30' : ''}`}>
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-accent/15 flex items-center justify-center">
              <FolderArchive className="w-5 h-5 text-accent-light" />
            </div>
            <div>
              <h3 className="text-sm font-semibold text-foreground">Download ZIP</h3>
              <p className="text-[10px] text-muted">Complete project with sources, tests & docs</p>
            </div>
          </div>
          <div className="space-y-1.5 mb-4 text-[11px]">
            <div className="flex justify-between text-muted"><span>Service layer ({targetLang || 'target'})</span><span className="text-foreground font-mono">{serviceCount} files</span></div>
            <div className="flex justify-between text-muted"><span>Data & configuration</span><span className="text-foreground font-mono">{repoCount + configCount} files</span></div>
            <div className="flex justify-between text-muted"><span>Unit tests</span><span className="text-foreground font-mono">{unitArtifactFiles.length} files ({totalUnitTests} cases)</span></div>
            <div className="flex justify-between text-muted"><span>Integration tests</span><span className="text-foreground font-mono">{intArtifactFiles.length} files ({totalIntTests} cases)</span></div>
            <div className="flex justify-between text-muted"><span>Documentation</span><span className="text-foreground font-mono">{docArtifactFiles.length} files ({docPages} pages)</span></div>
            <div className="flex justify-between text-muted"><span>Build config</span><span className="text-foreground font-mono">{buildFile}</span></div>
          </div>
          <button onClick={handleDownload} disabled={downloading || downloaded}
            className={`w-full py-2.5 rounded-lg text-xs font-semibold flex items-center justify-center gap-2 transition-all cursor-pointer ${
              downloaded ? 'bg-success/15 text-success border border-success/30' : 'gradient-accent text-white hover:opacity-90'
            } disabled:opacity-60`}>
            {downloading ? <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Packaging...</>
            : downloaded ? <><CheckCircle2 className="w-3.5 h-3.5" /> Downloaded</>
            : <><Download className="w-3.5 h-3.5" /> Download ZIP</>}
          </button>
        </motion.div>

        {/* Push to Git */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
          className={`glass rounded-xl p-5 transition-all ${pushed ? 'border border-success/30' : ''}`}>
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-purple-500/15 flex items-center justify-center">
              <GitBranch className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <h3 className="text-sm font-semibold text-foreground">Push to GitHub</h3>
              <p className="text-[10px] text-muted">Create branch with migration PR</p>
            </div>
          </div>
          <div className="space-y-2 mb-4">
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Repository</p>
              <p className="text-[11px] text-foreground font-mono truncate">{repoDisplay || '—'}</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Branch</p>
              <p className="text-[11px] text-foreground font-mono">scriba/migrate-{sourceLang.toLowerCase()}-to-{targetLang.toLowerCase()}</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Commit</p>
              <p className="text-[11px] text-foreground font-mono">feat: migrate {sourceLang} to {targetLang} ({sourceFileCount} files, {avgConfidence}% parity)</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Changes</p>
              <p className="text-[11px] text-foreground font-mono">+{totalTargetLines} lines, {displayGenFiles} files in bundle</p>
            </div>
          </div>
          {pushError && (
            <div className="flex items-start gap-2 text-[10px] text-danger bg-danger/10 border border-danger/20 rounded-lg px-2.5 py-2 mb-2">
              <AlertCircle className="w-3 h-3 shrink-0 mt-0.5" />{pushError}
            </div>
          )}
          {pushed && prUrl && (
            <a href={prUrl} target="_blank" rel="noopener noreferrer"
              className="flex items-center gap-1 text-[10px] text-accent-light hover:text-accent font-medium mb-2">
              <ExternalLink className="w-3 h-3" /> View Pull Request
            </a>
          )}
          <button onClick={handlePush} disabled={pushing || pushed}
            className={`w-full py-2.5 rounded-lg text-xs font-semibold flex items-center justify-center gap-2 transition-all cursor-pointer ${
              pushed ? 'bg-success/15 text-success border border-success/30' : 'bg-purple-600 text-white hover:bg-purple-500'
            } disabled:opacity-60`}>
            {pushing ? <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Creating PR...</>
            : pushed ? <><CheckCircle2 className="w-3.5 h-3.5" /> PR Created</>
            : <><GitBranch className="w-3.5 h-3.5" /> Push & Create PR</>}
          </button>
        </motion.div>

        {/* Deploy */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}
          className={`glass rounded-xl p-5 transition-all ${deployed ? 'border border-success/30' : ''}`}>
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-cyan-500/15 flex items-center justify-center">
              <Rocket className="w-5 h-5 text-cyan-400" />
            </div>
            <div>
              <h3 className="text-sm font-semibold text-foreground">Create CI/CD Pipeline</h3>
              <p className="text-[10px] text-muted">Push workflow to GitHub — merge to deploy</p>
            </div>
          </div>
          <div className="space-y-2 mb-4">
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Workflow</p>
              <p className="text-[11px] text-foreground font-mono">.github/workflows/scriba-deploy.yml</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Trigger</p>
              <p className="text-[11px] text-foreground font-mono">push to scriba/migrate-* or main</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Steps</p>
              <p className="text-[11px] text-foreground font-mono">build → test → deploy (configurable)</p>
            </div>
            <div className="glass-light rounded-lg px-3 py-1.5">
              <p className="text-[9px] text-muted uppercase tracking-wider">Pre-deploy checks</p>
              <p className="text-[11px] text-foreground font-mono">{totalUnitTests + totalIntTests} tests, security scan, lint</p>
            </div>
          </div>
          {deployError && (
            <div className="flex items-start gap-2 text-[10px] text-danger bg-danger/10 border border-danger/20 rounded-lg px-2.5 py-2 mb-2">
              <AlertCircle className="w-3 h-3 shrink-0 mt-0.5" />{deployError}
            </div>
          )}
          {deployed && deployPrUrl && (
            <a href={deployPrUrl} target="_blank" rel="noopener noreferrer"
              className="flex items-center gap-1 text-[10px] text-accent-light hover:text-accent font-medium mb-2">
              <ExternalLink className="w-3 h-3" /> View PR with CI/CD
            </a>
          )}
          <button onClick={handleDeploy} disabled={deploying || deployed}
            className={`w-full py-2.5 rounded-lg text-xs font-semibold flex items-center justify-center gap-2 transition-all cursor-pointer ${
              deployed ? 'bg-success/15 text-success border border-success/30' : 'bg-cyan-600 text-white hover:bg-cyan-500'
            } disabled:opacity-60`}>
            {deploying ? <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Setting up CI/CD...</>
            : deployed ? <><CheckCircle2 className="w-3.5 h-3.5" /> CI/CD Workflow Created</>
            : <><Rocket className="w-3.5 h-3.5" /> Create CI/CD Pipeline</>}
          </button>
        </motion.div>

        {qualityReportEligible && (
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.35 }}
            className="glass rounded-xl p-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-lg bg-amber-500/15 flex items-center justify-center">
                <BarChart3 className="w-5 h-5 text-amber-400" />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-foreground">Conversion Quality Report</h3>
                <p className="text-[10px] text-muted">Included in {capabilities.tier} plan</p>
              </div>
            </div>
            <div className="space-y-2 mb-4">
              <div className="glass-light rounded-lg px-3 py-1.5">
                <p className="text-[9px] text-muted uppercase tracking-wider">Functional parity</p>
                <p className="text-[11px] text-foreground font-mono">{avgConfidence}%</p>
              </div>
              <div className="glass-light rounded-lg px-3 py-1.5">
                <p className="text-[9px] text-muted uppercase tracking-wider">Coverage</p>
                <p className="text-[11px] text-foreground font-mono">{coverage}%</p>
              </div>
              <div className="glass-light rounded-lg px-3 py-1.5">
                <p className="text-[9px] text-muted uppercase tracking-wider">Documentation</p>
                <p className="text-[11px] text-foreground font-mono">{docPages} pages</p>
              </div>
              <div className="glass-light rounded-lg px-3 py-1.5">
                <p className="text-[9px] text-muted uppercase tracking-wider">Generated files</p>
                <p className="text-[11px] text-foreground font-mono">{displayGenFiles}</p>
              </div>
            </div>
            <button
              onClick={() => onNavigate?.('verification', projectId)}
              className="w-full py-2.5 rounded-lg text-xs font-semibold flex items-center justify-center gap-2 transition-all cursor-pointer bg-amber-500 text-white hover:bg-amber-400"
            >
              <BarChart3 className="w-3.5 h-3.5" /> Open Quality Report
            </button>
          </motion.div>
        )}
      </div>

      {/* Completion Banner */}
      <AnimatePresence>
        {(downloaded || pushed || deployed) && (
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} className="glass rounded-xl p-4 border border-success/20">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-success/15 flex items-center justify-center shrink-0">
                <CheckCircle2 className="w-5 h-5 text-success" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-success">Migration Complete</p>
                <p className="text-[11px] text-muted">
                  {sourceFileCount} {sourceLang.toUpperCase()} programs migrated to {displayGenFiles} {targetLang} files
                  with {avgConfidence}% functional parity, {totalUnitTests + totalIntTests} tests ({coverage}% coverage), and {docPages}-page documentation.
                  {pushed && ' Pull request created on GitHub.'}
                  {deployed && ' CI/CD pipeline workflow pushed to PR.'}
                </p>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                {prUrl && (
                  <a href={prUrl} target="_blank" rel="noopener noreferrer"
                    className="flex items-center gap-1 text-[11px] text-purple-400 hover:text-purple-300 font-medium">
                    <GitBranch className="w-3 h-3" /> PR
                  </a>
                )}
                {deployPrUrl && deployPrUrl !== prUrl && (
                  <a href={deployPrUrl} target="_blank" rel="noopener noreferrer"
                    className="flex items-center gap-1 text-[11px] text-cyan-400 hover:text-cyan-300 font-medium">
                    <Rocket className="w-3 h-3" /> CI/CD
                  </a>
                )}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
