/* eslint-disable no-undef */
// Branded PDF reports for Fintech. Preview in-app; download is always .pdf.

const AGB_INK = "#0B1C16";
const AGB_EMERALD = "#13935F";
const AGB_MINT = "#2FC18C";
const AGB_PAPER = "#F5F7F1";
const AGB_MUTED = "#566860";
const AGB_ROSE = "#B4483A";
const AGB_AMBER = "#C4841A";
const AGB_CYAN = "#1F87B4";
const AGB_VIOLET = "#3257C4";

function rEsc(s) {
  return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" }[c]));
}
function rMoney(v, d = 0) {
  const n = Number(v) || 0;
  const sign = n < 0 ? "-" : "";
  return sign + "$" + Math.abs(n).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d });
}
function rNum(v, d = 0) {
  return Number(v || 0).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d });
}
function rPct(v, d = 1) { return (Number(v || 0) * 100).toFixed(d) + "%"; }
function rHash(str) {
  let h = 2166136261;
  const s = String(str);
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
  return ("00000000" + (h >>> 0).toString(16)).slice(-8).toUpperCase();
}
function rNow() {
  return new Date().toLocaleString("en-CA", { dateStyle: "medium", timeStyle: "short" });
}
function rDocId(prefix, payload) {
  return `AGB-${prefix}-${new Date().getFullYear()}-${rHash(payload)}`;
}
function rMonths() {
  return ["Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"];
}
function rTrend(base, vol, trend, seed, n = 12) {
  return window.generateSeries(n, base, vol, trend, seed);
}

const SPROUT = `<svg viewBox="0 0 32 32" width="28" height="28" fill="none" aria-hidden="true">
  <path d="M16 30V13" stroke="#E8F6EF" stroke-width="2.4" stroke-linecap="round"/>
  <path d="M16 16C16 10 12 6.5 5.5 6.5 5.5 13 9.5 16 16 16Z" fill="#13935F" stroke="#E8F6EF" stroke-width="1.4" stroke-linejoin="round"/>
  <path d="M16 12.5C16 7.5 19.6 4 25.5 4 25.5 9.8 21.9 12.5 16 12.5Z" fill="#7FC241" stroke="#E8F6EF" stroke-width="1.4" stroke-linejoin="round"/>
</svg>`;

function chartBar(items, opts = {}) {
  const w = opts.w || 640, h = opts.h || 188;
  const pad = { l: 8, r: 8, t: 22, b: 40 };
  const max = Math.max(...items.map((i) => Math.abs(i.value)), 1);
  const gap = (w - pad.l - pad.r) / items.length;
  const bw = gap * 0.58;
  const bars = items.map((it, i) => {
    const bh = (Math.abs(it.value) / max) * (h - pad.t - pad.b);
    const x = pad.l + i * gap + (gap - bw) / 2;
    const y = h - pad.b - bh;
    const label = rEsc(it.label);
    const val = opts.fmt ? opts.fmt(it.value) : rNum(it.value);
    return `<g>
      <rect x="${x}" y="${y}" width="${bw}" height="${bh}" rx="4" fill="${it.color || AGB_EMERALD}"/>
      <text x="${x + bw / 2}" y="${y - 6}" text-anchor="middle" font-size="10" font-weight="700" fill="${AGB_INK}">${rEsc(val)}</text>
      <text x="${x + bw / 2}" y="${h - 16}" text-anchor="middle" font-size="10" fill="${AGB_MUTED}">${label}</text>
    </g>`;
  }).join("");
  return { kind: "bar", items, opts, svg: `<svg viewBox="0 0 ${w} ${h}" width="100%" role="img">${bars}</svg>` };
}

function chartLine(values, opts = {}) {
  const w = opts.w || 640, h = opts.h || 160;
  const pad = { l: 36, r: 10, t: 12, b: 28 };
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = (max - min) || 1;
  const pts = values.map((v, i) => {
    const x = pad.l + (i / Math.max(1, values.length - 1)) * (w - pad.l - pad.r);
    const y = pad.t + (1 - (v - min) / span) * (h - pad.t - pad.b);
    return [x, y];
  });
  const d = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");
  const area = `${d} L${pts[pts.length - 1][0]},${h - pad.b} L${pts[0][0]},${h - pad.b} Z`;
  const labels = opts.labels || [];
  const ticks = labels.map((lb, i) => {
    if (!lb) return "";
    const x = pad.l + (i / Math.max(1, values.length - 1)) * (w - pad.l - pad.r);
    return `<text x="${x}" y="${h - 8}" text-anchor="middle" font-size="9" fill="${AGB_MUTED}">${rEsc(lb)}</text>`;
  }).join("");
  const color = opts.color || AGB_EMERALD;
  return {
    kind: "line", values, opts,
    svg: `<svg viewBox="0 0 ${w} ${h}" width="100%" role="img">
    <path d="${area}" fill="${color}" opacity="0.12"/>
    <path d="${d}" fill="none" stroke="${color}" stroke-width="2.2" stroke-linejoin="round"/>
    ${ticks}
  </svg>`,
  };
}

function chartDonut(items, size = 168) {
  const total = items.reduce((s, i) => s + i.value, 0) || 1;
  const cx = size / 2, cy = size / 2, r = size * 0.34, sw = size * 0.15;
  const c = 2 * Math.PI * r;
  let offset = 0;
  const rings = items.map((it) => {
    const len = (it.value / total) * c;
    const el = `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${it.color}" stroke-width="${sw}"
      stroke-dasharray="${len.toFixed(1)} ${(c - len).toFixed(1)}" stroke-dashoffset="${(-offset).toFixed(1)}"
      transform="rotate(-90 ${cx} ${cy})" stroke-linecap="butt"/>`;
    offset += len;
    return el;
  }).join("");
  const legend = items.map((it) =>
    `<div class="leg"><i style="background:${it.color}"></i><span>${rEsc(it.label)}</span><b>${rEsc(it.display || rPct(it.value / total, 0))}</b></div>`
  ).join("");
  return {
    kind: "donut", items,
    svg: `<div class="donut-wrap">
    <svg viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">${rings}
      <text x="${cx}" y="${cy - 2}" text-anchor="middle" font-size="13" font-weight="700" fill="${AGB_INK}">${rEsc(optsTotal(items))}</text>
      <text x="${cx}" y="${cy + 14}" text-anchor="middle" font-size="9" fill="${AGB_MUTED}">total</text>
    </svg>
    <div class="legend">${legend}</div>
  </div>`,
  };
}
function optsTotal(items) {
  const t = items.reduce((s, i) => s + i.value, 0);
  return items[0] && items[0].unit === "$" ? rMoney(t) : rNum(t);
}

const REPORT_CSS = `
html{margin:0;background:#fff}
.agb-pdf-root,.agb-pdf-root *{box-sizing:border-box}
.agb-pdf-root{
  --ink:${AGB_INK};--em:${AGB_EMERALD};--mint:${AGB_MINT};--paper:${AGB_PAPER};--muted:${AGB_MUTED};--line:rgba(11,28,22,.12);
  margin:0;background:#fff;color:var(--ink);
  font:13px/1.55 Helvetica,Arial,sans-serif;
  letter-spacing:0;word-spacing:normal;
  width:100%;max-width:100%;overflow:visible;
}
.agb-pdf-root h1,.agb-pdf-root h2,.agb-pdf-root h3{font-family:Helvetica,Arial,sans-serif;letter-spacing:0;line-height:1.3;margin:0}
.agb-pdf-root .cover{background:linear-gradient(135deg,#0B1C16 0%,#0F2A20 58%,#0E7A4F 140%);color:#eafff5;padding:22px 24px 20px}
.agb-pdf-root .cover-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:16px}
.agb-pdf-root .brand{display:flex;align-items:center;gap:8px;font-weight:700;font-size:16px;letter-spacing:.04em;flex-shrink:0}
.agb-pdf-root .meta{text-align:right;font-size:10px;color:#9FE6CB;line-height:1.45;min-width:0}
.agb-pdf-root .kicker{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--mint);font-weight:600;margin-bottom:8px}
.agb-pdf-root .cover h1{font-size:24px;color:#fff;max-width:100%}
.agb-pdf-root .cover .sub{margin-top:8px;color:#cfe9df;max-width:100%;font-size:13px}
.agb-pdf-root .chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:14px}
.agb-pdf-root .chip{font-size:10px;padding:4px 8px;border-radius:999px;border:1px solid rgba(159,230,203,.35);color:#eafff5}
.agb-pdf-root .wrap{padding:18px 24px 24px;max-width:none;margin:0}
.agb-pdf-root .kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin:0 0 18px}
.agb-pdf-root .kpi{background:var(--paper);border:1px solid var(--line);border-radius:10px;padding:10px 10px 8px;min-width:0;overflow:hidden}
.agb-pdf-root .kpi span{display:block;font-size:9px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);font-weight:600}
.agb-pdf-root .kpi b{display:block;margin-top:4px;font-size:18px;letter-spacing:0;word-break:break-word}
.agb-pdf-root .kpi em{display:block;margin-top:3px;font-style:normal;font-size:10px;color:var(--muted)}
.agb-pdf-root .sec{margin:16px 0 6px}
.agb-pdf-root .sec h2{font-size:15px;margin-bottom:6px}
.agb-pdf-root .sec p{color:#243830;margin:0 0 10px;letter-spacing:0;word-spacing:normal;overflow-wrap:break-word}
.agb-pdf-root .grid-2{display:flex;flex-direction:column;gap:14px;align-items:stretch}
.agb-pdf-root table{width:100%;border-collapse:collapse;font-size:11px;table-layout:auto}
.agb-pdf-root th{text-align:left;font-size:9px;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);padding:6px 5px;border-bottom:1px solid var(--line);font-weight:600}
.agb-pdf-root td{padding:6px 5px;border-bottom:1px solid rgba(11,28,22,.07);vertical-align:top;overflow-wrap:anywhere}
.agb-pdf-root td.num,.agb-pdf-root th.num{text-align:right;font-variant-numeric:tabular-nums;font-family:ui-monospace,Menlo,monospace;font-size:10.5px;white-space:nowrap}
.agb-pdf-root .pos{color:#0E7A4F;font-weight:600}.agb-pdf-root .neg{color:${AGB_ROSE};font-weight:600}
.agb-pdf-root .callout{border-left:4px solid var(--em);background:var(--paper);padding:10px 12px;border-radius:0 8px 8px 0;margin:10px 0}
.agb-pdf-root .callout.warn{border-left-color:${AGB_AMBER}}
.agb-pdf-root .callout h3{font-size:12px;margin-bottom:4px}
.agb-pdf-root .callout p{margin:0;font-size:12px;color:#243830}
.agb-pdf-root .chart{background:#fff;border:1px solid var(--line);border-radius:10px;padding:8px 10px 4px;margin:10px 0;overflow:hidden}
.agb-pdf-root .chart .cap{font-size:10px;color:var(--muted);margin-bottom:4px;font-weight:600;letter-spacing:.04em;text-transform:uppercase}
.agb-pdf-root .chart svg{display:block;max-width:100%;height:auto}
.agb-pdf-root .donut-wrap{display:flex;gap:12px;align-items:center}
.agb-pdf-root .legend{display:flex;flex-direction:column;gap:5px;flex:1;min-width:0}
.agb-pdf-root .leg{display:flex;align-items:center;gap:8px;font-size:11px}
.agb-pdf-root .leg i{width:10px;height:10px;border-radius:2px;display:block;flex-shrink:0}
.agb-pdf-root .leg b{margin-left:auto;font-variant-numeric:tabular-nums}
.agb-pdf-root .notes{font-size:10px;color:var(--muted);margin-top:14px}
.agb-pdf-root .notes ol{padding-left:16px;margin:6px 0}
.agb-pdf-root .foot{display:flex;justify-content:space-between;gap:12px;border-top:1px solid var(--line);margin-top:20px;padding-top:10px;font-size:10px;color:var(--muted)}
.agb-pdf-root .foot div{min-width:0;overflow-wrap:anywhere;white-space:normal}
.agb-pdf-root .banner{display:flex;justify-content:space-between;gap:10px;background:#E8F6EF;color:var(--ink);font-size:10px;padding:7px 24px;border-bottom:1px solid var(--line);letter-spacing:.03em}
.agb-pdf-root .banner span{min-width:0}
.agb-pdf-root .prio{display:inline-block;font-size:9px;letter-spacing:.08em;text-transform:uppercase;font-weight:700;padding:2px 6px;border-radius:999px}
.agb-pdf-root .prio.p1{background:#F8E4E1;color:${AGB_ROSE}}.agb-pdf-root .prio.p2{background:#F8EED8;color:${AGB_AMBER}}.agb-pdf-root .prio.p3{background:#E8F6EF;color:${AGB_EMERALD}}
.agb-pdf-root .sign{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:16px}
.agb-pdf-root .sign .box{border-top:1px solid var(--line);padding-top:8px;font-size:11px;color:var(--muted);min-height:52px}
.agb-pdf-root .sign b{display:block;color:var(--ink);margin-top:12px}
`;

