/* eslint-disable no-undef */
// Fintech mode — Portfolio, GHG Tax, Carbon Credits, ROI, Markets, Water, Lending, Insurance, Reports.

const { useState: fnUseState, useMemo: fnUseMemo, useEffect: fnUseEffect } = React;

// ---------- Fintech action builders ----------
function actQuarterlyReport() {
  const { FARMS, KPIS } = window.AGB_DATA;
  downloadCSV("agrobotic-quarterly-portfolio.csv",
    ["Farm", "Region", "Crop", "Acres", "Revenue USD", "Carbon tCO2e", "Health"],
    FARMS.map((f) => [f.name, f.region, f.crop, f.acres, f.revenue_usd, Math.round(f.acres * 0.4), f.health]));
}
function actNewScenario() {
  const { REGIONS } = window.AGB_DATA;
  AGB_UI.form({ eyebrow: "Portfolio", title: "New scenario", subtitle: "Model a what-if across the portfolio.",
    submitLabel: "Run scenario", successMessage: "Scenario created · results updating",
    fields: [
      { key: "name", label: "Scenario name", placeholder: "e.g. Carbon price +$15", value: "" },
      { key: "lever", label: "Driver", type: "select", options: ["Carbon price", "Nitrogen cost", "Crop price", "Sensor adoption %", "Interest rate"] },
      { key: "delta", label: "Change", type: "range", min: -50, max: 50, step: 5, value: 15, suffix: "%" },
      { key: "horizon", label: "Horizon", type: "select", options: ["1 year", "3 years", "5 years"] },
    ] });
}
function actAuditTrail() {
  const rows = [
    { t: "2025-03-18 14:22", e: "VCS-1142 verified", who: "Verra", n: "2,400 t" },
    { t: "2025-03-15 09:10", e: "EcoSense data bundle exported", who: "system", n: "BC dairy" },
    { t: "2025-03-12 16:48", e: "GS-7821 listed", who: "I. El-Chami", n: "4,100 t" },
    { t: "2025-03-02 11:03", e: "NitroSense N₂O flux signed", who: "system", n: "Prairie" },
  ];
  AGB_UI.modal({ eyebrow: "Carbon", title: "Audit trail", subtitle: "Immutable record of credit issuance & verification.", wide: true,
    submitLabel: "Export trail", successToast: false,
    onSubmit: () => downloadCSV("carbon-audit-trail.csv", ["Timestamp", "Event", "Actor", "Detail"], rows.map((r) => [r.t, r.e, r.who, r.n])),
    body: (
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <DataTable rows={rows} idKey="t" columns={[
          { key: "t", label: "Timestamp", mono: true, dim: true },
          { key: "e", label: "Event", render: (r) => <span style={{ fontWeight: 500 }}>{r.e}</span> },
          { key: "who", label: "Actor" },
          { key: "n", label: "Detail", mono: true, align: "right" },
        ]} />
      </div>
    ) });
}
function actListCredits() {
  AGB_UI.form({ eyebrow: "Carbon", title: "List credits for sale", subtitle: "Publish sensor-verified credits to a registry.",
    submitLabel: "List credits", successMessage: "Credits listed on marketplace",
    fields: [
      { key: "source", label: "Source", type: "select", options: ["NitroSense N₂O", "EcoSense CH₄", "ForestSentinel", "Soil carbon"] },
      { key: "standard", label: "Registry", type: "select", options: ["Verra VCS", "Gold Standard", "American Carbon Registry", "ECCC Pilot"] },
      { key: "tons", label: "Volume", type: "number", value: 1000, suffix: "tCO₂e" },
      { key: "price", label: "Ask price", type: "number", value: 30, suffix: "$/t" },
      { key: "vintage", label: "Vintage", type: "select", options: ["2025", "2024", "2023"] },
    ] });
}
function actBuyCredit(sel) {
  AGB_UI.form({ eyebrow: sel.id, title: `Buy ${sel.name}`, subtitle: `${sel.standard} · ${fmtMoney(sel.price, 2)}/tCO₂e`,
    submitLabel: "Place order", successMessage: "Order placed · settlement in T+2",
    fields: [
      { key: "tons", label: "Quantity", type: "number", value: Math.min(500, sel.tons_avail), suffix: "tCO₂e" },
      { key: "type", label: "Order type", type: "select", options: ["Market", "Limit"] },
      { key: "retire", label: "Retire immediately (offset our own footprint)", type: "checkbox", value: false },
    ] });
}
function actSellCredit(sel) {
  AGB_UI.form({ eyebrow: sel.id, title: `Sell / list ${sel.name}`, submitLabel: "List for sale", successMessage: "Listed on order book",
    fields: [
      { key: "tons", label: "Quantity", type: "number", value: 250, suffix: "tCO₂e" },
      { key: "price", label: "Ask", type: "number", value: sel.price, suffix: "$/t" },
    ] });
}
function actNewReport() {
  AGB_UI.form({ eyebrow: "Reports", title: "Generate report", subtitle: "Sensor-backed export for a stakeholder.",
    submitLabel: "Generate", successMessage: "Report queued · ready shortly",
    fields: [
      { key: "type", label: "Report type", type: "select", options: ["ECCC Annual Emissions", "Verra VCS Bundle", "4R Nutrient Stewardship", "CA SB 261 Climate Disclosure", "Investor ESG", "Lender data feed"] },
      { key: "period", label: "Period", type: "select", options: ["Q1 2025", "2024", "2023", "Custom range"] },
      { key: "farms", label: "Scope", type: "select", options: ["All farms", "By region", "Single farm"] },
      { key: "format", label: "Format", type: "select", options: ["PDF", "CSV", "XBRL", "JSON"] },
    ] });
}
function actExportReport(report) {
  downloadText(`${report.name.replace(/\s+/g, "-")}-${report.period}.txt`,
    `AGROBOTIC — ${report.name}\nPeriod: ${report.period}\nCategory: ${report.category}\nStatus: ${report.status}\n\nThis is a sensor-verified compliance export generated from Agrobotic device data.\nAll figures are traceable to source sensors with an immutable audit trail.`);
}
function actNewFacility() {
  const { FARMS } = window.AGB_DATA;
  AGB_UI.form({ eyebrow: "Lending", title: "New financing facility", subtitle: "Originate a sensor-verified loan.",
    submitLabel: "Create facility", successMessage: "Facility created · underwriting started",
    fields: [
      { key: "farm", label: "Borrower", type: "select", options: FARMS.map((f) => ({ value: f.id, label: f.name })) },
      { key: "principal", label: "Principal", type: "number", value: 500000, suffix: "$" },
      { key: "rate", label: "Rate", type: "number", value: 4.5, suffix: "%" },
      { key: "term", label: "Term", type: "select", options: ["3 years", "5 years", "7 years", "10 years"] },
      { key: "type", label: "Facility type", type: "select", options: ["Operating line", "Equipment", "Land", "Bridge"] },
    ] });
}
function actQuotePolicy() {
  const { FARMS } = window.AGB_DATA;
  AGB_UI.form({ eyebrow: "Insurance", title: "Quote new policy", subtitle: "Sensor data re-prices coverage in real time.",
    submitLabel: "Generate quote", successMessage: "Quote generated · premium estimated",
    fields: [
      { key: "farm", label: "Farm", type: "select", options: FARMS.map((f) => ({ value: f.id, label: f.name })) },
      { key: "coverage", label: "Coverage amount", type: "number", value: 2000000, suffix: "$" },
      { key: "perils", label: "Perils", type: "select", options: ["Yield + Hail", "Multi-peril (MPCI)", "Drought + Frost", "Named perils"] },
      { key: "deductible", label: "Deductible", type: "select", options: ["5%", "10%", "15%", "25%"] },
    ] });
}

