'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  FolderKanban, FileCode2, Code2, ArrowRight, Activity,
  CheckCircle2, Loader2, AlertTriangle, FileText, Clock,
  Plus, Zap, GitBranch, Users, Calendar, TrendingUp,
  BarChart3, Cpu, ChevronRight,
  Target, Circle, Receipt,
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { useSession } from '../lib/session-context';
import { getPlanCapabilities } from '../lib/plan-access';
import { formatEur } from '../lib/conversion-pricing';
import {
  AreaChart, Area, ResponsiveContainer, XAxis, YAxis,
  Tooltip, CartesianGrid, PieChart, Pie, Cell,
  BarChart, Bar,
} from 'recharts';

function AnimatedNumber({ target, suffix = '' }: { target: number; suffix?: string }) {
  const [value, setValue] = useState(0);
  useEffect(() => {
    if (target === 0) return;
    const steps = 40;
    const inc = target / steps;
    let c = 0;
    const t = setInterval(() => {
      c += inc;
      if (c >= target) { setValue(target); clearInterval(t); }
      else setValue(Math.floor(c));
    }, 20);
    return () => clearInterval(t);
  }, [target]);
  return <>{value.toLocaleString()}{suffix}</>;
}

const statusConfig: Record<string, { label: string; color: string; bg: string; icon: typeof CheckCircle2; spin?: boolean }> = {
  completed:  { label: 'Completed',  color: 'text-green-400',   bg: 'bg-green-500/10',  icon: CheckCircle2 },
  converting: { label: 'Converting', color: 'text-accent-light', bg: 'bg-accent/10',    icon: Loader2, spin: true },
  validating: { label: 'Validating', color: 'text-amber-400',   bg: 'bg-amber-500/10', icon: Loader2, spin: true },
  analyzing:  { label: 'Analyzing',  color: 'text-sky-400',     bg: 'bg-sky-500/10',   icon: Loader2, spin: true },
  draft:      { label: 'Draft',      color: 'text-muted',       bg: 'bg-surface',       icon: FileText },
  failed:     { label: 'Failed',     color: 'text-red-400',     bg: 'bg-red-500/10',   icon: AlertTriangle },
};

/** Dashboard progress: DB `totalFiles` / `convertedFiles` are often unset until migration finishes, so we add fallbacks. */
function activeConversionProgress(project: Project): { percent: number; indeterminate: boolean } {
  const total = project.totalFiles ?? 0;
  const conv = project.convertedFiles ?? 0;
  if (total > 0) {
    return { percent: Math.min(100, Math.round((conv / total) * 100)), indeterminate: false };
  }
  const maxStep = project.maxReachedStep ?? 0;
  const pipelineMax = 8;
  if (maxStep > 0) {
    return { percent: Math.min(90, Math.round((maxStep / pipelineMax) * 100)), indeterminate: false };
  }
  if (['analyzing', 'converting', 'validating'].includes(project.status)) {
    return { percent: 0, indeterminate: true };
  }
  return { percent: 0, indeterminate: false };
}

function langLabel(id: string) {
  const map: Record<string, string> = {
    cobol: 'COBOL', java: 'Java', python: 'Python', csharp: 'C#',
    javascript: 'JS', typescript: 'TS', cpp: 'C++', fortran: 'Fortran',
    rpg: 'RPG', pl1: 'PL/I', ada: 'Ada', kotlin: 'Kotlin',
    scala: 'Scala', go: 'Go', rust: 'Rust', php: 'PHP',
    ruby: 'Ruby', swift: 'Swift', vb6: 'VB6', vbnet: 'VB.NET',
  };
  return map[id] ?? id;
}

interface Props {
  onNavigate: (section: string, projectId?: string) => void;
  projects?: Project[];
}

