// app/mines/[projectId]/results/page.js
//
// Minimalist white client-facing diligence dashboard for a Mines project.
// Server Component. Presents the production artifacts the agents produced:
// ingestion, structured drill/trench data + intercepts, comparable assets,
// the operator conceptual scenario (clearly labelled, not a resource), the
// valuation-readiness assessment, recommended work program, risk register,
// and every generated artifact rendered inline. Reads directly from the DB.

import Link from "next/link";
import { getDb } from "../../../../lib/db.js";
import { getProjectDataQuality } from "../../../../lib/mines/data-quality.js";
import ArtifactsPanel from "./artifacts-panel.jsx";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export async function generateMetadata({ params }) {
  const { projectId } = await params;
  try {
    const p = getDb().prepare("SELECT name FROM mines_projects WHERE id = ?").get(projectId);
    if (p?.name) return { title: `${p.name} — Diligence package` };
  } catch {}
  return { title: "Diligence package — Mines" };
}

// ── design tokens ──────────────────────────────────────────────────────────────
const INK = "#111318", SUB = "#5b626c", FAINT = "#8a8f99";
const LINE = "rgba(17,19,24,.09)", LINE_SOFT = "rgba(17,19,24,.06)";
const MARS = "#c2452a", MONO = "ui-monospace, SFMono-Regular, Menlo, monospace";
const GOOD = "#2f7d52", WARN = "#9a6a12";

