import { canAccessMembench } from "@/app/utils/auth"
import { redirect } from "next/navigation"
import { MembenchToggle } from "@/components/membench/membench-toggle"
import {
  PeakMemoryChart,
  AllocatorChart,
  HeadroomChart,
  MaxAllocChart,
} from "@/components/membench/membench-charts"

export const metadata = { title: "Memory Benchmark — Unstructured" }

/* ── static data ────────────────────────────────────────────────────── */

const SUITE = {
  baseline: {
    peak_gb: 1.66,
    total_gb: 16.398,
    allocs: 5_585_979,
    wall_s: 76.0,
    max_alloc_mb: 268,
    tests: 18,
    passed: 13,
    failed: 5,
  },
  current: {
    peak_gb: 1.473,
    total_gb: 20.239,
    allocs: 6_210_809,
    wall_s: 86.0,
    max_alloc_mb: 134,
    tests: 18,
    passed: 13,
    failed: 5,
  },
}

const PEAK_DELTA_PCT =
  ((SUITE.current.peak_gb - SUITE.baseline.peak_gb) / SUITE.baseline.peak_gb) * 100
const PEAK_DELTA_MB = Math.abs((SUITE.current.peak_gb - SUITE.baseline.peak_gb) * 1024)
const MAX_ALLOC_DELTA_PCT =
  ((SUITE.current.max_alloc_mb - SUITE.baseline.max_alloc_mb) / SUITE.baseline.max_alloc_mb) * 100
const POD_RAM_LIMIT_GB = 32

const TOP_ALLOC_BASELINE: [string, number][] = [
  ["_create_inference_session", 1.386],
  ["PIL Image.tobytes", 1.188],
  ["PIL Image.new", 1.001],
  ["load_prepare", 0.751],
  ["render", 0.649],
]

const TOP_ALLOC_CURRENT: [string, number][] = [
  ["PIL Image.tobytes", 1.802],
  ["PIL Image.new", 1.556],
  ["_create_inference_session", 1.328],
  ["load_prepare", 1.172],
  ["PIL Image.tobytes (2)", 0.889],
]

const SCENARIO_TABLE = [
  {
    scenario: "Full Suite (18 common tests)",
    bl_peak: "1.660 GB",
    cu_peak: "1.473 GB",
    delta: "-11.3%",
    bl_time: "76.0s",
    cu_time: "86.0s",
  },
  {
    scenario: "API hi_res (layout-parser-paper, 16p)",
    bl_peak: "1.515 GB",
    cu_peak: "1.419 GB",
    delta: "-6.3%",
    bl_time: "53.6s",
    cu_time: "60.2s",
  },
  {
    scenario: "od_only (Seeda Case Study)",
    bl_peak: "1.127 GB",
    cu_peak: "1.046 GB",
    delta: "-7.2%",
    bl_time: "1.96s",
    cu_time: "2.13s",
  },
]

const ENV_TABLE = [
  ["VM", "Azure Standard_D8s_v5 (8 vCPU, 32 GB RAM)"],
  ["OS", "Ubuntu 20.04"],
  ["Python", "3.12"],
  ["Profiler", "memray --native (captures C/C++ malloc, mmap)"],
  ["Test Runner", "memray run --native -o {out}.bin --force -m pytest -v"],
  ["Baseline Env", "/home/krrt7/bench/baseline-core + baseline-env (pre-Feb 2026)"],
  ["Current Env", "/home/krrt7/bench/current-core + current-env (main)"],
  ["Pre-run Protocol", "VM reboot + 5-min idle wait (clean Azure telemetry window)"],
  ["Production Target", "Knative pods, 1 CPU / 32 GB RAM, Standard_D48s_v5 nodes"],
  ["Test Scope", "18 common partition tests (od_only, hi_res, pptx, docx)"],
]

/* ── page ───────────────────────────────────────────────────────────── */

