'use client';

import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
import { useEffect, useState, type ReactNode } from 'react';
import { getEvalRunDetail, type EvalCaseRun, type EvalRunDetail } from '@/lib/admin-eval-runs';
import { useTranslation } from '@/lib/i18n';
import type { TranslationKey } from '@/lib/i18n/messages/en';

const SCORE_BUCKETS = [
  'workflow',
  'evidence_collection',
  'critical_evidence',
  'evidence_routing',
  'diagnosis',
] as const;

function formatDateTime(value: string | null | undefined): string {
  if (!value) return '—';
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}

function prettyLabel(value: string): string {
  if (!value) return '—';
  return value.replace(/_/g, ' ');
}

function normalizeContractEvalStatus(value: string, t: (key: TranslationKey) => string): string {
  const normalized = value.toLowerCase();
  if (!normalized) return '—';
  if (normalized === 'not_evaluated') return t('adminEvalRunDetail.contractNotEvaluated');
  if (normalized === 'fail') return t('adminEvalRunDetail.contractFailed');
  if (normalized === 'pass') return t('adminEvalRunDetail.contractPassed');
  return prettyLabel(value);
}

function StatusBadge({ value }: { value: string }) {
  const normalized = value.toLowerCase();
  let background = '#eef2ff';
  let color = '#4338ca';
  if (normalized === 'completed' || normalized === 'pass' || normalized === 'compared') {
    background = '#dcfce7';
    color = '#166534';
  } else if (normalized === 'running' || normalized === 'pending') {
    background = '#dbeafe';
    color = '#1d4ed8';
  } else if (normalized === 'failed' || normalized === 'invalid') {
    background = '#fee2e2';
    color = '#b91c1c';
  } else if (normalized === 'skipped') {
    background = '#fef3c7';
    color = '#92400e';
  }
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        padding: '4px 10px',
        borderRadius: 999,
        background,
        color,
        fontSize: 12,
        fontWeight: 700,
        textTransform: 'capitalize',
      }}
    >
      {prettyLabel(value)}
    </span>
  );
}

function Section({
  title,
  children,
}: {
  title: string;
  children: ReactNode;
}) {
  return (
    <div
      style={{
        background: '#fff',
        borderRadius: 14,
        border: '1px solid #ececf4',
        boxShadow: '0 2px 10px rgba(92,95,188,0.06)',
        padding: '18px 20px',
      }}
    >
      <div style={{ fontSize: 16, fontWeight: 700, color: '#1f2937', marginBottom: 14 }}>{title}</div>
      {children}
    </div>
  );
}

function MetaRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 12, padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
      <div style={{ fontSize: 12, color: '#6b7280' }}>{label}</div>
      <div style={{ fontSize: 13, color: '#1f2937', wordBreak: 'break-word' }}>{value}</div>
    </div>
  );
}

function caseResult(caseRun: EvalCaseRun): string {
  const judgment = caseRun.judgment;
  if (judgment?.judgment_verdict) return judgment.judgment_verdict;
  return caseRun.execution_status;
}

function durationSeconds(startedAt: string | null | undefined, finishedAt: string | null | undefined): number | null {
  if (!startedAt || !finishedAt) return null;
  const start = new Date(startedAt).getTime();
  const end = new Date(finishedAt).getTime();
  if (Number.isNaN(start) || Number.isNaN(end) || end < start) return null;
  return (end - start) / 1000;
}

function formatDuration(seconds: number | null | undefined): string {
  if (seconds == null) return '—';
  if (seconds < 60) return `${seconds.toFixed(1)}s`;
  if (seconds < 3600) return `${(seconds / 60).toFixed(1)}m`;
  return `${(seconds / 3600).toFixed(2)}h`;
}

function formatSigned(value: number | null | undefined, digits = 1): string {
  if (value == null || Number.isNaN(value)) return '—';
  const fixed = value.toFixed(digits);
  return value > 0 ? `+${fixed}` : fixed;
}

function formatEpochSeconds(value: unknown): string {
  if (typeof value !== 'number' || !Number.isFinite(value)) return '—';
  return formatDateTime(new Date(value * 1000).toISOString());
}

function asRecord(value: unknown): Record<string, unknown> {
  return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};
}