function num(v, opts = {}) {
  if (v == null || !Number.isFinite(Number(v))) return "—";
  return new Intl.NumberFormat("en-US", opts).format(Number(v));
}
function usd(n) {
  if (n == null || !Number.isFinite(Number(n))) return "—";
  const v = Number(n);
  if (v >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;
  if (v >= 1e6) return `$${(v / 1e6).toFixed(0)}M`;
  if (v >= 1e3) return `$${(v / 1e3).toFixed(0)}k`;
  return `$${v.toFixed(0)}`;
}
function jp(s) { try { return JSON.parse(s) || {}; } catch { return {}; } }

// Real comparable-asset figures (transcribed from the 43-101 §13 / S-K 1300 refs).
const COMPARABLES = [
  { name: "La Caridad", status: "Producing (reserves)", dist: "~25 km SE", tonnes: "2,100 Mt", cu: "0.21%", contained: "9,737 Mlb Cu", note: "+684 Mt @ 0.07% M+I resource" },
  { name: "Cananea / Buenavista", status: "Producing (reserves)", dist: "Same belt", tonnes: "2,413 Mt", cu: "0.44%", contained: "10,572 kt Cu", note: "+7,848 Mt @ 0.34% Inferred" },
  { name: "La Colorada breccia", status: "Historic (Cananea)", dist: "Same belt", tonnes: "7 Mt", cu: "6.0%", contained: "high-grade", note: "Breccia-hosted analogue" },
];

const RISKS = [
  ["No declared mineral resource (exploration risk)", "High", "Maiden resource drill program at El Choclo NW / Bata Sur"],
  ["Grade continuity at depth not yet demonstrated", "Medium", "Infill + step-out drilling; clay-alteration vectoring"],
  ["Metal price volatility", "Medium", "Long-dated optionality; structural copper demand"],
  ["Permitting / surface rights (Sonora)", "Medium", "Confirm tenure & community agreements in legal DD"],
  ["Historic-operator data provenance", "Low–Med", "Teck data verified vs lab certificates; re-log key holes"],
];

const PROGRAM = [
  "Detailed mapping + re-interpretation of existing geophysics over all four targets.",
  "Clay-alteration (SWIR) analysis of existing drill core to vector toward the porphyry centre.",
  "Phase-1 drilling of the El Choclo NW chalcocite-blanket target (highest-priority untested).",
  "Maiden mineral resource estimate if Phase-1 confirms continuity.",
];

// ── data load ────────────────────────────────────────────────────────────────
function loadResults(projectId) {
  const db = getDb();
  const project = db.prepare("SELECT * FROM mines_projects WHERE id = ?").get(projectId);
  if (!project) return null;
  const one = (sql, ...a) => db.prepare(sql).get(...a);
  const all = (sql, ...a) => db.prepare(sql).all(...a);

  // Anchor curated tables to the NI 43-101 source so background-daemon rows
  // loaded from arbitrary archive spreadsheets don't pollute the deliverable.
  const reportDocId = one("SELECT id FROM mines_source_documents WHERE project_id=? AND file_name='43-101 Batamote.pdf'", projectId)?.id || "";

  const counts = {
    documents: one("SELECT COUNT(*) n FROM mines_source_documents WHERE project_id=?", projectId).n,
    assays: one("SELECT COUNT(*) n FROM mines_assay_samples WHERE project_id=?", projectId).n,
    drill_holes: one("SELECT COUNT(*) n FROM mines_drill_holes WHERE project_id=? AND source_document_id=?", projectId, reportDocId).n,
    facts: one("SELECT COUNT(*) n FROM mines_extracted_facts WHERE project_id=?", projectId).n,
    chunks: one("SELECT COUNT(*) n FROM mines_document_chunks WHERE project_id=?", projectId).n,
    docs_extracted: one("SELECT COUNT(*) n FROM mines_source_documents WHERE project_id=? AND extraction_status IN ('complete','embedding_failed')", projectId).n,
  };
  let dq = null; try { dq = getProjectDataQuality(projectId); } catch {}

  const trench = one("SELECT COUNT(*) n, AVG(cu_pct) avg_cu, MAX(cu_pct) max_cu, AVG(ag_ppm) avg_ag FROM mines_assay_samples WHERE project_id=? AND sample_type='trench_channel'", projectId);
  const trenchRows = all("SELECT sample_id, width_m, cu_pct, ag_ppm FROM mines_assay_samples WHERE project_id=? AND sample_type='trench_channel' ORDER BY cu_pct DESC", projectId);
  const intercepts = all("SELECT a.sample_id, a.width_m, a.cu_pct, a.ag_ppm, a.other_grades_json, h.hole_id FROM mines_assay_samples a LEFT JOIN mines_drill_holes h ON h.id=a.drillhole_id WHERE a.project_id=? AND a.sample_type='drill_core' ORDER BY (a.cu_pct*a.width_m) DESC", projectId);
  const drillHoles = all("SELECT hole_id, collar_easting, collar_northing, collar_elevation, total_depth_m FROM mines_drill_holes WHERE project_id=? AND source_document_id=? ORDER BY hole_id", projectId, reportDocId);

  const allFacts = all("SELECT fact_type, value_text, page_or_location FROM mines_extracted_facts WHERE project_id=? ORDER BY fact_type", projectId);
  const targets = allFacts.filter(f => f.fact_type.startsWith("target_"));
  const workProgram = allFacts.find(f => f.fact_type === "work_program");
  const baseFacts = allFacts.filter(f => !f.fact_type.startsWith("target_") && !f.fact_type.startsWith("comparable_"));

  const opScen = all("SELECT scenario, assumptions_json, result_json FROM mines_valuation_scenarios WHERE project_id=? AND scenario LIKE 'operator_%' ORDER BY scenario", projectId)
    .map(r => ({ scenario: r.scenario.replace("operator_", ""), a: jp(r.assumptions_json), r: jp(r.result_json) }));
  const orderScen = ["low", "base", "high"];
  opScen.sort((x, y) => orderScen.indexOf(x.scenario) - orderScen.indexOf(y.scenario));

  const price = (c) => one("SELECT price_usd, source FROM mines_market_snapshots WHERE lower(commodity)=lower(?) ORDER BY fetched_at DESC LIMIT 1", c);

  const getContent = db.prepare("SELECT content FROM artifacts WHERE id=?");
  const artifacts = all("SELECT id, kind, title, created_at FROM artifacts WHERE project_id IN (?, ?) ORDER BY created_at DESC", projectId, project.os_project_id || "")
    .map(a => ({ ...a, content: getContent.get(a.id)?.content || "" }));
  // Investor presentation first (the accessible executive view), then the
  // diligence memo, then everything else by recency.
  const artifactRank = (a) =>
    a.kind === "mines_investor_presentation" ? 0 : a.title.includes("Diligence") ? 1 : 2;
  artifacts.sort((a, b) => artifactRank(a) - artifactRank(b));

  return { project, counts, dq, trench, trenchRows, intercepts, drillHoles, baseFacts, targets, workProgram, opScen, priceCu: price("Cu"), priceAg: price("Ag"), artifacts };
}

// ── components ───────────────────────────────────────────────────────────────
function Kicker({ children }) {
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 9, color: MARS, fontFamily: MONO, fontSize: 11, fontWeight: 600, letterSpacing: ".16em", textTransform: "uppercase" }}><span aria-hidden style={{ width: 22, height: 1, background: MARS }} />{children}</span>;
}
function SectionTitle({ children, note }) {
  return <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 16, margin: "0 0 16px", paddingTop: 30, borderTop: `1px solid ${LINE}` }}>
    <h2 style={{ margin: 0, fontSize: 19, fontWeight: 600, letterSpacing: "-.02em", color: INK }}>{children}</h2>
    {note && <span style={{ fontSize: 11.5, color: FAINT, fontFamily: MONO, whiteSpace: "nowrap" }}>{note}</span>}
  </div>;
}
function Metric({ label, value, unit, accent }) {
  return <div style={{ padding: "18px 20px", border: `1px solid ${LINE_SOFT}`, borderRadius: 14, background: "#fff", display: "flex", flexDirection: "column", gap: 8 }}>
    <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".13em", textTransform: "uppercase", color: FAINT }}>{label}</span>
    <span style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
      <b style={{ fontSize: 30, fontWeight: 300, letterSpacing: "-.045em", lineHeight: 1, color: accent || INK, fontFeatureSettings: '"tnum","lnum"' }}>{value}</b>
      {unit && <span style={{ fontSize: 12, color: FAINT, fontWeight: 600 }}>{unit}</span>}
    </span>
  </div>;
}
function Pill({ children, tone = "neutral" }) {
  const t = { neutral: { c: INK, b: LINE }, good: { c: GOOD, b: "rgba(47,125,82,.3)" }, warn: { c: WARN, b: "rgba(154,106,18,.3)" }, mars: { c: MARS, b: "rgba(194,69,42,.3)" } }[tone];
  return <span style={{ display: "inline-flex", padding: "4px 11px", borderRadius: 999, border: `1px solid ${t.b}`, color: t.c, fontSize: 11.5, fontWeight: 700 }}>{children}</span>;
}
function Th({ children, align = "left" }) { return <th style={{ padding: "9px 14px", textAlign: align, fontSize: 9.5, fontWeight: 800, letterSpacing: ".11em", textTransform: "uppercase", color: FAINT }}>{children}</th>; }
function Td({ children, align = "left", mono = false, strong = false }) { return <td style={{ padding: "9px 14px", textAlign: align, fontSize: mono ? 12 : 12.5, color: strong ? INK : "#374049", fontFamily: mono ? MONO : undefined, fontWeight: strong ? 650 : 400, whiteSpace: "nowrap" }}>{children}</td>; }
function DataCard({ children }) { return <div style={{ border: `1px solid ${LINE_SOFT}`, borderRadius: 14, background: "#fff", overflow: "hidden" }}><div style={{ overflowX: "auto" }}>{children}</div></div>; }
function PipelineStep({ n, label, sub }) {
  return <div style={{ display: "flex", gap: 12, alignItems: "flex-start", flex: "1 1 150px", minWidth: 140 }}>
    <span style={{ flexShrink: 0, width: 22, height: 22, borderRadius: "50%", border: `1.5px solid ${MARS}`, color: MARS, display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, fontFamily: MONO }}>{n}</span>
    <span style={{ display: "flex", flexDirection: "column", gap: 2 }}><span style={{ fontSize: 12.5, fontWeight: 650, color: INK }}>{label}</span><span style={{ fontSize: 11, color: FAINT }}>{sub}</span></span>
  </div>;
}