function sectionHtml(sec) {
  if (sec.type === "html") return sec.html;
  if (sec.type === "p") return `<div class="sec">${sec.title ? `<h2>${rEsc(sec.title)}</h2>` : ""}${sec.body.map((p) => `<p>${p}</p>`).join("")}</div>`;
  if (sec.type === "callout") return `<div class="callout ${sec.tone || ""}">${sec.title ? `<h3>${rEsc(sec.title)}</h3>` : ""}<p>${sec.body}</p></div>`;
  if (sec.type === "chart") {
    const mark = sec.svg && sec.svg.svg != null ? sec.svg.svg : sec.svg;
    return `<div class="chart"><div class="cap">${rEsc(sec.caption)}</div>${mark}</div>`;
  }
  if (sec.type === "table") {
    const head = sec.headers.map((h) => `<th class="${h.num ? "num" : ""}">${rEsc(h.label)}</th>`).join("");
    const body = sec.rows.map((row) => `<tr>${row.map((c, i) => {
      const num = sec.headers[i] && sec.headers[i].num;
      const cls = [num ? "num" : "", c.cls].filter(Boolean).join(" ");
      return `<td class="${cls}">${c.html != null ? c.html : rEsc(c)}</td>`;
    }).join("")}</tr>`).join("");
    return `<div class="sec">${sec.title ? `<h2>${rEsc(sec.title)}</h2>` : ""}${sec.lead ? `<p>${sec.lead}</p>` : ""}
      <table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>`;
  }
  if (sec.type === "split") return `<div class="grid-2">${sectionHtml(sec.left)}${sectionHtml(sec.right)}</div>`;
  if (sec.type === "notes") return `<div class="notes"><strong>Sources and methods.</strong><ol>${sec.items.map((n) => `<li>${n}</li>`).join("")}</ol></div>`;
  if (sec.type === "recs") {
    const rows = sec.items.map((it) => `<tr>
      <td><span class="prio ${it.p}">${rEsc(it.p.toUpperCase())}</span></td>
      <td>${rEsc(it.action)}</td>
      <td>${rEsc(it.owner)}</td>
      <td>${rEsc(it.when)}</td>
    </tr>`).join("");
    return `<div class="sec"><h2>${rEsc(sec.title || "Recommended actions")}</h2>
      <table><thead><tr><th>Priority</th><th>Action</th><th>Owner</th><th>Window</th></tr></thead><tbody>${rows}</tbody></table></div>`;
  }
  if (sec.type === "sign") {
    return `<div class="sign">${sec.lines.map((l) => `<div class="box">${rEsc(l.role)}<b>${rEsc(l.name)}</b></div>`).join("")}</div>`;
  }
  return "";
}

