import { useParams } from 'react-router-dom';
import { useMemo } from 'react';
import {
  Accordion,
  Alert,
  Badge,
  Button,
  Card,
  Col,
  Container,
  Row,
  Spinner,
} from 'react-bootstrap';
import { usePaperRun, useCancelPaperRun, usePaperRunPositions, usePaperRunCandles, useStrategy } from '../api/hooks';
import type { PaperRun } from '../types/api';
import EquityCurveChart from '../components/EquityCurveChart';
import CandlestickChart from '../components/CandlestickChart';
import { extractIndicatorSpecs } from '../utils/extractSmaSpecs';
import MetricLabel from '../components/MetricLabel';
import AppBreadcrumb from '../components/AppBreadcrumb';
import mdPnl from '../content/metrics/pnl.md?raw';
import mdReturn from '../content/metrics/return.md?raw';
import mdWinRate from '../content/metrics/win_rate.md?raw';
import mdProfitFactor from '../content/metrics/profit_factor.md?raw';
import mdSharpe from '../content/metrics/sharpe.md?raw';
import mdSortino from '../content/metrics/sortino.md?raw';
import mdMaxDrawdown from '../content/metrics/max_drawdown.md?raw';

const STATUS_BADGE: Record<PaperRun['status'], { bg: string; text?: string }> = {
  queued: { bg: 'info', text: 'dark' },
  running: { bg: 'primary' },
  complete: { bg: 'success' },
  failed: { bg: 'danger' },
  cancelled: { bg: 'secondary' },
};

function formatTimestamp(iso: string | null | undefined): string {
  if (!iso) return '--';
  return new Date(iso).toLocaleString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false,
  });
}

function durationBetween(start: string | null, end: string | null): string {
  if (!start || !end) return '--';
  const ms = new Date(end).getTime() - new Date(start).getTime();
  const totalSecs = Math.floor(ms / 1000);
  if (totalSecs < 60) return `${totalSecs}s`;
  const totalMins = Math.floor(totalSecs / 60);
  if (totalMins < 60) return `${totalMins}m ${totalSecs % 60}s`;
  const totalHours = Math.floor(totalMins / 60);
  if (totalHours < 48) return `${totalHours}h ${totalMins % 60}m`;
  const days = Math.floor(totalHours / 24);
  const remHours = totalHours % 24;
  return remHours > 0 ? `${days}d ${remHours}h` : `${days}d`;
}

/** Extract a numeric value from barter's nested metric wrappers. */
function extractNumber(value: unknown): number | null {
  if (value === null || value === undefined) return null;
  if (typeof value === 'number') return value;
  if (typeof value === 'string') {
    const n = parseFloat(value);
    return isNaN(n) ? null : n;
  }
  if (typeof value === 'object') {
    const obj = value as Record<string, unknown>;
    for (const key of ['value', '0', 'ratio', 'rate']) {
      if (key in obj) {
        const inner = extractNumber(obj[key]);
        if (inner !== null) return inner;
      }
    }
  }
  return null;
}

function formatMetric(value: unknown, decimals = 4): string {
  const n = extractNumber(value);
  if (n === null || n === 0) return '--';
  // Detect suspiciously large absolute values (barter bug remnants)
  if (Math.abs(n) > 1e15) return '--';
  return n.toFixed(decimals);
}

function formatPct(value: unknown): string {
  const n = extractNumber(value);
  if (n === null || n === 0) return '--';
  return `${(n * 100).toFixed(2)}%`;
}

/** Format a drawdown value: barter returns it as a positive magnitude, display as negative. */
function formatDrawdown(value: unknown): string {
  const n = extractNumber(value);
  if (n === null || n === 0) return '--';
  if (Math.abs(n) > 1e15) return '--';
  return `-${Math.abs(n).toFixed(4)}`;
}

function formatPnl(value: unknown): string {
  const n = extractNumber(value);
  if (n === null || n === 0) return '--';
  if (Math.abs(n) > 1e15) return '--';
  const sign = n >= 0 ? '+' : '';
  return `${sign}${n.toFixed(4)}`;
}

interface BacktestMetadata {
  trade_count?: number;
  candle_count?: number;
  candle_interval?: string;
  position_count?: number;
  data_range_start?: string;
  data_range_end?: string;
}

interface BalanceValue {
  free?: unknown;
  total?: unknown;
}

interface AssetEntry {
  exchange?: string;
  asset?: string;
  tear_sheet?: {
    balance_end?: BalanceValue;
    drawdown_max?: unknown;
  };
}