function getBucketDiagnostics(caseRun: EvalCaseRun) {
  const packet = asRecord(caseRun.judgment?.packet);
  return SCORE_BUCKETS.map((bucket) => {
    const bucketPacket = asRecord(packet[bucket]);
    const checks = Array.isArray(bucketPacket.checks) ? bucketPacket.checks as Record<string, unknown>[] : [];
    const failures = checks.filter((check) => {
      const passed = check.passed;
      const penalty = check.penalty_applied;
      const maxScore = check.max_score;
      const earned = check.earned_score;
      if (passed === false) return true;
      if (typeof penalty === 'number' && penalty > 0) return true;
      if (typeof maxScore === 'number' && typeof earned === 'number' && earned < maxScore) return true;
      return false;
    });
    return {
      bucket,
      status: String(bucketPacket.status || ''),
      score: typeof bucketPacket.score === 'number' ? bucketPacket.score : null,
      maxScore: typeof bucketPacket.max_score === 'number' ? bucketPacket.max_score : null,
      failures,
    };
  });
}

function getContractContext(caseRun: EvalCaseRun) {
  const audit = asRecord(caseRun.judgment?.audit);
  const contract = asRecord(audit.contract);
  const artifactResolution = asRecord(audit.artifact_resolution);
  const selected = asRecord(artifactResolution.selected_trace_candidate);
  return {
    expectedClusterId: String(contract.expected_cluster_id || ''),
    actualClusterId: String(contract.actual_cluster_id || selected.actual_cluster_id || ''),
    expectedWindowId: String(contract.expected_allowed_window_id || ''),
    actualStartTs: typeof selected.actual_start_ts === 'number' ? selected.actual_start_ts : null,
    actualEndTs: typeof selected.actual_end_ts === 'number' ? selected.actual_end_ts : null,
    timeWindowMatch: contract.time_window_match === true,
    clusterScopeMatch: contract.cluster_scope_match === true,
    manifestPathMismatch: artifactResolution.manifest_path_mismatch === true,
  };
}

function getInvalidContext(caseRun: EvalCaseRun) {
  const judgment = asRecord(caseRun.judgment);
  const packet = asRecord(judgment.packet);
  const audit = asRecord(judgment.audit);
  const packetArtifact = asRecord(packet.artifact_resolution);
  const auditArtifact = asRecord(audit.artifact_resolution);
  const selectedTrace = asRecord(auditArtifact.selected_trace_candidate);
  const executionContract = asRecord(packet.execution_contract);
  const summary = asRecord(caseRun.summary);
  const semanticEval = asRecord(summary.semantic_eval);
  const invalidReasons = Array.isArray(selectedTrace.invalid_reasons) ? selectedTrace.invalid_reasons.map(String) : [];
  return {
    verdict: String(judgment.judgment_verdict || ''),
    invalidSubtype: String(judgment.invalid_subtype || packetArtifact.invalid_subtype || ''),
    primaryFailureCode: String(judgment.primary_failure_code || packetArtifact.primary_failure_code || ''),
    artifactResolutionStatus: String(auditArtifact.status || packetArtifact.status || ''),
    executionContractStatus: String(executionContract.status || ''),
    packetStatus: String(semanticEval.packet_status || ''),
    finishReason: String(summary.finish_reason || ''),
    invalidReasons,
    actualClusterId: String(selectedTrace.actual_cluster_id || ''),
    actualStartTs: typeof selectedTrace.actual_start_ts === 'number' ? selectedTrace.actual_start_ts : null,
    actualEndTs: typeof selectedTrace.actual_end_ts === 'number' ? selectedTrace.actual_end_ts : null,
    diagnosisReportPresent: selectedTrace.diagnosis_report_present === true,
    summaryTxtPresent: selectedTrace.summary_txt_present === true,
    summaryJsonPresent: selectedTrace.summary_json_present === true,
  };
}

function getExecutionContractFailures(caseRun: EvalCaseRun): string[] {
  const packet = asRecord(caseRun.judgment?.packet);
  const executionContract = asRecord(packet.execution_contract);
  const checks = Array.isArray(executionContract.checks) ? executionContract.checks as Record<string, unknown>[] : [];
  return checks
    .filter((check) => check.passed === false)
    .map((check) => String(check.description || check.id || ''))
    .filter(Boolean)
    .slice(0, 3);
}

function bucketLabelKey(bucket: (typeof SCORE_BUCKETS)[number]): TranslationKey {
  switch (bucket) {
    case 'workflow':
      return 'adminEvalRunDetail.bucketWorkflow';
    case 'evidence_collection':
      return 'adminEvalRunDetail.bucketEvidenceCollection';
    case 'critical_evidence':
      return 'adminEvalRunDetail.bucketCriticalEvidence';
    case 'evidence_routing':
      return 'adminEvalRunDetail.bucketEvidenceRouting';
    case 'diagnosis':
      return 'adminEvalRunDetail.bucketDiagnosis';
  }
}