export default function GlobalDashboard({ onNavigate, projects: propProjects }: Props) {
  const [mounted, setMounted] = useState(false);
  const { user: sessionUser } = useSession();
  const [slotData, setSlotData] = useState<{ used: number; max: number } | null>(null);
  useEffect(() => { setMounted(true); }, []);

  useEffect(() => {
    if (!sessionUser?.companyId) return;
    fetch(`/api/companies/${sessionUser.companyId}`, { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d?.company && typeof d.company.conversionCount === 'number' && typeof d.company.maxConversions === 'number') {
          setSlotData({ used: d.company.conversionCount, max: d.company.maxConversions });
        }
      })
      .catch(() => {});
  }, [sessionUser?.companyId]);

  const isAdmin = sessionUser?.role === 'admin';
  const list = propProjects ?? [];
  const capabilities = getPlanCapabilities(sessionUser?.tier);

  // Compact billing summary (owner/admin only) — single source: the Invoices API.
  const [billing, setBilling] = useState<{ billableCents: number; creditRemainingCents: number; chargeDate: string | null } | null>(null);
  useEffect(() => {
    if (!(sessionUser?.isOwner || sessionUser?.role === 'admin')) { setBilling(null); return; }
    fetch('/api/billing/invoice', { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d?.invoice) setBilling({
          billableCents: d.invoice.amountCents ?? 0,
          creditRemainingCents: d.credits?.remainingCents ?? 0,
          chargeDate: d.period?.chargeDate ?? null,
        });
      })
      .catch(() => {});
  }, [sessionUser?.isOwner, sessionUser?.role]);

  const stats = {
    total:     list.length,
    active:    list.filter(p => ['analyzing','converting','validating'].includes(p.status)).length,
    completed: list.filter(p => p.status === 'completed').length,
    draft:     list.filter(p => p.status === 'draft').length,
    failed:    list.filter(p => p.status === 'failed').length,
  };

  const recent = [...list]
    .sort((a, b) => new Date(b.updatedAt ?? b.createdAt).getTime() - new Date(a.updatedAt ?? a.createdAt).getTime())
    .slice(0, 6);

  const allActivity = list
    .flatMap(p => (p.activity ?? []).map((a: any) => ({ ...a, projectName: p.name, projectId: p.id })))
    .filter((a: any) => {
      const t = a?.timestamp ? new Date(a.timestamp).getTime() : NaN;
      return Number.isFinite(t);
    })
    .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
    .slice(0, 12);

  const pairMap: Record<string, number> = {};
  list.forEach(p => {
    const key = `${langLabel(p.sourceLanguage)}→${langLabel(p.targetLanguage)}`;
    pairMap[key] = (pairMap[key] ?? 0) + 1;
  });
  const pairs = Object.entries(pairMap).map(([key, count]) => ({ key, count }));

  const activeProjects = list.filter(p => ['analyzing','converting','validating'].includes(p.status));

  // Engine health (fetched once on mount)
  const [engineStatus, setEngineStatus] = useState<{ status: string; version?: string; timestamp?: string } | null>(null);
  const [engineQuality, setEngineQuality] = useState<{
    count: number;
    avgQualityIndex: number | null;
    markerRate: number | null;
    avgCostUsd: number | null;
    levels: Record<string, number>;
    costBySourceLang: Record<string, { count: number; sumUsd: number; avgUsd: number }>;
    samples?: Array<{ qualityIndex: number; costUsd?: number; finishedAt: number }>;
  } | null>(null);

  useEffect(() => {
    fetch('/api/engine/health').then(r => r.ok ? r.json() : null).then(d => setEngineStatus(d)).catch(() => setEngineStatus(null));
    fetch('/api/engine/health/quality?limit=50').then(r => r.ok ? r.json() : null).then(d => setEngineQuality(d)).catch(() => setEngineQuality(null));
    const interval = setInterval(() => {
      fetch('/api/engine/health/quality?limit=50').then(r => r.ok ? r.json() : null).then(d => setEngineQuality(d)).catch(() => {});
    }, 45_000);
    return () => clearInterval(interval);
  }, []);

  // ── Empty state ──────────────────────────────────────────────────────────────
  if (list.length === 0) {
    return (
      <div className="space-y-5">
        <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">Dashboard</h2>
            <p className="text-sm text-muted mt-1">AI-powered code conversion platform</p>
          </div>
          <button onClick={() => onNavigate('new-conversion')}
            className="flex items-center gap-2 px-5 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity cursor-pointer glow-accent">
            <Plus className="w-4 h-4" /> New Conversion
          </button>
        </motion.div>

        {/* Hero empty */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
          className="glass rounded-2xl p-14 flex flex-col items-center text-center">
          <div className="w-20 h-20 rounded-full gradient-accent flex items-center justify-center mb-6 glow-accent">
            <Zap className="w-10 h-10 text-white" />
          </div>
          <h3 className="text-xl font-bold text-foreground mb-2">No conversions yet</h3>
          <p className="text-sm text-muted max-w-md mb-8 leading-relaxed">
            Create your first migration conversion. Connect a repository, configure source and target languages, and let Scriba AI handle the rest — end to end.
          </p>
          <button onClick={() => onNavigate('new-conversion')}
            className="flex items-center gap-2 px-8 py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity cursor-pointer glow-accent">
            <Plus className="w-4 h-4" /> Create First Conversion
          </button>
        </motion.div>

        {/* Engine quality health (§7) */}
        {engineQuality !== null && engineQuality.count > 0 && (
          <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
            className="glass rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-accent-light" /> Engine Quality Health
              </p>
              <span className="text-[10px] text-muted">{engineQuality.count} run{engineQuality.count !== 1 ? 's' : ''}</span>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Avg Quality</p>
                <p className="text-lg font-bold text-foreground">{engineQuality.avgQualityIndex !== null ? engineQuality.avgQualityIndex.toFixed(1) : '—'}</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Total runs</p>
                <p className="text-lg font-bold text-foreground">{engineQuality.count}</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Marker rate</p>
                <p className="text-lg font-bold text-success">{engineQuality.markerRate !== null ? `${(engineQuality.markerRate * 100).toFixed(0)}%` : '—'}</p>
              </div>
            </div>
          </motion.div>
        )}

        {/* Engine status */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="glass rounded-xl p-4 flex items-center gap-4">
          <Cpu className="w-5 h-5 text-accent-light" />
          <div className="flex-1">
            <p className="text-sm font-medium text-foreground">Scriba AI Engine</p>
            <p className="text-[10px] text-muted">{engineStatus?.version ? `v${engineStatus.version}` : 'Checking...'}</p>
          </div>
          <span className={`flex items-center gap-1.5 text-[11px] font-medium ${engineStatus?.status === 'ok' ? 'text-green-400' : 'text-amber-400'}`}>
            <Circle className={`w-2 h-2 ${engineStatus?.status === 'ok' ? 'fill-green-400' : 'fill-amber-400'}`} />
            {engineStatus?.status === 'ok' ? 'Online' : engineStatus ? 'Degraded' : 'Checking...'}
          </span>
        </motion.div>
      </div>
    );
  }

  // ── Full dashboard ───────────────────────────────────────────────────────────
  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">Dashboard</h2>
          <p className="text-sm text-muted mt-1">
            {stats.total} conversion{stats.total !== 1 ? 's' : ''}
            {stats.active > 0 && <span className="text-accent-light"> · {stats.active} active</span>}
          </p>
          {slotData && (
            <p className={`text-xs mt-1 ${slotData.used >= slotData.max ? 'text-amber-400' : 'text-muted'}`}>
              Conversion slots:{' '}
              <span className="font-semibold text-foreground">{slotData.used}/{slotData.max}</span>
              {slotData.used >= slotData.max && ' · Limit reached'}
            </p>
          )}
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => onNavigate('conversions')}
            className="px-4 py-2 rounded-lg glass text-sm text-foreground hover:border-accent/30 transition-all cursor-pointer">
            All Conversions
          </button>
          <button onClick={() => onNavigate('new-conversion')}
            className="flex items-center gap-2 px-5 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity cursor-pointer">
            <Plus className="w-4 h-4" /> New Conversion
          </button>
        </div>
      </motion.div>

      {/* ── KPI row (operations) ── */}
      <div className="grid grid-cols-5 gap-3">
        {[
          { label: 'Active', value: stats.active, icon: Activity, color: 'text-amber-400', desc: 'in progress' },
          { label: 'Completed', value: stats.completed, icon: CheckCircle2, color: 'text-green-400', desc: 'fully converted' },
          { label: 'Needs attention', value: stats.failed, icon: AlertTriangle, color: 'text-red-400', desc: 'failed runs' },
          {
            label: 'Avg quality',
            value: engineQuality?.avgQualityIndex != null ? Math.round(engineQuality.avgQualityIndex) : null,
            icon: BarChart3, color: 'text-accent-light', desc: 'engine quality index',
          },
          {
            label: 'AI-marked',
            value: engineQuality?.markerRate != null ? Math.round(engineQuality.markerRate * 100) : null,
            suffix: '%', icon: CheckCircle2, color: 'text-green-400', desc: 'compliance marker rate',
          },
        ].map((s, i) => (
          <motion.div key={s.label} initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }}
            className="glass rounded-xl p-4 hover:border-accent/20 transition-all">
            <div className="flex items-center justify-between mb-3">
              <span className="text-[10px] text-muted uppercase tracking-wider font-medium">{s.label}</span>
              <s.icon className={`w-4 h-4 ${s.color}`} />
            </div>
            <p className="text-3xl font-bold text-foreground mb-1">
              {s.value == null ? <span className="text-muted">—</span> : <AnimatedNumber target={s.value} suffix={s.suffix ?? ''} />}
            </p>
            <p className="text-[10px] text-muted">{s.desc}</p>
          </motion.div>
        ))}
      </div>

      {/* ── Charts row ── */}
      <div className="grid grid-cols-3 gap-4">

        {/* Status distribution donut */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="glass rounded-xl p-5">
          <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
            <BarChart3 className="w-4 h-4 text-accent-light" /> Conversion Status
          </h3>
          {mounted && (() => {
            const donutData = [
              { name: 'Completed', value: stats.completed, color: '#22c55e' },
              { name: 'Active',    value: stats.active,    color: '#ff914d' },
              { name: 'Draft',     value: stats.draft,     color: '#06b6d4' },
              { name: 'Failed',    value: stats.failed,    color: '#ef4444' },
            ].filter(d => d.value > 0);
            return (
              <div className="flex items-center gap-4">
                <ResponsiveContainer width={110} height={110}>
                  <PieChart>
                    <Pie data={donutData} cx="50%" cy="50%" innerRadius={32} outerRadius={50} dataKey="value" stroke="none">
                      {donutData.map((d, i) => <Cell key={i} fill={d.color} />)}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
                <div className="space-y-2 flex-1">
                  {donutData.map(d => (
                    <div key={d.name} className="flex items-center gap-2 text-xs">
                      <div className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: d.color }} />
                      <span className="text-muted">{d.name}</span>
                      <span className="ml-auto font-semibold text-foreground">{d.value}</span>
                    </div>
                  ))}
                </div>
              </div>
            );
          })()}
        </motion.div>

        {/* Projects per language (bar) */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}
          className="glass rounded-xl p-5">
          <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
            <Code2 className="w-4 h-4 text-accent-light" /> By Source Language
          </h3>
          {mounted && (() => {
            const langCount: Record<string, number> = {};
            list.forEach(p => { langCount[langLabel(p.sourceLanguage)] = (langCount[langLabel(p.sourceLanguage)] ?? 0) + 1; });
            const barData = Object.entries(langCount).map(([lang, count]) => ({ lang, count }));
            return barData.length > 0 ? (
              <ResponsiveContainer width="100%" height={110}>
                <BarChart data={barData} barSize={18}>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--brd)" vertical={false} />
                  <XAxis dataKey="lang" tick={{ fontSize: 10, fill: 'var(--mt)' }} />
                  <YAxis tick={{ fontSize: 10, fill: 'var(--mt)' }} allowDecimals={false} width={20} />
                  <Tooltip contentStyle={{ background: 'var(--tooltip-bg,#12131f)', border: '1px solid var(--brd)', borderRadius: '8px', fontSize: '12px', color: 'var(--fg)' }} />
                  <Bar dataKey="count" fill="#ff914d" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : <p className="text-xs text-muted italic">No data yet.</p>;
          })()}
        </motion.div>

        {/* Recent activity timeline */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
          className="glass rounded-xl p-5">
          <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-accent-light" /> Conversions Over Time
          </h3>
          {mounted && (() => {
            // Group by calendar month (sortable key) so the series is chronological, not object key order.
            const monthBuckets = new Map<string, { label: string; count: number }>();
            list.forEach(p => {
              const d = new Date(p.createdAt);
              if (Number.isNaN(d.getTime())) return;
              const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
              const label = d.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
              const cur = monthBuckets.get(key);
              if (cur) cur.count += 1;
              else monthBuckets.set(key, { label, count: 1 });
            });
            const timeData = [...monthBuckets.entries()]
              .sort((a, b) => a[0].localeCompare(b[0]))
              .map(([, v]) => ({ month: v.label, count: v.count }));
            return timeData.length > 0 ? (
              <ResponsiveContainer width="100%" height={110}>
                <AreaChart data={timeData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--brd)" />
                  <XAxis dataKey="month" tick={{ fontSize: 10, fill: 'var(--mt)' }} />
                  <YAxis tick={{ fontSize: 10, fill: 'var(--mt)' }} allowDecimals={false} width={20} />
                  <Tooltip contentStyle={{ background: 'var(--tooltip-bg,#12131f)', border: '1px solid var(--brd)', borderRadius: '8px', fontSize: '12px', color: 'var(--fg)' }} />
                  <Area type="monotone" dataKey="count" stroke="#ff914d" fill="#ff914d" fillOpacity={0.15} strokeWidth={2} />
                </AreaChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex flex-col items-center justify-center h-[110px] gap-2">
                <TrendingUp className="w-8 h-8 text-muted/40" />
                <p className="text-xs text-muted italic text-center">No creation dates to chart</p>
              </div>
            );
          })()}
        </motion.div>
      </div>

      {/* ── Active projects + Activity ── */}
      {activeProjects.length > 0 && (
        <div className="grid grid-cols-3 gap-4">
          <motion.div initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.1 }}
            className="col-span-2 glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
              <Activity className="w-4 h-4 text-accent-light animate-pulse" /> Active Conversions
            </h3>
            <div className="space-y-3">
              {activeProjects.map(p => {
                const sc = statusConfig[p.status] ?? statusConfig.draft;
                const Icon = sc.icon;
                const { percent: progress, indeterminate } = activeConversionProgress(p);
                return (
                  <button key={p.id} onClick={() => onNavigate('migration-flow', p.id)}
                    className="w-full glass-light rounded-lg px-4 py-3 text-left hover:border-accent/20 transition-all cursor-pointer group">
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <p className="text-sm font-medium text-foreground group-hover:text-accent-light transition-colors">{p.name}</p>
                        <span className={`flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full font-semibold ${sc.color} ${sc.bg} border border-current/20`}>
                          <Icon className={`w-3 h-3 ${sc.spin ? 'animate-spin' : ''}`} /> {sc.label}
                        </span>
                      </div>
                      <span className="text-xs font-mono text-foreground">{indeterminate ? '—' : `${progress}%`}</span>
                    </div>
                    <div className="relative h-1.5 bg-surface rounded-full overflow-hidden">
                      {indeterminate ? (
                        <motion.div
                          className="absolute top-0 left-0 h-full w-[32%] rounded-full bg-accent/90"
                          animate={{ left: ['-32%', '100%'] }}
                          transition={{ duration: 2.4, repeat: Infinity, ease: 'linear' }}
                        />
                      ) : (
                        <motion.div initial={{ width: 0 }} animate={{ width: `${progress}%` }} transition={{ duration: 1.2 }}
                          className="h-full rounded-full bg-accent" />
                      )}
                    </div>
                    <div className="flex items-center justify-between mt-1.5 text-[10px] text-muted">
                      <span className="font-mono">{langLabel(p.sourceLanguage)} → {langLabel(p.targetLanguage)}</span>
                      <span>{p.elapsedTime || 'Running…'}</span>
                    </div>
                  </button>
                );
              })}
            </div>
          </motion.div>

          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.15 }}
            className="glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
              <Clock className="w-4 h-4 text-accent-light" /> Activity
            </h3>
            <div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
              {allActivity.slice(0, 6).map((a: any, idx: number) => (
                <div key={a.id ?? idx} className="flex gap-2.5">
                  <div className="w-1.5 h-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-foreground leading-snug">{a.action}</p>
                    <p className="text-[10px] text-muted truncate">{a.projectName}</p>
                    <p className="text-[10px] text-muted">
                      {new Date(a.timestamp).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        </div>
      )}

      {/* ── Recent projects + side panels ── */}
      <div className="grid grid-cols-5 gap-4">

        {/* Recent projects table */}
        <motion.div initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.15 }}
          className="col-span-3 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">
              <FolderKanban className="w-4 h-4 text-accent-light" /> Conversions
            </h3>
            <button onClick={() => onNavigate('conversions')} className="text-xs text-accent-light hover:underline cursor-pointer flex items-center gap-0.5">
              View all <ChevronRight className="w-3 h-3" />
            </button>
          </div>
          <div className="space-y-2">
            {recent.map((p, i) => {
              const sc = statusConfig[p.status] ?? statusConfig.draft;
              const Icon = sc.icon;
              return (
                <motion.button key={p.id} initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.05 * i }}
                  onClick={() => onNavigate('conversion-dashboard', p.id)}
                  className="w-full glass-light rounded-lg px-4 py-3 flex items-center gap-4 hover:border-accent/20 transition-all cursor-pointer text-left group">
                  <div className="w-8 h-8 rounded-lg gradient-accent flex items-center justify-center text-[11px] font-bold text-white shrink-0">
                    {p.name.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground truncate group-hover:text-accent-light transition-colors">{p.name}</p>
                    <div className="flex items-center gap-3 mt-0.5">
                      <span className="text-[11px] text-muted font-mono">{langLabel(p.sourceLanguage)} → {langLabel(p.targetLanguage)}</span>
                      {p.repoUrl && (
                        <span className="flex items-center gap-1 text-[10px] text-muted">
                          <GitBranch className="w-3 h-3" />{p.repoUrl.replace(/^https?:\/\/[^/]+\//, '').slice(0, 28)}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-3 shrink-0">
                    {p.team?.length > 0 && (
                      <span className="flex items-center gap-1 text-[10px] text-muted">
                        <Users className="w-3 h-3" />{p.team.length}
                      </span>
                    )}
                    <span className="flex items-center gap-1 text-[10px] text-muted">
                      <Calendar className="w-3 h-3" />
                      {new Date(p.createdAt).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' })}
                    </span>
                    <span className={`flex items-center gap-1.5 text-[11px] px-2.5 py-1 rounded-full font-semibold ${sc.color} ${sc.bg} border border-current/20`}>
                      <Icon className={`w-3 h-3 ${sc.spin ? 'animate-spin' : ''}`} />
                      {sc.label}
                    </span>
                  </div>
                </motion.button>
              );
            })}
          </div>
        </motion.div>

        {/* Right column */}
        <div className="col-span-2 space-y-4">
          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.18 }}
            className="glass rounded-xl p-5">
            <div className="flex items-center justify-between gap-3">
              <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                <Receipt className="w-4 h-4 text-accent-light" /> Billing
              </h3>
              <span className="rounded-full bg-accent/10 px-2 py-1 text-[10px] font-semibold text-accent-light capitalize">
                {isAdmin ? 'admin' : capabilities.tier} plan
              </span>
            </div>

            {billing ? (
              <>
                <div className="mt-4 flex items-end justify-between">
                  <div>
                    <p className="text-[10px] text-muted uppercase tracking-wider">Billable this month</p>
                    <p className="text-2xl font-bold text-foreground tabular-nums">{formatEur(billing.billableCents / 100)}</p>
                  </div>
                  <button onClick={() => onNavigate('invoices')}
                    className="text-[11px] text-accent-light hover:underline cursor-pointer flex items-center gap-0.5">
                    View invoices <ChevronRight className="w-3 h-3" />
                  </button>
                </div>
                <div className="mt-3 grid grid-cols-2 gap-2 text-[11px]">
                  <div className="glass-light rounded-lg p-3">
                    <p className="text-muted uppercase tracking-wider">Credit remaining</p>
                    <p className="mt-1 text-sm font-semibold text-sky-400">{formatEur(billing.creditRemainingCents / 100)}</p>
                  </div>
                  <div className="glass-light rounded-lg p-3">
                    <p className="text-muted uppercase tracking-wider">Next charge</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">
                      {billing.chargeDate ? new Date(billing.chargeDate).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' }) : '—'}
                    </p>
                  </div>
                </div>
              </>
            ) : (
              <p className="mt-4 text-[11px] text-muted leading-relaxed">
                Billing is managed by your company owner. Conversions are charged monthly on the 1st, with the annual license credit applied first.
              </p>
            )}

            <div className="mt-4 grid grid-cols-2 gap-2 text-[11px]">
              <div className="glass-light rounded-lg p-3">
                <p className="text-muted uppercase tracking-wider">Support SLA</p>
                <p className="mt-1 text-sm font-semibold text-foreground">{capabilities.supportSla}</p>
              </div>
              <div className="glass-light rounded-lg p-3">
                <p className="text-muted uppercase tracking-wider">Quality report</p>
                <p className="mt-1 text-sm font-semibold text-foreground">{isAdmin || capabilities.hasQualityReport ? 'Included' : 'Upgrade required'}</p>
              </div>
            </div>
          </motion.div>

          {/* Quick actions */}
          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.2 }}
            className="glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
              <Zap className="w-4 h-4 text-accent-light" /> Quick Actions
            </h3>
            <div className="grid grid-cols-2 gap-2">
              {[
                { label: 'New Conversion', icon: Plus,         action: () => onNavigate('new-conversion'), accent: true },
                { label: 'All Conversions', icon: FolderKanban, action: () => onNavigate('conversions') },
                { label: 'Settings',      icon: Target,      action: () => onNavigate('settings') },
                { label: 'Documentation', icon: FileCode2,   action: () => {} },
              ].map(a => (
                <button key={a.label} onClick={a.action}
                  className={`flex items-center gap-2 px-3 py-2.5 rounded-lg text-xs font-medium transition-all cursor-pointer ${
                    a.accent
                      ? 'gradient-accent text-white hover:opacity-90'
                      : 'glass-light text-foreground hover:border-accent/20 hover:text-accent-light'
                  }`}>
                  <a.icon className="w-3.5 h-3.5" />{a.label}
                </button>
              ))}
            </div>
          </motion.div>

          {/* Language pairs */}
          {pairs.length > 0 && (
            <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.25 }}
              className="glass rounded-xl p-5">
              <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                <Code2 className="w-4 h-4 text-accent-light" /> Language Pairs
              </h3>
              <div className="space-y-2">
                {pairs.map(({ key, count }) => {
                  const [src, tgt] = key.split('→');
                  const pct = Math.round((count / stats.total) * 100);
                  return (
                    <div key={key} className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-mono text-foreground">{src}</span>
                        <ArrowRight className="w-3 h-3 text-accent-light shrink-0" />
                        <span className="text-xs font-mono text-foreground">{tgt}</span>
                        <span className="ml-auto text-[10px] text-muted">{count} conversion{count > 1 ? 's' : ''}</span>
                      </div>
                      <div className="h-1 bg-surface rounded-full overflow-hidden">
                        <div className="h-full bg-accent rounded-full transition-all duration-700" style={{ width: `${pct}%` }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            </motion.div>
          )}

          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.28 }}
            className="glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
              <Target className="w-4 h-4 text-accent-light" /> Plan Access
            </h3>
            <div className="space-y-2 text-xs">
              {([
                ['SSO', capabilities.hasSso],
                ['SOC 2 / ISO 27001', capabilities.hasSoc2Iso27001],
                ['EU AI Act', capabilities.hasEuAiAct],
                ['Granular RBAC', capabilities.hasGranularRbac],
                ['On-prem / air-gapped', capabilities.hasOnPrem],
                ['Dedicated Slack/Teams', capabilities.hasDedicatedChannel],
                ['Account manager', capabilities.hasAccountManager],
              ] as Array<[string, boolean]>).map(([label, enabled]) => (
                <div key={label} className="flex items-center justify-between rounded-lg glass-light px-3 py-2">
                  <span className="text-foreground">{label}</span>
                  <span className={isAdmin || enabled ? 'text-green-400 font-medium' : 'text-muted'}>
                    {isAdmin || enabled ? 'Enabled' : 'Not in plan'}
                  </span>
                </div>
              ))}
            </div>
          </motion.div>

          {/* Activity feed */}
          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }}
            className="glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
              <Clock className="w-4 h-4 text-accent-light" /> Recent Activity
            </h3>
            <div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
              {allActivity.length > 0 ? allActivity.map((a: any, idx: number) => (
                <div key={a.id ?? idx} className="flex gap-2.5">
                  <div className="w-1.5 h-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-foreground leading-snug">{a.action}</p>
                    <p className="text-[10px] text-muted truncate">{a.projectName} · {a.user}</p>
                    <p className="text-[10px] text-muted">
                      {new Date(a.timestamp).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                    </p>
                  </div>
                </div>
              )) : <p className="text-xs text-muted italic">No activity yet.</p>}
            </div>
          </motion.div>

        </div>
      </div>

      {/* ── Engine quality health card (§7) ── */}
      {engineQuality !== null && engineQuality.count > 0 && (() => {
        const samples = engineQuality.samples ?? [];
        const sparkData = samples.slice(-20).map((s, i) => ({ i, qi: s.qualityIndex, cost: s.costUsd ?? 0 }));
        const levelColors: Record<string, string> = { WOW: '#facc15', Q3: '#a78bfa', Q2: '#4ade80', Q1: '#60a5fa', none: '#6b7280' };
        const levelEntries = (['WOW', 'Q3', 'Q2', 'Q1', 'none'] as const)
          .map((lvl) => ({ name: lvl, value: engineQuality.levels[lvl] ?? 0, color: levelColors[lvl] }))
          .filter((e) => e.value > 0);
        return (
          <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.33 }}
            className="glass rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-accent-light" /> Engine Quality Health
              </p>
              <span className="text-[10px] text-muted">{engineQuality.count} run{engineQuality.count !== 1 ? 's' : ''} · updated every 45s</span>
            </div>

            {/* KPI row */}
            <div className="grid grid-cols-3 gap-3 mb-4">
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Avg Quality</p>
                <p className="text-xl font-bold text-foreground">{engineQuality.avgQualityIndex !== null ? engineQuality.avgQualityIndex.toFixed(1) : '—'}</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Marker rate</p>
                <p className="text-xl font-bold text-success">{engineQuality.markerRate !== null ? `${(engineQuality.markerRate * 100).toFixed(0)}%` : '—'}</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <p className="text-[10px] text-muted mb-1">Total runs</p>
                <p className="text-xl font-bold text-accent-light">{engineQuality.count}</p>
              </div>
            </div>

            {/* Charts row: sparkline + donut */}
            <div className="grid grid-cols-2 gap-4">
              {/* Quality sparkline */}
              {sparkData.length > 1 && (
                <div>
                  <p className="text-[10px] text-muted mb-1.5">Quality index — last {sparkData.length} runs</p>
                  <ResponsiveContainer width="100%" height={64}>
                    <AreaChart data={sparkData} margin={{ top: 2, right: 2, bottom: 0, left: 0 }}>
                      <defs>
                        <linearGradient id="qiGrad" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="#818cf8" stopOpacity={0.4} />
                          <stop offset="95%" stopColor="#818cf8" stopOpacity={0} />
                        </linearGradient>
                      </defs>
                      <YAxis domain={[0, 100]} hide />
                      <Tooltip
                        contentStyle={{ background: 'var(--color-glass)', border: '1px solid var(--color-border)', borderRadius: 6, fontSize: 10 }}
                        formatter={(v) => [`${v ?? ''}`, 'Quality']}
                        labelFormatter={() => ''}
                      />
                      <Area type="monotone" dataKey="qi" stroke="#818cf8" fill="url(#qiGrad)" strokeWidth={1.5} dot={false} />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
              )}

              {/* Level distribution donut */}
              {levelEntries.length > 0 && (
                <div>
                  <p className="text-[10px] text-muted mb-1.5">Level distribution</p>
                  <div className="flex items-center gap-3">
                    <PieChart width={64} height={64}>
                      <Pie data={levelEntries} cx={28} cy={28} innerRadius={18} outerRadius={30} paddingAngle={2} dataKey="value" strokeWidth={0}>
                        {levelEntries.map((e) => <Cell key={e.name} fill={e.color} />)}
                      </Pie>
                    </PieChart>
                    <div className="flex flex-col gap-0.5">
                      {levelEntries.map((e) => (
                        <span key={e.name} className="text-[9px] flex items-center gap-1.5">
                          <span className="w-2 h-2 rounded-full inline-block" style={{ background: e.color }} />
                          <span className="text-muted">{e.name}</span>
                          <span className="text-foreground font-semibold">{e.value}</span>
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>

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

      {/* ── AI Engine status ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.35 }}
        className="glass rounded-xl p-4 flex items-center gap-4">
        <Cpu className="w-5 h-5 text-accent-light" />
        <div className="flex-1">
          <p className="text-sm font-medium text-foreground">Scriba AI Engine</p>
          <p className="text-[10px] text-muted">{engineStatus?.version ? `v${engineStatus.version}` : 'Checking...'}</p>
        </div>
        <span className={`flex items-center gap-1.5 text-[11px] font-medium ${engineStatus?.status === 'ok' ? 'text-green-400' : 'text-amber-400'}`}>
          <Circle className={`w-2 h-2 ${engineStatus?.status === 'ok' ? 'fill-green-400' : 'fill-amber-400'}`} />
          {engineStatus?.status === 'ok' ? 'Online' : engineStatus ? 'Degraded' : 'Checking...'}
        </span>
      </motion.div>

    </div>
  );
}