// ==================== PORTFOLIO ====================
function FtPortfolio({ navigate }) {
  const { FARMS, KPIS, CROPS } = window.AGB_DATA;
  const totalAcres = FARMS.reduce((s, f) => s + f.acres, 0);
  const totalRev = FARMS.reduce((s, f) => s + f.revenue_usd, 0);

  return (
    <div>
      <PageHeader
        eyebrow="Fintech · Portfolio"
        title="Capital flow across the Agrobotic portfolio"
        sub="A unified financial view of every farm, every input, every output — grounded in sensor-verified data."
        actions={<>
          <button className="btn" onClick={actQuarterlyReport}><Icon name="download" size={14} /> Quarterly report</button>
          <button className="btn primary" onClick={actNewScenario}><Icon name="plus" size={14} /> New scenario</button>
        </>}
      />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12, padding: "0 var(--space-6) var(--space-4)" }}>
        <Stat label="Portfolio AUM"   value={fmtMoney(KPIS.fintech.aum_usd)}            delta={4.2} sparkline={generateSeries(20, 16, 0.4, 0.05, 1)} />
        <Stat label="Revenue YTD"     value={fmtMoney(KPIS.fintech.revenue_ytd)}        delta={7.8} sparkline={generateSeries(20, 8, 0.3, 0.04, 3)} />
        <Stat label="Carbon offset"   value={fmtNum(KPIS.fintech.carbon_offset_tons)}   unit="tCO₂e" delta={12.4} spark_color="var(--cyan)"  sparkline={generateSeries(20, 4, 0.3, 0.06, 5)} />
        <Stat label="Credit revenue"  value={fmtMoney(KPIS.fintech.carbon_revenue_usd)} delta={9.1} spark_color="var(--cyan)"  sparkline={generateSeries(20, 110, 6, 0.5, 7)} />
        <Stat label="Avg ROI"         value={fmtPct(KPIS.fintech.avg_roi_pct)}          delta={1.8} spark_color="var(--green)" sparkline={generateSeries(20, 22, 0.4, 0.03, 9)} />
        <Stat label="Tax liability"   value={fmtMoney(KPIS.fintech.tax_liability_usd)}  delta={-3.4} spark_color="var(--amber)" sparkline={generateSeries(20, 180, 4, -0.1, 11)} />
      </div>

      {/* Capital flow (sankey-ish) */}
      <div style={{ padding: "0 var(--space-6) var(--space-3)" }}>
        <div className="section-title"><span>Capital flow · 12-month trailing</span><span className="dim" style={{ fontWeight: 400, textTransform: "none", letterSpacing: 0, marginRight: 8 }}>Inputs → operations → outputs</span></div>
        <CapitalFlow />
      </div>

      {/* Farms table with mini financials */}
      <div style={{ padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="section-title"><span>Per-farm P&amp;L</span></div>
        <div className="card" style={{ padding: 0 }}>
          <DataTable rows={FARMS.map((f) => {
            const cost = f.revenue_usd * (0.55 + ((f.id.charCodeAt(2) % 5) * 0.02));
            const credits = Math.round(f.acres * 0.4) * 28;
            const profit = f.revenue_usd - cost + credits;
            return { ...f, cost, credits, profit, margin: profit / f.revenue_usd };
          })} columns={[
            { key: "name", label: "Farm", render: (r) => <div><div style={{ fontWeight: 500 }}>{r.name}</div><div className="dim mono" style={{ fontSize: 10 }}>{r.id} · {r.region}</div></div> },
            { key: "crop", label: "Crop" },
            { key: "acres", label: "Acres", mono: true, align: "right", render: (r) => fmtNum(r.acres) },
            { key: "revenue_usd", label: "Revenue", mono: true, align: "right", render: (r) => fmtMoney(r.revenue_usd) },
            { key: "cost", label: "Costs", mono: true, align: "right", render: (r) => fmtMoney(r.cost), dim: true },
            { key: "credits", label: "Carbon", mono: true, align: "right", render: (r) => <span style={{ color: "var(--cyan)" }}>{fmtMoney(r.credits)}</span> },
            { key: "profit", label: "Net", mono: true, align: "right", render: (r) => <span style={{ color: r.profit > 0 ? "var(--green)" : "var(--rose)", fontWeight: 500 }}>{fmtMoney(r.profit)}</span> },
            { key: "margin", label: "Margin", align: "right", render: (r) => (
              <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "flex-end" }}>
                <Bar value={r.margin * 100} max={50} color="var(--cyan)" />
                <span className="mono tnum" style={{ width: 40, textAlign: "right" }}>{fmtPct(r.margin, 1)}</span>
              </div>
            ) },
          ]} />
        </div>
      </div>
    </div>
  );
}