function sortByBaselineRegression(left: EvalCaseRun, right: EvalCaseRun): number {
  const leftDiff = left.baseline_comparison?.score_diff;
  const rightDiff = right.baseline_comparison?.score_diff;
  const leftValue = typeof leftDiff === 'number' ? leftDiff : Number.POSITIVE_INFINITY;
  const rightValue = typeof rightDiff === 'number' ? rightDiff : Number.POSITIVE_INFINITY;
  if (leftValue !== rightValue) return leftValue - rightValue;
  return left.case_id.localeCompare(right.case_id);
}

function averageComparableScores(values: { current: number; baseline: number; diff: number; maxScore: number | null }[]) {
  const currentAvg = values.length
    ? values.reduce((sum, value) => sum + value.current, 0) / values.length
    : null;
  const baselineAvg = values.length
    ? values.reduce((sum, value) => sum + value.baseline, 0) / values.length
    : null;
  const diffAvg = values.length
    ? values.reduce((sum, value) => sum + value.diff, 0) / values.length
    : null;
  const maxScoreValues = values
    .map((value) => value.maxScore)
    .filter((value): value is number => typeof value === 'number' && Number.isFinite(value));
  const maxScoreAvg = maxScoreValues.length
    ? maxScoreValues.reduce((sum, value) => sum + value, 0) / maxScoreValues.length
    : null;
  return { currentAvg, baselineAvg, diffAvg, maxScoreAvg };
}

