import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Activity,
  AlertTriangle,
  ArrowDownRight,
  ArrowRight,
  Boxes,
  Check,
  ChevronDown,
  CircleDot,
  Clock3,
  Gauge,
  GitBranch,
  HeartPulse,
  Layers3,
  Pause,
  Play,
  RefreshCw,
  Search,
  ShieldCheck,
  Sparkles,
  Users,
  X,
  Zap,
} from 'lucide-react';
import { fetchDashboard, quarantineImplementation, restoreImplementation, type DataSource } from './api';
import { mockDashboardData } from './mockData';
import type {
  DashboardData,
  HealthStatus,
  Implementation,
  Interaction,
  Quarantine,
  Severity,
  TelemetryEvent,
} from './types';

const refreshEveryMs = 20_000;

function formatCompact(value: number): string {
  return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(value);
}

function formatNumber(value: number): string {
  return new Intl.NumberFormat('en-US').format(value);
}

function formatTime(value: string): string {
  const date = new Date(value);
  return new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit' }).format(date);
}

function timeAgo(value: string, now = Date.now()): string {
  const seconds = Math.max(1, Math.floor((now - new Date(value).getTime()) / 1000));
  if (seconds < 60) return `${seconds}s ago`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86_400)}d ago`;
}

function Header({ source, activityAt, paused, onTogglePause, onRefresh }: {
  source: DataSource;
  activityAt: string;
  paused: boolean;
  onTogglePause: () => void;
  onRefresh: () => void;
}) {
  const [clock, setClock] = useState(Date.now());
  useEffect(() => {
    const timer = window.setInterval(() => setClock(Date.now()), 1_000);
    return () => window.clearInterval(timer);
  }, []);
  return (
    <header className="topbar">
      <a className="brand" href="#top" aria-label="Polyform dashboard home">
        <span className="brand-mark" aria-hidden="true"><Boxes size={18} strokeWidth={2.2} /></span>
        <span>POLYFORM</span>
      </a>
      <div className="topbar-actions">
        <div className={`source-pill ${source}`} role="status">
          <span className="status-dot" />
          {source === 'live' ? 'Live telemetry' : 'Demonstration data'}
        </div>
        <span className="last-updated">{activityAt ? `Latest execution ${timeAgo(activityAt, clock)}` : 'No executions yet'}</span>
        <button className="icon-button" onClick={onTogglePause} aria-label={paused ? 'Resume automatic refresh' : 'Pause automatic refresh'}>
          {paused ? <Play size={16} /> : <Pause size={16} />}
        </button>
        <button className="icon-button" onClick={onRefresh} aria-label="Refresh dashboard now">
          <RefreshCw size={16} />
        </button>
      </div>
    </header>
  );
}

function MetricCard({ icon, label, value, detail, tone = 'neutral' }: {
  icon: React.ReactNode;
  label: string;
  value: string;
  detail: React.ReactNode;
  tone?: 'neutral' | 'good' | 'accent';
}) {
  return (
    <article className={`metric-card ${tone}`}>
      <div className="metric-heading"><span className="metric-icon">{icon}</span><span>{label}</span></div>
      <strong>{value}</strong>
      <div className="metric-detail">{detail}</div>
    </article>
  );
}

function DiversityMap({ data }: { data: DashboardData }) {
  const max = Math.max(...data.implementationsPerFunction.map((item) => item.count));
  return (
    <section className="panel diversity-panel" aria-labelledby="diversity-title">
      <div className="panel-header">
        <div>
          <div className="eyebrow"><GitBranch size={13} /> Composition diversity</div>
          <h2 id="diversity-title">One product. Hundreds of active forms.</h2>
          <p>Each client draws one independently tested implementation from every specification function.</p>
        </div>
        <div className="composition-count">
          <strong>{formatCompact(data.summary.activeCompositions)}</strong>
          <span>active of {formatCompact(data.summary.possibleCompositions)} possible</span>
        </div>
      </div>

      <div className="spec-grid" role="list" aria-label="Implementations available per specification function">
        {data.implementationsPerFunction.map((item, index) => (
          <div className="spec-column" key={item.name} role="listitem">
            <span className="spec-index">{String(index + 1).padStart(2, '0')}</span>
            <div className="variant-stack" aria-label={`${item.count} implementations`}>
              {Array.from({ length: item.count }).map((_, variant) => (
                <i key={variant} style={{ opacity: 0.4 + ((variant + 1) / max) * 0.6 }} />
              ))}
            </div>
            <b>{item.count}</b>
            <span title={item.name}>{item.name}</span>
          </div>
        ))}
      </div>

      <div className="explain-flow" aria-label="How diversity localizes failures">
        <div><span className="flow-icon"><Users size={16} /></span><p><b>Assign</b><small>diverse compositions</small></p></div>
        <ArrowRight size={18} aria-hidden="true" />
        <div><span className="flow-icon"><Activity size={16} /></span><p><b>Compare</b><small>observable outcomes</small></p></div>
        <ArrowRight size={18} aria-hidden="true" />
        <div><span className="flow-icon hot"><CircleDot size={16} /></span><p><b>Localize</b><small>shared variants</small></p></div>
        <ArrowRight size={18} aria-hidden="true" />
        <div><span className="flow-icon safe"><ShieldCheck size={16} /></span><p><b>Quarantine</b><small>and recompose</small></p></div>
      </div>
    </section>
  );
}

function DistributionPanel({ data }: { data: DashboardData }) {
  return (
    <section className="panel" aria-labelledby="distribution-title">
      <div className="panel-header compact">
        <div>
          <div className="eyebrow"><Layers3 size={13} /> Population</div>
          <h2 id="distribution-title">Active composition / variant distribution</h2>
        </div>
        <button className="text-button">View all <ArrowRight size={14} /></button>
      </div>
      <div className="distribution-list">
        {data.compositions.map((composition, index) => (
          <div className="distribution-row" key={composition.id}>
            <div className={`composition-swatch swatch-${index + 1}`} />
            <div className="distribution-name">
              <b>{composition.label === '710 other compositions' ? composition.label : composition.label}</b>
              <span>{composition.clients} clients · {composition.failureRate.toFixed(1)}% failure</span>
            </div>
            <div className="distribution-bar"><i style={{ width: `${Math.max(composition.share, 2)}%` }} /></div>
            <strong>{composition.share.toFixed(1)}%</strong>
          </div>
        ))}
      </div>
      <p className="panel-note"><Sparkles size={14} /> 57% of clients have a composition shared by fewer than five peers.</p>
    </section>
  );
}

function RiskBadge({ status }: { status: HealthStatus }) {
  const labels = { healthy: 'Healthy', watch: 'Investigate', quarantined: 'Quarantined' };
  return <span className={`risk-badge ${status}`}><span />{labels[status]}</span>;
}

function ImplementationsPanel({ implementations, onQuarantine, onRestore }: {
  implementations: Implementation[];
  onQuarantine: (implementation: Implementation) => void;
  onRestore: (implementation: Implementation) => void;
}) {
  const [query, setQuery] = useState('');
  const [filter, setFilter] = useState<'all' | HealthStatus>('all');
  const filtered = implementations.filter((item) => {
    const matchesSearch = `${item.specFunction} ${item.variantName ?? item.id.split('.').at(-1)} ${item.id}`.toLowerCase().includes(query.toLowerCase());
    return matchesSearch && (filter === 'all' || item.status === filter);
  });

  return (
    <section className="panel implementations-panel" aria-labelledby="implementation-title">
      <div className="panel-header table-heading">
        <div>
          <div className="eyebrow"><Gauge size={13} /> Association analysis</div>
          <h2 id="implementation-title">Failure risk by implementation</h2>
          <p>Risk is compared with alternative implementations of the same specification function.</p>
        </div>
        <div className="table-tools">
          <label className="search-box">
            <Search size={15} aria-hidden="true" />
            <span className="sr-only">Search implementations</span>
            <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Find variant" />
          </label>
          <label className="select-box">
            <span className="sr-only">Filter by status</span>
            <select value={filter} onChange={(event) => setFilter(event.target.value as typeof filter)}>
              <option value="all">All statuses</option>
              <option value="watch">Investigate</option>
              <option value="quarantined">Quarantined</option>
              <option value="healthy">Healthy</option>
            </select>
            <ChevronDown size={14} aria-hidden="true" />
          </label>
        </div>
      </div>
      <div className="table-wrap">
        <table>
          <thead><tr><th>Implementation</th><th>Clients</th><th>Executions</th><th>Failures</th><th>Failure rate</th><th>Relative risk</th><th>Confidence</th><th>Status</th><th><span className="sr-only">Actions</span></th></tr></thead>
          <tbody>
            {filtered.map((item) => (
              <tr key={item.id} className={`${item.status === 'quarantined' ? 'muted-row' : ''} ${item.experimental ? 'controlled-fault-row' : ''}`}>
                <td><span className="variant-chip" title={item.variantName ?? item.id}>{item.variant}</span><div><b>{item.specFunction}</b><small>{item.variantName ?? item.id.split('.').at(-1)}{item.experimental && <span className="controlled-fault-badge">Controlled fault</span>}</small></div></td>
                <td>{formatNumber(item.clients)}</td>
                <td>{formatCompact(item.executions)}</td>
                <td>{formatNumber(item.failures)}</td>
                <td><b className={item.failureRate > 2 ? 'danger-text' : ''}>{item.failureRate.toFixed(2)}%</b></td>
                <td><div className="risk-meter"><i style={{ width: `${Math.min(item.relativeRisk / 5 * 100, 100)}%` }} /><span>{item.relativeRisk.toFixed(1)}×</span></div></td>
                <td>{item.confidence.toFixed(1)}%</td>
                <td><RiskBadge status={item.status} /></td>
                <td>
                  {item.sourceUrl && <a className="row-action source-action" href={item.sourceUrl} target="_blank" rel="noreferrer" aria-label={`View source for ${item.variant}`}>Investigate</a>}
                  {item.status === 'watch' && <button className="row-action" onClick={() => onQuarantine(item)} aria-label={`Quarantine ${item.variant}`}>Quarantine</button>}
                  {item.status === 'quarantined' && <button className="row-action restore-action" onClick={() => onRestore(item)} aria-label={`Restore ${item.variant}`}>Restore</button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {filtered.length === 0 && <div className="empty-state">No implementations match this view.</div>}
      <div className="method-note"><ShieldCheck size={15} /><span><b>What this means:</b> DEFLATE·F3 fails 3.2× as often as peers performing the same job, after accounting for composition exposure.</span></div>
    </section>
  );
}

function InteractionsPanel({ interactions }: { interactions: Interaction[] }) {
  const maxLift = Math.max(...interactions.map((item) => item.lift));
  return (
    <section className="panel" aria-labelledby="interaction-title">
      <div className="panel-header compact">
        <div>
          <div className="eyebrow"><Zap size={13} /> Pairwise signal</div>
          <h2 id="interaction-title">Risky combinations</h2>
          <p>Variants that are disproportionately risky only when deployed together.</p>
        </div>
      </div>
      <div className="interaction-list">
        {interactions.map((item, index) => (
          <article className="interaction" key={`${item.first}-${item.second}`}>
            <div className="interaction-rank">0{index + 1}</div>
            <div className="pair"><span>{item.first}</span><X size={13} /><span>{item.second}</span></div>
            <div className="interaction-bar"><i style={{ width: `${item.lift / maxLift * 100}%` }} /></div>
            <div className="interaction-stat"><b>{item.lift.toFixed(2)}×</b><span>risk lift</span></div>
            <div className="interaction-meta"><span>{item.observedFailureRate.toFixed(1)}% observed</span><span>{item.expectedFailureRate.toFixed(1)}% expected</span><span>{item.clients} clients</span></div>
          </article>
        ))}
      </div>
    </section>
  );
}

function QuarantinePanel({ quarantines, data }: { quarantines: Quarantine[]; data: DashboardData }) {
  const current = quarantines[0];
  const currentStage = data.healthSequence.at(-1);
  const previousStage = data.healthSequence.slice(0, -1).reverse().find((stage) => stage.executions > 0) ?? currentStage;
  const hasAfterMeasurement = Boolean(current && currentStage && currentStage.executions > 0);
  const beforeHealthy = previousStage?.healthyRate ?? 0;
  const afterHealthy = currentStage?.healthyRate ?? 0;
  const healthyImprovement = afterHealthy - beforeHealthy;
  return (
    <section className="panel quarantine-panel" aria-labelledby="quarantine-title">
      <div className="panel-header compact">
        <div>
          <div className="eyebrow"><ShieldCheck size={13} /> Intervention</div>
          <h2 id="quarantine-title">Healthy executions after quarantine</h2>
          <p>{current ? (hasAfterMeasurement ? `${current.variant} removed from assignment · ${currentStage?.executions} executions since the latest quarantine` : `${current.variant} removed from assignment · waiting for new executions`) : 'No quarantine yet. Investigate a suspect, then quarantine it to measure the change.'}</p>
        </div>
        {current && hasAfterMeasurement && <div className="recovery-stat"><ArrowDownRight size={18} /><b>{healthyImprovement >= 0 ? '+' : ''}{healthyImprovement.toFixed(1)}</b><span>healthy points</span></div>}
      </div>
      <div className="trend-chart" aria-label="Healthy executions by quarantine sequence">
        <div className="y-labels"><span>100%</span><span>50%</span><span>0%</span></div>
        <div className="trend-plot">
          <div className="grid-line top" /><div className="grid-line mid" /><div className="grid-line bottom" />
          <div className="trend-bars">
            {data.healthSequence.map((stage, index) => (
              <div className="trend-column" key={`${stage.label}-${index}`}>
                <i className={index === 0 ? 'before' : 'after'} style={{ height: `${stage.executions > 0 ? stage.healthyRate : 0}%` }} title={stage.executions > 0 ? `${stage.label}: ${stage.healthyRate.toFixed(1)}% healthy across ${stage.executions} executions` : `${stage.label}: no executions measured`} />
                <span>{stage.label}<small>{stage.executions > 0 ? `${stage.executions} runs` : 'no data'}</small></span>
              </div>
            ))}
          </div>
        </div>
      </div>
      {current && <div className="before-after">
        <div><span>Before</span><b>{beforeHealthy.toFixed(1)}%</b><small>healthy executions</small></div>
        <ArrowRight size={20} />
        <div className="after"><span>After</span><b>{hasAfterMeasurement ? `${afterHealthy.toFixed(1)}%` : '—'}</b><small>{hasAfterMeasurement ? 'healthy executions' : 'collecting executions'}</small></div>
        <div className="recompose-progress"><span><b>{current.recomposedClients}/{current.affectedClients}</b> clients recomposed</span><div><i style={{ width: `${current.recomposedClients / current.affectedClients * 100}%` }} /></div></div>
      </div>}
    </section>
  );
}

const severityIcons: Record<Severity, React.ReactNode> = {
  critical: <AlertTriangle size={15} />,
  warning: <CircleDot size={15} />,
  success: <Check size={15} />,
  info: <Activity size={15} />,
};

function EventRow({ event }: { event: TelemetryEvent }) {
  return (
    <li className="event-row">
      <span className={`event-icon ${event.severity}`}>{severityIcons[event.severity]}</span>
      <div className="event-main">
        <div><b>{event.message}</b><span className={`event-kind ${event.severity}`}>{event.kind.replaceAll('_', ' ')}</span></div>
        <p><span>{event.clientId}</span><span>{event.implementationId}</span><span>{event.specFunction}</span></p>
        {event.recentCalls.length > 0 && <div className="call-chain">{event.recentCalls.map((call, index) => <span key={call}>{index > 0 && <ArrowRight size={11} />}{call}</span>)}</div>}
      </div>
      <time dateTime={event.timestamp} title={new Date(event.timestamp).toLocaleString()}>{timeAgo(event.timestamp)}</time>
    </li>
  );
}

function TelemetryPanel({ events }: { events: TelemetryEvent[] }) {
  const [active, setActive] = useState('all');
  const filtered = active === 'all' ? events : events.filter((event) => event.severity === active);
  return (
    <section className="panel telemetry-panel" aria-labelledby="telemetry-title">
      <div className="panel-header telemetry-heading">
        <div>
          <div className="eyebrow"><Activity size={13} /> Observable events</div>
          <h2 id="telemetry-title">Telemetry stream</h2>
          <p>Hard failures and composition changes only. No filenames or file contents collected.</p>
        </div>
        <div className="filter-tabs" aria-label="Filter telemetry events">
          {['all', 'critical', 'warning', 'success'].map((filter) => <button key={filter} className={active === filter ? 'active' : ''} onClick={() => setActive(filter)}>{filter}</button>)}
        </div>
      </div>
      <ol className="event-list">
        {filtered.map((event) => <EventRow event={event} key={event.id} />)}
      </ol>
    </section>
  );
}

function QuarantineDialog({ implementation, onClose, onConfirm, busy }: {
  implementation: Implementation;
  onClose: () => void;
  onConfirm: () => void;
  busy: boolean;
}) {
  return (
    <div className="dialog-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
      <section className="dialog" role="dialog" aria-modal="true" aria-labelledby="dialog-title">
        <button className="dialog-close" onClick={onClose} aria-label="Close dialog"><X size={17} /></button>
        <span className="dialog-icon"><ShieldCheck size={22} /></span>
        <div className="eyebrow">Quarantine implementation</div>
        <h2 id="dialog-title">Remove {implementation.variant} from circulation?</h2>
        <p>New clients will no longer receive this variant. Its {formatNumber(implementation.clients)} active clients will receive replacement compositions on their next check-in.</p>
        <div className="dialog-evidence"><span>Relative risk <b>{implementation.relativeRisk.toFixed(1)}×</b></span><span>Confidence <b>{implementation.confidence.toFixed(1)}%</b></span></div>
        <div className="dialog-actions"><button className="button secondary" onClick={onClose}>Cancel</button><button className="button danger" disabled={busy} onClick={onConfirm}>{busy ? 'Quarantining…' : 'Quarantine & recompose'}</button></div>
      </section>
    </div>
  );
}

function RestoreDialog({ implementation, onClose, onConfirm, busy }: {
  implementation: Implementation;
  onClose: () => void;
  onConfirm: () => void;
  busy: boolean;
}) {
  return (
    <div className="dialog-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
      <section className="dialog" role="dialog" aria-modal="true" aria-labelledby="restore-dialog-title">
        <button className="dialog-close" onClick={onClose} aria-label="Close dialog"><X size={17} /></button>
        <span className="dialog-icon"><RefreshCw size={22} /></span>
        <div className="eyebrow">Restore implementation</div>
        <h2 id="restore-dialog-title">Return {implementation.variant} to circulation?</h2>
        <p>Future clients may receive this implementation again. Existing clients will keep their current healthy compositions unless another recomposition is needed.</p>
        {implementation.experimental && <div className="dialog-evidence"><span>This is a marked <b>controlled fault</b> used for the experiment.</span></div>}
        <div className="dialog-actions"><button className="button secondary" onClick={onClose}>Cancel</button><button className="button danger" disabled={busy} onClick={onConfirm}>{busy ? 'Restoring…' : 'Restore implementation'}</button></div>
      </section>
    </div>
  );
}

export default function App({ releaseId }: { releaseId?: number } = {}) {
  const [data, setData] = useState<DashboardData>(mockDashboardData);
  const [source, setSource] = useState<DataSource>('demo');
  const [error, setError] = useState<string | undefined>();
  const [paused, setPaused] = useState(false);
  const [loading, setLoading] = useState(false);
  const [quarantineTarget, setQuarantineTarget] = useState<Implementation | null>(null);
  const [restoreTarget, setRestoreTarget] = useState<Implementation | null>(null);
  const [quarantining, setQuarantining] = useState(false);
  const [restoring, setRestoring] = useState(false);
  const [toast, setToast] = useState<string | null>(null);

  const refresh = useCallback(async (signal?: AbortSignal) => {
    setLoading(true);
    try {
      const result = await fetchDashboard(signal, releaseId);
      setData(result.data);
      setSource(result.source);
      setError(result.error);
    } catch (refreshError) {
      if (!(refreshError instanceof DOMException && refreshError.name === 'AbortError')) setError('Unable to refresh dashboard');
    } finally {
      setLoading(false);
    }
  }, [releaseId]);

  useEffect(() => {
    const controller = new AbortController();
    void refresh(controller.signal);
    return () => controller.abort();
  }, [refresh]);

  useEffect(() => {
    if (paused) return;
    const timer = window.setInterval(() => void refresh(), refreshEveryMs);
    return () => window.clearInterval(timer);
  }, [paused, refresh]);

  useEffect(() => {
    if (!toast) return;
    const timer = window.setTimeout(() => setToast(null), 4500);
    return () => window.clearTimeout(timer);
  }, [toast]);

  const healthImprovement = useMemo(() => data.summary.previousFailureRate - data.summary.populationFailureRate, [data]);

  async function confirmQuarantine() {
    if (!quarantineTarget) return;
    setQuarantining(true);
    try {
      if (source === 'live') await quarantineImplementation(quarantineTarget.id, quarantineTarget.releaseId, `${quarantineTarget.relativeRisk.toFixed(1)}× relative risk at ${quarantineTarget.confidence.toFixed(1)}% confidence`);
      setData((current) => ({
        ...current,
        implementations: current.implementations.map((item) => item.id === quarantineTarget.id ? { ...item, status: 'quarantined', clients: 0 } : item),
      }));
      setToast(source === 'live' ? `${quarantineTarget.variant} quarantined. Recomposition queued.` : `Demo: ${quarantineTarget.variant} moved to quarantine.`);
      setQuarantineTarget(null);
    } catch (quarantineError) {
      setToast(quarantineError instanceof Error ? quarantineError.message : 'Quarantine request failed');
    } finally {
      setQuarantining(false);
    }
  }

  async function confirmRestore() {
    if (!restoreTarget) return;
    setRestoring(true);
    try {
      if (source === 'live') await restoreImplementation(restoreTarget.id, restoreTarget.releaseId, 'Restored by dashboard operator');
      setData((current) => ({
        ...current,
        implementations: current.implementations.map((item) => item.id === restoreTarget.id ? { ...item, status: 'watch' } : item),
      }));
      setToast(source === 'live' ? `${restoreTarget.variant} restored for future assignments.` : `Demo: ${restoreTarget.variant} restored.`);
      setRestoreTarget(null);
      if (source === 'live') await refresh();
    } catch (restoreError) {
      setToast(restoreError instanceof Error ? restoreError.message : 'Restore request failed');
    } finally {
      setRestoring(false);
    }
  }

  return (
    <div id="top" className="app-shell">
      <Header source={source} activityAt={data.generatedAt} paused={paused} onTogglePause={() => setPaused((value) => !value)} onRefresh={() => void refresh()} />
      {source === 'demo' && <div className="connection-banner" role="status"><AlertTriangle size={15} /><span><b>API unavailable.</b> Showing representative experiment data so the dashboard remains explorable.</span>{error && <span className="connection-detail" title={error}>{error}</span>}</div>}
      <main>
        <section className="hero" aria-labelledby="page-title">
          <div>
            <div className="release-line"><span className="release-dot" /> {data.release.name} {data.release.version} · {data.release.status} release
              {data.release.repositoryUrl && <a href={data.release.repositoryUrl} target="_blank" rel="noreferrer">Source</a>}
              {data.release.artifactUrl && <a href={data.release.artifactUrl}>Download</a>}
            </div>
            <h1 id="page-title">Population health</h1>
            <p>Combinatorial observability across independently generated ZIP implementations.</p>
          </div>
          <div className="hero-status">
            <div className="health-ring" style={{ '--health': `${100 - data.summary.populationFailureRate * 4}%` } as React.CSSProperties}><span><HeartPulse size={18} /><b>{(100 - data.summary.populationFailureRate).toFixed(1)}%</b><small>healthy executions</small></span></div>
          </div>
        </section>

        <section className="metric-grid" aria-label="Key experiment metrics">
          <MetricCard icon={<Users size={17} />} label="Registered clients" value={formatNumber(data.summary.clients)} detail={<><b>{formatNumber(data.summary.activeClients)}</b> active now</>} />
          <MetricCard icon={<GitBranch size={17} />} label="Spec functions" value={String(data.summary.specFunctions)} detail={<><b>{data.summary.implementations}</b> accepted implementations</>} />
          <MetricCard icon={<Boxes size={17} />} label="Possible compositions" value={formatCompact(data.summary.possibleCompositions)} detail={<><b>{data.summary.activeCompositions}</b> observed in population</>} tone="accent" />
          <MetricCard icon={<Activity size={17} />} label="Telemetry events" value={formatCompact(data.summary.telemetryEvents)} detail={<>observable events, no user content</>} />
          <MetricCard icon={<ShieldCheck size={17} />} label="Healthy executions" value={`${(100 - data.summary.populationFailureRate).toFixed(1)}%`} detail={data.quarantines.length > 0 ? <span className="good-detail"><ArrowDownRight size={13} /> {healthImprovement >= 0 ? '+' : ''}{healthImprovement.toFixed(1)} pts after quarantine</span> : <>live baseline · quarantine to compare</>} tone="good" />
        </section>

        <DiversityMap data={data} />

        <div className="two-column">
          <DistributionPanel data={data} />
          <InteractionsPanel interactions={data.interactions} />
        </div>

        <ImplementationsPanel implementations={data.implementations} onQuarantine={setQuarantineTarget} onRestore={setRestoreTarget} />
        <QuarantinePanel quarantines={data.quarantines} data={data} />
        <TelemetryPanel events={data.telemetry} />
      </main>
      <footer>
        <div><span className="brand-mark small"><Boxes size={14} /></span><b>Polyform</b><span>Combinatorially diversified software</span></div>
        <div><Clock3 size={13} /><span>{paused ? 'Automatic refresh paused' : `Refreshes every ${refreshEveryMs / 1000} seconds`}</span>{loading && <span className="loading-label">Refreshing…</span>}</div>
      </footer>
      {quarantineTarget && <QuarantineDialog implementation={quarantineTarget} onClose={() => setQuarantineTarget(null)} onConfirm={() => void confirmQuarantine()} busy={quarantining} />}
      {restoreTarget && <RestoreDialog implementation={restoreTarget} onClose={() => setRestoreTarget(null)} onConfirm={() => void confirmRestore()} busy={restoring} />}
      {toast && <div className="toast" role="status"><Check size={16} />{toast}</div>}
    </div>
  );
}