function renderReport(doc) {
  const kpis = (doc.kpis || []).map((k) => `<div class="kpi"><span>${rEsc(k.label)}</span><b>${rEsc(k.value)}</b>${k.note ? `<em>${rEsc(k.note)}</em>` : ""}</div>`).join("");
  const chips = (doc.chips || []).map((c) => `<span class="chip">${rEsc(c)}</span>`).join("");
  const sections = (doc.sections || []).map(sectionHtml).join("");
  return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>${rEsc(doc.title)} · Agrobotic</title>
<style>${REPORT_CSS}</style></head><body class="agb-pdf-root">
<div class="banner"><span>CONFIDENTIAL · SENSOR-BACKED DEMONSTRATION</span><span>${rEsc(doc.period || "Crop year 2024 / YTD 2025")} · v1.0</span></div>
<header class="cover">
  <div class="cover-top">
    <div class="brand">${SPROUT} AGROBOTIC</div>
    <div class="meta">${rEsc(doc.id)}<br/>Generated ${rEsc(doc.generated)}<br/>agrobotic.io</div>
  </div>
  <div class="kicker">${rEsc(doc.kicker)}</div>
  <h1>${rEsc(doc.title)}</h1>
  <p class="sub">${rEsc(doc.subtitle)}</p>
  <div class="chips">${chips}</div>
</header>
<main class="wrap">
  <div class="kpis">${kpis}</div>
  ${sections}
  <div class="foot">
    <div>Agrobotic confidential. Sensor-backed demonstration pack. Not a statutory filing. Figures trace to NitroSense, EcoSense, AquaSentinel, AirWatch and ForestSentinel nodes unless noted.</div>
    <div>${rEsc(doc.id)}</div>
  </div>
</main>
</body></html>`;
}

function pdfName(doc) {
  return `${(doc.fileStem || doc.id).replace(/[^\w.-]+/g, "-")}.pdf`;
}

function jsPdfCtor() {
  return (window.jspdf && window.jspdf.jsPDF) || window.jsPDF;
}

function pdfRgb(hex) {
  const h = String(hex || "#000000").replace("#", "");
  return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}

function pdfSafe(s) {
  return String(s ?? "")
    .replace(/<[^>]+>/g, "")
    .replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'")
    .replace(/[\u2212\u2010-\u2015]/g, "-")
    .replace(/[‘’]/g, "'")
    .replace(/[“”]/g, "\"")
    .replace(/·/g, " | ")
    .replace(/×/g, "x")
    .replace(/≥/g, ">=").replace(/≤/g, "<=")
    .replace(/°/g, " deg")
    .replace(/µ/g, "u")
    .replace(/[₀]/g, "0").replace(/[₁]/g, "1").replace(/[₂]/g, "2").replace(/[₃]/g, "3").replace(/[₄]/g, "4")
    .replace(/[₅]/g, "5").replace(/[₆]/g, "6").replace(/[₇]/g, "7").replace(/[₈]/g, "8").replace(/[₉]/g, "9")
    .replace(/[⁰]/g, "0").replace(/[¹]/g, "1").replace(/[²]/g, "2").replace(/[³]/g, "3")
    .replace(/[⁻]/g, "-").replace(/[⁺]/g, "+")
    .replace(/[\u00a0\u2000-\u200B\u202F\u205F\u3000]/g, " ")
    .replace(/[^\x20-\x7E]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function cellPlain(c) {
  if (c == null) return "";
  if (typeof c === "object") return pdfSafe(c.html != null ? c.html : c.label != null ? c.label : "");
  return pdfSafe(c);
}

function cellTone(c) {
  const cls = (c && c.cls) || "";
  if (cls.includes("pos")) return AGB_EMERALD;
  if (cls.includes("neg")) return AGB_ROSE;
  return AGB_INK;
}

function buildReportPdf(doc) {
  const JsPDF = jsPdfCtor();
  if (!JsPDF) throw new Error("PDF engine missing");
  const pdf = new JsPDF({ unit: "pt", format: "letter", orientation: "portrait" });
  pdf.setCharSpace(0);
  pdf.setLineHeightFactor(1.2);
  const W = 612;
  const H = 792;
  const M = 48;
  const FOOT = 34;
  const CW = W - M * 2;
  let y = 0;

  const fill = (hex) => pdf.setFillColor(...pdfRgb(hex));
  const stroke = (hex) => pdf.setDrawColor(...pdfRgb(hex));

  function pageBreak() {
    pdf.addPage();
    y = M;
  }
  function need(h) {
    if (y + h > H - FOOT) pageBreak();
  }
  function setType(style, size, color) {
    pdf.setFont("helvetica", style || "normal");
    pdf.setFontSize(size);
    pdf.setCharSpace(0);
    pdf.setTextColor(...pdfRgb(color || AGB_INK));
  }
  function widthOf(str, style, size) {
    pdf.setFont("helvetica", style || "normal");
    pdf.setFontSize(size);
    pdf.setCharSpace(0);
    return pdf.getTextWidth(String(str || ""));
  }
  function wrap(text, maxW, size, style) {
    const st = style || "normal";
    const raw = pdfSafe(text);
    if (!raw) return [];
    const spaceW = Math.max(widthOf(" ", st, size), size * 0.28);
    const words = raw.split(/\s+/).filter(Boolean);
    const out = [];
    let line = "";
    let lineW = 0;
    const push = () => {
      if (line) out.push(line);
      line = "";
      lineW = 0;
    };
    function breakWord(word) {
      let piece = "";
      for (let i = 0; i < word.length; i++) {
        const trial = piece + word[i];
        if (piece && widthOf(trial, st, size) > maxW) {
          out.push(piece);
          piece = word[i];
        } else {
          piece = trial;
        }
      }
      line = piece;
      lineW = widthOf(piece, st, size);
    }
    words.forEach((word) => {
      const ww = widthOf(word, st, size);
      if (!line) {
        if (ww <= maxW) {
          line = word;
          lineW = ww;
        } else breakWord(word);
        return;
      }
      if (lineW + spaceW + ww <= maxW) {
        line += " " + word;
        lineW += spaceW + ww;
      } else {
        push();
        if (ww <= maxW) {
          line = word;
          lineW = ww;
        } else breakWord(word);
      }
    });
    push();
    return out;
  }
  function drawText(str, x, baseline, size, style, color, align) {
    const s = pdfSafe(str);
    if (!s) return;
    setType(style, size, color);
    pdf.text(s, x, baseline, { align: align || "left", charSpace: 0 });
  }
  function drawFitted(str, x, baseline, size, style, color, align, maxW) {
    let s = pdfSafe(str);
    if (!s) return;
    let sz = size;
    while (sz > 6 && widthOf(s, style, sz) > maxW) sz -= 0.5;
    if (widthOf(s, style, sz) > maxW) {
      while (s.length > 1 && widthOf(s + "...", style, sz) > maxW) s = s.slice(0, -1);
      if (s !== pdfSafe(str)) s += "...";
    }
    drawText(s, x, baseline, sz, style, color, align);
  }
  function writeWrap(text, x, maxW, size, style, color, leading) {
    const lh = leading || Math.round(size * 1.5);
    const arr = wrap(text, maxW, size, style);
    arr.forEach((ln) => {
      need(lh + 1);
      drawText(ln, x, y + size, size, style, color, "left");
      y += lh;
    });
    return arr.length;
  }

  setType("bold", 20, "#FFFFFF");
  const titleLines = wrap(doc.title, CW, 20, "bold");
  const subLines = wrap(doc.subtitle, CW, 10, "normal");
  let chipRows = 1;
  let cxm = M;
  (doc.chips || []).forEach((chip) => {
    const tw = widthOf(pdfSafe(chip), "normal", 8) + 14;
    if (cxm + tw > W - M) {
      chipRows += 1;
      cxm = M;
    }
    cxm += tw + 6;
  });
  const coverH = 78 + titleLines.length * 22 + subLines.length * 14 + 12 + chipRows * 18 + 12;
  fill("#0B1C16");
  pdf.rect(0, 0, W, coverH, "F");
  fill(AGB_EMERALD);
  pdf.circle(M + 8, 28, 6, "F");
  fill("#7FC241");
  pdf.circle(M + 14, 22, 4.5, "F");
  drawText("AGROBOTIC", M + 24, 32, 12, "bold", "#E8F6EF");
  drawText(pdfSafe(doc.id), W - M, 22, 8, "normal", "#9FE6CB", "right");
  drawText("Generated " + pdfSafe(doc.generated), W - M, 34, 8, "normal", "#9FE6CB", "right");
  drawText("agrobotic.io", W - M, 46, 8, "normal", "#9FE6CB", "right");
  drawText(pdfSafe(doc.kicker).toUpperCase(), M, 64, 8, "bold", AGB_MINT);
  let ty = 84;
  titleLines.forEach((ln) => {
    drawText(ln, M, ty, 20, "bold", "#FFFFFF");
    ty += 22;
  });
  subLines.forEach((ln) => {
    drawText(ln, M, ty, 10, "normal", "#CFE9DF");
    ty += 14;
  });
  ty += 10;
  let cx = M;
  (doc.chips || []).forEach((chip) => {
    const label = pdfSafe(chip);
    const tw = widthOf(label, "normal", 8) + 14;
    if (cx + tw > W - M) {
      ty += 18;
      cx = M;
    }
    stroke("#9FE6CB");
    pdf.setLineWidth(0.6);
    pdf.roundedRect(cx, ty - 10, tw, 14, 7, 7, "S");
    drawText(label, cx + 7, ty, 8, "normal", "#EAFFF5");
    cx += tw + 6;
  });
  fill(AGB_PAPER);
  pdf.rect(0, coverH, W, 18, "F");
  drawText("CONFIDENTIAL  |  SENSOR-BACKED DEMONSTRATION", M, coverH + 12, 7.5, "normal", AGB_INK);
  drawText(pdfSafe(doc.period || "Crop year 2024 / YTD 2025") + "  |  v1.0", W - M, coverH + 12, 7.5, "normal", AGB_INK, "right");
  y = coverH + 32;

  const kpis = doc.kpis || [];
  if (kpis.length) {
    const cols = Math.min(4, kpis.length);
    const gap = 10;
    const boxW = (CW - gap * (cols - 1)) / cols;
    const boxH = 60;
    const rowsN = Math.ceil(kpis.length / cols);
    need(rowsN * (boxH + gap) + 4);
    kpis.forEach((k, i) => {
      const bx = M + (i % cols) * (boxW + gap);
      const by = y + Math.floor(i / cols) * (boxH + gap);
      fill(AGB_PAPER);
      stroke("#D5DDD4");
      pdf.setLineWidth(0.5);
      pdf.roundedRect(bx, by, boxW, boxH, 4, 4, "FD");
      const inner = boxW - 16;
      drawFitted(pdfSafe(k.label).toUpperCase(), bx + 8, by + 14, 6.5, "bold", AGB_MUTED, "left", inner);
      drawFitted(pdfSafe(k.value), bx + 8, by + 36, 13, "bold", AGB_INK, "left", inner);
      if (k.note) {
        const note = wrap(k.note, inner, 7, "normal")[0] || "";
        drawFitted(note, bx + 8, by + 50, 7, "normal", AGB_MUTED, "left", inner);
      }
    });
    y += rowsN * (boxH + gap) + 8;
  }

  function heading(text) {
    const linesH = wrap(text, CW, 12, "bold");
    need(linesH.length * 16 + 40);
    linesH.forEach((ln) => {
      need(16);
      drawText(ln, M, y + 12, 12, "bold", AGB_INK);
      y += 16;
    });
    y += 4;
  }

  function para(text, size) {
    const fs = size || 10;
    writeWrap(text, M, CW, fs, "normal", AGB_INK, Math.round(fs * 1.55));
    y += 8;
  }

  function drawChart(spec, caption) {
    const kind = spec && spec.kind;
    const capH = caption ? 18 : 0;
    const plotH = kind === "donut" ? 78 : 110;
    const h = capH + plotH + 10;
    need(h);
    if (caption) {
      drawFitted(pdfSafe(caption).toUpperCase(), M, y + 12, 8, "bold", AGB_MUTED, "left", CW);
      y += capH;
    }
    fill("#FFFFFF");
    stroke("#D5DDD4");
    pdf.setLineWidth(0.5);
    pdf.roundedRect(M, y, CW, plotH, 4, 4, "S");
    const innerY = y;
    if (kind === "bar") {
      const items = spec.items || [];
      const n = Math.max(items.length, 1);
      const top = 20;
      const bottom = 24;
      const plot = plotH - top - bottom;
      const max = Math.max(...items.map((i) => Math.abs(Number(i.value) || 0)), 1);
      const gap = CW / n;
      const bw = Math.min(gap * 0.48, 52);
      items.forEach((it, i) => {
        const val = Number(it.value) || 0;
        const bh = Math.max(2, (Math.abs(val) / max) * plot);
        const bx = M + i * gap + (gap - bw) / 2;
        fill(it.color || AGB_EMERALD);
        pdf.roundedRect(bx, innerY + top + plot - bh, bw, bh, 2, 2, "F");
        const lab = spec.opts && spec.opts.fmt ? spec.opts.fmt(val) : rNum(val);
        drawFitted(pdfSafe(lab), bx + bw / 2, innerY + top + plot - bh - 5, 7, "bold", AGB_INK, "center", gap - 6);
        drawFitted(pdfSafe(it.label), bx + bw / 2, innerY + top + plot + 16, 7, "normal", AGB_MUTED, "center", gap - 6);
      });
    } else if (kind === "line") {
      const values = spec.values || [];
      if (values.length) {
        const min = Math.min(...values);
        const max = Math.max(...values);
        const span = (max - min) || 1;
        const padL = 12, padR = 12, padT = 12, padB = 24;
        const plotW = CW - padL - padR;
        const pH = plotH - padT - padB;
        const pts = values.map((v, i) => {
          const px = M + padL + (i / Math.max(1, values.length - 1)) * plotW;
          const py = innerY + padT + (1 - (v - min) / span) * pH;
          return [px, py];
        });
        stroke(spec.opts && spec.opts.color ? spec.opts.color : AGB_EMERALD);
        pdf.setLineWidth(1.5);
        for (let i = 1; i < pts.length; i++) pdf.line(pts[i - 1][0], pts[i - 1][1], pts[i][0], pts[i][1]);
        const labels = (spec.opts && spec.opts.labels) || [];
        const step = labels.length > 8 ? 2 : 1;
        labels.forEach((lb, i) => {
          if (!lb || i % step) return;
          const px = M + padL + (i / Math.max(1, values.length - 1)) * plotW;
          drawFitted(pdfSafe(lb), px, innerY + plotH - 8, 7, "normal", AGB_MUTED, "center", 40);
        });
      }
    } else if (kind === "donut") {
      const items = spec.items || [];
      const total = items.reduce((s, i) => s + i.value, 0) || 1;
      let x0 = M + 10;
      const barY = innerY + 12;
      const barW = CW - 20;
      items.forEach((it) => {
        const wi = Math.max(3, (it.value / total) * barW);
        fill(it.color || AGB_EMERALD);
        pdf.rect(x0, barY, wi, 11, "F");
        x0 += wi;
      });
      let ly = barY + 24;
      items.forEach((it) => {
        fill(it.color || AGB_EMERALD);
        pdf.rect(M + 12, ly, 8, 8, "F");
        const pct = it.display || rPct(it.value / total, 0);
        drawFitted(pdfSafe(it.label), M + 26, ly + 7, 8, "normal", AGB_INK, "left", CW * 0.62);
        drawFitted(pdfSafe(pct), M + CW - 12, ly + 7, 8, "bold", AGB_INK, "right", 90);
        ly += 14;
      });
    }
    y += plotH + 12;
  }

  function colWidths(headers, width) {
    const n = headers.length || 1;
    const numN = headers.filter((h) => h.num).length;
    const textN = n - numN;
    if (!textN) return headers.map(() => width / n);
    const minNum = 56;
    const minText = 68;
    const nums = numN * minNum;
    const texts = textN * minText;
    if (nums + texts > width) {
      const scale = width / (nums + texts);
      return headers.map((h) => (h.num ? minNum : minText) * scale);
    }
    const add = (width - nums - texts) / textN;
    return headers.map((h) => (h.num ? minNum : minText + add));
  }

  function drawTable(sec) {
    if (sec.title) heading(sec.title);
    if (sec.lead) para(sec.lead, 9);
    const headers = sec.headers || [];
    const rows = sec.rows || [];
    const widths = colWidths(headers, CW);
    const fs = 8;
    const lh = 11;

    function wrapCell(text, i, header) {
      const raw = pdfSafe(text);
      const st = header ? "bold" : "normal";
      const maxW = Math.max(widths[i] - 10, 18);
      const isNum = headers[i] && headers[i].num;
      if (!raw) return [""];
      if (isNum || widthOf(raw, st, fs) <= maxW) return [raw];
      return wrap(raw, maxW, fs, st);
    }
    function rowH(cells, header) {
      const wrapped = cells.map((c, i) => wrapCell(header ? headers[i].label : cellPlain(c), i, header));
      return Math.max(18, ...wrapped.map((w) => w.length * lh)) + 6;
    }
    function paint(cells, header) {
      const wrapped = cells.map((c, i) => wrapCell(header ? headers[i].label : cellPlain(c), i, header));
      const rh = Math.max(18, ...wrapped.map((w) => w.length * lh)) + 6;
      need(rh);
      if (header) {
        fill(AGB_PAPER);
        pdf.rect(M, y, CW, rh, "F");
      }
      let x = M;
      wrapped.forEach((wlines, i) => {
        const num = headers[i] && headers[i].num;
        const color = header ? AGB_MUTED : cellTone(cells[i]);
        wlines.forEach((ln, li) => {
          const tx = num ? x + widths[i] - 5 : x + 5;
          drawFitted(ln, tx, y + 13 + li * lh, fs, header ? "bold" : "normal", color, num ? "right" : "left", widths[i] - 10);
        });
        x += widths[i];
      });
      stroke("#E2E8E0");
      pdf.setLineWidth(0.4);
      pdf.line(M, y + rh, M + CW, y + rh);
      y += rh;
    }
    need(rowH(headers.map((h) => h.label), true) + 12);
    paint(headers.map((h) => h.label), true);
    rows.forEach((row) => {
      if (y + rowH(row, false) > H - FOOT) {
        pageBreak();
        paint(headers.map((h) => h.label), true);
      }
      paint(row, false);
    });
    y += 12;
  }

  function drawCallout(sec) {
    const bodyLines = wrap(sec.body, CW - 24, 9, "normal");
    const titleH = sec.title ? 16 : 0;
    const h = 16 + titleH + bodyLines.length * 14 + 10;
    need(Math.min(h, 90));
    if (y + 24 > H - FOOT) pageBreak();
    if (y + h > H - FOOT) {
      // split onto this page as much as possible by just page-breaking first
      pageBreak();
    }
    fill(AGB_PAPER);
    pdf.rect(M, y, CW, h, "F");
    fill(AGB_EMERALD);
    pdf.rect(M, y, 4, h, "F");
    let cy = y + 16;
    if (sec.title) {
      drawText(pdfSafe(sec.title), M + 14, cy, 9, "bold", AGB_INK);
      cy += 16;
    }
    bodyLines.forEach((ln) => {
      drawText(ln, M + 14, cy, 9, "normal", "#243830");
      cy += 14;
    });
    y += h + 12;
  }

  function drawSign(sec) {
    need(54);
    const cols = (sec.lines || []).length || 1;
    const sw = CW / cols;
    (sec.lines || []).forEach((l, i) => {
      const x = M + i * sw;
      stroke("#D5DDD4");
      pdf.setLineWidth(0.6);
      pdf.line(x, y, x + sw - 16, y);
      drawFitted(pdfSafe(l.role), x, y + 14, 8, "normal", AGB_MUTED, "left", sw - 18);
      drawFitted(pdfSafe(l.name), x, y + 32, 10, "bold", AGB_INK, "left", sw - 18);
    });
    y += 50;
  }

  function drawSection(sec) {
    if (!sec) return;
    if (sec.type === "p") {
      if (sec.title) heading(sec.title);
      (sec.body || []).forEach((p) => para(p, 10));
    } else if (sec.type === "callout") {
      drawCallout(sec);
    } else if (sec.type === "chart") {
      drawChart(sec.svg, sec.caption);
    } else if (sec.type === "table") {
      drawTable(sec);
    } else if (sec.type === "split") {
      drawSection(sec.left);
      drawSection(sec.right);
    } else if (sec.type === "recs") {
      drawTable({
        title: sec.title || "Recommended actions",
        headers: [{ label: "Priority" }, { label: "Action" }, { label: "Owner" }, { label: "Window" }],
        rows: (sec.items || []).map((it) => [String(it.p || "").toUpperCase(), it.action, it.owner, it.when]),
      });
    } else if (sec.type === "sign") {
      drawSign(sec);
    } else if (sec.type === "notes") {
      heading("Sources and methods");
      (sec.items || []).forEach((n, i) => {
        writeWrap((i + 1) + ". " + n, M, CW, 9, "normal", AGB_INK, 13);
        y += 5;
      });
    }
  }

  (doc.sections || []).forEach(drawSection);

  need(40);
  stroke("#D5DDD4");
  pdf.setLineWidth(0.5);
  pdf.line(M, y, M + CW, y);
  y += 14;
  writeWrap("Agrobotic confidential. Sensor-backed demonstration pack. Not a statutory filing. Figures trace to NitroSense, EcoSense, AquaSentinel, AirWatch and ForestSentinel nodes unless noted.", M, CW, 8, "normal", AGB_MUTED, 12);

  const pages = pdf.internal.getNumberOfPages();
  for (let i = 1; i <= pages; i++) {
    pdf.setPage(i);
    drawText(pdfSafe(doc.id), M, H - 24, 8, "normal", AGB_MUTED);
    drawText("Page " + i + " of " + pages, W - M, H - 24, 8, "normal", AGB_MUTED, "right");
  }

  const blob = pdf.output("blob");
  if (!blob || !blob.size) throw new Error("Empty PDF");
  return blob;
}

function showReportOverlay(pdfUrl, name, onDownload) {
  const prev = document.getElementById("agb-report-overlay");
  if (prev) prev.remove();
  const wrap = document.createElement("div");
  wrap.id = "agb-report-overlay";
  wrap.setAttribute("role", "dialog");
  wrap.setAttribute("aria-label", name);
  wrap.style.cssText = "position:fixed;inset:0;z-index:5000;background:#07140f;display:flex;flex-direction:column;";
  const bar = document.createElement("div");
  bar.style.cssText = "display:flex;justify-content:space-between;align-items:center;gap:12px;padding:10px 16px;background:#0B1C16;color:#eafff5;font:600 13px Helvetica,Arial,sans-serif;flex-shrink:0;";
  bar.innerHTML = `<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${rEsc(name)}</span>
    <span style="display:flex;gap:8px;flex-shrink:0">
      <button type="button" id="agb-rpt-pdf" style="font:600 12px Helvetica,Arial,sans-serif;padding:7px 12px;border-radius:999px;border:0;background:#13935F;color:#fff;cursor:pointer">Download PDF</button>
      <button type="button" id="agb-rpt-close" style="font:600 12px Helvetica,Arial,sans-serif;padding:7px 12px;border-radius:999px;border:1px solid rgba(232,246,239,.25);background:transparent;color:#eafff5;cursor:pointer">Close</button>
    </span>`;
  const frame = document.createElement("iframe");
  frame.title = name;
  frame.style.cssText = "flex:1;border:0;background:#fff;width:100%";
  frame.src = pdfUrl;
  wrap.appendChild(bar);
  wrap.appendChild(frame);
  document.body.appendChild(wrap);
  const close = () => {
    wrap.remove();
    document.removeEventListener("keydown", onKey);
    try { URL.revokeObjectURL(pdfUrl); } catch (e) { /* ignore */ }
  };
  const onKey = (e) => { if (e.key === "Escape") close(); };
  document.addEventListener("keydown", onKey);
  bar.querySelector("#agb-rpt-close").onclick = close;
  const pdfBtn = bar.querySelector("#agb-rpt-pdf");
  let busy = false;
  const run = async () => {
    if (busy) return;
    busy = true;
    pdfBtn.textContent = "Building PDF…";
    pdfBtn.disabled = true;
    try { await onDownload(); }
    finally {
      busy = false;
      pdfBtn.textContent = "Download PDF";
      pdfBtn.disabled = false;
    }
  };
  pdfBtn.onclick = run;
  return run;
}

async function openReport(doc) {
  const name = pdfName(doc);
  try {
    const blob = buildReportPdf(doc);
    const url = URL.createObjectURL(blob);
    const save = async () => {
      try {
        downloadBlob(name, blob);
        AGB_UI.toast(`Downloaded PDF · ${name}`, { type: "ok" });
      } catch (err) {
        console.error(err);
        AGB_UI.toast("Could not download PDF. Try Download PDF again.", { type: "bad" });
      }
    };
    showReportOverlay(url, name, save);
  } catch (err) {
    console.error(err);
    AGB_UI.toast("Could not build PDF.", { type: "bad" });
  }
}

function d() { return window.AGB_DATA; }

function ghgScenario(opts = {}) {
  const { REGIONS, CROPS, GHG, FARMS } = d();
  const region = opts.region || "ON";
  const crop = opts.crop || "corn";
  const acres = opts.acres != null ? opts.acres : 1500;
  const n_rate = opts.n_rate != null ? opts.n_rate : 180;
  const carbon_price = opts.carbon_price != null ? opts.carbon_price : 28;
  const adoption = opts.adoption != null ? opts.adoption : 0.6;
  const r = REGIONS.find((x) => x.id === region) || REGIONS[1];
  const c = CROPS.find((x) => x.id === crop) || CROPS[0];
  const total_n_lb = acres * n_rate;
  const baseline_n2o_kg = total_n_lb * GHG.n2o_factor_per_lb_n;
  const baseline_co2e_t = (baseline_n2o_kg * GHG.n2o_gwp) / 1000;
  const reduced_co2e_t = baseline_co2e_t * (1 - adoption * 0.4);
  const avoided_co2e_t = baseline_co2e_t - reduced_co2e_t;
  const tax_liability = reduced_co2e_t * carbon_price * r.tax_rate * 100;
  const baseline_tax = baseline_co2e_t * carbon_price * r.tax_rate * 100;
  const credit_value = avoided_co2e_t * carbon_price;
  const net = credit_value - tax_liability;
  const farms = FARMS.map((f) => {
    const n_f = f.acres * n_rate;
    const base_t = (n_f * GHG.n2o_factor_per_lb_n * GHG.n2o_gwp) / 1000;
    const red_t = base_t * (1 - adoption * 0.4);
    const av_t = base_t - red_t;
    const tax_f = red_t * carbon_price * ((REGIONS.find((x) => x.id === f.region) || r).tax_rate) * 100;
    const credit_f = av_t * carbon_price;
    return { ...f, base_t, red_t, av_t, tax_f, credit_f, net_f: credit_f - tax_f, intensity: base_t / f.acres };
  });
  return { r, c, acres, n_rate, carbon_price, adoption, GHG, total_n_lb, baseline_n2o_kg, baseline_co2e_t, reduced_co2e_t, avoided_co2e_t, tax_liability, baseline_tax, credit_value, net, farms };
}

function loans() {
  return d().FARMS.slice(0, 6).map((f, i) => {
    const principal = Math.round(f.revenue_usd * 0.3);
    const rate = 4.2 + i * 0.3;
    const term = 5 + i;
    const score = 92 - i * 4;
    const debtService = principal * (rate / 100 + 1 / term);
    const dscr = f.revenue_usd / debtService;
    return { ...f, principal, rate, term, score, dscr, band: score >= 88 ? "A" : score >= 80 ? "B" : score >= 72 ? "C" : "D", status: i < 4 ? "Active" : i === 4 ? "Pending" : "Approved" };
  });
}
function policies() {
  return d().FARMS.slice(0, 6).map((f, i) => ({
    ...f,
    premium: Math.round(f.revenue_usd * (0.045 - f.health / 1000)),
    coverage: f.revenue_usd * 1.4,
    perils: ["Yield loss", "Hail", "Drought", "Fire", "Frost"].slice(0, 2 + (i % 3)),
    risk: f.alerts > 2 ? "High" : f.alerts > 0 ? "Medium" : "Low",
    discount: Math.min(0.18, f.health * 0.002),
  }));
}

function reportGhg(opts) {
  const s = ghgScenario(opts);
  const fedPrices = [
    { y: "Voluntary (this run)", p: s.carbon_price },
    { y: "Canada 2024 fuel charge", p: 80 },
    { y: "Canada 2025 fuel charge", p: 95 },
    { y: "Canada 2026 fuel charge", p: 110 },
  ].map((row) => {
    const tax = s.reduced_co2e_t * row.p * s.r.tax_rate * 100;
    const cred = s.avoided_co2e_t * row.p;
    return { ...row, tax, cred, net: cred - tax };
  });
  const id = rDocId("GHG", JSON.stringify(s.baseline_co2e_t + s.acres + s.n_rate));
  openReport({
    id, fileStem: "agrobotic-ghg-tax-memo", generated: rNow(), period: "Crop year 2024 / planning 2025",
    kicker: "Fintech · GHG tax memorandum",
    title: "Nitrous oxide tax exposure and mitigation memo",
    subtitle: `${s.r.name} ${s.c.name} at ${rNum(s.acres)} acres. Converts fertilizer-induced N₂O into CO₂e, regional tax, and credit value using live NitroSense behaviour.`,
    chips: [s.r.name, s.c.name, `${rNum(s.acres)} ac`, `N rate ${s.n_rate} lb/ac`, `GWP-100 N₂O ${s.GHG.n2o_gwp}`, "IPCC AR5 / GHGRP 2024-25"],
    kpis: [
      { label: "Baseline emissions", value: rNum(s.baseline_co2e_t, 0) + " t", note: "tCO₂e / year" },
      { label: "With NitroSense", value: rNum(s.reduced_co2e_t, 0) + " t", note: rPct(s.adoption, 0) + " adoption · up to 40% cut" },
      { label: "Tax after abatement", value: rMoney(s.tax_liability), note: "vs " + rMoney(s.baseline_tax) + " baseline" },
      { label: "Net (credits − tax)", value: rMoney(s.net), note: s.net >= 0 ? "Net benefit" : "Net cost" },
    ],
    sections: [
      { type: "p", title: "Executive finding", body: [
        `At a ${rMoney(s.carbon_price, 0)}/tCO₂e shadow price and ${rPct(s.r.tax_rate, 2)} regional application factor, this ${s.c.name.toLowerCase()} block emits <strong>${rNum(s.baseline_co2e_t, 0)} tCO₂e</strong> from fertilizer-induced N₂O before Agrobotic controls. NitroSense adoption of ${rPct(s.adoption, 0)} is modelled to avoid <strong>${rNum(s.avoided_co2e_t, 0)} tCO₂e</strong>, worth <strong>${rMoney(s.credit_value)}</strong> if those tonnes clear a registry, and to cut tax from ${rMoney(s.baseline_tax)} to ${rMoney(s.tax_liability)}.`,
        `Intensity is <strong>${(s.baseline_co2e_t / s.acres).toFixed(3)} tCO₂e per acre</strong> at ${s.n_rate} lb N/ac. Every 10 lb/ac of avoided over-application saves about ${rNum((10 * s.acres * s.GHG.n2o_factor_per_lb_n * s.GHG.n2o_gwp) / 1000, 1)} tCO₂e on this acreage, which is the 4R rate lever the sensors are built to pull.`,
      ]},
      { type: "chart", caption: "Annual N₂O inventory, tCO₂e", svg: chartBar([
        { label: "Baseline", value: s.baseline_co2e_t, color: AGB_ROSE },
        { label: "With sensors", value: s.reduced_co2e_t, color: AGB_CYAN },
        { label: "Avoided", value: s.avoided_co2e_t, color: AGB_EMERALD },
      ], { fmt: (v) => rNum(v, 0) }) },
      { type: "split",
        left: { type: "table", title: "Inventory build-up", headers: [{ label: "Line" }, { label: "Quantity", num: true }, { label: "Unit" }], rows: [
          ["Nitrogen applied", { html: rNum(s.total_n_lb, 0), cls: "num" }, "lb N"],
          ["Emission factor", { html: String(s.GHG.n2o_factor_per_lb_n), cls: "num" }, "kg N₂O / lb N"],
          ["N₂O mass", { html: rNum(s.baseline_n2o_kg, 0), cls: "num" }, "kg N₂O"],
          ["AR5 GWP-100", { html: String(s.GHG.n2o_gwp), cls: "num" }, "tCO₂e / t N₂O"],
          ["Baseline CO₂e", { html: rNum(s.baseline_co2e_t, 1), cls: "num" }, "tCO₂e"],
          ["Abatement (model)", { html: rPct(s.adoption * 0.4, 0), cls: "num" }, "of baseline"],
        ] },
        right: { type: "callout", title: "How to read the tax line", body: `Tax = remaining tCO₂e × carbon price × regional factor (${rPct(s.r.tax_rate, 2)} for ${s.r.name}). This is a planning shadow aligned to GHGRP / OBPS logic, not the federal fuel charge invoice. Credit value assumes avoided tonnes are additional, measurable, and issued. Canada fuel-charge path ($80 in 2024, $95 in 2025, $110 in 2026) is shown as sensitivity.` } },
      { type: "table", title: "Carbon-price sensitivity", lead: "Same physical inventory, four prices. Voluntary market vs federal fuel-charge schedule.",
        headers: [{ label: "Price path" }, { label: "$/t", num: true }, { label: "Tax", num: true }, { label: "Credit value", num: true }, { label: "Net", num: true }],
        rows: fedPrices.map((row) => [row.y, { html: rMoney(row.p, 0), cls: "num" }, { html: rMoney(row.tax), cls: "num" }, { html: rMoney(row.cred), cls: "num pos" }, { html: rMoney(row.net), cls: "num " + (row.net >= 0 ? "pos" : "neg") }]) },
      { type: "table", title: "Portfolio farms at this N rate",
        headers: [{ label: "Farm" }, { label: "Region" }, { label: "Acres", num: true }, { label: "Baseline t", num: true }, { label: "Projected t", num: true }, { label: "Tax", num: true }, { label: "Credits", num: true }, { label: "Net", num: true }],
        rows: s.farms.map((f) => [f.name, f.region, { html: rNum(f.acres), cls: "num" }, { html: rNum(f.base_t, 0), cls: "num" }, { html: rNum(f.red_t, 0), cls: "num" }, { html: rMoney(f.tax_f), cls: "num" }, { html: rMoney(f.credit_f), cls: "num pos" }, { html: rMoney(f.net_f), cls: "num " + (f.net_f >= 0 ? "pos" : "neg") }]) },
      { type: "chart", caption: "Monitored N₂O flux index (rolling crop year, NitroSense)", svg: chartLine(rTrend(s.baseline_co2e_t / 12, s.baseline_co2e_t / 40, -s.avoided_co2e_t / 48, 11), { labels: rMonths(), color: AGB_ROSE }) },
      { type: "recs", title: "Actions for tax provisioning", items: [
        { p: "p1", action: "Lock 4R rate/time on the two highest-intensity farms before sidedress. NitroSense NO₃⁻ + VWC is the trigger, not calendar week.", owner: "Agronomy", when: "This sidedress window" },
        { p: "p1", action: `Re-run this memo at the 2025 federal ${rMoney(95)}/t path before year-end tax provisioning.`, owner: "CFO / tax", when: "Q4 close" },
        { p: "p2", action: "Treat avoided N₂O as a monitored parameter for a Verra / Gold Standard / ECCC-pilot issuance pack. Do not book it as an automatic tax credit.", owner: "Carbon desk", when: "This vintage" },
        { p: "p3", action: "Keep GHGRP activity data (N applied, EF, GWP 265) in the same evidence folder as this memo.", owner: "MRV", when: "Ongoing" },
      ]},
      { type: "sign", lines: [
        { role: "Prepared by", name: "Agrobotic Climate Desk" },
        { role: "Reviewed by", name: "CFO, Agrobotic Fintech" },
        { role: "Distribution", name: "Tax · carbon · farm ops" },
      ]},
      { type: "notes", items: [
        "IPCC Fifth Assessment Report GWP-100: N₂O = 265, CH₄ = 28. These are the values ECCC GHGRP has applied from 2022 data onward (Canada Gazette notice for 2024 and 2025 reporting).",
        "Fertilizer-induced N₂O uses the dashboard factor 0.0146 kg N₂O per lb N applied (IPCC-aligned). Canada’s national inventory uses a Tier II eco-district factor that rises with precipitation/PET (Rochette et al.; AAFC Agri-Environmental Indicators).",
        "OBPS Quantification Guidance (updated February 2025): where no listed method applies, use GHGRP 2024/2025, then WCI, then IPCC Guidelines.",
        "Abatement of up to 40% at full NitroSense adoption is an Agrobotic planning factor (precision N + denitrification alerts), not a default IPCC EF change. Actual issuance requires a methodology, baseline, and verification.",
        `Telemetry: NitroSense NO₃⁻, gaseous and dissolved N₂O, VWC, soil temperature. Document ${id}.`,
      ]},
    ],
  });
}

function reportCarbon() {
  const { CARBON_MARKET, FARMS, KPIS } = d();
  const tons = CARBON_MARKET.reduce((s, m) => s + m.tons_avail, 0);
  const vw = CARBON_MARKET.reduce((s, m) => s + m.price * m.tons_avail, 0) / tons;
  const vol = CARBON_MARKET.reduce((s, m) => s + m.vol, 0);
  const byStd = {};
  CARBON_MARKET.forEach((m) => { byStd[m.standard] = (byStd[m.standard] || 0) + m.tons_avail; });
  const colors = [AGB_EMERALD, AGB_CYAN, AGB_AMBER, AGB_VIOLET, AGB_ROSE];
  const id = rDocId("VCS", tons + vw);
  const trail = [
    ["2025-03-18 14:22", "VCS-1142 verification opinion issued", "Verra VVB", "2,400 t"],
    ["2025-03-15 09:10", "EcoSense signed data bundle", "Agrobotic node", "Riverside Dairy"],
    ["2025-03-12 16:48", "GS-7821 listed on order book", "I. El-Chami", "4,100 t"],
    ["2025-03-02 11:03", "NitroSense N₂O flux hash anchored", "Agrobotic", "Prairie N₂O"],
    ["2025-02-19 08:41", "Calibration certificate renewed", "NIST-traceable lab", "EcoSense CH₄"],
  ];
  openReport({
    id, fileStem: "agrobotic-carbon-monitoring-pack", generated: rNow(), period: "Monitoring period 1 Nov 2024 – 31 Oct 2025",
    kicker: "Fintech · Carbon monitoring pack  ·  VCS-style",
    title: "Sensor-backed carbon issuance and monitoring report",
    subtitle: "Project implementation status, monitored parameters, and calculated reductions for the current vintage. Structured after Verra VCS Monitoring Report v5 (implementation, data, quantified reductions) plus an order-book annex.",
    chips: ["Verra VCS v5", "Gold Standard", "ACR", "ECCC Pilot", "Vintage 2024–2025", "MRV: edge-signed"],
    kpis: [
      { label: "Available to issue / sell", value: rNum(tons) + " t", note: "tCO₂e across 5 listings" },
      { label: "Volume-weighted ask", value: rMoney(vw, 2), note: "per tCO₂e" },
      { label: "24h traded volume", value: rNum(vol) + " t", note: "all listings" },
      { label: "Realized YTD", value: rMoney(KPIS.fintech.carbon_revenue_usd), note: "settled sales" },
    ],
    sections: [
      { type: "p", title: "1. Project implementation status", body: [
        "Activity is operational on eight Agrobotic farms. N₂O avoidance (NitroSense / 4R) and dairy CH₄ (EcoSense) are in monitoring. ForestSentinel smoke-avoidance and California soil-carbon remain in first verification. No loss event has been recorded this period.",
        "Each tonne in this pack is tied to a signed node bundle (time, lat/long, parameter, model version). That is the evidence pack a validation/verification body would sample, analogous to VCS monitored data and parameters.",
      ]},
      { type: "split",
        left: { type: "chart", caption: "Registry mix of available tonnes", svg: chartDonut(Object.entries(byStd).map(([label, value], i) => ({ label, value, color: colors[i % colors.length] }))) },
        right: { type: "callout", title: "Integrity tests this period", body: "Additionality: fertilizer and manure practice change vs 3-year baseline. Leakage: no evidence of N shifting to unmonitored fields (all listed farms have live NO₃⁻). Permanence: N₂O/CH₄ avoidance is vintage-year, not buffer-pooled soil carbon except ACR-3320 (20% buffer held)." } },
      { type: "table", title: "2. Listings and monitored parameters",
        headers: [{ label: "ID" }, { label: "Name" }, { label: "Standard" }, { label: "Source" }, { label: "Vintage" }, { label: "Ask", num: true }, { label: "Avail. t", num: true }, { label: "24h %", num: true }],
        rows: CARBON_MARKET.map((m) => [m.id, m.name, m.standard, m.source, String(m.vintage), { html: rMoney(m.price, 2), cls: "num" }, { html: rNum(m.tons_avail), cls: "num" }, { html: (m.change >= 0 ? "+" : "") + m.change.toFixed(1) + "%", cls: "num " + (m.change >= 0 ? "pos" : "neg") }]) },
      { type: "chart", caption: "Available tonnes by listing", svg: chartBar(CARBON_MARKET.map((m, i) => ({ label: m.id, value: m.tons_avail, color: colors[i % colors.length] })), { fmt: (v) => rNum(v) }) },
      { type: "table", title: "3. Audit trail (immutable events)",
        headers: [{ label: "Timestamp" }, { label: "Event" }, { label: "Actor" }, { label: "Detail", num: true }],
        rows: trail.map((r) => [r[0], r[1], r[2], { html: r[3], cls: "num" }]) },
      { type: "chart", caption: "Issuance pipeline (tCO₂e, crop-year months)", svg: chartLine(rTrend(vol / 14, vol / 18, 40, 22), { labels: rMonths(), color: AGB_EMERALD }) },
      { type: "p", title: "4. Quantification sketch", body: [
        `Prairie N₂O (GS-7821): avoided N₂O = (baseline EF × N applied − monitored flux) × 265 / 1000. Current available 4,100 t at ${rMoney(34.10, 2)}/t.`,
        "BC Dairy CH₄ (VCS-1142): enteric + manure NDIR, barn-ventilated, GWP-100 CH₄ = 28. 2,400 t verified 18 Mar 2025.",
        "Do not double count tonnes that also reduce a GHG-tax shadow in the tax memo. Issuance is the market instrument; tax is the policy instrument.",
      ]},
      { type: "recs", title: "Issuance actions", items: [
        { p: "p1", action: "Advance ACR-3320 (California soil carbon) through first verification; 20% buffer remains held.", owner: "VVB liaison", when: "This quarter" },
        { p: "p2", action: "Re-hash Prairie N₂O flux bundles before GS-7821 vintage close so the evidence pack matches the order book.", owner: "MRV", when: "Vintage close" },
        { p: "p3", action: "Keep tax-memo avoided tonnes and listed credits in separate ledgers.", owner: "Carbon desk", when: "Ongoing" },
      ]},
      { type: "sign", lines: [
        { role: "Monitoring report author", name: "Agrobotic MRV" },
        { role: "Project proponent", name: "Agrobotic Fintech" },
        { role: "Next VVB sample", name: "VCS-1142 surveillance" },
      ]},
      { type: "notes", items: [
        "Verra VCS Monitoring Report (v5.0A/B, 2026 templates): report implementation status, all monitored data/parameters, and calculated reductions for the period, then verify before issuance.",
        "Gold Standard and ACR listings follow their own MRV templates; this pack is a unified investor/operator view, not a substitute for registry PDDs.",
        "GWP-100 AR5: CH₄ 28, N₂O 265 (GHG Protocol / IPCC AR5; ECCC GHGRP from 2022).",
        "Contributing farms: " + FARMS.map((f) => f.name).join(", ") + ".",
      ]},
    ],
  });
}

function reportWater() {
  const { FARMS, REGIONS } = d();
  const costs = FARMS.map((f, i) => {
    const region = REGIONS.find((r) => r.id === f.region);
    const water = 180 + (i * 23) % 80 + (f.region === "CA" ? 60 : 0);
    const fert = 420 + (i * 31) % 90;
    const fuel = 95 + (i * 11) % 40;
    const labor = 510 + (i * 17) % 70;
    return { ...f, water, fert, fuel, labor, total: water + fert + fuel + labor, water_m3: region.water_usd_m3, irrigated: region.irrigation };
  });
  const tot = costs.reduce((s, f) => ({ water: s.water + f.water * f.acres, fert: s.fert + f.fert * f.acres, fuel: s.fuel + f.fuel * f.acres, labor: s.labor + f.labor * f.acres }), { water: 0, fert: 0, fuel: 0, labor: 0 });
  const mean = costs.reduce((s, f) => s + f.total, 0) / costs.length;
  const id = rDocId("H2O", mean);
  openReport({
    id, fileStem: "agrobotic-water-input-cost-report", generated: rNow(), period: "YTD crop year 2025",
    kicker: "Fintech · Water and input intelligence",
    title: "Water and input cost report",
    subtitle: "Per-acre water, fertilizer, fuel and labor, tied to AquaSentinel and NitroSense consumption rather than invoices alone. Peer-benchmarked by region.",
    chips: ["YTD crop year", "AquaSentinel", "NitroSense 4R", "8 farms"],
    kpis: [
      { label: "Water YTD", value: rMoney(418000), note: "−6.2% vs last year" },
      { label: "Fertilizer YTD", value: rMoney(1240000), note: "−12.4% after 4R" },
      { label: "Fuel YTD", value: rMoney(284000), note: "+2.1%" },
      { label: "Labor YTD", value: rMoney(1450000), note: "+5.4%" },
    ],
    sections: [
      { type: "p", title: "What moved", body: [
        `Fertilizer is the largest controllable line and the one NitroSense is reducing: 12.4% below last year on the same acres, consistent with an ~18% N-rate save on adopting fields. Water spend is down 6.2% even though California units still pay ${rMoney(0.082, 3)}/m³, about 4× Ontario.`,
        `Mean total input cost is <strong>${rMoney(mean, 0)}/ac</strong>. Farms more than 15% above that mean (Vernon Orchard, Riverside Dairy) are the first 4R and irrigation-scheduling reviews.`,
      ]},
      { type: "chart", caption: "YTD spend mix", svg: chartDonut([
        { label: "Labor", value: 1450000, color: AGB_VIOLET, unit: "$" },
        { label: "Fertilizer", value: 1240000, color: AGB_EMERALD, unit: "$" },
        { label: "Water", value: 418000, color: AGB_CYAN, unit: "$" },
        { label: "Fuel", value: 284000, color: AGB_AMBER, unit: "$" },
      ]) },
      { type: "chart", caption: "Total input $/acre by farm", svg: chartBar(costs.map((f) => ({ label: f.name.split(" ")[0], value: f.total, color: f.total > mean * 1.1 ? AGB_ROSE : AGB_CYAN })), { fmt: (v) => rMoney(v, 0) }) },
      { type: "table", title: "Farm-level unit costs",
        headers: [{ label: "Farm" }, { label: "Region" }, { label: "Water $/ac", num: true }, { label: "Fert $/ac", num: true }, { label: "Fuel $/ac", num: true }, { label: "Labor $/ac", num: true }, { label: "Total", num: true }, { label: "vs mean", num: true }],
        rows: costs.map((f) => {
          const vs = (f.total - mean) / mean;
          return [f.name, f.region, { html: rMoney(f.water, 0), cls: "num" }, { html: rMoney(f.fert, 0), cls: "num" }, { html: rMoney(f.fuel, 0), cls: "num" }, { html: rMoney(f.labor, 0), cls: "num" }, { html: rMoney(f.total, 0), cls: "num" }, { html: (vs >= 0 ? "+" : "") + rPct(vs, 0), cls: "num " + (vs > 0.08 ? "neg" : "pos") }];
        }) },
      { type: "table", title: "Regional water tariff and irrigation flag",
        headers: [{ label: "Region" }, { label: "Climate" }, { label: "Rain in", num: true }, { label: "$/m³", num: true }, { label: "Irrigated" }],
        rows: d().REGIONS.map((r) => [r.name, r.climate.replace(/_/g, " "), { html: String(r.rain_in), cls: "num" }, { html: rMoney(r.water_usd_m3, 3), cls: "num" }, r.irrigation ? "Yes" : "No"]) },
      { type: "chart", caption: "Fertilizer spend index ($000, crop year)", svg: chartLine(rTrend(1240 / 12, 18, -4, 31), { labels: rMonths(), color: AGB_EMERALD }) },
      { type: "callout", title: "AquaSentinel operational note", body: "On-device TinyML classifies water CLEAN / RISKY / POLLUTED (>94% on polluted hold-out). TDS and ORP dominate SHAP. A RISKY flag on an irrigation canal is treated as a cost and compliance event, not only a quality event: pumping into a restricted discharge window is unproductive spend." },
      { type: "recs", title: "Input desk actions", items: [
        { p: "p1", action: "Irrigation-scheduling review at Vernon Orchard (highest tariff, health 68, four alerts). Hold AquaSentinel RISKY days out of pump windows.", owner: "Water ops", when: "14 days" },
        { p: "p2", action: "4R rate audit at Riverside Dairy: labor + fert unit costs sit above the book mean.", owner: "Agronomy", when: "This month" },
        { p: "p3", action: "Lock last year's 18% N-rate save into the 2026 nutrient plan so fertilizer YTD does not rebound.", owner: "Farm ops", when: "Pre-plant" },
      ]},
      { type: "sign", lines: [
        { role: "Prepared by", name: "Input intelligence" },
        { role: "Reviewed by", name: "COO" },
        { role: "Data sources", name: "AquaSentinel · NitroSense" },
      ]},
      { type: "notes", items: [
        "4R Nutrient Stewardship (Fertilizer Canada / The Fertilizer Institute): right source, rate, time, place. Rate and time are the two levers NitroSense closes with live NO₃⁻ and moisture.",
        "Water unit rates from regional planning table in AGB_DATA (California $0.082/m³ vs BC $0.018/m³).",
        "YTD dollar totals match the live Water · inputs dashboard KPIs.",
      ]},
    ],
  });
}

function reportLending() {
  const rows = loans();
  const outstanding = rows.reduce((s, l) => s + l.principal, 0);
  const wRate = rows.reduce((s, l) => s + l.rate * l.principal, 0) / outstanding;
  const avgScore = Math.round(rows.reduce((s, l) => s + l.score, 0) / rows.length);
  const id = rDocId("LND", outstanding);
  openReport({
    id, fileStem: "agrobotic-lending-credit-memo", generated: rNow(), period: "Credit committee · March 2025",
    kicker: "Fintech · Agricultural credit memorandum",
    title: "Sensor-backed lending pack",
    subtitle: "Facility-level risk using yield, soil, GHG and alert telemetry. Score is 0–100 (dashboard) with letter bands for credit committee. Live data feed on every borrower.",
    chips: ["Private credit", "Operating + term", "Live covenant feed", "Default 0.8%"],
    kpis: [
      { label: "Outstanding", value: rMoney(outstanding), note: "6 facilities" },
      { label: "Wtd avg coupon", value: wRate.toFixed(2) + "%", note: "−40 bp YoY" },
      { label: "Avg Agrobotic Score", value: String(avgScore), note: "Band " + (avgScore >= 88 ? "A" : "B") },
      { label: "Observed default", value: "0.8%", note: "trailing 12 months" },
    ],
    sections: [
      { type: "p", title: "Committee summary", body: [
        "The book is concentrated in grain and specialty horticulture with dairy as the highest-alert name (Riverside, 3 open alerts). Scores 72–92 map to bands A–C. Pricing already differentiates: 4.20% at score 92 versus 5.70% at score 72, about 30 bp per 4 score points.",
        "Recommended hold: no new unsecured operating lines below band B without a NitroSense/AquaSentinel feed. Pending Big Sky Wheat (score 76, band C) should close only with a moisture-deficit covenant.",
      ]},
      { type: "chart", caption: "Agrobotic Score by borrower", svg: chartBar(rows.map((l) => ({ label: l.name.split(" ")[0], value: l.score, color: l.score >= 85 ? AGB_EMERALD : l.score >= 75 ? AGB_AMBER : AGB_ROSE })), { fmt: (v) => String(v) }) },
      { type: "table", title: "Facility tape",
        headers: [{ label: "Borrower" }, { label: "Region" }, { label: "Principal", num: true }, { label: "Rate", num: true }, { label: "Term", num: true }, { label: "Score", num: true }, { label: "Band" }, { label: "DSCR", num: true }, { label: "Status" }],
        rows: rows.map((l) => [l.name, l.region, { html: rMoney(l.principal), cls: "num" }, { html: l.rate.toFixed(2) + "%", cls: "num" }, { html: l.term + "y", cls: "num" }, { html: String(l.score), cls: "num" }, l.band, { html: l.dscr.toFixed(2) + "x", cls: "num" }, l.status]) },
      { type: "split",
        left: { type: "p", title: "Score drivers (this book)", body: [
          "<strong>40%</strong> yield and revenue stability versus the region (crop sensors and satellite NDVI).",
          "<strong>25%</strong> soil water and nitrate from NitroSense and AquaSentinel. Deficit and runoff flags cut the score.",
          "<strong>20%</strong> GHG and compliance trajectory (N2O and CH4 versus baseline).",
          "<strong>15%</strong> operating alerts and gateway uptime. Missed telemetry is a credit event.",
        ] },
        right: { type: "callout", title: "Pricing grid in force", body: "Band A (88–100): SOFR + 180–220 bp. Band B (80–87): +240–300 bp. Band C (72–79): +320–400 bp plus moisture covenant. Below 72: decline or require first-loss partner. Sensor-live discount: −15 bp when 95%+ uptime for 90 days." } },
      { type: "chart", caption: "Book-level Agrobotic Score (12 months)", svg: chartLine(rTrend(avgScore - 4, 1.6, 0.35, 44), { labels: rMonths(), color: AGB_CYAN }) },
      { type: "recs", title: "Credit committee actions", items: [
        { p: "p1", action: "Big Sky Wheat (score 76, band C): close only with a moisture-deficit covenant and live NitroSense feed.", owner: "Credit", when: "This IC" },
        { p: "p1", action: "Riverside Dairy (3 open alerts): no increase in unsecured operating line until EcoSense CH₄ and manure alerts clear.", owner: "Credit", when: "This IC" },
        { p: "p2", action: "Apply −15 bp sensor-live discount only where gateway uptime ≥95% for 90 days.", owner: "Pricing", when: "Next reset" },
        { p: "p3", action: "Push monthly lender feed (R6) to existing notes; scores in this memo must match the feed.", owner: "Portfolio ops", when: "Month-end" },
      ]},
      { type: "sign", lines: [
        { role: "Credit analyst", name: "Agrobotic Lending" },
        { role: "Committee chair", name: "Head of credit" },
        { role: "Covenant monitor", name: "Live sensor feed" },
      ]},
      { type: "notes", items: [
        "Structure inspired by agricultural underwriting scorecards that combine a 300–850 style composite, risk bands A–E, and soil/weather/yield telemetry (e.g. land-core / index-insurance practice). Dashboard scores remain 0–100 for operator UX.",
        "DSCR here is revenue / (principal × (coupon + 1/term)), a screening ratio, not audited cash-flow DSCR.",
        "Covenants proposed: minimum VWC vs crop-stage curve; max rolling 7-day N₂O; no more than 2 unresolved high alerts.",
      ]},
    ],
  });
}

function reportInsurance() {
  const rows = policies();
  const coverage = rows.reduce((s, p) => s + p.coverage, 0);
  const premium = rows.reduce((s, p) => s + p.premium, 0);
  const avgDisc = rows.reduce((s, p) => s + p.discount, 0) / rows.length;
  const id = rDocId("INS", coverage);
  openReport({
    id, fileStem: "agrobotic-insurance-risk-report", generated: rNow(), period: "Bound book · 2025 crop year",
    kicker: "Fintech · Parametric and MPCI pricing pack",
    title: "Crop insurance risk and premium report",
    subtitle: "Sensor health re-prices coverage continuously. Healthier telemetry means lower premium and cleaner parametric triggers, in the spirit of RMA index-based weather plans and soil-health premium discounts.",
    chips: ["MPCI + parametric annex", "2 open claims", "Live soil / NDVI / smoke indices"],
    kpis: [
      { label: "Coverage in force", value: rMoney(coverage), note: "sum insured" },
      { label: "Premiums YTD", value: rMoney(premium), note: "−4.8% with discounts" },
      { label: "Avg sensor discount", value: rPct(avgDisc, 0), note: "off manual premium" },
      { label: "Open claims", value: "2", note: "hail + irrigation interruption" },
    ],
    sections: [
      { type: "p", title: "Portfolio view", body: [
        `Gross written premium ${rMoney(premium)} on ${rMoney(coverage)} of liability (rate-on-line ${(premium / coverage * 100).toFixed(2)}%). Sensor discounts average ${rPct(avgDisc, 0)}, concentrated in Story County Corn and McLean Soy (health 91 and 88). Vernon Orchard (health 68, 4 alerts) is High risk and should not receive the parametric annex until AquaSentinel RISKY flags clear.`,
      ]},
      { type: "chart", caption: "Premium by policy", svg: chartBar(rows.map((p) => ({ label: p.name.split(" ")[0], value: p.premium, color: p.risk === "Low" ? AGB_EMERALD : p.risk === "Medium" ? AGB_AMBER : AGB_ROSE })), { fmt: (v) => rMoney(v) }) },
      { type: "table", title: "Bound policies",
        headers: [{ label: "Named insured" }, { label: "Coverage", num: true }, { label: "Premium", num: true }, { label: "Risk" }, { label: "Perils" }, { label: "Discount", num: true }, { label: "Health", num: true }],
        rows: rows.map((p) => [p.name, { html: rMoney(p.coverage), cls: "num" }, { html: rMoney(p.premium), cls: "num" }, { html: p.risk, cls: p.risk === "Low" ? "pos" : p.risk === "High" ? "neg" : "" }, p.perils.join(", "), { html: "−" + rPct(p.discount, 0), cls: "num pos" }, { html: String(p.health), cls: "num" }]) },
      { type: "p", title: "Parametric annex (proposed wording sketch)", body: [
        "<strong>Index A, drought:</strong> 30-day mean root-zone VWC vs farm baseline, NitroSense + satellite soil moisture. Strike: 25th percentile of the last 10 seasons. Exit: 5th percentile. Payout linear 0–100% of annex limit.",
        "<strong>Index B, hail proxy:</strong> dual-pol radar + on-farm impact (optional). Not a substitute for MPCI hail where FCIC products exist.",
        "<strong>Index C, smoke / fire:</strong> ForestSentinel / AirWatch PM2.5 24h > 55 µg/m³ for 3 consecutive days on orchard blocks (Vernon).",
        "Basis risk is disclosed: payout follows the index, not a loss adjuster’s field walk. That is the RMA index-based weather product tradeoff.",
      ]},
      { type: "chart", caption: "Indicative loss ratio (premium vs reserved, crop year %)", svg: chartLine(rTrend(42, 6, 0.4, 55), { labels: rMonths(), color: AGB_AMBER }) },
      { type: "callout", title: "Open claims", body: "CL-4411 Hilltop Acres hail (MPCI, adjuster assigned). CL-4418 Vernon irrigation interruption (parametric Index A near strike; AquaSentinel canal RISKY on 12 Oct). Reserves inside current premium." },
      { type: "recs", title: "Underwriting actions", items: [
        { p: "p1", action: "Hold the parametric annex on Vernon until AquaSentinel RISKY flags clear and health > 75.", owner: "Underwriting", when: "Immediate" },
        { p: "p2", action: "Confirm CL-4411 hail reserve with the MPCI adjuster before month-end bordereau.", owner: "Claims", when: "Month-end" },
        { p: "p3", action: "Keep MPCI as the primary product; parametric remains an annex. Disclose basis risk in every quote.", owner: "Product", when: "Ongoing" },
      ]},
      { type: "sign", lines: [
        { role: "Underwriter", name: "Agrobotic Insurance desk" },
        { role: "Actuarial review", name: "Index + MPCI pricing" },
        { role: "Claims", name: "CL-4411 · CL-4418 open" },
      ]},
      { type: "notes", items: [
        "USDA RMA FCIC procedures handbook 17050 lists required contents for index-based weather plans (index definition, states/counties, actuarial method, A.M. Best, subsidies). This pack is an operator/reinsurer briefing, not an FCIC submission.",
        "Soil-health premium discounts are an emerging actuarial practice (e.g. Land Core working-group models). Applied here as a health-score discount cap of 18%.",
        "Correlation: higher health, higher discount. Scatter on the Insurance page is the live view of the same policies.",
      ]},
    ],
  });
}

function reportEccc() {
  const s = ghgScenario({ region: "ON", crop: "corn", acres: 1500, n_rate: 180, carbon_price: 95, adoption: 0.6 });
  const id = rDocId("ECCC", s.baseline_co2e_t);
  openReport({
    id, fileStem: "agrobotic-eccc-annual-emissions-2024", generated: rNow(), period: "Calendar 2024 inventory",
    kicker: "Regulatory pack  ·  GHGRP-aligned",
    title: "Annual agricultural GHG inventory (ECCC-style)",
    subtitle: "Facility-style inventory of CO₂e from soils N₂O, enteric CH₄ and manure, using AR5 GWPs required for 2024–2025 GHGRP reporting. Demonstration using Agrobotic farms, not a Single Window filing.",
    chips: ["GHGRP 2024/2025", "AR5 GWP", "N₂O 265", "CH₄ 28", "Period 2024"],
    kpis: [
      { label: "Total CO₂e", value: rNum(s.farms.reduce((a, f) => a + f.red_t, 0) + 1840, 0) + " t", note: "after on-farm controls" },
      { label: "Soils N₂O", value: rNum(s.farms.reduce((a, f) => a + f.red_t, 0), 0) + " t", note: "fertilizer-induced" },
      { label: "Livestock CH₄", value: "1,840 t", note: "Riverside Dairy EcoSense" },
      { label: "YoY", value: "−11.4%", note: "vs 2023 inventory" },
    ],
    sections: [
      { type: "p", title: "Scope and gases", body: [
        "Gases reported: CO₂ (GWP 1), CH₄ (28), N₂O (265), matching Table 1 of ECCC’s GHGRP technical guidance for 2024 and 2025. SF₆ and fluorinated gases are not material on these farms.",
        "Sources: IPCC agriculture categories 3.A enteric, 3.B manure, 3.D agricultural soils. Activity data from NitroSense (N applied, soil N₂O) and EcoSense (barn CH₄).",
      ]},
      { type: "table", title: "Source category roll-up (tCO₂e)",
        headers: [{ label: "IPCC / GHGRP line" }, { label: "Gas" }, { label: "Activity" }, { label: "tCO₂e", num: true }],
        rows: [
          ["3.D Agricultural soils (direct N₂O)", "N₂O", "Synthetic N + crop residue", { html: rNum(s.farms.reduce((a, f) => a + f.red_t, 0), 0), cls: "num" }],
          ["3.A Enteric fermentation", "CH₄", "Dairy herd, Riverside", { html: "1,120", cls: "num" }],
          ["3.B Manure management", "CH₄ + N₂O", "Lagoon + bedded pack", { html: "720", cls: "num" }],
          ["2.A.4 Liming / urea CO₂", "CO₂", "Not material this year", { html: "0", cls: "num" }],
        ] },
      { type: "chart", caption: "Soils N₂O by farm after controls, tCO₂e", svg: chartBar(s.farms.map((f) => ({ label: f.name.split(" ")[0], value: f.red_t, color: AGB_EMERALD })), { fmt: (v) => rNum(v, 0) }) },
      { type: "callout", title: "Filing note", body: "Facilities at or above the GHGRP threshold file through ECCC Single Window. OBPS reporters can use the OBPS-to-GHGRP printout. This document is the internal evidence pack (activity data, EFs, GWPs) that would populate those screens." },
      { type: "recs", title: "Filing checklist", items: [
        { p: "p1", action: "Confirm AR5 GWPs (N₂O 265, CH₄ 28) are the values locked in the 2024 Single Window return.", owner: "Compliance", when: "Filing window" },
        { p: "p2", action: "Attach NitroSense N-applied and EcoSense CH₄ activity tables as supporting files.", owner: "MRV", when: "Filing window" },
        { p: "p3", action: "Do not treat this pack as the statutory filing. It is the evidence binder.", owner: "General counsel", when: "Ongoing" },
      ]},
      { type: "sign", lines: [
        { role: "Inventory compiler", name: "Agrobotic MRV" },
        { role: "Responsible officer", name: "CFO" },
        { role: "Period", name: "Calendar 2024" },
      ]},
      { type: "notes", items: [
        "ECCC Notice with respect to reporting of GHGs for 2024 and 2025; technical guidance on gases and GWPs.",
        "AAFC Agricultural Greenhouse Gases technical chapter: Canada uses IPCC 2006 with a Tier II country-specific soils method.",
        "Quantities are Agrobotic telemetry scaled to the demo portfolio.",
      ]},
    ],
  });
}

function reportVerraBundle() {
  reportCarbon();
}

function report4R() {
  const { FARMS } = d();
  const id = rDocId("4R", FARMS.length);
  openReport({
    id, fileStem: "agrobotic-4r-nutrient-stewardship-2024", generated: rNow(), period: "Crop year 2024",
    kicker: "Sustainability pack  ·  4R Nutrient Stewardship",
    title: "4R implementation and outcome report",
    subtitle: "Right source, right rate, right time, right place. NitroSense closes rate and time with live nitrate, moisture and temperature; this pack is the year-end evidence for retailers, growers and Fertilizer Canada-style programs.",
    chips: ["4R", "NitroSense", "Crop year 2024", "N save 18% on adopting acres"],
    kpis: [
      { label: "Acres under 4R", value: rNum(FARMS.reduce((s, f) => s + f.acres, 0)), note: "all monitored farms" },
      { label: "N rate vs prior", value: "−18%", note: "adopting fields" },
      { label: "Yield", value: "+3%", note: "where rate was optimized, not cut blindly" },
      { label: "N₂O", value: "−24%", note: "vs field baseline flux" },
    ],
    sections: [
      { type: "p", title: "The four rights, as operated", body: [
        "<strong>Source:</strong> UAN and ESN on corn; ammonium sulfate where sulfur is limiting (Story County). Recorded on each application event.",
        "<strong>Rate:</strong> NitroSense NO₃⁻ 0–30 cm vs crop-stage curve. Applications skipped when soil nitrate already met the next 10-day demand.",
        "<strong>Time:</strong> sidedress triggered by denitrification-risk model (NO₃⁻ × VWC × soil temperature), not calendar week 5.",
        "<strong>Place:</strong> 2×2 and Y-drop on corn; banded canola in SK. Broadcast only on alfalfa.",
      ]},
      { type: "table", title: "Farm outcomes",
        headers: [{ label: "Farm" }, { label: "Crop" }, { label: "Acres", num: true }, { label: "Health", num: true }, { label: "4R status" }],
        rows: FARMS.map((f) => [f.name, f.crop, { html: rNum(f.acres), cls: "num" }, { html: String(f.health), cls: "num" }, f.health >= 80 ? "Verified" : "In progress"]) },
      { type: "chart", caption: "Seasonal nitrate (ppm NO₃⁻, book mean)", svg: chartLine(rTrend(22, 3.2, -0.4, 62), { labels: rMonths(), color: AGB_EMERALD }) },
      { type: "table", title: "Right-by-right score (book)",
        headers: [{ label: "Right" }, { label: "Practice" }, { label: "Evidence" }, { label: "Score", num: true }],
        rows: [
          ["Source", "UAN / ESN / AMS by crop", "As-applied tickets + product SKU", { html: "88", cls: "num pos" }],
          ["Rate", "NO₃⁻ vs crop-stage curve", "NitroSense 0–30 cm", { html: "91", cls: "num pos" }],
          ["Time", "Denitrification-risk trigger", "NO₃⁻ × VWC × soil T model", { html: "86", cls: "num pos" }],
          ["Place", "2×2, Y-drop, banded canola", "Applicator logs", { html: "79", cls: "num" }],
        ] },
      { type: "callout", title: "What this is not", body: "4R is a stewardship framework, not a carbon methodology. Tonnes in the carbon pack still need a credited methodology. 4R is the agronomic story those tonnes rest on." },
      { type: "recs", title: "2025 4R plan", items: [
        { p: "p1", action: "Move Vernon Orchard and Big Sky Wheat from In progress to Verified: place and time scores are the gap.", owner: "Agronomy", when: "Pre-plant 2025" },
        { p: "p2", action: "Keep the 18% N-rate save; do not cut further where yield lift was the 3% that paid for the program.", owner: "Farm ops", when: "Nutrient plan" },
        { p: "p3", action: "Export this pack with the GHG tax memo so retailers and 4R programs see the same N story.", owner: "Sustainability", when: "Year-end" },
      ]},
      { type: "sign", lines: [
        { role: "4R advisor", name: "Agrobotic agronomy" },
        { role: "Grower lead", name: "Portfolio ops" },
        { role: "Retailer copy", name: "On request" },
      ]},
      { type: "notes", items: ["The Fertilizer Institute / Fertilizer Canada 4R framework.", "Agrobotic edge models: nitrate spike flags, denitrification risk, 4R dashboard recommendations."] },
    ],
  });
}

function reportSb261() {
  const { KPIS, FARMS } = d();
  const id = rDocId("SB261", KPIS.fintech.aum_usd);
  openReport({
    id, fileStem: "agrobotic-sb261-climate-risk-2024", generated: rNow(), period: "Reporting cycle 2024 (first-cycle draft)",
    kicker: "California SB 261  ·  TCFD / IFRS S2 style",
    title: "Climate-related financial risk report",
    subtitle: "Biennial climate risk and adaptation disclosure patterned on TCFD and IFRS S2, the frameworks SB 261 (HSC § 38533) accepts. Prepared as a portfolio pack for entities with California exposure (Vernon Orchard and downstream buyers). Not a CARB docket filing.",
    chips: ["SB 261", "TCFD", "IFRS S2", "First report cycle 2026"],
    kpis: [
      { label: "CA acres in book", value: rNum(410), note: "Vernon Orchard" },
      { label: "Water tariff", value: rMoney(0.082, 3) + "/m³", note: "highest in book" },
      { label: "Physical risk names", value: "2", note: "drought + smoke" },
      { label: "Transition price used", value: "$95/t", note: "2025 federal / shadow" },
    ],
    sections: [
      { type: "p", title: "Governance", body: ["Climate risk is reviewed in the same operating cadence as GHG tax and insurance: CFO owns transition (carbon price, 4R, credits); COO owns physical (water, heat, fire smoke). Board pack includes this report twice a year."] },
      { type: "p", title: "Strategy", body: ["Physical: California orchard water and smoke; Prairie drought; dairy heat stress. Transition: fertilizer N₂O priced at the federal fuel-charge path; voluntary credits as a hedge. Strategy is sensor density on high-tariff and high-GWP acres, not a one-time offset purchase."] },
      { type: "table", title: "Risk register (material items)",
        headers: [{ label: "Risk" }, { label: "Type" }, { label: "Horizon" }, { label: "Metric" }, { label: "Mitigation" }],
        rows: [
          ["Irrigation cost and curtailment", "Physical", "0–3 y", "$/m³ and AquaSentinel RISKY days", "Scheduling + deficit irrigation on Vernon"],
          ["Wildfire smoke on fruit quality", "Physical", "seasonal", "PM2.5 days > 55 µg/m³", "AirWatch / ForestSentinel alerts"],
          ["Fertilizer N₂O cost of carbon", "Transition", "1–5 y", "tCO₂e × $95", "4R + NitroSense; credit issuance"],
          ["Index-insurance basis risk", "Physical / financial", "seasonal", "VWC vs yield residual", "Keep MPCI; parametric is annex only"],
        ] },
      { type: "p", title: "Metrics and targets", body: [
        `Book-level avoided N₂O and CH₄: ${rNum(KPIS.fintech.carbon_offset_tons)} tCO₂e YTD. Credit revenue ${rMoney(KPIS.fintech.carbon_revenue_usd)}. Target: 15% soils N₂O intensity cut by 2027 vs 2023 on adopting acres.`,
      ]},
      { type: "chart", caption: "Regional water tariff ($/m³). California is the physical-risk outlier.", svg: chartBar(d().REGIONS.map((r) => ({ label: r.id, value: r.water_usd_m3, color: r.id === "CA" ? AGB_ROSE : AGB_CYAN })), { fmt: (v) => rMoney(v, 3) }) },
      { type: "table", title: "Scenario sketch (transition + physical)",
        headers: [{ label: "Scenario" }, { label: "Carbon price" }, { label: "Water" }, { label: "P&L read-through" }],
        rows: [
          ["Current policy", "$80–95/t fuel-charge path", "CA $0.082/m³", "Tax memo + water report as run"],
          ["Delayed transition", "Voluntary ~$28/t only", "Tariff + 15%", "Credits still pay; CA orchard margin tight"],
          ["Accelerated 1.5 °C-aligned", "$110+ by 2026, then higher", "Curtailment days +2×", "4R + sensors are the hedge, not offsets alone"],
        ] },
      { type: "recs", title: "Disclosure actions", items: [
        { p: "p1", action: "Keep this as a draft until CARB first-cycle guidance is locked. Do not post to a public docket from this demo.", owner: "General counsel", when: "Until 2026 cycle" },
        { p: "p2", action: "Attach the GHG tax memo and water report as metric annexes (TCFD / IFRS S2 metrics pillar).", owner: "CFO", when: "Board pack" },
        { p: "p3", action: "Board review twice a year: physical (Vernon water/smoke) and transition (N₂O price).", owner: "Board sec.", when: "H1 / H2" },
      ]},
      { type: "sign", lines: [
        { role: "Disclosure owner", name: "CFO" },
        { role: "Physical risk", name: "COO" },
        { role: "Status", name: "Draft · not a CARB filing" },
      ]},
      { type: "notes", items: [
        "SB 261 applies to US companies doing business in California with >$500M revenue; reports are biennial, posted on the company site, with the link on CARB’s docket. Insurance companies are excluded.",
        "Accepted frameworks: TCFD (June 2017) or successor, IFRS S2, or another regulated-exchange / government framework (HSC § 38533(b)(3)(A)).",
        "CARB checklist (Nov 2025): governance, strategy, risk management, metrics; first-cycle data may be best-available.",
      ]},
    ],
  });
}

function reportEsg() {
  const { KPIS, FARMS } = d();
  const id = rDocId("ESG", KPIS.fintech.revenue_ytd);
  openReport({
    id, fileStem: "agrobotic-investor-esg-q1-2025", generated: rNow(), period: "Q1 2025",
    kicker: "Investor pack  ·  Q1 2025",
    title: "Quarterly ESG and climate operating report",
    subtitle: "Operator-grade ESG for LPs and strategic buyers: emissions intensity, water, 4R, safety air quality, and the carbon P&L. ISSB-like metrics without the full S1/S2 filing.",
    chips: ["Q1 2025", "8 farms", "AUM " + rMoney(KPIS.fintech.aum_usd)],
    kpis: [
      { label: "AUM", value: rMoney(KPIS.fintech.aum_usd), note: "+4.2%" },
      { label: "Revenue YTD", value: rMoney(KPIS.fintech.revenue_ytd), note: "+7.8%" },
      { label: "Offsets / credits", value: rNum(KPIS.fintech.carbon_offset_tons) + " t", note: rMoney(KPIS.fintech.carbon_revenue_usd) + " revenue" },
      { label: "Avg ROI", value: rPct(KPIS.fintech.avg_roi_pct, 1), note: "sensor adoption" },
    ],
    sections: [
      { type: "chart", caption: "Farm health (proxy for E&S operating quality)", svg: chartBar(FARMS.map((f) => ({ label: f.name.split(" ")[0], value: f.health, color: f.health >= 80 ? AGB_EMERALD : AGB_AMBER })), { fmt: (v) => String(v) }) },
      { type: "p", title: "Quarter highlights", body: [
        "N₂O intensity down on Prairie canola after sidedress-on-sensor. Dairy CH₄ listing VCS-1142 verified. Two insurance claims open, not material to AUM. No lost-time incidents; AirWatch barn peaks stayed under the internal 25 ppm NH₃ trigger.",
      ]},
      { type: "table", title: "Portfolio snapshot",
        headers: [{ label: "Farm" }, { label: "Region" }, { label: "Crop" }, { label: "Acres", num: true }, { label: "Revenue", num: true }, { label: "Alerts", num: true }],
        rows: FARMS.map((f) => [f.name, f.region, f.crop, { html: rNum(f.acres), cls: "num" }, { html: rMoney(f.revenue_usd), cls: "num" }, { html: String(f.alerts), cls: "num" }]) },
      { type: "table", title: "Climate P&L (operator view)",
        headers: [{ label: "Line" }, { label: "YTD", num: true }, { label: "Notes" }],
        rows: [
          ["Sensor-backed credit revenue", { html: rMoney(KPIS.fintech.carbon_revenue_usd), cls: "num pos" }, "Settled sales"],
          ["GHG tax shadow (planning)", { html: rMoney(KPIS.fintech.tax_liability_usd), cls: "num" }, "See GHG tax memo"],
          ["Eligible credit inventory", { html: rMoney(KPIS.fintech.eligible_credits_usd), cls: "num pos" }, "Not yet issued / sold"],
          ["Insurance savings vs manual", { html: rMoney(KPIS.fintech.insurance_savings_usd), cls: "num pos" }, "Sensor discounts"],
        ] },
      { type: "chart", caption: "Revenue run-rate index ($M)", svg: chartLine(rTrend(KPIS.fintech.revenue_ytd / 12 / 1e6, 0.12, 0.04, 71), { labels: rMonths(), color: AGB_VIOLET }) },
      { type: "recs", title: "LP talking points this quarter", items: [
        { p: "p1", action: "Lead with verified VCS-1142 and the 12.4% fertilizer save, not a generic ESG narrative.", owner: "IR", when: "Q1 call" },
        { p: "p2", action: "Disclose two open insurance claims and Vernon as the physical-risk name. Do not bury them.", owner: "IR", when: "Q1 call" },
        { p: "p3", action: "Metrics are operational, not assured. Say that out loud.", owner: "IR", when: "Every pack" },
      ]},
      { type: "sign", lines: [
        { role: "Prepared for", name: "LPs and strategic buyers" },
        { role: "Prepared by", name: "Agrobotic IR + Climate Desk" },
        { role: "Assurance", name: "None this cycle" },
      ]},
      { type: "notes", items: ["Metrics are operational, not assured. Carbon tonnes follow the monitoring pack, not an LP-level Scope 3 inventory.", "Health is the live Agrobotic farm score (sensors, yield, alerts)."] },
    ],
  });
}

function reportLenderFeed() {
  reportLending();
}

function reportIowa() {
  const farm = d().FARMS.find((f) => f.id === "F-005") || d().FARMS[0];
  const id = rDocId("ISA", farm.acres);
  openReport({
    id, fileStem: "agrobotic-iowa-soybean-baseline-2024", generated: rNow(), period: "2024 on-farm baseline",
    kicker: "Partner pack  ·  Iowa Soybean Association style baseline",
    title: "Story County on-farm baseline",
    subtitle: `${farm.name}, ${farm.acres} acres of corn in a soybean rotation. Field-level baseline for water quality, nitrate, and yield so year-2 practice change is measurable.`,
    chips: ["Story County, IA", "Corn / soy rotation", "2024 baseline", farm.owner],
    kpis: [
      { label: "Acres", value: rNum(farm.acres), note: farm.crop },
      { label: "Health", value: String(farm.health), note: "Agrobotic score" },
      { label: "Revenue", value: rMoney(farm.revenue_usd), note: "last crop year" },
      { label: "Sensors", value: String(farm.sensors), note: "NitroSense + AquaSentinel" },
    ],
    sections: [
      { type: "p", title: "Why a baseline", body: [
        "Conservation and 4R programs only pay or credit a delta. This pack freezes 2024 nitrate, tile-water, yield and N rate so 2025 cover-crop or reduced-N trials have a farm-specific control, not a county average.",
      ]},
      { type: "table", title: "Baseline markers",
        headers: [{ label: "Marker" }, { label: "2024 value" }, { label: "How measured" }],
        rows: [
          ["Yield", "178 bu/ac planning yield (crop table)", "Combine + satellite NDVI fusion"],
          ["N rate", "180 lb/ac standard corn", "As-applied + NitroSense"],
          ["Tile nitrate", "Season mean 22 ppm NO₃⁻", "AquaSentinel / NitroSense drainage"],
          ["Soil VWC 30 cm", "Season mean 34%", "NitroSense"],
          ["N₂O flux", "Sub-ppm, event-driven spikes at wet-warm sidedress", "NitroSense dual-mode"],
        ] },
      { type: "chart", caption: "Tile nitrate (ppm NO₃⁻) 2024 baseline", svg: chartLine(rTrend(22, 2.8, 0.15, 81), { labels: rMonths(), color: AGB_CYAN }) },
      { type: "callout", title: "2025 trial gate", body: "A practice change is ‘real’ here if tile-season mean NO₃⁻ falls ≥15% without a yield loss >2 bu/ac, on the same 1,840 acres. That is the number we would take to a cost-share or carbon methodology." },
      { type: "recs", title: "Year-2 protocol", items: [
        { p: "p1", action: "Freeze these 2024 markers. Do not rebase mid-trial.", owner: "On-farm network", when: "Locked" },
        { p: "p2", action: "Cover-crop or reduced-N treatment only on strips with the same NitroSense depth and tile outlets.", owner: "Story Holdings", when: "2025 season" },
        { p: "p3", action: "If the gate is hit, package this baseline with the 4R and carbon packs for cost-share / issuance.", owner: "Sustainability", when: "Post-harvest 2025" },
      ]},
      { type: "sign", lines: [
        { role: "Grower of record", name: farm.owner },
        { role: "Baseline author", name: "Agrobotic agronomy" },
        { role: "County", name: "Story County, Iowa" },
      ]},
      { type: "notes", items: ["Framed like on-farm network baselines used by grower associations (Iowa Soybean Association and similar). Not an ISA publication.", "Story Holdings owner of record. Sensors live since March 2023."] },
    ],
  });
}

function reportQuarterly() {
  reportEsg();
}

function generate(kind, opts) {
  const map = {
    ghg: reportGhg,
    carbon: reportCarbon,
    water: reportWater,
    inputs: reportWater,
    lending: reportLending,
    insurance: reportInsurance,
    eccc: reportEccc,
    verra: reportVerraBundle,
    "4r": report4R,
    sb261: reportSb261,
    esg: reportEsg,
    "lender-feed": reportLenderFeed,
    iowa: reportIowa,
    quarterly: reportQuarterly,
  };
  const fn = map[kind];
  if (!fn) { AGB_UI.toast("Unknown report type", { type: "bad" }); return; }
  fn(opts || {});
}

function generateListed(report) {
  const key = ({
    R1: "eccc", R2: "verra", R3: "4r", R4: "sb261", R5: "esg", R6: "lender-feed", R7: "iowa",
  })[report.id];
  if (report.status === "Draft" && report.id === "R4") {
    generate("sb261");
    return;
  }
  generate(key || "esg");
}

function generateFromForm(values) {
  const type = values.type || "";
  if (type.includes("ECCC")) return generate("eccc");
  if (type.includes("Verra")) return generate("verra");
  if (type.includes("4R")) return generate("4r");
  if (type.includes("SB 261")) return generate("sb261");
  if (type.includes("ESG")) return generate("esg");
  if (type.includes("Lender")) return generate("lender-feed");
  generate("esg");
}

Object.assign(window, { AGB_REPORTS: { generate, generateListed, generateFromForm, reportGhg } });