export default function AdminEvalRunDetailPage() {
  const { t } = useTranslation();
  const params = useParams<{ runId: string }>();
  const searchParams = useSearchParams();
  const runId = typeof params.runId === 'string' ? params.runId : '';
  const currentQuery = searchParams.toString();
  const runsHref = currentQuery ? `/admin/evaluations/runs?${currentQuery}` : '/admin/evaluations/runs';
  const caseHistoryHref = (caseId: string) =>
    `/admin/evaluations/cases/${encodeURIComponent(caseId)}${currentQuery ? `?${currentQuery}` : ''}`;
  const [run, setRun] = useState<EvalRunDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    async function load() {
      if (!runId) return;
      setLoading(true);
      setError('');
      try {
        const detail = await getEvalRunDetail(runId);
        if (!cancelled) setRun(detail);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : t('adminEvalRunDetail.loadError'));
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [runId, t]);

  if (loading) {
    return <div style={{ paddingTop: 8, fontSize: 14, color: '#6b7280' }}>{t('adminEvalRunDetail.loading')}</div>;
  }

  if (error || !run) {
    return (
      <div style={{ paddingTop: 8 }}>
        <Link href={runsHref} style={{ fontSize: 13, fontWeight: 600, color: '#5c5fbc', textDecoration: 'none' }}>
          {t('adminEvalRunDetail.backToRuns')}
        </Link>
        <div style={{ marginTop: 16, padding: '14px 16px', borderRadius: 12, background: '#fef2f2', border: '1px solid #fecaca', color: '#991b1b', fontSize: 13 }}>
          {error || t('adminEvalRunDetail.notFound')}
        </div>
      </div>
    );
  }

  const scoredCaseRuns = run.case_runs.filter((caseRun) => typeof caseRun.judgment?.score === 'number');
  const totalScore = scoredCaseRuns.reduce((sum, caseRun) => sum + Number(caseRun.judgment?.score || 0), 0);
  const avgScore = scoredCaseRuns.length ? totalScore / scoredCaseRuns.length : null;
  const runWallClockSeconds = durationSeconds(run.started_at, run.finished_at);
  const sortedCaseRuns = [...run.case_runs].sort(sortByBaselineRegression);
  const bucketAverageRows = SCORE_BUCKETS.map((bucket) => {
    const comparedPairs = sortedCaseRuns
      .map((caseRun) => {
        const currentBucket = caseRun.baseline_comparison?.current_bucket_scores?.[bucket];
        const baselineBucket = caseRun.baseline_comparison?.baseline_bucket_scores?.[bucket];
        const current = currentBucket?.score;
        const baseline = baselineBucket?.score;
        if (typeof current !== 'number' || typeof baseline !== 'number') {
          return null;
        }
        const maxScore = typeof currentBucket?.max_score === 'number'
          ? currentBucket.max_score
          : typeof baselineBucket?.max_score === 'number'
            ? baselineBucket.max_score
            : null;
        return { current, baseline, diff: current - baseline, maxScore };
      })
      .filter((value): value is { current: number; baseline: number; diff: number; maxScore: number | null } => value !== null);
    return { bucket, ...averageComparableScores(comparedPairs) };
  });
  const totalAverageRow = averageComparableScores(
    sortedCaseRuns
      .map((caseRun) => {
        const bucketPairs = SCORE_BUCKETS.map((bucket) => {
          const currentBucket = caseRun.baseline_comparison?.current_bucket_scores?.[bucket];
          const baselineBucket = caseRun.baseline_comparison?.baseline_bucket_scores?.[bucket];
          const current = currentBucket?.score;
          const baseline = baselineBucket?.score;
          if (typeof current !== 'number' || typeof baseline !== 'number') {
            return null;
          }
          const maxScore = typeof currentBucket?.max_score === 'number'
            ? currentBucket.max_score
            : typeof baselineBucket?.max_score === 'number'
              ? baselineBucket.max_score
              : null;
          return { current, baseline, maxScore };
        });
        if (bucketPairs.some((value) => value === null)) {
          return null;
        }
        const completeBucketPairs = bucketPairs as { current: number; baseline: number; maxScore: number | null }[];
        const current = completeBucketPairs.reduce((sum, value) => sum + value.current, 0);
        const baseline = completeBucketPairs.reduce((sum, value) => sum + value.baseline, 0);
        const maxScores = completeBucketPairs.map((value) => value.maxScore);
        const maxScore = maxScores.every((value): value is number => typeof value === 'number')
          ? maxScores.reduce((sum, value) => sum + value, 0)
          : null;
        return { current, baseline, diff: current - baseline, maxScore };
      })
      .filter((value): value is { current: number; baseline: number; diff: number; maxScore: number | null } => value !== null)
  );

  return (
    <div style={{ paddingTop: 8 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <div style={{ marginBottom: 8 }}>
            <Link href={runsHref} style={{ fontSize: 13, fontWeight: 600, color: '#5c5fbc', textDecoration: 'none' }}>
              {t('adminEvalRunDetail.backToRuns')}
            </Link>
          </div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, color: '#1a1a2e' }}>{run.id}</h1>
          <p style={{ margin: '8px 0 0', fontSize: 14, lineHeight: 1.6, color: '#6b7280' }}>{t('adminEvalRunDetail.subtitle')}</p>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <StatusBadge value={run.execution_status} />
          <StatusBadge value={run.comparison_status} />
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 16, marginBottom: 16 }}>
        <Section title={t('adminEvalRunDetail.runMetadata')}>
          <MetaRow label={t('adminEvalRunDetail.metaSuite')} value={run.suite_id} />
          <MetaRow label={t('adminEvalRunDetail.metaSuiteVersion')} value={run.suite_version || '—'} />
          <MetaRow label={t('adminEvalRunDetail.metaTriggerMode')} value={prettyLabel(run.trigger_mode)} />
          <MetaRow label={t('adminEvalRunDetail.metaScheduleDate')} value={run.schedule_date || '—'} />
          <MetaRow label={t('adminEvalRunDetail.metaStartedAt')} value={formatDateTime(run.started_at)} />
          <MetaRow label={t('adminEvalRunDetail.metaFinishedAt')} value={formatDateTime(run.finished_at)} />
        </Section>

        <Section title={t('adminEvalRunDetail.runtimeMetadata')}>
          <MetaRow label={t('adminEvalRunDetail.metaAgentType')} value={run.agent_type || '—'} />
          <MetaRow label={t('adminEvalRunDetail.metaResolvedModel')} value={run.resolved_model || '—'} />
          <MetaRow label={t('adminEvalRunDetail.metaComparisonStatus')} value={prettyLabel(run.comparison_status)} />
          <MetaRow label={t('adminEvalRunDetail.metaPromoteEligibility')} value={prettyLabel(run.promote_eligibility)} />
          <MetaRow label={t('adminEvalRunDetail.metaBaselineId')} value={run.baseline_id || '—'} />
        </Section>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12, marginBottom: 16 }}>
        {[
          [t('adminEvalRunDetail.kpiCases'), String(run.case_count)],
          [t('adminEvalRunDetail.kpiPassed'), String(run.passed_count)],
          [t('adminEvalRunDetail.kpiFailed'), String(run.failed_count)],
          [t('adminEvalRunDetail.kpiInvalid'), String(run.invalid_count)],
          [t('adminEvalRunDetail.kpiAvgScore'), avgScore != null ? avgScore.toFixed(1) : '—'],
          [t('adminEvalRunDetail.kpiRunDuration'), formatDuration(runWallClockSeconds)],
        ].map(([label, value]) => (
          <div key={label} style={{ background: '#fff', borderRadius: 14, border: '1px solid #ececf4', boxShadow: '0 2px 10px rgba(92,95,188,0.06)', padding: '16px 18px' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</div>
            <div style={{ marginTop: 8, fontSize: 24, fontWeight: 700, color: '#1f2937' }}>{value}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gap: 16, marginBottom: 16 }}>
        <Section title={t('adminEvalRunDetail.bucketScores')}>
          <div style={{ marginBottom: 10, fontSize: 12, color: '#6b7280' }}>
            {t('adminEvalRunDetail.bucketScoresNote')}
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 800 }}>
              <thead>
                <tr style={{ background: '#f8fafc' }}>
                  {[t('adminEvalRunDetail.bucketColumn'), t('adminEvalRunDetail.currentScoreColumn'), t('adminEvalRunDetail.baselineScoreColumn'), t('adminEvalRunDetail.diffScoreColumn'), t('adminEvalRunDetail.maxScoreColumn')].map((label) => (
                    <th key={label} style={{ padding: '10px 12px', fontSize: 12, textAlign: 'left', color: '#6b7280', borderBottom: '1px solid #e5e7eb' }}>
                      {label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {bucketAverageRows.map((row) => (
                  <tr key={`bucket-avg-${row.bucket}`}>
                    <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                      {t(bucketLabelKey(row.bucket))}
                    </td>
                    <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                      {row.currentAvg != null ? row.currentAvg.toFixed(1) : '—'}
                    </td>
                    <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                      {row.baselineAvg != null ? row.baselineAvg.toFixed(1) : '—'}
                    </td>
                    <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: row.diffAvg != null && row.diffAvg < 0 ? '#b91c1c' : '#166534' }}>
                      {formatSigned(row.diffAvg)}
                    </td>
                    <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                      {row.maxScoreAvg != null ? row.maxScoreAvg.toFixed(1) : '—'}
                    </td>
                  </tr>
                ))}
                <tr>
                  <td style={{ padding: '11px 12px', borderTop: '1px solid #e5e7eb', fontSize: 13, fontWeight: 700, color: '#111827', background: '#f8fafc' }}>
                    {t('adminEvalRunDetail.bucketTotal')}
                  </td>
                  <td style={{ padding: '11px 12px', borderTop: '1px solid #e5e7eb', fontSize: 13, fontWeight: 700, color: '#111827', background: '#f8fafc' }}>
                    {totalAverageRow.currentAvg != null ? totalAverageRow.currentAvg.toFixed(1) : '—'}
                  </td>
                  <td style={{ padding: '11px 12px', borderTop: '1px solid #e5e7eb', fontSize: 13, fontWeight: 700, color: '#111827', background: '#f8fafc' }}>
                    {totalAverageRow.baselineAvg != null ? totalAverageRow.baselineAvg.toFixed(1) : '—'}
                  </td>
                  <td style={{ padding: '11px 12px', borderTop: '1px solid #e5e7eb', fontSize: 13, fontWeight: 700, color: totalAverageRow.diffAvg != null && totalAverageRow.diffAvg < 0 ? '#b91c1c' : '#166534', background: '#f8fafc' }}>
                    {formatSigned(totalAverageRow.diffAvg)}
                  </td>
                  <td style={{ padding: '11px 12px', borderTop: '1px solid #e5e7eb', fontSize: 13, fontWeight: 700, color: '#111827', background: '#f8fafc' }}>
                    {totalAverageRow.maxScoreAvg != null ? totalAverageRow.maxScoreAvg.toFixed(1) : '—'}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </Section>
      </div>

      <div style={{ marginTop: 16 }}>
        <Section title={t('adminEvalRunDetail.caseTableTitle')}>
          <div style={{ display: 'grid', gap: 16 }}>
            {sortedCaseRuns.map((caseRun) => (
              <details
                key={caseRun.id}
                style={{
                  border: '1px solid #e5e7eb',
                  borderRadius: 14,
                  background: '#fff',
                  overflow: 'hidden',
                }}
              >
                {(() => {
                  const contractContext = getContractContext(caseRun);
                  const bucketDiagnostics = getBucketDiagnostics(caseRun);
                  const invalidContext = getInvalidContext(caseRun);
                  return (
                    <>
                      <summary
                        style={{
                          cursor: 'pointer',
                          listStyle: 'none',
                          padding: 16,
                        }}
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'flex-start', flexWrap: 'wrap' }}>
                          <div>
                            <Link
                              href={caseHistoryHref(caseRun.case_id)}
                              style={{ color: '#4338ca', textDecoration: 'none', fontWeight: 700, fontSize: 15 }}
                              onClick={(event) => event.stopPropagation()}
                            >
                              {caseRun.case_id}
                            </Link>
                            <div style={{ marginTop: 8, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                              <StatusBadge value={caseRun.execution_status} />
                              <StatusBadge value={caseResult(caseRun)} />
                            </div>
                          </div>
                          <div style={{ minWidth: 320, display: 'grid', gap: 6 }}>
                            <div style={{ display: 'grid', gridTemplateColumns: '86px 1fr', gap: 8, alignItems: 'start' }}>
                              <div style={{ fontSize: 12, color: '#64748b', fontWeight: 700 }}>{t('adminEvalRunDetail.summaryScoreLabel')}</div>
                              <div style={{ fontSize: 13, color: '#374151', wordBreak: 'break-word' }}>
                                {t('adminEvalRunDetail.scoreCompareTemplate', {
                                  current: String(caseRun.judgment?.score ?? '—'),
                                  baseline: String(caseRun.baseline_comparison?.baseline_score ?? '—'),
                                  diff: formatSigned(caseRun.baseline_comparison?.score_diff),
                                })}
                              </div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '86px 1fr', gap: 8, alignItems: 'start' }}>
                              <div style={{ fontSize: 12, color: '#64748b', fontWeight: 700 }}>{t('adminEvalRunDetail.summaryFailureLabel')}</div>
                              <div style={{ fontSize: 12, color: '#64748b', wordBreak: 'break-word' }}>{caseRun.judgment?.primary_failure_code || '—'}</div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '86px 1fr', gap: 8, alignItems: 'start' }}>
                              <div style={{ fontSize: 12, color: '#64748b', fontWeight: 700 }}>{t('adminEvalRunDetail.summaryWorkspaceLabel')}</div>
                              <div style={{ fontSize: 12, color: '#64748b', wordBreak: 'break-word' }}>{caseRun.workspace_id || '—'}</div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '86px 1fr', gap: 8, alignItems: 'start' }}>
                              <div style={{ fontSize: 12, color: '#64748b', fontWeight: 700 }}>{t('adminEvalRunDetail.summaryTimeLabel')}</div>
                              <div style={{ fontSize: 12, color: '#64748b', wordBreak: 'break-word' }}>
                                {formatDateTime(caseRun.started_at)} · {formatDateTime(caseRun.finished_at)}
                              </div>
                            </div>
                          </div>
                        </div>
                      </summary>

                      <div style={{ padding: '0 16px 16px' }}>

                        {invalidContext.verdict === 'invalid' ? (
                          <div>
                            <div
                              style={{
                                marginTop: 14,
                                border: '1px solid #fecaca',
                                borderRadius: 12,
                                padding: '12px 14px',
                                background: '#fef2f2',
                              }}
                            >
                              <div style={{ fontSize: 13, fontWeight: 700, color: '#991b1b', marginBottom: 8 }}>
                                {t('adminEvalRunDetail.invalidSummaryTitle')}
                              </div>
                              <div style={{ display: 'grid', gap: 6, fontSize: 13, color: '#7f1d1d' }}>
                                <div>
                                  {t('adminEvalRunDetail.invalidReasonTemplate', {
                                    subtype: invalidContext.invalidSubtype || '—',
                                    failure: invalidContext.primaryFailureCode || '—',
                                  })}
                                </div>
                                {invalidContext.primaryFailureCode === 'contract_failed' ? (
                                  <>
                                    <div>
                                      {t('adminEvalRunDetail.invalidContractClusterTemplate', {
                                        expected: contractContext.expectedClusterId || '—',
                                        actual: contractContext.actualClusterId || '—',
                                      })}
                                    </div>
                                    <div>
                                      {t('adminEvalRunDetail.invalidContractWindowTemplate', {
                                        expected: contractContext.expectedWindowId || '—',
                                        actualStart: formatEpochSeconds(contractContext.actualStartTs),
                                        actualEnd: formatEpochSeconds(contractContext.actualEndTs),
                                      })}
                                    </div>
                                  </>
                                ) : null}
                                {invalidContext.primaryFailureCode === 'execution_contract_failed' ? (
                                  <div>
                                    {t('adminEvalRunDetail.invalidExecutionContractTemplate', {
                                      reasons: getExecutionContractFailures(caseRun).join(' ; ') || '—',
                                    })}
                                  </div>
                                ) : null}
                                <div>
                                  {t('adminEvalRunDetail.invalidStatusTemplate', {
                                    artifact: invalidContext.artifactResolutionStatus || '—',
                                    contract: normalizeContractEvalStatus(invalidContext.executionContractStatus, t),
                                    packet: invalidContext.packetStatus || '—',
                                    finish: invalidContext.finishReason || '—',
                                  })}
                                </div>
                                <div>
                                  {t('adminEvalRunDetail.invalidTraceTemplate', {
                                    cluster: invalidContext.actualClusterId || '—',
                                    start: formatEpochSeconds(invalidContext.actualStartTs),
                                    end: formatEpochSeconds(invalidContext.actualEndTs),
                                  })}
                                </div>
                                <div>
                                  {t('adminEvalRunDetail.invalidArtifactsTemplate', {
                                    report: invalidContext.diagnosisReportPresent ? t('adminEvalRunDetail.contractMatched') : t('adminEvalRunDetail.contractMismatch'),
                                    summaryTxt: invalidContext.summaryTxtPresent ? t('adminEvalRunDetail.contractMatched') : t('adminEvalRunDetail.contractMismatch'),
                                    summaryJson: invalidContext.summaryJsonPresent ? t('adminEvalRunDetail.contractMatched') : t('adminEvalRunDetail.contractMismatch'),
                                  })}
                                </div>
                                {invalidContext.invalidReasons.length ? (
                                  <div>{t('adminEvalRunDetail.invalidReasonsList', { reasons: invalidContext.invalidReasons.join(', ') })}</div>
                                ) : null}
                              </div>
                            </div>
                          </div>
                        ) : null}

                        {invalidContext.verdict !== 'invalid' ? (
                          <div style={{ marginTop: 14, overflowX: 'auto' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 720 }}>
                              <thead>
                                <tr style={{ background: '#f8fafc' }}>
                                  {[t('adminEvalRunDetail.bucketColumn'), t('adminEvalRunDetail.currentScoreColumn'), t('adminEvalRunDetail.baselineScoreColumn'), t('adminEvalRunDetail.diffScoreColumn')].map((label) => (
                                    <th key={label} style={{ padding: '10px 12px', fontSize: 12, textAlign: 'left', color: '#6b7280', borderBottom: '1px solid #e5e7eb' }}>
                                      {label}
                                    </th>
                                  ))}
                                </tr>
                              </thead>
                              <tbody>
                                {SCORE_BUCKETS.map((bucket) => {
                                  const currentBucket = caseRun.baseline_comparison?.current_bucket_scores?.[bucket] || {};
                                  const baselineBucket = caseRun.baseline_comparison?.baseline_bucket_scores?.[bucket] || {};
                                  const currentScore = currentBucket.score;
                                  const currentMax = currentBucket.max_score;
                                  const baselineScore = baselineBucket.score;
                                  const baselineMax = baselineBucket.max_score;
                                  const diff = caseRun.baseline_comparison?.bucket_score_diffs?.[bucket] ?? null;
                                  return (
                                    <tr key={`${caseRun.id}-${bucket}`}>
                                      <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                                        {t(bucketLabelKey(bucket))}
                                      </td>
                                      <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                                        {currentScore != null ? `${currentScore}${currentMax != null ? ` / ${currentMax}` : ''}` : '—'}
                                      </td>
                                      <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: '#1f2937' }}>
                                        {baselineScore != null ? `${baselineScore}${baselineMax != null ? ` / ${baselineMax}` : ''}` : '—'}
                                      </td>
                                      <td style={{ padding: '10px 12px', borderBottom: '1px solid #f1f5f9', fontSize: 13, color: diff != null && diff < 0 ? '#b91c1c' : '#166534' }}>
                                        {formatSigned(diff)}
                                      </td>
                                    </tr>
                                  );
                                })}
                              </tbody>
                            </table>
                          </div>
                        ) : null}

                        <div style={{ marginTop: 14 }}>
                          <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 8 }}>{t('adminEvalRunDetail.judgingConditionsTitle')}</div>
                          {(caseRun.baseline_comparison?.influential_checks || []).length ? (
                            <div style={{ display: 'grid', gap: 8 }}>
                              {(caseRun.baseline_comparison?.influential_checks || []).map((check) => (
                                <div key={`${caseRun.id}-${check.bucket}-${check.check_id}`} style={{ border: '1px solid #e5e7eb', borderRadius: 10, padding: '10px 12px', background: '#fafafa' }}>
                                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center' }}>
                                    <div style={{ fontSize: 12, fontWeight: 700, color: '#475569' }}>{t(bucketLabelKey(check.bucket as (typeof SCORE_BUCKETS)[number]))}</div>
                                    <div style={{ fontSize: 12, fontWeight: 700, color: '#b91c1c' }}>
                                      {t('adminEvalRunDetail.impactLabel', { score: check.impact_score.toFixed(1) })}
                                    </div>
                                  </div>
                                  <div style={{ marginTop: 6, fontSize: 13, color: '#1f2937' }}>{check.description}</div>
                                  {check.snippet ? <div style={{ marginTop: 6, fontSize: 12, color: '#64748b' }}>{check.snippet}</div> : null}
                                  {check.semantic_notes?.length ? <div style={{ marginTop: 6, fontSize: 12, color: '#64748b' }}>{check.semantic_notes.join(' ')}</div> : null}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div style={{ fontSize: 13, color: '#6b7280' }}>{t('adminEvalRunDetail.judgingConditionsEmpty')}</div>
                          )}
                        </div>

                        <div style={{ marginTop: 14 }}>
                          <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 8 }}>{t('adminEvalRunDetail.bucketFailureDetailsTitle')}</div>
                          <div style={{ display: 'grid', gap: 10 }}>
                            {bucketDiagnostics.map((bucket) => (
                              <div key={`${caseRun.id}-${bucket.bucket}-details`} style={{ border: '1px solid #e5e7eb', borderRadius: 10, padding: '10px 12px', background: '#fff' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
                                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1f2937' }}>{t(bucketLabelKey(bucket.bucket))}</div>
                                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                                    <StatusBadge value={bucket.status || 'unknown'} />
                                    <span style={{ fontSize: 12, color: '#64748b' }}>
                                      {bucket.score != null ? `${bucket.score}${bucket.maxScore != null ? ` / ${bucket.maxScore}` : ''}` : '—'}
                                    </span>
                                  </div>
                                </div>
                                {bucket.failures.length ? (
                                  <div style={{ marginTop: 8, display: 'grid', gap: 8 }}>
                                    {bucket.failures.map((failure, index) => {
                                      const rules = Array.isArray(failure.rules) ? failure.rules as Record<string, unknown>[] : [];
                                      const notes = Array.isArray(failure.semantic_notes) ? failure.semantic_notes as string[] : [];
                                      return (
                                        <div key={`${caseRun.id}-${bucket.bucket}-failure-${index}`} style={{ borderTop: '1px solid #f1f5f9', paddingTop: 8 }}>
                                          <div style={{ fontSize: 13, color: '#1f2937' }}>{String(failure.description || failure.id || '—')}</div>
                                          <div style={{ marginTop: 4, fontSize: 12, color: '#64748b' }}>
                                            {t('adminEvalRunDetail.checkScoreTemplate', {
                                              earned: String(failure.earned_score ?? '—'),
                                              max: String(failure.max_score ?? '—'),
                                              penalty: String(failure.penalty_applied ?? '—'),
                                            })}
                                          </div>
                                          {typeof failure.snippet === 'string' && failure.snippet ? (
                                            <div style={{ marginTop: 4, fontSize: 12, color: '#64748b' }}>{failure.snippet}</div>
                                          ) : null}
                                          {rules.length ? (
                                            <div style={{ marginTop: 6, display: 'grid', gap: 4 }}>
                                              {rules.map((rule, ruleIndex) => (
                                                <div key={`${caseRun.id}-${bucket.bucket}-rule-${ruleIndex}`} style={{ fontSize: 12, color: '#475569' }}>
                                                  {t('adminEvalRunDetail.ruleTemplate', {
                                                    source: String(rule.source || '—'),
                                                    matcher: String(rule.matcher || '—'),
                                                    matched: rule.matched === true ? t('adminEvalRunDetail.contractMatched') : t('adminEvalRunDetail.contractMismatch'),
                                                    actual: String(rule.snippet || rule.matched_keyword || JSON.stringify(rule.matched_keys || [])),
                                                  })}
                                                </div>
                                              ))}
                                            </div>
                                          ) : null}
                                          {notes.length ? (
                                            <div style={{ marginTop: 6, fontSize: 12, color: '#64748b' }}>{notes.join(' ')}</div>
                                          ) : null}
                                        </div>
                                      );
                                    })}
                                  </div>
                                ) : (
                                  <div style={{ marginTop: 8, fontSize: 12, color: '#64748b' }}>{t('adminEvalRunDetail.bucketFailureEmpty')}</div>
                                )}
                              </div>
                            ))}
                          </div>
                        </div>

                        <details style={{ marginTop: 14 }}>
                          <summary style={{ cursor: 'pointer', fontSize: 13, fontWeight: 700, color: '#374151' }}>
                            {t('adminEvalRunDetail.rawOutputTitle')}
                          </summary>
                          <pre
                            style={{
                              margin: '10px 0 0',
                              padding: 14,
                              borderRadius: 12,
                              background: '#0f172a',
                              color: '#e2e8f0',
                              fontSize: 12,
                              lineHeight: 1.55,
                              overflowX: 'auto',
                              whiteSpace: 'pre-wrap',
                            }}
                          >
                            {caseRun.output_text || t('adminEvalRunDetail.rawOutputEmpty')}
                          </pre>
                        </details>
                      </div>
                    </>
                  );
                })()}
              </details>
            ))}
          </div>
        </Section>
      </div>
    </div>
  );
}