// Sankey-style capital flow
function CapitalFlow() {
  const sources = [
    { id: "ops",    label: "Operations",    value: 5800000, color: "var(--cyan)" },
    { id: "carbon", label: "Carbon credits", value: 122300,  color: "var(--green)" },
    { id: "inputs", label: "Input costs",    value: -3200000, color: "var(--amber)" },
    { id: "labor",  label: "Labor",          value: -1450000, color: "var(--violet)" },
    { id: "fin",    label: "Financing",      value: -180000,  color: "var(--rose)" },
  ];
  const net = sources.reduce((s, x) => s + x.value, 0);
  const w = 1100, h = 220;
  const padL = 20, padR = 20, padT = 24, padB = 24;
  const midX = w / 2;
  const totalAbs = sources.reduce((s, x) => s + Math.abs(x.value), 0);
  const usable = h - padT - padB;
  let yPos = padT;
  const flows = sources.map((s) => {
    const sh = (Math.abs(s.value) / totalAbs) * usable;
    const flow = { ...s, y0: yPos, y1: yPos + sh, height: sh };
    yPos += sh;
    return flow;
  });

  return (
    <div className="card" style={{ padding: 16, overflow: "hidden" }}>
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", display: "block" }}>
        {/* Left labels (sources) */}
        {flows.map((f) => {
          // Curve to center node
          const ctrlX = (padL + 240 + midX) / 2;
          const cy = (f.y0 + f.y1) / 2;
          const targetY = h / 2;
          return (
            <g key={f.id}>
              <path d={`
                M${padL + 240},${f.y0}
                C${ctrlX},${f.y0} ${ctrlX},${targetY - f.height / 2} ${midX - 60},${targetY - f.height / 2}
                L${midX - 60},${targetY + f.height / 2}
                C${ctrlX},${targetY + f.height / 2} ${ctrlX},${f.y1} ${padL + 240},${f.y1} Z
              `} fill={f.color} opacity="0.3" />
              {/* source rect */}
              <rect x={padL} y={f.y0} width="240" height={f.height} fill={f.color} opacity="0.85" rx="2" />
              <text x={padL + 12} y={f.y0 + 16} fontSize="11" fill="var(--bg)" fontWeight="600">{f.label}</text>
              <text x={padL + 12} y={f.y0 + 30} fontSize="10" fill="var(--bg)" opacity="0.85" fontFamily="var(--font-mono)">
                {f.value > 0 ? "+" : ""}{fmtMoney(f.value)}
              </text>
            </g>
          );
        })}
        {/* Center: net */}
        <rect x={midX - 60} y={padT} width="120" height={h - padT - padB} fill="var(--surface-2)" stroke="var(--border-strong)" rx="6" />
        <text x={midX} y={h / 2 - 16} fontSize="11" textAnchor="middle" fill="var(--text-dim)" textTransform="uppercase">Net flow</text>
        <text x={midX} y={h / 2 + 6} fontSize="22" fontWeight="700" textAnchor="middle" fill={net > 0 ? "var(--green)" : "var(--rose)"} fontFamily="var(--font-mono)">{fmtMoney(net)}</text>
        <text x={midX} y={h / 2 + 24} fontSize="10" textAnchor="middle" fill="var(--text-faint)">12-mo trailing</text>
        {/* Right: outputs distribution */}
        {[
          { label: "Retained earnings", v: net * 0.55, color: "var(--green)" },
          { label: "Capex reinvested",  v: net * 0.30, color: "var(--cyan)" },
          { label: "Distributions",     v: net * 0.15, color: "var(--violet)" },
        ].map((o, i) => {
          const oh = (o.v / net) * (h - padT - padB);
          const oy = padT + [0, (h - padT - padB) * 0.55, (h - padT - padB) * 0.85][i];
          const ctrlX = (midX + 60 + w - padR - 240) / 2;
          const cy = oy + oh / 2;
          const targetMidY = h / 2;
          return (
            <g key={o.label}>
              <path d={`
                M${midX + 60},${targetMidY - oh / 2}
                C${ctrlX},${targetMidY - oh / 2} ${ctrlX},${oy} ${w - padR - 240},${oy}
                L${w - padR - 240},${oy + oh}
                C${ctrlX},${oy + oh} ${ctrlX},${targetMidY + oh / 2} ${midX + 60},${targetMidY + oh / 2} Z
              `} fill={o.color} opacity="0.25" />
              <rect x={w - padR - 240} y={oy} width="240" height={oh} fill={o.color} opacity="0.85" rx="2" />
              <text x={w - padR - 240 + 12} y={oy + 16} fontSize="11" fill="var(--bg)" fontWeight="600">{o.label}</text>
              <text x={w - padR - 240 + 12} y={oy + 30} fontSize="10" fill="var(--bg)" opacity="0.85" fontFamily="var(--font-mono)">{fmtMoney(o.v)}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

// ==================== GHG TAX ====================
function FtGhgTax() {
  const { REGIONS, CROPS, GHG, FARMS } = window.AGB_DATA;
  const [region, setRegion] = fnUseState("ON");
  const [crop, setCrop] = fnUseState("corn");
  const [acres, setAcres] = fnUseState(1500);
  const [n_rate, setN_rate] = fnUseState(180);
  const [carbon_price, setCarbon_price] = fnUseState(28);
  const [adoption, setAdoption] = fnUseState(0.6); // % of farm using NitroSense

  const r = REGIONS.find((x) => x.id === region);
  const c = CROPS.find((x) => x.id === crop);

  // Calculations
  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); // 40% reduction at full adoption
  const avoided_co2e_t = baseline_co2e_t - reduced_co2e_t;
  const tax_liability = reduced_co2e_t * carbon_price * r.tax_rate * 100; // simplified
  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;

  return (
    <div>
      <PageHeader
        eyebrow="Fintech · GHG tax"
        title="GHG emissions tax estimator"
        sub="Drive the inputs. The model converts sensor-verified nitrogen behaviour into projected tax liability and carbon credit value, per region."
      />
      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 12, padding: "0 var(--space-6) var(--space-6)" }}>
        {/* Inputs */}
        <div className="card" style={{ alignSelf: "flex-start", position: "sticky", top: 16 }}>
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Scenario inputs</div></div>
          <div className="card-bd" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Knob label="Region" inline>
              <select className="input" value={region} onChange={(e) => setRegion(e.target.value)}>
                {REGIONS.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
              </select>
            </Knob>
            <Knob label="Crop" inline>
              <select className="input" value={crop} onChange={(e) => setCrop(e.target.value)}>
                {CROPS.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
              </select>
            </Knob>
            <Slider label="Acres" value={acres} min={50} max={10000} step={50} onChange={setAcres} suffix="ac" />
            <Slider label="Nitrogen rate" value={n_rate} min={20} max={300} step={5} onChange={setN_rate} suffix="lb/ac" />
            <Slider label="Carbon price" value={carbon_price} min={5} max={120} step={1} onChange={setCarbon_price} prefix="$" suffix="/tCO₂e" />
            <Slider label="NitroSense adoption" value={adoption} min={0} max={1} step={0.05} onChange={setAdoption} fmt={(v) => fmtPct(v, 0)} />
            <div style={{ padding: 10, background: "var(--bg-elev)", borderRadius: 8, fontSize: 11, color: "var(--text-dim)" }}>
              <strong style={{ color: "var(--text-2)" }}>Method:</strong> IPCC Tier 1 N₂O factor (0.0146 kg N₂O / lb N applied), GWP 265, regional tax rate {fmtPct(r.tax_rate, 2)}, with up to 40% reduction at full NitroSense adoption per ECCC 2023.
            </div>
          </div>
        </div>
        {/* Outputs */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div className="card">
            <div className="card-hd">
              <div style={{ fontSize: 13, fontWeight: 500 }}>Projected outcomes</div>
              <div className="dim" style={{ fontSize: 11 }}>{r.name} · {c.name} · {fmtNum(acres)} ac</div>
            </div>
            <div className="card-bd" style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
              <Gauge value={reduced_co2e_t} min={0} max={baseline_co2e_t} w={260} color="var(--cyan)" unit="tCO₂e/yr"
                     label={`reduced from ${baseline_co2e_t.toFixed(0)} t baseline`}
                     segments={[{ at: 0, label: "best" }, { at: baseline_co2e_t, label: "baseline" }]} />
              <Gauge value={Math.max(0, net)} min={-baseline_tax} max={baseline_tax} w={260} color={net >= 0 ? "var(--green)" : "var(--rose)"}
                     unit="$/yr" label={net >= 0 ? "net benefit" : "net cost"} />
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
            <Stat label="Baseline emissions" value={baseline_co2e_t.toFixed(0)} unit="tCO₂e" sparkline={generateSeries(20, 100, 2, 0, 1)} spark_color="var(--rose)" />
            <Stat label="With NitroSense"    value={reduced_co2e_t.toFixed(0)} unit="tCO₂e" sparkline={generateSeries(20, 70, 2, -0.2, 2)} spark_color="var(--cyan)" />
            <Stat label="Avoided"            value={avoided_co2e_t.toFixed(0)} unit="tCO₂e" sparkline={generateSeries(20, 30, 1, 0.2, 3)} spark_color="var(--green)" />
            <Stat label="Credit value"       value={fmtMoney(credit_value)}     sparkline={generateSeries(20, 12, 0.8, 0.1, 4)} spark_color="var(--green)" />
          </div>

          <div className="card">
            <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Per-farm projection</div></div>
            <div className="card-bd" style={{ padding: 0 }}>
              <DataTable rows={FARMS.slice(0, 6).map((f) => {
                const acres_f = f.acres;
                const n_f = acres_f * 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)?.tax_rate || 0.015) * 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 };
              })} columns={[
                { key: "name", label: "Farm" },
                { key: "region", label: "Region", mono: true, dim: true },
                { key: "acres", label: "Acres", mono: true, align: "right", render: (r) => fmtNum(r.acres) },
                { key: "base_t", label: "Baseline", mono: true, align: "right", render: (r) => r.base_t.toFixed(0) + " t" },
                { key: "red_t",  label: "Projected", mono: true, align: "right", render: (r) => r.red_t.toFixed(0) + " t" },
                { key: "tax_f",  label: "Tax",       mono: true, align: "right", render: (r) => <span style={{ color: "var(--rose)" }}>{fmtMoney(r.tax_f)}</span> },
                { key: "credit_f", label: "Credits", mono: true, align: "right", render: (r) => <span style={{ color: "var(--green)" }}>{fmtMoney(r.credit_f)}</span> },
                { key: "net_f", label: "Net", mono: true, align: "right", render: (r) => <span style={{ fontWeight: 600, color: r.net_f >= 0 ? "var(--green)" : "var(--rose)" }}>{fmtMoney(r.net_f)}</span> },
              ]} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Knob({ label, children, inline }) {
  return (
    <div>
      <div className="dim" style={{ fontSize: 11, marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 500 }}>{label}</div>
      {children}
    </div>
  );
}

function Slider({ label, value, min, max, step, onChange, suffix = "", prefix = "", fmt }) {
  const display = fmt ? fmt(value) : `${prefix}${typeof value === "number" ? (step < 1 ? value.toFixed(2) : value.toLocaleString()) : value}${suffix ? " " + suffix : ""}`;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
        <div className="dim" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 500 }}>{label}</div>
        <div className="mono tnum" style={{ fontSize: 12, color: "var(--primary)" }}>{display}</div>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
             onChange={(e) => onChange(+e.target.value)}
             style={{
               width: "100%", appearance: "none", height: 4, borderRadius: 999,
               background: `linear-gradient(to right, var(--primary) 0%, var(--primary) ${((value - min) / (max - min)) * 100}%, var(--surface-2) ${((value - min) / (max - min)) * 100}%)`,
               outline: "none",
             }} />
    </div>
  );
}

// ==================== CARBON CREDITS ====================
function FtCarbon() {
  const { CARBON_MARKET, FARMS } = window.AGB_DATA;
  const [selected, setSelected] = fnUseState(CARBON_MARKET[0].id);
  const sel = CARBON_MARKET.find((m) => m.id === selected);

  return (
    <div>
      <PageHeader
        eyebrow="Fintech · Carbon"
        title="Carbon credit marketplace"
        sub="Sensor-verified credits generated by Agrobotic devices, listed across major registries. Buy, sell, or retire from one console."
        actions={<><button className="btn" onClick={actAuditTrail}><Icon name="download" size={14} /> Audit trail</button><button className="btn primary" onClick={actListCredits}><Icon name="plus" size={14} /> List credits</button></>}
      />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, padding: "0 var(--space-6) var(--space-4)" }}>
        <Stat label="Available credits" value={fmtNum(CARBON_MARKET.reduce((s, m) => s + m.tons_avail, 0))} unit="tCO₂e" delta={6.4} spark_color="var(--cyan)" sparkline={generateSeries(20, 18, 0.6, 0.06, 1)} />
        <Stat label="Avg price" value={fmtMoney(CARBON_MARKET.reduce((s, m) => s + m.price, 0) / CARBON_MARKET.length, 2)} unit="/ tCO₂e" delta={2.3} spark_color="var(--green)" sparkline={generateSeries(20, 29, 0.5, 0.04, 3)} />
        <Stat label="Vol 24h" value={fmtNum(CARBON_MARKET.reduce((s, m) => s + m.vol, 0))} unit="tCO₂e" delta={11.2} spark_color="var(--cyan)" sparkline={generateSeries(20, 60, 4, 0.2, 5)} />
        <Stat label="Realized · YTD" value={fmtMoney(122300)} delta={8.9} spark_color="var(--green)" sparkline={generateSeries(20, 110, 5, 0.4, 7)} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 12, padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card" style={{ padding: 0 }}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Order book</div>
          </div>
          <DataTable rows={CARBON_MARKET} idKey="id" selectedId={selected} onRowClick={(r) => setSelected(r.id)} columns={[
            { key: "name", label: "Credit", render: (r) => (
              <div>
                <div style={{ fontWeight: 500 }}>{r.name}</div>
                <div className="dim mono" style={{ fontSize: 10 }}>{r.id} · {r.standard}</div>
              </div>
            ) },
            { key: "source", label: "Source", render: (r) => <span className="tag info" style={{ fontSize: 10 }}>{r.source}</span> },
            { key: "vintage", label: "Vintage", mono: true },
            { key: "price", label: "Price", mono: true, align: "right", render: (r) => fmtMoney(r.price, 2) },
            { key: "change", label: "24h", mono: true, align: "right", render: (r) => (
              <span style={{ color: r.change >= 0 ? "var(--green)" : "var(--rose)" }}>{r.change >= 0 ? "+" : ""}{r.change.toFixed(1)}%</span>
            ) },
            { key: "vol", label: "Vol", mono: true, align: "right", render: (r) => fmtNum(r.vol) },
            { key: "tons_avail", label: "Available", mono: true, align: "right", render: (r) => fmtNum(r.tons_avail) },
          ]} />
        </div>

        {/* Detail panel */}
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div className="card-hd">
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{sel.name}</div>
              <div className="dim mono" style={{ fontSize: 11, marginTop: 2 }}>{sel.id} · {sel.standard} · Vintage {sel.vintage}</div>
            </div>
            <span className="tag info">{sel.source}</span>
          </div>
          <div className="card-bd" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
              <div>
                <div className="dim" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Last price</div>
                <div className="mono tnum" style={{ fontSize: 30, fontWeight: 700 }}>{fmtMoney(sel.price, 2)}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="mono" style={{ fontSize: 14, color: sel.change >= 0 ? "var(--green)" : "var(--rose)" }}>{sel.change >= 0 ? "▲" : "▼"} {Math.abs(sel.change)}%</div>
                <div className="dim" style={{ fontSize: 11 }}>24h change</div>
              </div>
            </div>
            <AreaChart series={generateSeries(60, sel.price, 0.6, 0.02, sel.id.charCodeAt(0))} h={180} color="var(--green)" yLabel="$ / tCO₂e" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <button className="btn primary" style={{ justifyContent: "center", padding: "12px 0", fontSize: 14 }} onClick={() => actBuyCredit(sel)}>Buy {fmtNum(sel.tons_avail)} t</button>
              <button className="btn" style={{ justifyContent: "center", padding: "12px 0", fontSize: 14 }} onClick={() => actSellCredit(sel)}>Sell / list</button>
            </div>
            <div className="h-rule" />
            <div>
              <div className="section-title" style={{ margin: "0 0 8px" }}>Backing data</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 12 }}>
                <Row k="Verifier" v={sel.standard} mono />
                <Row k="Tons available" v={fmtNum(sel.tons_avail)} mono />
                <Row k="Sensor source" v={sel.source} />
                <Row k="Farms contributing" v="3 farms" />
                <Row k="Last audit" v="2025-03-18" mono />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({ k, v, mono }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid var(--border-faint)" }}>
      <span className="dim">{k}</span>
      <span className={mono ? "mono" : ""}>{v}</span>
    </div>
  );
}