interface ConfigBalance {
  asset: string;
  balance: { total: unknown; free: unknown };
}

interface TearSheetData {
  pnl?: unknown;
  sharpe_ratio?: unknown;
  sortino_ratio?: unknown;
  calmar_ratio?: unknown;
  win_rate?: unknown;
  profit_factor?: unknown;
  pnl_drawdown_max?: unknown;
  pnl_return?: unknown;
}

interface ConditionPassRate {
  path: string;
  kind: string;
  comment?: string;
  true_count: number;
  true_rate: number;
  insufficient_data_count: number;
}

interface RuleAuditSummary {
  rule_index: number;
  rule_comment?: string;
  times_fired: number;
  fire_rate: number;
  conditions: ConditionPassRate[];
}

interface ConditionAuditSummary {
  total_bars: number;
  rules: RuleAuditSummary[];
}

interface ResultSummary {
  time_engine_start?: string;
  time_engine_end?: string;
  instruments?: Record<string, TearSheetData>;
  assets?: AssetEntry[];
  backtest_metadata?: BacktestMetadata;
  condition_audit_summary?: ConditionAuditSummary;
}

export default function PaperRunDetailPage() {
  const { id } = useParams<{ id: string }>();
  const { data: run, isLoading, isError, error } = usePaperRun(id!);
  const cancelMutation = useCancelPaperRun();
  const isComplete = run?.status === 'complete';
  const { data: strategy } = useStrategy(run?.strategy_id ?? undefined);
  const { data: positionsData } = usePaperRunPositions(isComplete ? id : undefined, 5000);
  const { data: candlesData } = usePaperRunCandles(isComplete ? id : undefined, run?.candle_interval ?? null);

  // Extract indicator specs from the strategy config, keeping only those whose timeframe
  // matches the chart's candle interval (null timeframe = primary = matches too).
  const indicatorSpecs = useMemo(() => {
    const cfg = run?.config as Record<string, unknown> | undefined;
    const all = extractIndicatorSpecs(cfg?.strategy);
    return all.filter((s) => s.timeframe === null || s.timeframe === run?.candle_interval);
  }, [run?.config, run?.candle_interval]);

  if (isLoading) {
    return (
      <Container>
        <Spinner animation="border" />
      </Container>
    );
  }

  if (isError) {
    return (
      <Container>
        <Alert variant="danger">{(error as Error).message}</Alert>
      </Container>
    );
  }

  if (!run) return null;

  const badge = STATUS_BADGE[run.status];
  const summary = run.result_summary as ResultSummary | null;
  const meta = summary?.backtest_metadata;

  return (
    <Container>
      <AppBreadcrumb />
      {strategy && (() => {
        const inst = (run.config as Record<string, unknown>)?.instrument as Record<string, unknown> | undefined;
        const exchange = typeof inst?.exchange === 'string' ? inst.exchange : null;
        const nameEx = typeof inst?.name_exchange === 'string' ? inst.name_exchange : null;
        return (
          <div className="mb-3">
            <h4 className="mb-0">
              {strategy.name}
              <small className="text-muted ms-2" style={{ fontWeight: 400, fontSize: '0.6em' }}>v{strategy.version}</small>
            </h4>
            {(exchange || nameEx) && (
              <small className="text-muted">
                {[exchange, nameEx].filter(Boolean).join(' · ')}
              </small>
            )}
          </div>
        );
      })()}
      {/* Header card */}
      <Card className="mb-3">
        <Card.Body>
          <div className="d-flex align-items-center justify-content-between mb-2">
            <div>
              <Badge bg={badge.bg} text={badge.text as never} className="me-2" style={{ fontSize: '0.9em' }}>
                {run.status === 'running' && (
                  <Spinner
                    size="sm"
                    animation="border"
                    className="me-1"
                    style={{ width: '0.7em', height: '0.7em' }}
                  />
                )}
                {run.status}
              </Badge>
              <Badge bg="secondary" className="me-2">{run.mode}</Badge>
              <code style={{ fontSize: '0.85em' }}>{run.id}</code>
            </div>
            {run.status === 'queued' && (
              <Button
                size="sm"
                variant="outline-danger"
                disabled={cancelMutation.isPending}
                onClick={() => cancelMutation.mutate(run.id)}
              >
                Cancel
              </Button>
            )}
          </div>
          <Row className="mb-2">
            <Col sm={3}>
              <small className="text-muted">Starts At</small>
              <div>{formatTimestamp(run.starts_at)}</div>
            </Col>
            <Col sm={3}>
              <small className="text-muted">Finishes At</small>
              <div>{formatTimestamp(run.finishes_at)}</div>
            </Col>
            <Col sm={3}>
              <small className="text-muted">Duration</small>
              <div>{durationBetween(run.starts_at, run.finishes_at)}</div>
            </Col>
            <Col sm={3}>
              <small className="text-muted">Worker</small>
              <div>{run.worker_id ? <code style={{ fontSize: '0.8em' }}>{run.worker_id}</code> : '--'}</div>
            </Col>
          </Row>
          <Row>
            <Col sm={3}>
              <small className="text-muted">Started</small>
              <div>{formatTimestamp(run.started_at)}</div>
            </Col>
            <Col sm={3}>
              <small className="text-muted">Completed</small>
              <div>
                {formatTimestamp(run.completed_at)}
                {run.started_at && run.completed_at && (
                  <small className="text-muted ms-1">
                    ({durationBetween(run.started_at, run.completed_at)})
                  </small>
                )}
              </div>
            </Col>
          </Row>
        </Card.Body>
      </Card>

      {cancelMutation.isError && (
        <Alert variant="danger" className="mb-3">
          {(cancelMutation.error as Error).message}
        </Alert>
      )}

      {/* Error message for failed runs */}
      {run.status === 'failed' && run.error_message && (
        <Alert variant="danger" className="mb-3">
          <Alert.Heading>Error</Alert.Heading>
          <pre className="mb-0" style={{ whiteSpace: 'pre-wrap' }}>
            {run.error_message}
          </pre>
        </Alert>
      )}

      {/* Result summary for completed runs */}
      {run.status === 'complete' && summary && (
        <>
          {/* Key metrics row */}
          <Row className="mb-3">
            {meta?.trade_count != null && (
              <Col sm={3}>
                <Card className="h-100 text-center">
                  <Card.Body className="py-3">
                    <div style={{ fontSize: '1.6em', fontWeight: 600 }}>
                      {meta.trade_count.toLocaleString()}
                    </div>
                    <small className="text-muted">Trades Replayed</small>
                  </Card.Body>
                </Card>
              </Col>
            )}
            {meta?.candle_count != null && (
              <Col sm={3}>
                <Card className="h-100 text-center">
                  <Card.Body className="py-3">
                    <div style={{ fontSize: '1.6em', fontWeight: 600 }}>
                      {meta.candle_count.toLocaleString()}
                    </div>
                    <small className="text-muted">
                      Candles Replayed{meta.candle_interval ? ` (${meta.candle_interval})` : ''}
                    </small>
                  </Card.Body>
                </Card>
              </Col>
            )}
            {positionsData != null && (
              <Col sm={3}>
                <Card className="h-100 text-center">
                  <Card.Body className="py-3">
                    <div style={{ fontSize: '1.6em', fontWeight: 600 }}>
                      {positionsData.total.toLocaleString()}
                    </div>
                    <small className="text-muted">Closed Positions</small>
                  </Card.Body>
                </Card>
              </Col>
            )}
            {(() => {
              // Count assets with a non-zero end balance that weren't in the initial config
              // (i.e. base assets acquired by open positions that were never closed).
              const cfg = run.config as Record<string, unknown>;
              const initialState = (cfg?.execution as Record<string, unknown>)?.initial_state as Record<string, unknown>;
              const rawBalances = (initialState?.balances ?? []) as ConfigBalance[];
              const openCount = (summary.assets ?? []).filter((entry) => {
                const assetName = entry.asset ?? '';
                const endFree = extractNumber(entry.tear_sheet?.balance_end?.free);
                const startFree = extractNumber(rawBalances.find((b) => b.asset === assetName)?.balance?.free) ?? 0;
                // An asset has an open position if it ended with more free balance than it started with
                // (i.e. a buy was placed but not closed).
                return endFree != null && endFree > startFree + 1e-10;
              }).length;
              if (openCount === 0) return null;
              return (
                <Col sm={3}>
                  <Card className="h-100 text-center border-warning">
                    <Card.Body className="py-3">
                      <div style={{ fontSize: '1.6em', fontWeight: 600, color: '#fd7e14' }}>
                        {openCount}
                      </div>
                      <small className="text-muted">Open Position{openCount !== 1 ? 's' : ''} at End</small>
                    </Card.Body>
                  </Card>
                </Col>
              );
            })()}
            {summary.instruments && Object.values(summary.instruments).map((sheet, i) => {
              const pnl = extractNumber(sheet.pnl);
              if (pnl === null || Math.abs(pnl) > 1e15) return null;
              const isPositive = pnl >= 0;
              return (
                <Col sm={3} key={i}>
                  <Card className="h-100 text-center">
                    <Card.Body className="py-3">
                      <div style={{ fontSize: '1.6em', fontWeight: 600, color: isPositive ? '#198754' : '#dc3545' }}>
                        {formatPnl(sheet.pnl)}
                      </div>
                      <small className="text-muted">Total PnL</small>
                    </Card.Body>
                  </Card>
                </Col>
              );
            })}
            {summary.instruments && Object.values(summary.instruments).map((sheet, i) => {
              const wr = extractNumber(sheet.win_rate);
              if (wr === null) return null;
              return (
                <Col sm={3} key={i}>
                  <Card className="h-100 text-center">
                    <Card.Body className="py-3">
                      <div style={{ fontSize: '1.6em', fontWeight: 600 }}>
                        {formatPct(sheet.win_rate)}
                      </div>
                      <small className="text-muted">Win Rate</small>
                    </Card.Body>
                  </Card>
                </Col>
              );
            })}
          </Row>

          {/* Data range + engine times */}
          <Card className="mb-3">
            <Card.Header>Run Details</Card.Header>
            <Card.Body>
              <Row>
                {meta?.data_range_start && (
                  <Col sm={3}>
                    <small className="text-muted">Data Start</small>
                    <div>{formatTimestamp(meta.data_range_start)}</div>
                  </Col>
                )}
                {meta?.data_range_end && (
                  <Col sm={3}>
                    <small className="text-muted">Data End</small>
                    <div>{formatTimestamp(meta.data_range_end)}</div>
                  </Col>
                )}
                <Col sm={3}>
                  <small className="text-muted">Engine Start</small>
                  <div>{formatTimestamp(summary.time_engine_start)}</div>
                </Col>
                <Col sm={3}>
                  <small className="text-muted">Engine End</small>
                  <div>{formatTimestamp(summary.time_engine_end)}</div>
                </Col>
              </Row>
            </Card.Body>
          </Card>

          {/* Candlestick chart (candle-mode backtests only) */}
          {candlesData && candlesData.candles.length > 0 && (
            <Card className="mb-3">
              <Card.Header>
                Price Chart
                <small className="text-muted ms-2">
                  {candlesData.total.toLocaleString()} {candlesData.interval} candles
                </small>
              </Card.Header>
              <Card.Body className="p-0">
                <CandlestickChart
                  candles={candlesData.candles}
                  interval={candlesData.interval}
                  indicatorSpecs={indicatorSpecs}
                  positions={positionsData?.positions}
                />
              </Card.Body>
            </Card>
          )}

          {/* Equity curve */}
          {positionsData && positionsData.positions.length > 0 && (
            <Card className="mb-3">
              <Card.Header>
                Equity Curve
                <small className="text-muted ms-2">
                  {positionsData.total.toLocaleString()} closed position{positionsData.total !== 1 ? 's' : ''}
                  {positionsData.sampled < positionsData.total && (
                    <span className="ms-1">(showing {positionsData.sampled.toLocaleString()} sampled)</span>
                  )}
                </small>
              </Card.Header>
              <Card.Body className="pt-3 pb-2 px-2">
                <EquityCurveChart positions={positionsData.positions} />
              </Card.Body>
            </Card>
          )}

          {/* Instrument statistics */}
          {summary.instruments && Object.keys(summary.instruments).length > 0 && (
            Object.entries(summary.instruments).map(([name, sheet]) => {
              // Colour helpers: sign-based (PnL, return, drawdown) and
              // threshold-based for ratios where the scale has known meaning.
              const signColor = (v: unknown) => {
                const n = extractNumber(v);
                if (n == null || Math.abs(n) > 1e15) return undefined;
                return n >= 0 ? '#198754' : '#dc3545';
              };
              // Thresholds for higher-is-better ratios (Sharpe, Sortino, etc.)
              // < 0 → red, 0–1 → orange, 1–2 → neutral, ≥ 2 → green
              const ratioColor = (v: unknown) => {
                const n = extractNumber(v);
                if (n == null || Math.abs(n) > 1e15) return undefined;
                if (n < 0)   return '#dc3545'; // bad
                if (n < 1)   return '#fd7e14'; // below acceptable
                if (n < 2)   return '#6c757d'; // acceptable but not great
                return '#198754';              // good
              };
              // Profit factor: < 1 red, 1–1.5 orange, ≥ 1.5 green
              const pfColor = (v: unknown) => {
                const n = extractNumber(v);
                if (n == null || Math.abs(n) > 1e15) return undefined;
                if (n < 1)   return '#dc3545';
                if (n < 1.5) return '#fd7e14';
                return '#198754';
              };
              // Win rate: < 40% red, 40–50% orange, ≥ 50% green
              const wrColor = (v: unknown) => {
                const n = extractNumber(v);
                if (n == null) return undefined;
                if (n < 0.4)  return '#dc3545';
                if (n < 0.5)  return '#fd7e14';
                return '#198754';
              };

              const metrics: [string, string, string, string | undefined][] = [
                ['PnL',           formatPnl(sheet.pnl),               mdPnl,          signColor(sheet.pnl)],
                ['Return',        formatPct(sheet.pnl_return),         mdReturn,       signColor(sheet.pnl_return)],
                ['Win Rate',      formatPct(sheet.win_rate),           mdWinRate,      wrColor(sheet.win_rate)],
                ['Profit Factor', formatMetric(sheet.profit_factor, 3), mdProfitFactor, pfColor(sheet.profit_factor)],
                ['Sharpe',        formatMetric(sheet.sharpe_ratio, 3),  mdSharpe,       ratioColor(sheet.sharpe_ratio)],
                ['Sortino',       formatMetric(sheet.sortino_ratio, 3), mdSortino,      ratioColor(sheet.sortino_ratio)],
                ['Max Drawdown',  formatDrawdown(sheet.pnl_drawdown_max), mdMaxDrawdown, sheet.pnl_drawdown_max != null ? '#dc3545' : undefined],
              ];
              return (
                <Card className="mb-3" key={name}>
                  <Card.Header>
                    Performance — <code>{name}</code>
                  </Card.Header>
                  <Card.Body>
                    <Row>
                      {metrics.map(([label, value, markdown, color]) => (
                        <Col key={label} xs={6} sm={4} md={3} className="mb-3">
                          <small className="text-muted d-block">
                            <MetricLabel label={label} markdown={markdown} />
                          </small>
                          <span style={{ fontWeight: 600, color: value === '--' ? undefined : color }}>
                            {value}
                          </span>
                        </Col>
                      ))}
                    </Row>
                  </Card.Body>
                </Card>
              );
            })
          )}

          {/* Asset balances */}
          {summary.assets && summary.assets.length > 0 && (() => {
            const cfg = run.config as Record<string, unknown>;
            const initialState = (cfg?.execution as Record<string, unknown>)?.initial_state as Record<string, unknown>;
            const rawBalances = (initialState?.balances ?? []) as ConfigBalance[];
            const configBalanceMap = new Map<string, number>(
              rawBalances.map((b) => [b.asset, extractNumber(b.balance?.total) ?? 0])
            );

            return (
              <Card className="mb-3">
                <Card.Header>Asset Balances</Card.Header>
                <Card.Body>
                  <Row>
                    {summary.assets!.map((entry, i) => {
                      const assetName = entry.asset ?? '--';
                      const endTotal = extractNumber(entry.tear_sheet?.balance_end?.total);
                      const startTotal = configBalanceMap.get(assetName) ?? null;
                      const change = startTotal != null && endTotal != null ? endTotal - startTotal : null;
                      const changePct = change != null && startTotal ? (change / startTotal) * 100 : null;
                      const changeColor = change == null ? undefined : change >= 0 ? '#198754' : '#dc3545';
                      return (
                        <Col key={i} xs={12} sm={6} md={4} className="mb-3">
                          <div className="border rounded p-3 h-100">
                            <div className="mb-2">
                              <code style={{ fontSize: '1em' }}>{assetName}</code>
                            </div>
                            <Row className="g-2 text-center">
                              <Col xs={4}>
                                <small className="text-muted d-block">Start</small>
                                <span style={{ fontWeight: 500 }}>
                                  {startTotal != null ? startTotal.toFixed(4) : '--'}
                                </span>
                              </Col>
                              <Col xs={4}>
                                <small className="text-muted d-block">End</small>
                                <span style={{ fontWeight: 500 }}>
                                  {endTotal != null ? endTotal.toFixed(4) : '--'}
                                </span>
                              </Col>
                              <Col xs={4}>
                                <small className="text-muted d-block">Change</small>
                                <span style={{ fontWeight: 600, color: changeColor }}>
                                  {change != null
                                    ? `${change >= 0 ? '+' : ''}${change.toFixed(4)}`
                                    : '--'}
                                </span>
                                {changePct != null && (
                                  <small className="d-block" style={{ color: changeColor }}>
                                    {`${changePct >= 0 ? '+' : ''}${changePct.toFixed(2)}%`}
                                  </small>
                                )}
                              </Col>
                            </Row>
                          </div>
                        </Col>
                      );
                    })}
                  </Row>
                </Card.Body>
              </Card>
            );
          })()}

          {summary?.condition_audit_summary && (() => {
            const cas = summary.condition_audit_summary!;

            function passRateColor(rate: number): string {
              if (rate < 0.05) return '#dc3545';
              if (rate < 0.2)  return '#fd7e14';
              return 'inherit';
            }

            function downloadDetail() {
              const runId = id!;
              fetch(`/api/v1/paper-runs/${runId}/condition-audit/detail?limit=10000`)
                .then(r => r.json())
                .then(data => {
                  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = `condition-audit-${runId}.json`;
                  a.click();
                  URL.revokeObjectURL(url);
                });
            }

            return (
              <Card className="mb-3">
                <Card.Header className="d-flex align-items-center justify-content-between">
                  <strong>Condition Audit</strong>
                  <div className="d-flex gap-2 align-items-center">
                    <small className="text-muted">{cas.total_bars} bars evaluated</small>
                    <Button size="sm" variant="outline-secondary" onClick={downloadDetail}>
                      Download detail JSON
                    </Button>
                  </div>
                </Card.Header>
                <Card.Body style={{ overflowX: 'auto' }}>
                  {cas.rules.map(rule => (
                    <div key={rule.rule_index} className="mb-4">
                      <div className="mb-1">
                        <strong>Rule {rule.rule_index}</strong>
                        {rule.rule_comment && (
                          <span className="text-muted ms-2" style={{ fontSize: '0.9em' }}>{rule.rule_comment}</span>
                        )}
                        <span className="ms-2 badge bg-secondary">fired {rule.times_fired}× ({(rule.fire_rate * 100).toFixed(1)}%)</span>
                      </div>
                      <table className="table table-sm table-bordered mb-0" style={{ fontSize: '0.85em' }}>
                        <thead className="table-light">
                          <tr>
                            <th>Condition</th>
                            <th>Kind</th>
                            <th>Pass rate</th>
                            <th>True count</th>
                            <th>Insufficient data</th>
                          </tr>
                        </thead>
                        <tbody>
                          {rule.conditions
                            .slice()
                            .sort((a, b) => a.true_rate - b.true_rate)
                            .map(cond => (
                              <tr key={cond.path}>
                                <td>
                                  <code style={{ fontSize: '0.85em' }}>{cond.path}</code>
                                  {cond.comment && (
                                    <div className="text-muted" style={{ fontSize: '0.8em' }}>{cond.comment}</div>
                                  )}
                                </td>
                                <td><code>{cond.kind}</code></td>
                                <td style={{ color: passRateColor(cond.true_rate), fontWeight: cond.true_rate < 0.05 ? 'bold' : 'normal' }}>
                                  {(cond.true_rate * 100).toFixed(1)}%
                                </td>
                                <td>{cond.true_count}</td>
                                <td>{cond.insufficient_data_count > 0 ? cond.insufficient_data_count : '—'}</td>
                              </tr>
                            ))}
                        </tbody>
                      </table>
                    </div>
                  ))}
                </Card.Body>
              </Card>
            );
          })()}

          <Accordion className="mb-3">
            <Accordion.Item eventKey="0">
              <Accordion.Header>Raw Result JSON</Accordion.Header>
              <Accordion.Body>
                <pre style={{ whiteSpace: 'pre-wrap', fontSize: '0.85em' }}>
                  {JSON.stringify(run.result_summary, null, 2)}
                </pre>
              </Accordion.Body>
            </Accordion.Item>
          </Accordion>
        </>
      )}

      {/* Config accordion */}
      <Accordion className="mb-3">
        <Accordion.Item eventKey="0">
          <Accordion.Header>Config</Accordion.Header>
          <Accordion.Body>
            <pre style={{ whiteSpace: 'pre-wrap', fontSize: '0.85em' }}>
              {JSON.stringify(run.config, null, 2)}
            </pre>
          </Accordion.Body>
        </Accordion.Item>
      </Accordion>
    </Container>
  );
}