// ── page ────────────────────────────────────────────────────────────────────────
export default async function MinesResultsPage({ params }) {
  const { projectId } = await params;
  const d = loadResults(projectId);
  if (!d) {
    return <main style={{ height: "100%", overflowY: "auto", background: "#fff", color: INK, display: "grid", placeItems: "center", fontFamily: "Inter, system-ui, sans-serif", borderRadius: 18 }}>
      <div style={{ textAlign: "center" }}><Kicker>Mines · Results</Kicker><h1 style={{ fontSize: 28, fontWeight: 600, margin: "12px 0" }}>No project found</h1><Link href="/mines" style={{ color: MARS, textDecoration: "none", fontWeight: 600 }}>← Back to portfolio</Link></div>
    </main>;
  }
  const { project, counts, dq, trench, trenchRows, intercepts, drillHoles, baseFacts, targets, workProgram, opScen, priceCu, priceAg, artifacts } = d;
  const completenessPct = dq ? Math.round((dq.completeness_score || 0) * 100) : 0;
  const factLabel = (t) => t.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
  const baseScen = opScen.find(s => s.scenario === "base");

  return (
    <main style={{ height: "100%", overflowY: "auto", background: "#ffffff", color: INK, fontFamily: "Inter, system-ui, -apple-system, sans-serif", WebkitFontSmoothing: "antialiased", borderRadius: 18 }}>
      <div style={{ maxWidth: 1060, margin: "0 auto", padding: "clamp(28px,5vw,64px) clamp(20px,4vw,40px) 96px" }}>

        {/* Header */}
        <Link href={`/mines/${projectId}`} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: SUB, textDecoration: "none", marginBottom: 26 }}><span aria-hidden>←</span> {project.name} overview</Link>
        <Kicker>MadarX · Mines · Investment diligence package</Kicker>
        <h1 style={{ margin: "14px 0 10px", fontSize: "clamp(2.4rem, 6vw, 4rem)", fontWeight: 300, letterSpacing: "-.05em", lineHeight: 1.0 }}>{project.name}</h1>
        <p style={{ margin: 0, fontSize: 15, color: SUB, lineHeight: 1.6, maxWidth: 740 }}>
          {project.deposit_type || "Porphyry copper (±Ag)"} · {project.asset_stage} stage · {project.state_province || "Sonora"}, {project.country}.
          Autonomous agents ingested the NI 43-101 and full archive, structured the geoscience data, benchmarked
          comparable assets, and produced the diligence artifacts below.
        </p>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 18 }}>
          <Pill tone="warn">Exploration target</Pill>
          <Pill tone="neutral">Cananea–La Caridad belt</Pill>
          <Pill tone="mars">T2 DCF blocked</Pill>
          <Pill tone="good">No fabricated resource</Pill>
        </div>

        {/* Pipeline */}
        <div style={{ marginTop: 34, padding: "22px", border: `1px solid ${LINE_SOFT}`, borderRadius: 16, background: "#fcfcfb" }}>
          <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".13em", textTransform: "uppercase", color: FAINT }}>What the agents ran</span>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "20px 16px", marginTop: 16 }}>
            <PipelineStep n="1" label="Catalog" sub={`${num(counts.documents)} files`} />
            <PipelineStep n="2" label="Extract" sub={`${num(counts.docs_extracted)} docs · ${num(counts.chunks)} chunks`} />
            <PipelineStep n="3" label="Benchmark" sub="comparable assets" />
            <PipelineStep n="4" label="Value" sub="readiness + scenario" />
            <PipelineStep n="5" label="Report" sub={`${artifacts.length} artifacts`} />
          </div>
        </div>

        {/* Metrics */}
        <SectionTitle note="structured SQL · provenance-linked">Project at a glance</SectionTitle>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12 }}>
          <Metric label="Files cataloged" value={num(counts.documents)} />
          <Metric label="Docs extracted" value={num(counts.docs_extracted)} />
          <Metric label="Text chunks" value={num(counts.chunks)} />
          <Metric label="Drill holes" value={num(counts.drill_holes)} />
          <Metric label="Drill intercepts" value={num(intercepts.length)} />
          <Metric label="Avg trench Cu" value={trench?.avg_cu != null ? num(trench.avg_cu, { maximumFractionDigits: 3 }) : "—"} unit="% Cu" accent={MARS} />
        </div>

        {/* Operator scenario — the headline $ (clearly labelled) */}
        <SectionTitle note="mines_valuation_scenario_report">Indicative value — operator scenario</SectionTitle>
        <div style={{ padding: "18px 20px", border: `1px solid ${LINE}`, borderLeft: `3px solid ${WARN}`, borderRadius: 14, background: "#fffdf6", marginBottom: 14, fontSize: 13.5, lineHeight: 1.6, color: INK }}>
          <strong>Conceptual exploration target — not a mineral resource.</strong> No resource is declared, so no definitive valuation is produced.
          The range below is an operator-supplied conceptual exploration target (tonnage/grade as a range). It is conceptual; exploration is
          insufficient to define a resource; and it is uncertain whether further work will delineate one. In-situ values are order-of-magnitude
          exploration optionality only — <strong>not</strong> a resource, reserve, or valuation opinion.
        </div>
        {opScen.length > 0 && (
          <>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px,1fr))", gap: 12 }}>
              {opScen.map(s => (
                <div key={s.scenario} style={{ padding: "18px 20px", border: `1px solid ${LINE_SOFT}`, borderRadius: 14, background: s.scenario === "base" ? "#fffaf0" : "#fff", display: "flex", flexDirection: "column", gap: 7 }}>
                  <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".13em", textTransform: "uppercase", color: s.scenario === "base" ? MARS : FAINT }}>{s.scenario} scenario</span>
                  <b style={{ fontSize: 30, fontWeight: 300, letterSpacing: "-.045em", color: INK }}>{usd(s.r.in_situ_value_usd)}</b>
                  <span style={{ fontSize: 11.5, color: SUB }}>{num(s.a.resource_tonnes / 1e6)} Mt @ {num(s.a.grade_cu_pct, { maximumFractionDigits: 2 })}% Cu</span>
                </div>
              ))}
            </div>
            <p style={{ margin: "12px 2px 0", fontSize: 11.5, color: FAINT }}>
              In-situ = contained recoverable metal × price × 3% in-situ factor (exploration). Prices: Cu {usd(priceCu?.price_usd)}/lb · Ag {usd(priceAg?.price_usd)}/oz ({priceCu?.source || "snapshot"}).
            </p>
          </>
        )}

        {/* Valuation readiness */}
        <SectionTitle note="mines_valuation_readiness_report">Valuation readiness (definitive)</SectionTitle>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px,1fr))", gap: 12 }}>
          <Metric label="Definitive value" value="N/A" accent={WARN} />
          <Metric label="Tier (when resourced)" value="T1" unit="in-situ" />
          <Metric label="DCF gate" value="Blocked" accent={MARS} />
          <Metric label="Data completeness" value={`${completenessPct}`} unit="%" />
        </div>
        <p style={{ margin: "12px 2px 0", fontSize: 12.5, color: SUB, lineHeight: 1.6 }}>
          The system selected <strong>T1 in-situ</strong> as the eventual tier but produced <strong>no dollar value</strong> — no resource tonnage exists and it will not invent one.
          T2 DCF is hard-blocked (missing reserves, opex, production schedule). This is the definitive path; the scenario above is illustrative only.
        </p>

        {/* Comparable assets */}
        <SectionTitle note="43-101 §13 · S-K 1300 refs">Comparable assets in the belt</SectionTitle>
        <DataCard>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr><Th>Asset</Th><Th>Status</Th><Th>Distance</Th><Th align="right">Tonnage</Th><Th align="right">Cu grade</Th><Th>Contained / note</Th></tr></thead>
            <tbody>
              {COMPARABLES.map(c => (
                <tr key={c.name} style={{ borderTop: `1px solid ${LINE_SOFT}` }}>
                  <Td strong>{c.name}</Td><Td>{c.status}</Td><Td>{c.dist}</Td>
                  <Td align="right" mono>{c.tonnes}</Td><Td align="right" mono strong>{c.cu}</Td><Td>{c.contained} · {c.note}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </DataCard>
        <p style={{ margin: "10px 2px 0", fontSize: 11.5, color: FAINT }}>Analogues establish the geological model and the in-ground value range for a successful porphyry discovery. Not a prediction of Batamote tonnage or grade.</p>

        {/* Drill intercepts */}
        <SectionTitle note="Table 4 · Cu × width ranked">Best drill intercepts</SectionTitle>
        <DataCard>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr><Th>Hole / interval</Th><Th align="right">Width (m)</Th><Th align="right">Cu %</Th><Th align="right">Ag g/t</Th><Th align="right">CuEq %</Th><Th>Target</Th></tr></thead>
            <tbody>
              {intercepts.map(i => { const o = jp(i.other_grades_json); return (
                <tr key={i.sample_id} style={{ borderTop: `1px solid ${LINE_SOFT}` }}>
                  <Td mono strong>{i.sample_id}</Td>
                  <Td align="right" mono>{num(i.width_m, { maximumFractionDigits: 1 })}</Td>
                  <Td align="right" mono strong>{num(i.cu_pct, { maximumFractionDigits: 3 })}</Td>
                  <Td align="right" mono>{num(i.ag_ppm, { maximumFractionDigits: 1 })}</Td>
                  <Td align="right" mono>{o.cueq_pct != null ? num(o.cueq_pct, { maximumFractionDigits: 3 }) : "—"}</Td>
                  <Td>{o.area || "—"}</Td>
                </tr>
              ); })}
            </tbody>
          </table>
        </DataCard>

        {/* Trench assays */}
        <SectionTitle note="Table 2 · Bata Sur trenching">Trench geochemistry</SectionTitle>
        <DataCard>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr><Th>Trench</Th><Th align="right">Width (m)</Th><Th align="right">Cu %</Th><Th align="right">Cu (ppm)</Th><Th align="right">Ag g/t</Th></tr></thead>
            <tbody>
              {trenchRows.map(a => (
                <tr key={a.sample_id} style={{ borderTop: `1px solid ${LINE_SOFT}` }}>
                  <Td mono strong>{a.sample_id}</Td>
                  <Td align="right" mono>{num(a.width_m, { maximumFractionDigits: 1 })}</Td>
                  <Td align="right" mono strong>{num(a.cu_pct, { maximumFractionDigits: 4 })}</Td>
                  <Td align="right" mono>{num(a.cu_pct * 10000, { maximumFractionDigits: 0 })}</Td>
                  <Td align="right" mono>{num(a.ag_ppm, { maximumFractionDigits: 2 })}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </DataCard>

        {/* Targets */}
        <SectionTitle note="43-101 §14">Exploration targets</SectionTitle>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px,1fr))", gap: 12 }}>
          {targets.map(t => (
            <div key={t.fact_type} style={{ border: `1px solid ${LINE_SOFT}`, borderRadius: 14, padding: "16px 18px", background: "#fff" }}>
              <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".06em", textTransform: "uppercase", color: MARS }}>{t.fact_type.replace("target_", "").replace(/_/g, " ")}</span>
              <p style={{ margin: "8px 0 0", fontSize: 12.5, color: "#374049", lineHeight: 1.55 }}>{t.value_text}</p>
            </div>
          ))}
        </div>

        {/* Drill collars */}
        <SectionTitle note="Table 3 · Teck 2011–12 · UTM 12N">Drill-hole collars</SectionTitle>
        <DataCard>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr><Th>Hole ID</Th><Th align="right">Easting</Th><Th align="right">Northing</Th><Th align="right">Elev (m)</Th><Th align="right">Depth (m)</Th></tr></thead>
            <tbody>
              {drillHoles.map(h => (
                <tr key={h.hole_id} style={{ borderTop: `1px solid ${LINE_SOFT}` }}>
                  <Td mono strong>{h.hole_id}</Td>
                  <Td align="right" mono>{num(h.collar_easting, { maximumFractionDigits: 1 })}</Td>
                  <Td align="right" mono>{num(h.collar_northing, { maximumFractionDigits: 0 })}</Td>
                  <Td align="right" mono>{num(h.collar_elevation, { maximumFractionDigits: 0 })}</Td>
                  <Td align="right" mono>{num(h.total_depth_m, { maximumFractionDigits: 1 })}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </DataCard>

        {/* Recommended work program */}
        <SectionTitle note="QP recommendations + planning estimate">Recommended work program</SectionTitle>
        {workProgram && <p style={{ margin: "0 0 12px", fontSize: 13, color: "#374049", lineHeight: 1.6 }}>{workProgram.value_text} <span style={{ color: FAINT, fontFamily: MONO, fontSize: 11 }}>{workProgram.page_or_location}</span></p>}
        <ol style={{ margin: 0, paddingLeft: 20, fontSize: 13, color: "#374049", lineHeight: 1.8 }}>
          {PROGRAM.map((p, i) => <li key={i}>{p}</li>)}
        </ol>

        {/* Risk register */}
        <SectionTitle>Risk register</SectionTitle>
        <DataCard>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead><tr><Th>Risk</Th><Th>Severity</Th><Th>Mitigation</Th></tr></thead>
            <tbody>
              {RISKS.map((r, i) => (
                <tr key={i} style={{ borderTop: `1px solid ${LINE_SOFT}` }}>
                  <Td strong>{r[0]}</Td>
                  <Td><Pill tone={r[1] === "High" ? "mars" : r[1] === "Medium" ? "warn" : "neutral"}>{r[1]}</Pill></Td>
                  <Td>{r[2]}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </DataCard>

        {/* Extracted facts */}
        <SectionTitle note="every claim cites the 43-101">Extracted facts</SectionTitle>
        <div style={{ display: "grid", gap: 10 }}>
          {baseFacts.map(f => (
            <div key={f.fact_type} style={{ border: `1px solid ${LINE_SOFT}`, borderRadius: 12, padding: "13px 16px", background: "#fff", display: "flex", gap: 16, alignItems: "flex-start" }}>
              <span style={{ flexShrink: 0, width: 130, fontSize: 11, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: MARS, paddingTop: 1 }}>{factLabel(f.fact_type)}</span>
              <span style={{ fontSize: 12.5, color: "#374049", lineHeight: 1.55, flex: 1 }}>{f.value_text}</span>
              <span style={{ flexShrink: 0, fontSize: 10.5, color: FAINT, fontFamily: MONO }}>{f.page_or_location}</span>
            </div>
          ))}
        </div>

        {/* Artifacts produced — open in a movable modal, publish to a dashboard space */}
        <SectionTitle note="open in a window · publish to a space">Artifacts produced</SectionTitle>
        <ArtifactsPanel
          projectId={projectId}
          defaultSpaceId={project.default_space_id || ""}
          artifacts={artifacts.map(a => ({ id: a.id, kind: a.kind, title: a.title, content: a.content }))}
        />

        {/* Limitations */}
        <div style={{ marginTop: 36, paddingTop: 22, borderTop: `1px solid ${LINE}`, fontSize: 12, color: FAINT, lineHeight: 1.7 }}>
          <strong style={{ color: SUB }}>Limitations.</strong> Structured figures are transcribed/extracted from the Batamote NI 43-101 (effective 09 Jun 2025) and archive;
          comparable-asset figures are from public S-K 1300 reports referenced therein. Metal prices are dated market snapshots. The operator scenario is a
          conceptual exploration target, not a mineral resource or valuation opinion. This package is decision-support analysis and not investment advice.
        </div>
      </div>
    </main>
  );
}