export default async function MembenchPage() {
  const allowed = await canAccessMembench()
  if (!allowed) redirect("/")

  const b = SUITE.baseline
  const c = SUITE.current

  return (
    <div className="min-h-screen bg-white dark:bg-zinc-950 font-sans text-zinc-900 dark:text-zinc-200">
      {/* ── Hero ── */}
      <div className="border-b border-zinc-200 dark:border-zinc-800 bg-gradient-to-br from-zinc-100 via-green-50/40 to-zinc-100 dark:from-zinc-950 dark:via-[#0c1a0f] dark:to-zinc-950 px-6 pb-14 pt-16 text-center">
        <div
          className="text-[13px] font-bold text-green-600 dark:text-green-400 mb-3"
          style={{ letterSpacing: "0.15em" }}
        >
          UNSTRUCTURED
        </div>
        <h1
          className="text-[36px] font-extrabold tracking-tight text-zinc-900 dark:text-zinc-50"
          style={{ letterSpacing: "-0.02em" }}
        >
          Core Product Memory Benchmark
        </h1>
        <p className="mx-auto mt-3 max-w-[640px] text-[17px] text-zinc-500 dark:text-zinc-400">
          Peak RAM reduction measured with memray --native across the partition test suite
        </p>
        <div className="mt-6 flex flex-wrap items-center justify-center gap-6 text-[13px] text-zinc-400 dark:text-zinc-500">
          <span>April 2026</span>
          <span>|</span>
          <span>Baseline: pre-Feb 2026</span>
          <span>|</span>
          <span>18 common partition tests</span>
          <span>|</span>
          <span>Azure Standard_D8s_v5 VM</span>
        </div>
      </div>

      {/* ── Hero Metrics ── */}
      <div
        className="mx-auto -mt-10 grid max-w-4xl grid-cols-2 gap-5 px-6 lg:grid-cols-4"
        style={{ position: "relative", zIndex: 1 }}
      >
        {[
          {
            value: `${PEAK_DELTA_PCT.toFixed(1)}%`,
            label: "Peak RAM",
            detail: `${b.peak_gb.toFixed(2)} GB → ${c.peak_gb.toFixed(2)} GB`,
          },
          {
            value: `${Math.round(PEAK_DELTA_MB)} MB`,
            label: "Absolute Reduction",
            detail: "Peak high-water mark savings",
          },
          {
            value: `${MAX_ALLOC_DELTA_PCT.toFixed(0)}%`,
            label: "Max Single Allocation",
            detail: `${b.max_alloc_mb} MB → ${c.max_alloc_mb} MB`,
          },
          {
            value: "0",
            label: "New Regressions",
            detail: `Same ${c.passed}/${c.tests} pass rate on both`,
          },
        ].map(m => (
          <div
            key={m.label}
            className="rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 px-6 py-8 text-center shadow-sm dark:shadow-none"
          >
            <div
              className="font-mono leading-none text-green-600 dark:text-green-400"
              style={{ fontSize: "42px", fontWeight: 800, letterSpacing: "-0.02em" }}
            >
              {m.value}
            </div>
            <div className="mt-2 text-[15px] font-semibold text-zinc-800 dark:text-zinc-200">
              {m.label}
            </div>
            <div className="mt-1 text-[13px] text-zinc-500 dark:text-zinc-400">{m.detail}</div>
          </div>
        ))}
      </div>

      {/* ── Toggle + Views ── */}
      <div className="mx-auto max-w-4xl px-6 pb-20">
        <MembenchToggle execView={<ExecView />} engView={<EngView />} />
      </div>

      {/* ── Footer ── */}
      <div className="border-t border-zinc-200 dark:border-zinc-800 py-8 text-center">
        <div
          className="text-[11px] font-bold text-zinc-400 dark:text-zinc-500 mb-1"
          style={{ letterSpacing: "0.15em" }}
        >
          UNSTRUCTURED
        </div>
        <p className="text-xs text-zinc-400 dark:text-zinc-500">
          Core Product Memory Benchmark — April 2026
        </p>
      </div>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════════════════════
   EXECUTIVE VIEW
   ═══════════════════════════════════════════════════════════════════════ */

function ExecView() {
  const b = SUITE.baseline
  const c = SUITE.current

  return (
    <div className="space-y-14">
      {/* ── Peak Memory by Scenario ── */}
      <Section
        title="Peak Memory by Scenario"
        subtitle="High-water mark during document processing — the metric that determines OOM risk."
      >
        <Card>
          <PeakMemoryChart />
        </Card>
      </Section>

      {/* ── What Does This Mean? ── */}
      <Section title="What Does This Mean?" subtitle="How these numbers affect production pods.">
        <div className="flex flex-wrap gap-5">
          <Card className="flex-1 min-w-[260px]">
            <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">Lower OOM risk</h4>
            <p className="mt-2 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
              Peak memory during the full partition suite dropped from {b.peak_gb.toFixed(2)} GB to{" "}
              {c.peak_gb.toFixed(2)} GB — a {Math.round(PEAK_DELTA_MB)} MB reduction. For Knative
              pods with a 32 GB RAM limit, this means more headroom before the OOM killer terminates
              the container.
            </p>
          </Card>
          <Card className="flex-1 min-w-[260px]">
            <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">
              Halved largest allocation
            </h4>
            <p className="mt-2 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
              The single largest memory allocation dropped from {b.max_alloc_mb} MB to{" "}
              {c.max_alloc_mb} MB — a 50% reduction. Large contiguous allocations are the primary
              cause of memory fragmentation and allocation failures even when total free memory
              appears sufficient.
            </p>
          </Card>
          <Card className="flex-1 min-w-[260px]">
            <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">
              Zero regressions
            </h4>
            <p className="mt-2 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
              Both environments pass the same {c.passed} of {c.tests} partition tests. The{" "}
              {c.failed} failures are pre-existing docx edge cases present in the baseline — not
              regressions from the optimization work.
            </p>
          </Card>
        </div>
      </Section>

      {/* ── Pod Headroom ── */}
      <Section
        title="Production Pod Headroom"
        subtitle="Current peak usage vs. the Knative pod RAM limit of 32 GB."
      >
        <Card>
          <HeadroomChart />
          <div className="flex flex-wrap gap-6 mt-4">
            <div>
              <div
                className="font-mono leading-none text-green-600 dark:text-green-400"
                style={{ fontSize: "32px", fontWeight: 800 }}
              >
                {((c.peak_gb / POD_RAM_LIMIT_GB) * 100).toFixed(1)}%
              </div>
              <div className="mt-1 text-[13px] text-zinc-500 dark:text-zinc-400">
                of pod limit used (current)
              </div>
            </div>
            <div>
              <div
                className="font-mono leading-none text-zinc-800 dark:text-zinc-200"
                style={{ fontSize: "32px", fontWeight: 800 }}
              >
                {(POD_RAM_LIMIT_GB - c.peak_gb).toFixed(1)} GB
              </div>
              <div className="mt-1 text-[13px] text-zinc-500 dark:text-zinc-400">
                headroom remaining
              </div>
            </div>
          </div>
          <p className="mt-4 rounded-lg bg-zinc-50 dark:bg-white/[0.03] p-3 text-xs text-zinc-400 dark:text-zinc-500">
            Note: Peak memory is measured per-process during document processing. Actual pod usage
            includes OS overhead, model weights in shared memory, and other sidecar containers.
            These figures represent the process-level high-water mark.
          </p>
        </Card>
      </Section>

      {/* ── Largest Single Allocation ── */}
      <Section
        title="Largest Single Allocation"
        subtitle="The biggest contiguous block requested in a single malloc/mmap call."
      >
        <Card>
          <MaxAllocChart />
        </Card>
      </Section>

      {/* ── Suite-Level Comparison ── */}
      <Section
        title="Suite-Level Comparison"
        subtitle="Aggregate metrics from 18 common partition tests."
      >
        <Card>
          <div className="overflow-x-auto">
            {/* header */}
            <div className="flex gap-4 border-b-2 border-zinc-200 dark:border-zinc-800 pb-2.5 text-[11px] font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-300">
              <div className="flex-1">Metric</div>
              <div className="w-36 text-right">Baseline</div>
              <div className="w-36 text-right">Current</div>
              <div className="w-20 text-center">Delta</div>
            </div>
            <StatRow
              label="Peak Memory"
              baseline={b.peak_gb}
              current={c.peak_gb}
              unit="GB"
              format={v => v.toFixed(3)}
              better="lower"
            />
            <StatRow
              label="Total Allocated"
              baseline={b.total_gb}
              current={c.total_gb}
              unit="GB"
              format={v => v.toFixed(1)}
              better="lower"
            />
            <StatRow
              label="Allocation Count"
              baseline={b.allocs}
              current={c.allocs}
              unit=""
              format={v => v.toLocaleString()}
              better="lower"
            />
            <StatRow
              label="Max Single Alloc"
              baseline={b.max_alloc_mb}
              current={c.max_alloc_mb}
              unit="MB"
              format={v => v.toFixed(0)}
              better="lower"
            />
            <StatRow
              label="Wall Time"
              baseline={b.wall_s}
              current={c.wall_s}
              unit="s"
              format={v => v.toFixed(1)}
              better="lower"
            />
            <StatRow
              label="Tests Passed"
              baseline={b.passed}
              current={c.passed}
              unit={`/ ${b.tests}`}
              format={v => v.toFixed(0)}
              better="higher"
            />
          </div>
          <p className="mt-4 text-xs text-zinc-400 dark:text-zinc-500">
            Total allocated increased because current uses more frequent smaller allocations — peak
            (the OOM-risk metric) still decreased. This pattern indicates better memory recycling.
          </p>
        </Card>
      </Section>

      {/* ── Implications & Next Steps ── */}
      <Section title="Implications & Next Steps">
        <Card>
          <ActionItem
            text="Peak RAM reduced 11.3% — same workload fits in a smaller memory footprint"
            done
          />
          <ActionItem
            text="Max single allocation halved — lower fragmentation risk under memory pressure"
            done
          />
          <ActionItem text="Zero test regressions — safe to deploy without functional risk" done />
          <ActionItem text="Run full E2E suite benchmarks (all tests, not just common set) for comprehensive coverage" />
          <ActionItem text="Profile top allocators (PIL Image ops, ONNX sessions) for further reduction opportunities" />
          <ActionItem text="Evaluate reducing pod memory request from 32 GB based on production telemetry" />
        </Card>
      </Section>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════════════════════
   ENGINEERING VIEW
   ═══════════════════════════════════════════════════════════════════════ */

function EngView() {
  return (
    <div className="space-y-14">
      {/* ── Per-Scenario Results ── */}
      <Section
        title="Per-Scenario Results"
        subtitle="Individual test scenarios measured with memray --native. VM rebooted + 5-min idle before each run."
      >
        <Card>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b-2 border-zinc-200 dark:border-zinc-800 text-left text-[11px] font-bold uppercase tracking-wider text-green-600 dark:text-green-400">
                  <th className="py-2.5 pr-4">Scenario</th>
                  <th className="py-2.5 w-24 text-right">Baseline Peak</th>
                  <th className="py-2.5 w-24 text-right">Current Peak</th>
                  <th className="py-2.5 w-20 text-center">Delta</th>
                  <th className="py-2.5 w-20 text-right">BL Time</th>
                  <th className="py-2.5 w-20 text-right">CU Time</th>
                </tr>
              </thead>
              <tbody>
                {SCENARIO_TABLE.map((r, i) => (
                  <tr
                    key={r.scenario}
                    className={`border-b border-zinc-100 dark:border-zinc-800 ${i % 2 ? "bg-zinc-50/50 dark:bg-white/[0.02]" : ""}`}
                  >
                    <td className="py-2.5 pr-4 text-zinc-800 dark:text-zinc-200">{r.scenario}</td>
                    <td className="py-2.5 w-24 text-right font-mono text-zinc-500 dark:text-zinc-400">
                      {r.bl_peak}
                    </td>
                    <td className="py-2.5 w-24 text-right font-mono font-semibold text-zinc-800 dark:text-zinc-200">
                      {r.cu_peak}
                    </td>
                    <td className="py-2.5 w-20 text-center font-bold text-green-600 dark:text-green-400">
                      {r.delta}
                    </td>
                    <td className="py-2.5 w-20 text-right font-mono text-zinc-500 dark:text-zinc-400">
                      {r.bl_time}
                    </td>
                    <td className="py-2.5 w-20 text-right font-mono text-zinc-500 dark:text-zinc-400">
                      {r.cu_time}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </Section>

      {/* ── Top Memory Allocators ── */}
      <Section
        title="Top Memory Allocators"
        subtitle="Functions with highest total allocated bytes over the 18-test suite lifetime (memray --native)."
      >
        <Card>
          <AllocatorChart />
        </Card>

        <div className="flex flex-wrap gap-5 mt-5">
          <Card className="flex-1 min-w-[300px]">
            <div
              className="text-[11px] font-bold text-amber-600 dark:text-amber-400 mb-4"
              style={{ letterSpacing: "0.1em" }}
            >
              BASELINE TOP 5
            </div>
            {TOP_ALLOC_BASELINE.map(([name, size], i) => (
              <div
                key={name}
                className="flex items-center gap-2 border-b border-zinc-100 dark:border-zinc-800 py-2 last:border-b-0"
              >
                <span className="font-mono text-[13px] text-zinc-400 dark:text-zinc-500">
                  {i + 1}.
                </span>
                <span className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                  {name}
                </span>
                <span className="font-mono text-[13px] text-zinc-500 dark:text-zinc-400 ml-auto">
                  {size.toFixed(3)} GB
                </span>
              </div>
            ))}
          </Card>
          <Card className="flex-1 min-w-[300px]">
            <div
              className="text-[11px] font-bold text-green-600 dark:text-green-400 mb-4"
              style={{ letterSpacing: "0.1em" }}
            >
              CURRENT TOP 5
            </div>
            {TOP_ALLOC_CURRENT.map(([name, size], i) => (
              <div
                key={name}
                className="flex items-center gap-2 border-b border-zinc-100 dark:border-zinc-800 py-2 last:border-b-0"
              >
                <span className="font-mono text-[13px] text-zinc-400 dark:text-zinc-500">
                  {i + 1}.
                </span>
                <span className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                  {name}
                </span>
                <span className="font-mono text-[13px] text-zinc-500 dark:text-zinc-400 ml-auto">
                  {size.toFixed(3)} GB
                </span>
              </div>
            ))}
          </Card>
        </div>
      </Section>

      {/* ── Key Observations ── */}
      <Section title="Key Observations">
        <ObservationCard
          title="ONNX Session Overhead Down"
          badge="Improved"
          badgeColor="bg-green-500 text-zinc-950"
          borderColor="border-l-green-400"
          body="_create_inference_session dropped from #1 allocator (1.386 GB) in baseline to #3 (1.328 GB) in current. The ONNX Runtime session creation path allocates less overall, contributing to the peak reduction."
        />
        <ObservationCard
          title="PIL Image Operations Increased"
          badge="Expected"
          badgeColor="bg-amber-400 text-zinc-950"
          borderColor="border-l-amber-400"
          body="PIL Image.tobytes and Image.new increased in total allocation (e.g. tobytes: 1.188 → 1.802 GB). This reflects more frequent smaller image operations rather than fewer large ones — the pattern that reduces peak memory while increasing total throughput."
        />
        <ObservationCard
          title="Pre-Existing Test Failures (5 docx)"
          badge="Not a regression"
          badgeColor="bg-zinc-400 text-zinc-950"
          borderColor="border-l-zinc-400"
          body="5 of 18 tests fail on both baseline and current — all docx/pptx edge cases (but_not_when_the_partitioning_strategy_is_fast, PIL cannot recognize, Pillow can_only_read_the_image_on_Windows). These were excluded from the common test set count but still run; they are not related to the memory optimization work."
        />
      </Section>

      {/* ── Benchmark Environment ── */}
      <Section title="Benchmark Environment">
        <Card>
          <DataTable columns={["Parameter", "Value"]} rows={ENV_TABLE} />
        </Card>
      </Section>

      {/* ── Methodology ── */}
      <Section title="Methodology">
        <Card>
          <ol className="list-decimal pl-5 space-y-3 text-sm leading-relaxed text-zinc-700 dark:text-zinc-200">
            <li>
              VM rebooted before each environment&apos;s run to ensure clean memory state and enable
              Azure telemetry correlation
            </li>
            <li>
              5-minute idle wait after reboot for OS caches, Azure agents, and background processes
              to stabilize
            </li>
            <li>
              Each test suite runs under memray run --native, which instruments both Python
              allocations and native C/C++ allocations (malloc, calloc, realloc, mmap) via
              LD_PRELOAD
            </li>
            <li>
              memray stats extracts peak memory (high-water mark), total allocated, allocation
              count, wall time, and top allocating functions from the binary trace
            </li>
            <li>
              Common test set: 18 partition tests that exist in both baseline and current codebases,
              ensuring apples-to-apples comparison
            </li>
            <li>
              Identical test deselection applied to both: 6 baseline-only tests (docx/pptx edge
              cases not present in current) excluded via pytest -k filters
            </li>
          </ol>
        </Card>
      </Section>

      {/* ── Engineering Action Items ── */}
      <Section title="Engineering Action Items">
        <Card>
          <ActionItem text="Run full E2E benchmarks with all tests (not just common set) for both environments" />
          <ActionItem text="Add API pipeline tests (test_api_hi_res, test_api_od_only) to the standard benchmark suite" />
          <ActionItem text="Profile PIL Image.tobytes hot path — largest allocator in current (1.802 GB total)" />
          <ActionItem text="Investigate load_prepare growth (0.751 → 1.172 GB) for optimization opportunities" />
          <ActionItem text="Measure with production-scale documents (100+ page PDFs) to validate scaling behavior" />
          <ActionItem text="Correlate memray peaks with Azure pod-level metrics for production memory modeling" />
          <ActionItem text="Evaluate reducing Knative pod memory request from 32 GB based on observed peaks" />
        </Card>
      </Section>
    </div>
  )
}

/* ── shared components ──────────────────────────────────────────────── */

function Section({
  title,
  subtitle,
  children,
}: {
  title: string
  subtitle?: string
  children: React.ReactNode
}) {
  return (
    <div>
      <h2
        className="text-[22px] font-bold text-zinc-900 dark:text-zinc-200"
        style={{ letterSpacing: "-0.01em" }}
      >
        {title}
      </h2>
      {subtitle && (
        <p className="mt-1.5 text-sm leading-relaxed text-zinc-500 dark:text-zinc-400">
          {subtitle}
        </p>
      )}
      <div className="mt-6">{children}</div>
    </div>
  )
}

function Card({ children, className = "" }: { children: React.ReactNode; className?: string }) {
  return (
    <div
      className={`rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-sm dark:shadow-none ${className}`}
      style={{ padding: "28px 32px" }}
    >
      {children}
    </div>
  )
}

function ActionItem({ text, done = false }: { text: string; done?: boolean }) {
  return (
    <div className="flex items-center gap-3 border-b border-zinc-100 dark:border-zinc-800 py-2.5 last:border-b-0">
      <span
        className={`text-sm ${done ? "text-green-500 dark:text-green-400" : "text-zinc-400 dark:text-zinc-500"}`}
      >
        {done ? "●" : "○"}
      </span>
      <span className="text-sm text-zinc-800 dark:text-zinc-200">{text}</span>
    </div>
  )
}

function StatRow({
  label,
  baseline,
  current,
  unit,
  format,
  better = "lower",
}: {
  label: string
  baseline: number
  current: number
  unit: string
  format: (v: number) => string
  better?: "lower" | "higher"
}) {
  const delta = ((current - baseline) / baseline) * 100
  const improved = better === "lower" ? delta < 0 : delta > 0
  const deltaText = `${delta > 0 ? "+" : ""}${delta.toFixed(1)}%`

  return (
    <div className="flex items-center gap-4 border-b border-zinc-100 dark:border-zinc-800 py-3 last:border-b-0">
      <div className="flex-1 text-sm font-semibold text-zinc-800 dark:text-zinc-200">{label}</div>
      <div className="w-36 text-right font-mono text-sm text-zinc-500 dark:text-zinc-400">
        {format(baseline)} {unit}
      </div>
      <div className="w-36 text-right font-mono text-sm font-semibold text-zinc-800 dark:text-zinc-200">
        {format(current)} {unit}
      </div>
      <div className="w-20 text-center">
        <span
          className={`inline-block rounded-md px-2 py-0.5 text-xs font-bold ${
            delta === 0
              ? "bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400"
              : improved
                ? "bg-green-100 text-green-700 dark:bg-green-400/10 dark:text-green-400"
                : "bg-red-100 text-red-700 dark:bg-red-400/10 dark:text-red-400"
          }`}
        >
          {deltaText}
        </span>
      </div>
    </div>
  )
}

function ObservationCard({
  title,
  badge,
  badgeColor,
  borderColor,
  body,
}: {
  title: string
  badge: string
  badgeColor: string
  borderColor: string
  body: string
}) {
  return (
    <div
      className={`mb-4 rounded-xl border border-zinc-200 dark:border-zinc-800 border-l-4 ${borderColor} bg-white dark:bg-zinc-900 p-5 shadow-sm dark:shadow-none`}
    >
      <div className="mb-3 flex flex-wrap items-center gap-3">
        <span className="text-base font-bold text-zinc-900 dark:text-zinc-200">{title}</span>
        <span
          className={`inline-block rounded-full ${badgeColor} px-2.5 py-0.5 text-xs font-semibold`}
        >
          {badge}
        </span>
      </div>
      <p className="text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">{body}</p>
    </div>
  )
}

function DataTable({ columns, rows }: { columns: string[]; rows: string[][] }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b-2 border-zinc-200 dark:border-zinc-800 text-left text-[11px] font-bold uppercase tracking-wider text-green-600 dark:text-green-400">
            {columns.map(c => (
              <th key={c} className="py-2.5 pr-4">
                {c}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr
              key={i}
              className={`border-b border-zinc-100 dark:border-zinc-800 ${i % 2 ? "bg-zinc-50/50 dark:bg-white/[0.02]" : ""}`}
            >
              {row.map((cell, j) => (
                <td key={j} className="py-2.5 pr-4 text-zinc-700 dark:text-zinc-200">
                  {cell}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