// ==================== ROI ====================
function FtRoi() {
  const { ROI_PRESETS, FAMILIES, FARMS } = window.AGB_DATA;
  const [family, setFamily] = fnUseState("NitroSense");
  const preset = ROI_PRESETS[family];
  const [acres, setAcres] = fnUseState(1500);
  const [cows, setCows] = fnUseState(200);

  const calc = fnUseMemo(() => {
    if (family === "NitroSense") {
      const capex = preset.capex_per_ac * acres;
      const opex = preset.opex_per_ac_yr * acres;
      const n_saved_usd = acres * 180 * 0.62 * preset.n_savings_pct; // 180 lb/ac × $0.62/lb
      const yield_lift_usd = acres * 178 * 4.32 * preset.yield_lift_pct;
      const credit_usd = acres * 0.4 * 28 * preset.n2o_reduction_pct;
      const annual_benefit = n_saved_usd + yield_lift_usd + credit_usd;
      const payback_months = (capex / (annual_benefit / 12)) || 0;
      const roi = (annual_benefit - opex) / capex;
      return { capex, opex, annual_benefit, roi, payback_months,
        breakdown: [
          { label: "Nitrogen savings",   v: n_saved_usd, color: "var(--green)" },
          { label: "Yield uplift",       v: yield_lift_usd, color: "var(--cyan)" },
          { label: "Carbon credits",     v: credit_usd, color: "var(--violet)" },
          { label: "OpEx",               v: -opex, color: "var(--amber)" },
        ]};
    } else if (family === "EcoSense") {
      const capex = preset.capex_per_cow * cows;
      const opex = preset.opex_per_cow_yr * cows;
      const feed_savings = cows * 6 * 365 * 0.4 * preset.feed_savings_pct; // crude feed cost proxy
      const credit_usd = cows * preset.carbon_credit_per_cow_yr;
      const annual_benefit = feed_savings + credit_usd;
      const payback_months = (capex / (annual_benefit / 12)) || 0;
      const roi = (annual_benefit - opex) / capex;
      return { capex, opex, annual_benefit, roi, payback_months,
        breakdown: [
          { label: "Feed savings",       v: feed_savings, color: "var(--green)" },
          { label: "Carbon credits",     v: credit_usd, color: "var(--violet)" },
          { label: "OpEx",               v: -opex, color: "var(--amber)" },
        ] };
    } else if (family === "ForestSentinel" || family === "AirWatch") {
      const capex = preset.capex_per_node * 12;
      const opex = preset.opex_per_node_yr * 12;
      const benefit = family === "ForestSentinel" ? 18400 : 11600;
      const annual_benefit = benefit;
      return { capex, opex, annual_benefit, roi: (annual_benefit - opex) / capex, payback_months: (capex / (annual_benefit / 12)),
        breakdown: [
          { label: family === "ForestSentinel" ? "Insurance + fire risk" : "Worker safety + compliance", v: benefit, color: "var(--green)" },
          { label: "OpEx", v: -opex, color: "var(--amber)" },
        ] };
    } else if (family === "EcoNitro") {
      const nodes = Math.max(1, Math.round(acres / 200));
      const capex = preset.capex_per_node * nodes;
      const opex = preset.opex_per_node_yr * nodes;
      const n_saved = acres * 180 * 0.62 * preset.n_savings_pct;
      const credit = nodes * preset.combined_credit_per_node_yr;
      const annual_benefit = n_saved + credit;
      return { capex, opex, annual_benefit, roi: (annual_benefit - opex) / capex, payback_months: (capex / (annual_benefit / 12)),
        breakdown: [
          { label: "Nitrogen savings",   v: n_saved, color: "var(--green)" },
          { label: "Combined credits (N₂O+CH₄)", v: credit, color: "var(--violet)" },
          { label: "OpEx",               v: -opex, color: "var(--amber)" },
        ] };
    } else {
      const capex = (preset.capex_per_node || preset.capex_per_zone) * 12;
      const opex = (preset.opex_per_node_yr || preset.opex_per_zone_yr) * 12;
      const benefit = 18400 + (family === "AquaSentinel" ? 12200 : 0);
      const annual_benefit = benefit;
      return { capex, opex, annual_benefit, roi: (annual_benefit - opex) / capex, payback_months: (capex / (annual_benefit / 12)),
        breakdown: [
          { label: "Insurance/compliance savings", v: benefit, color: "var(--green)" },
          { label: "OpEx",                          v: -opex, color: "var(--amber)" },
        ] };
    }
  }, [family, acres, cows]);

  return (
    <div>
      <PageHeader
        eyebrow="Fintech · ROI"
        title="Sensor adoption ROI"
        sub="What does a farm save (or earn) by deploying Agrobotic devices? The model blends input savings, yield lift, and credit revenue."
      />
      <div style={{ padding: "0 var(--space-6) var(--space-3)" }}>
        <Tabs variant="pill" active={family} onChange={setFamily} tabs={Object.keys(FAMILIES).map((f) => ({ id: f, label: f }))} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 12, padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card" style={{ alignSelf: "flex-start" }}>
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Farm inputs</div></div>
          <div className="card-bd" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {family === "EcoSense"
              ? <Slider label="Herd size" value={cows} min={20} max={2000} step={10} onChange={setCows} suffix="cows" />
              : <Slider label="Acres deployed" value={acres} min={50} max={10000} step={50} onChange={setAcres} suffix="ac" />}
            <div style={{ padding: 12, background: "var(--bg-elev)", borderRadius: 8, fontSize: 11, color: "var(--text-dim)", lineHeight: 1.5 }}>
              <strong style={{ color: "var(--text-2)", display: "block", marginBottom: 6 }}>{family} preset</strong>
              {family === "NitroSense" && <>CAPEX ${preset.capex_per_ac}/ac · OpEx ${preset.opex_per_ac_yr}/ac/yr<br/>N savings {fmtPct(preset.n_savings_pct, 0)} · yield +{fmtPct(preset.yield_lift_pct, 0)} · N₂O -{fmtPct(preset.n2o_reduction_pct, 0)}</>}
              {family === "EcoSense" && <>CAPEX ${preset.capex_per_cow}/cow · OpEx ${preset.opex_per_cow_yr}/cow/yr<br/>CH₄ -{fmtPct(preset.ch4_reduction_pct, 0)} · feed -{fmtPct(preset.feed_savings_pct, 0)} · credit ${preset.carbon_credit_per_cow_yr}/cow/yr</>}
              {family === "ForestSentinel" && <>CAPEX ${preset.capex_per_node}/node · OpEx ${preset.opex_per_node_yr}/node/yr<br/>Insurance discount {fmtPct(preset.insurance_discount_pct, 0)} on premium</>}
              {family === "AquaSentinel" && <>CAPEX ${preset.capex_per_zone}/zone · OpEx ${preset.opex_per_zone_yr}/zone/yr<br/>Water -{fmtPct(preset.water_savings_pct, 0)} · runoff compliance verified</>}
              {family === "AirWatch" && <>CAPEX ${preset.capex_per_node}/node · OpEx ${preset.opex_per_node_yr}/node/yr<br/>Worker safety + community air quality compliance</>}
              {family === "EcoNitro" && <>CAPEX ${preset.capex_per_node}/node · OpEx ${preset.opex_per_node_yr}/node/yr<br/>N -{fmtPct(preset.n_savings_pct, 0)} · CH₄ -{fmtPct(preset.ch4_reduction_pct, 0)} · N₂O -{fmtPct(preset.n2o_reduction_pct, 0)} · combined credit ${preset.combined_credit_per_node_yr}/node/yr</>}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
            <Stat label="CAPEX" value={fmtMoney(calc.capex)} sparkline={generateSeries(20, 100, 2, 0, 1)} spark_color="var(--amber)" />
            <Stat label="Annual benefit" value={fmtMoney(calc.annual_benefit)} delta={11.4} sparkline={generateSeries(20, 60, 3, 0.3, 2)} spark_color="var(--green)" />
            <Stat label="ROI · year 1" value={fmtPct(calc.roi)} delta={null} sparkline={generateSeries(20, 30, 1, 0.1, 3)} spark_color="var(--green)" />
            <Stat label="Payback" value={calc.payback_months.toFixed(0)} unit="months" sparkline={generateSeries(20, 18, 1, -0.05, 4)} spark_color="var(--cyan)" />
          </div>
          <div className="card">
            <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Benefit breakdown · year 1</div></div>
            <div className="card-bd">
              <StackBar segments={calc.breakdown.map((b) => ({ ...b, value: Math.abs(b.v) }))} h={14} />
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, marginTop: 14 }}>
                {calc.breakdown.map((b) => (
                  <div key={b.label} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12 }}>
                    <span style={{ width: 12, height: 12, borderRadius: 2, background: b.color }} />
                    <span style={{ flex: 1 }}>{b.label}</span>
                    <span className="mono tnum" style={{ color: b.v >= 0 ? "var(--green)" : "var(--rose)" }}>{b.v >= 0 ? "+" : ""}{fmtMoney(b.v)}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>5-year cashflow</div></div>
            <div className="card-bd">
              <BarChart h={180} color="var(--green)"
                        data={[-calc.capex, calc.annual_benefit - calc.opex, calc.annual_benefit - calc.opex + 1000, calc.annual_benefit - calc.opex + 2000, calc.annual_benefit - calc.opex + 3500].map((v) => Math.abs(v))}
                        labels={["Yr 0", "Yr 1", "Yr 2", "Yr 3", "Yr 4"]} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== MARKETS ====================
function FtMarkets() {
  const { CROPS } = window.AGB_DATA;
  return (
    <div>
      <PageHeader eyebrow="Fintech · Markets" title="Crop pricing & commodity forecasts"
                  sub="Spot prices, futures, and an Agrobotic-flavoured forecast model trained on weather, yield, and on-farm sensor signals." />
      <div style={{ padding: "0 var(--space-6) var(--space-6)", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 12 }}>
        <div className="card">
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Corn · $/bu · 60-day</div><Tabs variant="pill" active="60" onChange={() => {}} tabs={[{ id: "30", label: "30D" }, { id: "60", label: "60D" }, { id: "180", label: "180D" }]} /></div>
          <div className="card-bd"><AreaChart series={generateSeries(60, 4.32, 0.08, 0.005, 9)} h={260} color="var(--amber)" yLabel="$/bu" labels={Array.from({length:60},(_,i)=>i%10===0?`D${i}`:"")} /></div>
        </div>
        <div className="card" style={{ padding: 0 }}>
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Commodities</div></div>
          <DataTable rows={CROPS.map((c, i) => ({
            ...c, change: ((i * 7 % 21) - 10) / 10,
            spark: generateSeries(20, 100, 3, 0, c.id.charCodeAt(0))
          }))} columns={[
            { key: "name", label: "Crop", render: (r) => <div style={{ fontWeight: 500 }}>{r.name}</div> },
            { key: "price_per_bu", label: "Price", mono: true, align: "right", render: (r) => r.price_per_bu ? "$" + r.price_per_bu.toFixed(2) : "—" },
            { key: "unit", label: "Unit", dim: true },
            { key: "change", label: "24h", mono: true, align: "right", render: (r) => <span style={{ color: r.change >= 0 ? "var(--green)" : "var(--rose)" }}>{r.change >= 0 ? "+" : ""}{(r.change * 100).toFixed(1)}%</span> },
            { key: "spark", label: "30D", render: (r) => <Sparkline data={r.spark} color="var(--primary)" w={80} h={22} fill={false} /> },
          ]} />
        </div>

        <div className="card" style={{ gridColumn: "span 2" }}>
          <div className="card-hd">
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Forecast accuracy by crop</div>
              <div className="dim" style={{ fontSize: 11, marginTop: 2 }}>Model: weather + on-farm yield sensors + USDA historicals. Higher = better.</div>
            </div>
          </div>
          <div className="card-bd"><BarChart h={200} color="var(--cyan)" data={[88, 82, 75, 70, 91, 67, 79]} labels={["Corn", "Soy", "Wheat", "Canola", "Alfalfa", "Blueberry", "Dairy"]} /></div>
        </div>
      </div>
    </div>
  );
}

// ==================== WATER / INPUTS ====================
function FtWater() {
  const { FARMS, REGIONS } = window.AGB_DATA;
  return (
    <div>
      <PageHeader eyebrow="Fintech · Inputs" title="Water & input cost tracking"
                  sub="Costs per acre across water, fertilizer, fuel, labor. Compare against region peers. Sensor data ties consumption to fields." />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, padding: "0 var(--space-6) var(--space-4)" }}>
        <Stat label="Water · YTD" value="$418k" delta={-6.2} sparkline={generateSeries(20, 45, 2, -0.2, 1)} spark_color="var(--cyan)" />
        <Stat label="Fertilizer · YTD" value="$1.24M" delta={-12.4} sparkline={generateSeries(20, 130, 4, -0.4, 3)} spark_color="var(--green)" />
        <Stat label="Fuel · YTD" value="$284k" delta={2.1} sparkline={generateSeries(20, 28, 1.5, 0.1, 5)} spark_color="var(--amber)" />
        <Stat label="Labor · YTD" value="$1.45M" delta={5.4} sparkline={generateSeries(20, 130, 3, 0.3, 7)} spark_color="var(--violet)" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card">
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Cost per acre — by farm</div></div>
          <div className="card-bd">
            <BarChart h={240} color="var(--cyan)"
                      data={FARMS.map((f, i) => 180 + (i * 23) % 80 + (f.region === "CA" ? 60 : 0))}
                      labels={FARMS.map((f) => f.name.split(" ")[0])} />
          </div>
        </div>
        <div className="card">
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Water cost by region</div></div>
          <div className="card-bd">
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {REGIONS.map((r) => (
                <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12 }}>
                  <div className="mono" style={{ width: 36 }}>{r.id}</div>
                  <div style={{ flex: 1 }}><Bar value={r.water_usd_m3} max={0.1} color="var(--cyan)" /></div>
                  <div className="mono tnum" style={{ width: 70, textAlign: "right" }}>${r.water_usd_m3.toFixed(3)}/m³</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== LENDING ====================
function FtLending() {
  const { FARMS } = window.AGB_DATA;
  const loans = FARMS.slice(0, 6).map((f, i) => ({
    ...f,
    principal: Math.round(f.revenue_usd * 0.3),
    rate: 4.2 + (i * 0.3),
    term: 5 + i,
    score: 92 - (i * 4),
    status: i < 4 ? "Active" : i === 4 ? "Pending" : "Approved",
  }));
  return (
    <div>
      <PageHeader eyebrow="Fintech · Lending"
                  title="Sensor-verified financing"
                  sub="On-farm data raises the floor for lenders — yield records, soil health, GHG behaviour all factor into a transparent risk score."
                  actions={<button className="btn primary" onClick={actNewFacility}><Icon name="plus" size={14} /> New facility</button>} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, padding: "0 var(--space-6) var(--space-4)" }}>
        <Stat label="Outstanding" value={fmtMoney(loans.reduce((s, l) => s + l.principal, 0))} delta={4.2} sparkline={generateSeries(20, 110, 2, 0.1, 1)} spark_color="var(--cyan)" />
        <Stat label="Avg rate" value={(loans.reduce((s, l) => s + l.rate, 0) / loans.length).toFixed(2) + "%"} delta={-0.4} sparkline={generateSeries(20, 5, 0.1, -0.01, 3)} spark_color="var(--green)" />
        <Stat label="Avg score" value={Math.round(loans.reduce((s, l) => s + l.score, 0) / loans.length)} delta={2.1} sparkline={generateSeries(20, 85, 1, 0.05, 5)} />
        <Stat label="Default rate" value="0.8%" delta={-0.3} spark_color="var(--green)" sparkline={generateSeries(20, 1, 0.1, -0.02, 7)} />
      </div>
      <div style={{ padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card" style={{ padding: 0 }}>
          <DataTable rows={loans} columns={[
            { key: "name", label: "Borrower", render: (r) => <div><div style={{ fontWeight: 500 }}>{r.name}</div><div className="dim mono" style={{ fontSize: 10 }}>{r.id} · {r.region}</div></div> },
            { key: "principal", label: "Principal", mono: true, align: "right", render: (r) => fmtMoney(r.principal) },
            { key: "rate", label: "Rate", mono: true, align: "right", render: (r) => r.rate.toFixed(2) + "%" },
            { key: "term", label: "Term", mono: true, align: "right", render: (r) => r.term + "y" },
            { key: "score", label: "Agrobotic Score", align: "right", render: (r) => (
              <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "flex-end" }}>
                <Bar value={r.score} color={r.score > 85 ? "var(--green)" : r.score > 70 ? "var(--amber)" : "var(--rose)"} />
                <span className="mono tnum" style={{ width: 30, textAlign: "right" }}>{r.score}</span>
              </div>
            ) },
            { key: "verified", label: "Data feed", render: () => <span className="tag ok">live</span> },
            { key: "status", label: "Status", render: (r) => <span className={"tag " + (r.status === "Active" ? "ok" : r.status === "Pending" ? "warn" : "info")}>{r.status}</span> },
          ]} />
        </div>
      </div>
    </div>
  );
}

// ==================== INSURANCE ====================
function FtInsurance() {
  const { FARMS } = window.AGB_DATA;
  const policies = 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),
  }));
  return (
    <div>
      <PageHeader eyebrow="Fintech · Insurance"
                  title="Risk-priced crop insurance"
                  sub="Sensor data continuously re-prices coverage. Healthier sensor signal = lower premiums, higher payouts."
                  actions={<button className="btn primary" onClick={actQuotePolicy}><Icon name="shield" size={14} /> Quote new policy</button>} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, padding: "0 var(--space-6) var(--space-4)" }}>
        <Stat label="Coverage in force" value={fmtMoney(policies.reduce((s, p) => s + p.coverage, 0))} delta={3.2} sparkline={generateSeries(20, 18, 0.3, 0.05, 1)} />
        <Stat label="Premiums · YTD" value={fmtMoney(policies.reduce((s, p) => s + p.premium, 0))} delta={-4.8} sparkline={generateSeries(20, 65, 2, -0.1, 3)} spark_color="var(--green)" />
        <Stat label="Sensor discount avg" value={fmtPct(policies.reduce((s, p) => s + p.discount, 0) / policies.length, 0)} delta={2.1} spark_color="var(--green)" sparkline={generateSeries(20, 12, 0.4, 0.04, 5)} />
        <Stat label="Open claims" value="2" delta={-50} spark_color="var(--rose)" sparkline={generateSeries(20, 4, 0.5, -0.1, 7)} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 12, padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card" style={{ padding: 0 }}>
          <DataTable rows={policies} columns={[
            { key: "name", label: "Policy" },
            { key: "coverage", label: "Coverage", mono: true, align: "right", render: (r) => fmtMoney(r.coverage) },
            { key: "premium", label: "Premium", mono: true, align: "right", render: (r) => fmtMoney(r.premium) },
            { key: "risk", label: "Risk", render: (r) => <span className={"tag " + (r.risk === "Low" ? "ok" : r.risk === "Medium" ? "warn" : "bad")}>{r.risk}</span> },
            { key: "perils", label: "Perils", dim: true, render: (r) => r.perils.join(", ") },
            { key: "discount", label: "Discount", mono: true, align: "right", render: (r) => <span style={{ color: "var(--green)" }}>-{fmtPct(r.discount, 0)}</span> },
          ]} />
        </div>
        <div className="card">
          <div className="card-hd"><div style={{ fontSize: 13, fontWeight: 500 }}>Risk × Discount</div><span className="dim" style={{ fontSize: 11 }}>Each dot is a policy</span></div>
          <div className="card-bd">
            <Scatter w={420} h={240} xLabel="Health score" yLabel="Discount"
                     points={policies.map((p) => ({ x: p.health, y: p.discount * 100, r: 4 + (p.coverage / 1e6), color: p.risk === "Low" ? "var(--green)" : p.risk === "Medium" ? "var(--amber)" : "var(--rose)" }))} />
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== REPORTS ====================
function FtReports() {
  const reports = [
    { id: "R1", name: "ECCC Annual Emissions Report", period: "2024", category: "Regulatory", status: "Ready", size: "2.4MB" },
    { id: "R2", name: "Verra VCS Carbon Bundle",      period: "Q1 2025", category: "Carbon registry", status: "Ready", size: "8.2MB" },
    { id: "R3", name: "4R Nutrient Stewardship",       period: "2024", category: "Sustainability", status: "Ready", size: "1.1MB" },
    { id: "R4", name: "California SB 261 Climate Disclosure", period: "2024", category: "Regulatory", status: "Draft", size: "—" },
    { id: "R5", name: "Investor ESG Quarterly",         period: "Q1 2025", category: "Investor", status: "Ready", size: "3.6MB" },
    { id: "R6", name: "Lender data feed (monthly)",     period: "Mar 2025", category: "Lender", status: "Ready", size: "0.8MB" },
    { id: "R7", name: "Iowa Soybean Assoc. baseline",   period: "2024", category: "Partner", status: "Ready", size: "1.4MB" },
  ];
  return (
    <div>
      <PageHeader eyebrow="Fintech · Reports"
                  title="Sustainability & compliance exports"
                  sub="One-click sensor-backed reports for regulators, registries, lenders, and investors. All audit-trailed."
                  actions={<><button className="btn primary" onClick={actNewReport}><Icon name="plus" size={14} /> New report</button></>} />
      <div style={{ padding: "0 var(--space-6) var(--space-6)" }}>
        <div className="card" style={{ padding: 0 }}>
          <DataTable rows={reports} columns={[
            { key: "name", label: "Report", render: (r) => <div style={{ display: "flex", alignItems: "center", gap: 10 }}><Icon name="file" size={16} color="var(--primary)" /><div><div style={{ fontWeight: 500 }}>{r.name}</div><div className="dim mono" style={{ fontSize: 10 }}>{r.id}</div></div></div> },
            { key: "period", label: "Period", mono: true },
            { key: "category", label: "Category", render: (r) => <span className="tag info" style={{ fontSize: 10 }}>{r.category}</span> },
            { key: "status", label: "Status", render: (r) => <span className={"tag " + (r.status === "Ready" ? "ok" : "warn")}>{r.status}</span> },
            { key: "size", label: "Size", mono: true, dim: true, align: "right" },
            { key: "actions", label: "", render: (r) => <button className="btn primary" onClick={() => actExportReport(r)}><Icon name="download" size={13} /> Export</button> },
          ]} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  FtPortfolio, FtGhgTax, FtCarbon, FtRoi, FtMarkets, FtWater, FtLending, FtInsurance, FtReports,
});
