/* FORGE — Pump tenant Act 1-2 screens (S05, S06, S07, S10, S13, S14)
   Babel-standalone in-browser React. NO ES imports / exports.
   Globals used: React, navigate, getActiveTenant, registerPumpRoute, Icons.
   Hook destructures uniquely aliased to avoid global scope collisions. */

const { useState: uSA12, useMemo: uMA12, useEffect: uEA12 } = React;

// ───────── shared paper-deck atoms (mirror landing.jsx) ────────────
const A12_PAPER_BG       = "oklch(0.985 0.004 85)";
const A12_PAPER_BG_2     = "oklch(0.93 0.005 85)";
const A12_PAPER_BG_3     = "oklch(0.965 0.005 85)";
const A12_PAPER_INK      = "oklch(0.16 0.01 85)";
const A12_PAPER_INK_2    = "oklch(0.30 0.01 85)";
const A12_PAPER_INK_3    = "oklch(0.46 0.01 85)";
const A12_PAPER_INK_4    = "oklch(0.60 0.01 85)";
const A12_PAPER_LINE     = "oklch(0.84 0.006 85)";
const A12_PAPER_LINE_S   = "oklch(0.90 0.005 85)";
const A12_ACCENT         = "oklch(0.78 0.16 75)";
const A12_GREEN          = "oklch(0.66 0.13 145)";
const A12_RED            = "oklch(0.58 0.18 28)";
const A12_AMBER          = "oklch(0.78 0.13 70)";
const A12_BLUE           = "oklch(0.62 0.10 235)";
const A12_GRAY           = "oklch(0.78 0.005 85)";

const A12_FONT_UI    = "var(--font-ui)";
const A12_FONT_MONO  = "var(--font-mono)";
const A12_FONT_SERIF = "var(--font-serif)";

// Locale-aware money/date — degrades gracefully when forgeI18n not yet loaded.
function _a12_money(minor, currency, fallback) {
  const i18n = (typeof window !== "undefined") ? window.forgeI18n : null;
  if (i18n && typeof i18n.formatMoneyMinor === "function") {
    const out = i18n.formatMoneyMinor(minor, currency || "INR");
    if (out) return out;
  }
  return fallback;
}
function _a12_date(iso, fallback) {
  const i18n = (typeof window !== "undefined") ? window.forgeI18n : null;
  if (i18n && typeof i18n.formatDate === "function") {
    const out = i18n.formatDate(iso);
    if (out) return out;
  }
  return fallback || iso;
}

// shared root container style
function a12Root() {
  return {
    background: A12_PAPER_BG,
    color: A12_PAPER_INK,
    minHeight: "100vh",
    overflowY: "auto",
    fontFamily: A12_FONT_UI,
    fontSize: 14,
    lineHeight: 1.5,
    width: "100%",
    position: "absolute",
    inset: 0,
    WebkitFontSmoothing: "antialiased",
  };
}

function a12Container() {
  return { maxWidth: 1280, margin: "0 auto", padding: "32px 40px", width: "100%" };
}

function a12Mono() {
  return {
    fontFamily: A12_FONT_MONO,
    fontSize: 12,
    letterSpacing: "0.08em",
    textTransform: "uppercase",
    color: A12_PAPER_INK_3,
  };
}

function A12Card(props) {
  const merged = Object.assign({
    background: A12_PAPER_BG_3,
    border: `1px solid ${A12_PAPER_LINE}`,
    borderRadius: 10,
    padding: 20,
  }, props.style || {});
  return React.createElement("div", { style: merged }, props.children);
}

function A12Pill(props) {
  const tone = props.tone || "default";
  const palette = {
    default: { bg: A12_PAPER_BG_3, fg: A12_PAPER_INK_2, bd: A12_PAPER_LINE },
    accent:  { bg: A12_PAPER_BG_3, fg: A12_ACCENT,      bd: A12_ACCENT      },
    green:   { bg: A12_PAPER_BG_3, fg: A12_GREEN,       bd: A12_GREEN       },
    red:     { bg: A12_PAPER_BG_3, fg: A12_RED,         bd: A12_RED         },
    amber:   { bg: A12_PAPER_BG_3, fg: A12_AMBER,       bd: A12_AMBER       },
    blue:    { bg: A12_PAPER_BG_3, fg: A12_BLUE,        bd: A12_BLUE        },
    mute:    { bg: A12_PAPER_BG_2, fg: A12_PAPER_INK_3, bd: A12_PAPER_LINE  },
  }[tone] || { bg: A12_PAPER_BG_3, fg: A12_PAPER_INK_2, bd: A12_PAPER_LINE };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      height: 22, padding: "0 10px", borderRadius: 999,
      fontFamily: A12_FONT_MONO, fontSize: 12,
      letterSpacing: "0.08em", textTransform: "uppercase",
      border: `1px solid ${palette.bd}`,
      color: palette.fg, background: palette.bg,
    }}>{props.children}</span>
  );
}

function A12Btn(props) {
  const variant = props.variant || "primary";
  const [h, setH] = uSA12(false);
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center",
    gap: 8, cursor: "pointer", fontFamily: A12_FONT_UI, fontWeight: 600,
    letterSpacing: "-0.005em", borderRadius: 8,
    transition: "transform .12s ease, background .12s ease, border-color .12s ease",
    border: "1px solid transparent", whiteSpace: "nowrap", userSelect: "none",
    height: 38, padding: "0 18px", fontSize: 13,
    transform: h ? "translateY(-1px)" : "translateY(0)",
  };
  let palette;
  if (variant === "primary") {
    palette = { background: A12_ACCENT, color: "oklch(0.14 0.02 55)", borderColor: A12_ACCENT };
  } else if (variant === "secondary") {
    palette = { background: h ? A12_PAPER_INK : "transparent", color: h ? A12_PAPER_BG : A12_PAPER_INK, borderColor: A12_PAPER_INK };
  } else {
    palette = { background: h ? A12_PAPER_BG_2 : "transparent", color: A12_PAPER_INK_2, borderColor: A12_PAPER_LINE };
  }
  return (
    <button
      onClick={props.onClick}
      onMouseEnter={() => setH(true)}
      onMouseLeave={() => setH(false)}
      style={Object.assign({}, base, palette, props.style || {})}
    >{props.children}</button>
  );
}

function A12Header(props) {
  return (
    <div style={{ marginBottom: 28 }}>
      <div style={Object.assign({}, a12Mono(), { marginBottom: 8 })}>{props.eyebrow}</div>
      <h1 style={{
        fontFamily: A12_FONT_SERIF, fontSize: 34, fontWeight: 400,
        letterSpacing: "-0.015em", margin: 0, color: A12_PAPER_INK,
      }}>{props.title}</h1>
      {props.subtitle && (
        <div style={{ marginTop: 8, color: A12_PAPER_INK_3, fontSize: 14 }}>{props.subtitle}</div>
      )}
    </div>
  );
}

// helper: safe nav
function a12Nav(path) {
  if (typeof navigate === "function") navigate(path);
}

// ════════════════════════════════════════════════════════════════════
// S05 — RFQ intake
// ════════════════════════════════════════════════════════════════════
function ScreenRFQIntake() {
  const [customer, setCustomer]   = uSA12("Helios AgriFlow Pvt Ltd");
  const [shipTo, setShipTo]       = uSA12("Ahmedabad, IN");
  const [qty, setQty]             = uSA12(500);
  const [hp, setHp]               = uSA12("1.0");
  const [bore, setBore]           = uSA12('4"');
  const [head, setHead]           = uSA12(120);
  const [flow, setFlow]           = uSA12(160);
  const [privateLabel, setPL]     = uSA12(true);
  const [brand, setBrand]         = uSA12("Helios");
  const [due, setDue]             = uSA12("2026-06-24");
  const [notes, setNotes]         = uSA12(
    "Private-label run — Helios artwork rev B. BEE 3-star band. Cable 30m, mono-block. 14-day FAI window before pilot lot."
  );
  const [flash, setFlash] = uSA12("");
  uEA12(() => {
    if (!flash) return;
    const t = setTimeout(() => setFlash(""), 2400);
    return () => clearTimeout(t);
  }, [flash]);

  // ₹24.5 L = 24,50,000 INR = 245,000,000 paise. Values re-render via forgeI18n.
  const priorRFQs = [
    { id: "RFQ-2024-118", date: "2024-11-04", sku: "M-26102 · 0.75HP",  qty: 350, status: "won",     value: _a12_money("245000000", "INR", "₹24.5 L"), note: "Private-label, BEE-3"  },
    { id: "RFQ-2025-062", date: "2025-04-22", sku: "M-31507 · 2.0HP",   qty: 120, status: "lost",    value: _a12_money("290000000", "INR", "₹29.0 L"), note: "Lost on price (-7%)"   },
    { id: "RFQ-2025-141", date: "2025-09-09", sku: "M-26102 · 0.75HP",  qty: 250, status: "won",     value: _a12_money("178000000", "INR", "₹17.8 L"), note: "Repeat artwork carry"  },
  ];

  const fld = {
    width: "100%",
    height: 38,
    padding: "0 12px",
    fontFamily: A12_FONT_UI,
    fontSize: 14,
    color: A12_PAPER_INK,
    background: A12_PAPER_BG,
    border: `1px solid ${A12_PAPER_LINE}`,
    borderRadius: 8,
    outline: "none",
  };
  const lbl = Object.assign({}, a12Mono(), { display: "block", marginBottom: 6 });

  function onSubmit() {
    a12Nav("/forge/matcher");
  }

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <A12Header
          eyebrow="Forge · RFQ-INTAKE"
          title="Inbound RFQ — Helios AgriFlow"
          subtitle="Capture envelope. Match performance. Open cost-out."
        />

        <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 24 }}>
          {/* ───── Form ───── */}
          <A12Card>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
              <div style={a12Mono()}>RFQ-2026-024 · draft</div>
              <div style={{ display: "flex", gap: 8 }}>
                <A12Pill tone="amber">private-label</A12Pill>
                <A12Pill tone="blue">repeat customer</A12Pill>
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
              <div>
                <label style={lbl} htmlFor="fld-pump-1">Customer</label>
                <input id="fld-pump-1" name="fld-pump-1" style={fld} value={customer} onChange={(e) => setCustomer(e.target.value)} />
              </div>
              <div>
                <label style={lbl} htmlFor="fld-pump-2">Ship-to</label>
                <input id="fld-pump-2" name="fld-pump-2" style={fld} value={shipTo} onChange={(e) => setShipTo(e.target.value)} />
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 16 }}>
              <div>
                <label style={lbl} htmlFor="fld-pump-3">Quantity (units)</label>
                <input id="fld-pump-3" name="fld-pump-3" type="number" style={fld} value={qty} onChange={(e) => setQty(Number(e.target.value))} />
              </div>
              <div>
                <label style={lbl} htmlFor="fld-pump-4">Motor HP</label>
                <select id="fld-pump-4" name="fld-pump-4" style={fld} value={hp} onChange={(e) => setHp(e.target.value)}>
                  <option>0.5</option><option>0.75</option><option>1.0</option>
                  <option>1.5</option><option>2.0</option><option>3.0</option>
                </select>
              </div>
              <div>
                <label style={lbl} htmlFor="fld-pump-5">Bore size</label>
                <select id="fld-pump-5" name="fld-pump-5" style={fld} value={bore} onChange={(e) => setBore(e.target.value)}>
                  <option>3"</option><option>4"</option><option>5"</option><option>6"</option>
                </select>
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 16 }}>
              <div>
                <label style={lbl} htmlFor="fld-pump-6">Head (m)</label>
                <input id="fld-pump-6" name="fld-pump-6" type="number" style={fld} value={head} onChange={(e) => setHead(Number(e.target.value))} />
              </div>
              <div>
                <label style={lbl} htmlFor="fld-pump-7">Flow (LPM)</label>
                <input id="fld-pump-7" name="fld-pump-7" type="number" style={fld} value={flow} onChange={(e) => setFlow(Number(e.target.value))} />
              </div>
              <div>
                <label style={lbl} htmlFor="fld-pump-8">Target delivery</label>
                <input id="fld-pump-8" name="fld-pump-8" type="date" style={fld} value={due} onChange={(e) => setDue(e.target.value)} />
              </div>
            </div>

            <div style={{
              display: "grid", gridTemplateColumns: "auto 1fr", gap: 16,
              padding: 14, background: A12_PAPER_BG_2,
              border: `1px solid ${A12_PAPER_LINE_S}`, borderRadius: 8, marginBottom: 16,
              alignItems: "center",
            }}>
              <label style={{ display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                <input type="checkbox" id="rfq-private-label" name="rfq-private-label" checked={privateLabel} onChange={(e) => setPL(e.target.checked)} />
                <span style={a12Mono()}>private-label</span>
              </label>
              <input
                id="rfq-brand-name"
                name="rfq-brand-name"
                aria-label="Brand name"
                style={Object.assign({}, fld, { opacity: privateLabel ? 1 : 0.4 })}
                value={brand}
                onChange={(e) => setBrand(e.target.value)}
                disabled={!privateLabel}
                placeholder="Brand name"
              />
            </div>

            <div style={{ marginBottom: 20 }}>
              <label htmlFor="fld-pump-notes">
                <span style={lbl}>Notes</span>
                <textarea
                  id="fld-pump-notes"
                  name="fld-pump-notes"
                  style={Object.assign({}, fld, { height: 88, padding: "10px 12px", resize: "vertical", lineHeight: 1.5 })}
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                />
              </label>
            </div>

            {flash && (
              <div style={{
                marginBottom: 12, padding: 10,
                background: "oklch(0.95 0.06 145)",
                border: `1px solid ${A12_GREEN}`,
                color: A12_GREEN, borderRadius: 8,
                fontFamily: A12_FONT_MONO, fontSize: 12,
              }}>{flash}</div>
            )}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <A12Btn variant="tertiary" onClick={() => {
                const _q = function (err) { return err && (err.status === 404 || err.status === 400); };
                if (window.forgeApi && typeof window.forgeApi.mutate === "function") {
                  window.forgeApi.mutate("rfqs", { op: "add", path: "/-", value: { id: "RFQ-2026-024", status: "draft", customer: customer, ship_to: shipTo, qty: qty, hp: hp, bore: bore, head: head, flow: flow, due: due, private_label: privateLabel, brand: brand, notes: notes, ts: Date.now() } })
                    .then(function () { setFlash("Draft saved · RFQ-2026-024"); })
                    .catch(function (err) { setFlash(_q(err) ? "Draft queued · RFQ-2026-024" : "Save failed · " + (err && err.message || "unknown")); });
                } else {
                  setFlash("Draft queued · RFQ-2026-024");
                }
              }}>Save draft</A12Btn>
              <A12Btn variant="secondary" onClick={() => {
                const _q = function (err) { return err && (err.status === 404 || err.status === 400); };
                if (window.forgeApi && typeof window.forgeApi.mutate === "function") {
                  window.forgeApi.mutate("rfqs", { op: "add", path: "/-", value: { id: "RFQ-2026-024", status: "declined", customer: customer, ts: Date.now() } })
                    .then(function () { setFlash("Decline noted · RFQ-2026-024"); })
                    .catch(function (err) { setFlash(_q(err) ? "Decline queued · RFQ-2026-024" : "Decline failed · " + (err && err.message || "unknown")); });
                } else {
                  setFlash("Decline queued · RFQ-2026-024");
                }
              }}>Decline</A12Btn>
              <A12Btn variant="primary" onClick={onSubmit}>
                Match performance envelope →
              </A12Btn>
            </div>
          </A12Card>

          {/* ───── Right rail ───── */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <A12Card>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 14 })}>Helios · prior RFQs</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {priorRFQs.map((r) => {
                  const tone = r.status === "won" ? "green" : r.status === "lost" ? "red" : "amber";
                  return (
                    <div key={r.id} style={{
                      borderTop: `1px solid ${A12_PAPER_LINE_S}`,
                      paddingTop: 12,
                    }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                        <span style={{ fontFamily: A12_FONT_MONO, fontSize: 12, color: A12_PAPER_INK }}>{r.id}</span>
                        <A12Pill tone={tone}>{r.status}</A12Pill>
                      </div>
                      <div style={{ fontSize: 13, color: A12_PAPER_INK_2, marginBottom: 4 }}>
                        {r.sku} · {r.qty} units · {r.value}
                      </div>
                      <div style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>
                        {_a12_date(r.date, r.date)} — {r.note}
                      </div>
                    </div>
                  );
                })}
              </div>
            </A12Card>

            <A12Card style={{ background: A12_PAPER_BG_2 }}>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 10 })}>Heuristic preview</div>
              <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 16, color: A12_PAPER_INK, marginBottom: 8 }}>
                160 LPM @ 120m head
              </div>
              <div style={{ fontSize: 12, color: A12_PAPER_INK_3, lineHeight: 1.6 }}>
                Likely match: <b style={{ color: A12_PAPER_INK }}>M-27418</b> (V4 chassis · 22-stage). Repeat-artwork carryover from Helios PO-2024-118 cuts FAI cycle by ~10 days.
              </div>
            </A12Card>
          </div>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// S06 — Performance envelope matcher
// ════════════════════════════════════════════════════════════════════
function ScreenPerformanceMatcher() {
  // candidate SKUs (3 real + 2 made up)
  const candidates = [
    { sku: "M-27418", head: 120, flow: 162, eta: 47, carry: 87, cost: 9300,  fit: 96, winner: true,  desc: "V4 · 22-stage · 1.0HP" },
    { sku: "M-26102", head: 96,  flow: 145, eta: 43, carry: 100, cost: 7140, fit: 78, winner: false, desc: "V4 · 18-stage · 0.75HP" },
    { sku: "M-31507", head: 168, flow: 220, eta: 51, carry: 62, cost: 24210, fit: 71, winner: false, desc: "V6 · 28-stage · 2.0HP" },
    { sku: "M-27210", head: 110, flow: 150, eta: 44, carry: 71, cost: 8650,  fit: 84, winner: false, desc: "V4 · 20-stage · 1.0HP" },
    { sku: "M-28104", head: 132, flow: 175, eta: 46, carry: 58, cost: 10120, fit: 81, winner: false, desc: "V4 · 24-stage · 1.0HP" },
  ];

  const target = { head: 120, flow: 160 };

  // svg scatter chart — head (Y) vs flow (X)
  const W = 720, H = 320, P = 48;
  const minF = 100, maxF = 240, minH = 60, maxH = 200;
  function xS(f) { return P + ((f - minF) / (maxF - minF)) * (W - P * 2); }
  function yS(h) { return H - P - ((h - minH) / (maxH - minH)) * (H - P * 2); }

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <A12Header
          eyebrow="Forge · MATCHER"
          title="Performance envelope match"
          subtitle="Required duty: 160 LPM @ 120m head — ranked candidate SKUs."
        />

        {/* ───── Scatter / bubble chart ───── */}
        <A12Card style={{ marginBottom: 24, padding: 24 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div style={a12Mono()}>HEAD (m) × FLOW (LPM) · bubble = efficiency</div>
            <div style={{ display: "flex", gap: 10 }}>
              <A12Pill tone="red">required duty</A12Pill>
              <A12Pill tone="accent">candidates</A12Pill>
            </div>
          </div>

          <svg width={W} height={H} style={{ display: "block", margin: "0 auto" }}>
            {/* grid */}
            {[60, 90, 120, 150, 180].map((h) => (
              <g key={"gh" + h}>
                <line x1={P} y1={yS(h)} x2={W - P} y2={yS(h)} stroke={A12_PAPER_LINE_S} strokeDasharray="2 4" />
                <text x={P - 10} y={yS(h) + 4} textAnchor="end" fontFamily={A12_FONT_MONO} fontSize="10" fill={A12_PAPER_INK_3}>{h}</text>
              </g>
            ))}
            {[100, 140, 180, 220].map((f) => (
              <g key={"gf" + f}>
                <line x1={xS(f)} y1={P} x2={xS(f)} y2={H - P} stroke={A12_PAPER_LINE_S} strokeDasharray="2 4" />
                <text x={xS(f)} y={H - P + 16} textAnchor="middle" fontFamily={A12_FONT_MONO} fontSize="10" fill={A12_PAPER_INK_3}>{f}</text>
              </g>
            ))}

            {/* axes */}
            <line x1={P} y1={H - P} x2={W - P} y2={H - P} stroke={A12_PAPER_LINE} />
            <line x1={P} y1={P}     x2={P}     y2={H - P} stroke={A12_PAPER_LINE} />
            <text x={W / 2} y={H - 12} textAnchor="middle" fontFamily={A12_FONT_MONO} fontSize="11" fill={A12_PAPER_INK_3}>FLOW · LPM</text>
            <text x={14} y={H / 2} transform={`rotate(-90 14 ${H / 2})`} textAnchor="middle" fontFamily={A12_FONT_MONO} fontSize="11" fill={A12_PAPER_INK_3}>HEAD · m</text>

            {/* candidate bubbles */}
            {candidates.map((c, i) => {
              const r = 6 + (c.eta - 40) * 1.6;
              return (
                <g key={c.sku}>
                  <circle
                    cx={xS(c.flow)} cy={yS(c.head)} r={r}
                    fill={c.winner ? A12_ACCENT : A12_BLUE}
                    fillOpacity={c.winner ? 0.7 : 0.3}
                    stroke={c.winner ? A12_ACCENT : A12_BLUE}
                    strokeWidth={c.winner ? 2 : 1}
                  />
                  <text
                    x={xS(c.flow)} y={yS(c.head) - r - 6}
                    textAnchor="middle"
                    fontFamily={A12_FONT_MONO} fontSize="11"
                    fill={c.winner ? A12_PAPER_INK : A12_PAPER_INK_2}
                    fontWeight={c.winner ? 600 : 400}
                  >{c.sku}</text>
                </g>
              );
            })}

            {/* required duty — red diamond */}
            <g>
              <polygon
                points={`${xS(target.flow)},${yS(target.head) - 10} ${xS(target.flow) + 10},${yS(target.head)} ${xS(target.flow)},${yS(target.head) + 10} ${xS(target.flow) - 10},${yS(target.head)}`}
                fill={A12_RED} stroke={A12_RED}
              />
              <text x={xS(target.flow) + 14} y={yS(target.head) + 4} fontFamily={A12_FONT_MONO} fontSize="11" fill={A12_RED} fontWeight="600">
                duty 160@120
              </text>
            </g>
          </svg>
        </A12Card>

        {/* ───── Match table ───── */}
        <A12Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div style={a12Mono()}>Ranked match · 5 candidates</div>
            <A12Pill tone="green">winner: M-27418</A12Pill>
          </div>

          <div style={{ overflow: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr style={{ background: A12_PAPER_BG_2, borderBottom: `1px solid ${A12_PAPER_LINE}` }}>
                  {[
                    { c: "SKU", num: false },
                    { c: "DESC", num: false },
                    { c: "head@duty", num: true },
                    { c: "flow@duty", num: true },
                    { c: "η %", num: true },
                    { c: "carryover %", num: true },
                    { c: "₹ unit", num: true },
                    { c: "fit", num: true },
                    { c: "actions", num: false },
                  ].map((h) => (
                    <th key={h.c} style={{
                      textAlign: h.num ? "right" : "left", padding: "10px 12px",
                      fontFamily: A12_FONT_MONO, fontSize: 12,
                      letterSpacing: "0.08em", textTransform: "uppercase",
                      color: A12_PAPER_INK_3,
                    }}>{h.c}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {candidates.map((c) => (
                  <tr key={c.sku} style={{
                    borderBottom: `1px solid ${A12_PAPER_LINE_S}`,
                    background: c.winner ? "oklch(0.96 0.04 95)" : "transparent",
                  }}>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, color: A12_PAPER_INK, fontWeight: c.winner ? 600 : 400 }}>{c.sku}</td>
                    <td style={{ padding: "10px 12px", color: A12_PAPER_INK_3 }}>{c.desc}</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{c.head}m</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{c.flow} LPM</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{c.eta}%</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums", color: c.carry >= 80 ? A12_GREEN : c.carry >= 60 ? A12_AMBER : A12_RED }}>{c.carry}%</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>₹{c.cost.toLocaleString("en-IN")}</td>
                    <td style={{ padding: "10px 12px", fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 600, color: c.fit >= 90 ? A12_GREEN : c.fit >= 80 ? A12_AMBER : A12_PAPER_INK_3 }}>{c.fit}</td>
                    <td style={{ padding: "10px 12px" }}>
                      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                        <button onClick={() => a12Nav("/forge/ebom")} style={a12RowBtn()}>BOM</button>
                        <button onClick={() => a12Nav("/forge/quote")} style={a12RowBtn()}>cost-out</button>
                        <button onClick={() => a12Nav("/forge/carryover")} style={a12RowBtn()}>carryover</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={{ marginTop: 18, display: "flex", justifyContent: "flex-end", gap: 10 }}>
            <A12Btn variant="tertiary" onClick={() => a12Nav("/forge/rfq")}>← back to RFQ</A12Btn>
            <A12Btn variant="primary" onClick={() => a12Nav("/forge/quote")}>Lock M-27418 → quote builder</A12Btn>
          </div>
        </A12Card>
      </div>
    </div>
  );
}

function a12RowBtn() {
  return {
    padding: "4px 10px",
    fontFamily: A12_FONT_MONO,
    fontSize: 12,
    letterSpacing: "0.06em",
    textTransform: "uppercase",
    color: A12_PAPER_INK_2,
    background: A12_PAPER_BG_3,
    border: `1px solid ${A12_PAPER_LINE}`,
    borderRadius: 6,
    cursor: "pointer",
  };
}

// ════════════════════════════════════════════════════════════════════
// S07 — Interchangeability matrix
// ════════════════════════════════════════════════════════════════════
function ScreenInterchangeabilityMatrix() {
  const motors = ["V3", "V4 ECO", "V4 ECO NEMA", "V4 REGULAR", "V5", "V6 NEMA", "V6 RUNNING", "V8 RUNNING"];
  const pumps  = ["V3", "V4", "V4 MF", "V5 MF", "V5 RF", "V6 AM", "V6 AR", "V7 BM0-L", "V8 BM", "V10"];

  // matrix: cell = { hp: "0.5-1.0HP" or null, affinity: "high" | "partial" | "none" }
  // synthetic but plausible
  const M = {
    "V3": { "V3": { hp: "0.5-0.75", a: "high" }, "V4": { hp: "0.5-0.75", a: "partial" } },
    "V4 ECO": { "V4": { hp: "0.5-1.5", a: "high" }, "V4 MF": { hp: "0.75-1.5", a: "high" }, "V5 MF": { hp: "1.0-1.5", a: "partial" } },
    "V4 ECO NEMA": { "V4": { hp: "1.0-1.5", a: "high" }, "V4 MF": { hp: "1.0-2.0", a: "high" }, "V5 MF": { hp: "1.0-2.0", a: "partial" }, "V5 RF": { hp: "1.5-2.0", a: "partial" } },
    "V4 REGULAR": { "V4": { hp: "0.75-1.0", a: "high" }, "V4 MF": { hp: "1.0-1.5", a: "high" }, "V5 MF": { hp: "1.5-2.0", a: "partial" } },
    "V5": { "V5 MF": { hp: "1.0-2.0", a: "high" }, "V5 RF": { hp: "1.5-2.0", a: "high" }, "V6 AM": { hp: "2.0-3.0", a: "partial" } },
    "V6 NEMA": { "V6 AM": { hp: "2.0-5.0", a: "high" }, "V6 AR": { hp: "3.0-5.0", a: "high" }, "V7 BM0-L": { hp: "5.0-7.5", a: "partial" } },
    "V6 RUNNING": { "V6 AM": { hp: "2.0-5.0", a: "high" }, "V6 AR": { hp: "3.0-5.0", a: "high" }, "V7 BM0-L": { hp: "5.0-7.5", a: "partial" } },
    "V8 RUNNING": { "V7 BM0-L": { hp: "5.0-10", a: "partial" }, "V8 BM": { hp: "7.5-15", a: "high" }, "V10": { hp: "10-25", a: "partial" } },
  };

  const [bore, setBore]     = uSA12("4\"");
  const [hpFilter, setHpF]  = uSA12("any");
  const [stages, setStages] = uSA12("any");

  // count valid configurations
  let validCount = 0;
  motors.forEach((m) => pumps.forEach((p) => {
    if (M[m] && M[m][p]) validCount += 1;
  }));

  function cellColor(a, dim) {
    if (!a) return dim ? A12_PAPER_BG_3 : A12_PAPER_BG_3;
    if (a === "high")    return "oklch(0.92 0.06 145)";
    if (a === "partial") return "oklch(0.95 0.06 70)";
    return A12_GRAY;
  }

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <A12Header
          eyebrow="Forge · INTERCHANGE"
          title="Interchangeability matrix"
          subtitle="Motor families × pump families. Cell = compatible HP range. Color = carryover affinity."
        />

        <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 24 }}>
          {/* ───── Sidebar filters ───── */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <A12Card>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 14 })}>Filters</div>

              <div style={{ marginBottom: 14 }}>
                <div style={Object.assign({}, a12Mono(), { fontSize: 12, marginBottom: 6 })}>Bore</div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {['4"', '5"', '6"'].map((b) => (
                    <button
                      key={b}
                      onClick={() => setBore(b)}
                      style={Object.assign({}, a12RowBtn(), {
                        background: bore === b ? A12_ACCENT : A12_PAPER_BG_3,
                        color: bore === b ? "oklch(0.14 0.02 55)" : A12_PAPER_INK_2,
                        borderColor: bore === b ? A12_ACCENT : A12_PAPER_LINE,
                      })}
                    >{b}</button>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: 14 }}>
                <div style={Object.assign({}, a12Mono(), { fontSize: 12, marginBottom: 6 })}>HP range</div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {["any", "0.5-1.5", "1.5-3", "3-7.5", "7.5+"].map((h) => (
                    <button
                      key={h}
                      onClick={() => setHpF(h)}
                      style={Object.assign({}, a12RowBtn(), {
                        background: hpFilter === h ? A12_ACCENT : A12_PAPER_BG_3,
                        color: hpFilter === h ? "oklch(0.14 0.02 55)" : A12_PAPER_INK_2,
                        borderColor: hpFilter === h ? A12_ACCENT : A12_PAPER_LINE,
                      })}
                    >{h}</button>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: 4 }}>
                <div style={Object.assign({}, a12Mono(), { fontSize: 12, marginBottom: 6 })}>Stages</div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {["any", "≤18", "20-24", "26+"].map((s) => (
                    <button
                      key={s}
                      onClick={() => setStages(s)}
                      style={Object.assign({}, a12RowBtn(), {
                        background: stages === s ? A12_ACCENT : A12_PAPER_BG_3,
                        color: stages === s ? "oklch(0.14 0.02 55)" : A12_PAPER_INK_2,
                        borderColor: stages === s ? A12_ACCENT : A12_PAPER_LINE,
                      })}
                    >{s}</button>
                  ))}
                </div>
              </div>
            </A12Card>

            <A12Card style={{ background: A12_PAPER_BG_2 }}>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 8 })}>Result</div>
              <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 28, color: A12_PAPER_INK, marginBottom: 4 }}>
                {validCount}
              </div>
              <div style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>
                valid configurations under current filters
              </div>
            </A12Card>

            <A12Card>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 10 })}>Legend</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {[
                  { c: "oklch(0.92 0.06 145)", l: "high reuse" },
                  { c: "oklch(0.95 0.06 70)",  l: "partial reuse" },
                  { c: A12_GRAY,                l: "incompatible (×)" },
                ].map((x) => (
                  <div key={x.l} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ width: 16, height: 16, background: x.c, border: `1px solid ${A12_PAPER_LINE}`, borderRadius: 3 }} />
                    <span style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>{x.l}</span>
                  </div>
                ))}
              </div>
            </A12Card>
          </div>

          {/* ───── Matrix ───── */}
          <A12Card style={{ overflow: "auto" }}>
            <div style={a12Mono()}>matrix · {motors.length} × {pumps.length}</div>
            <table style={{ borderCollapse: "collapse", marginTop: 14, fontSize: 12 }}>
              <thead>
                <tr>
                  <th style={a12CellHead()}></th>
                  {pumps.map((p) => (
                    <th key={p} style={a12CellHead()}>{p}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {motors.map((m) => (
                  <tr key={m}>
                    <th style={Object.assign({}, a12CellHead(), { textAlign: "left", paddingRight: 12 })}>{m}</th>
                    {pumps.map((p) => {
                      const cell = M[m] && M[m][p];
                      return (
                        <td key={p} style={{
                          width: 88, height: 44,
                          background: cellColor(cell && cell.a),
                          border: `1px solid ${A12_PAPER_LINE_S}`,
                          textAlign: "center",
                          fontFamily: A12_FONT_MONO,
                          fontSize: 12,
                          color: cell ? A12_PAPER_INK : A12_PAPER_INK_3,
                        }}>
                          {cell ? cell.hp : "×"}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>

            {/* explanation card */}
            <div style={{
              marginTop: 24, padding: 18,
              background: "oklch(0.96 0.04 95)",
              border: `1px solid ${A12_ACCENT}`,
              borderRadius: 10,
            }}>
              <div style={Object.assign({}, a12Mono(), { color: A12_ACCENT, marginBottom: 8 })}>Selected configuration</div>
              <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 18, color: A12_PAPER_INK, marginBottom: 6 }}>
                M-27418 — V4 motor base + V4 pump chassis · 22 stages
              </div>
              <div style={{ fontSize: 13, color: A12_PAPER_INK_2, lineHeight: 1.6 }}>
                87% carryover from <b>M-26102</b> platform · 4 parts swapped (motor base LHP, impeller stage size, pump shaft length, NRV size). Tooling carries through; 2 vendor PPAPs needed (Athena, Vega).
              </div>
              <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
                <A12Btn variant="primary" onClick={() => a12Nav("/forge/carryover")}>Open carryover →</A12Btn>
                <A12Btn variant="tertiary" onClick={() => a12Nav("/forge/ebom")}>Open BOM</A12Btn>
              </div>
            </div>
          </A12Card>
        </div>
      </div>
    </div>
  );
}

function a12CellHead() {
  return {
    padding: "8px 12px",
    fontFamily: A12_FONT_MONO,
    fontSize: 12,
    letterSpacing: "0.06em",
    textTransform: "uppercase",
    color: A12_PAPER_INK_3,
    background: A12_PAPER_BG_2,
    border: `1px solid ${A12_PAPER_LINE_S}`,
    fontWeight: 500,
    whiteSpace: "nowrap",
  };
}

// ════════════════════════════════════════════════════════════════════
// S10 — EBOM diff: V5→V4 carryover (M-26102 → M-27418)
// ════════════════════════════════════════════════════════════════════
function ScreenEBOMDiff() {
  const [flash, setFlash] = uSA12("");
  uEA12(() => {
    if (!flash) return;
    const t = setTimeout(() => setFlash(""), 2400);
    return () => clearTimeout(t);
  }, [flash]);
  // synthetic side-by-side — predecessor (left) vs current (right)
  // status: "same" | "swap" | "added" | "removed"
  const rows = [
    { pn: "10.01", desc: "Motor housing assembly",      lhs: "MH-V4-075",    rhs: "MH-V4-100",    status: "swap",    note: "uprated for 1.0HP" },
    { pn: "10.02", desc: "Stator stack",                lhs: "ST-V4-18",     rhs: "ST-V4-22",     status: "swap",    note: "+4 lams for 1.0HP head" },
    { pn: "10.04", desc: "Rotor shaft",                 lhs: "RS-V4-160",    rhs: "RS-V4-180",    status: "swap",    note: "+20mm length" },
    { pn: "10.05", desc: "Rotor stamping",              lhs: "RT-V4-A",      rhs: "RT-V4-A",      status: "same",    note: "" },
    { pn: "10.06", desc: "Stator stamping",             lhs: "SS-V4-A",      rhs: "SS-V4-A",      status: "same",    note: "" },
    { pn: "10.07", desc: "Stator outer shell",          lhs: "SH-V4",        rhs: "SH-V4",        status: "same",    note: "" },
    { pn: "10.08", desc: "Bearing — top (C3)",          lhs: "BR-6203-C3",   rhs: "BR-6203-C3",   status: "same",    note: "" },
    { pn: "10.09", desc: "Bearing — bottom (C3)",       lhs: "BR-6202-C3",   rhs: "BR-6202-C3",   status: "same",    note: "" },
    { pn: "10.10", desc: "Motor base (LHP)",            lhs: "MB-V4-LHP",    rhs: "MB-V4-LHP-X",  status: "swap",    note: "thicker foot — ECO-0042" },
    { pn: "10.11", desc: "Top cover plate",             lhs: "TC-V4",        rhs: "TC-V4",        status: "same",    note: "" },
    { pn: "10.12", desc: "Copper winding wire (kg)",    lhs: "CW-1.20mm 1.8kg", rhs: "CW-1.20mm 2.1kg", status: "swap", note: "+0.3kg per unit" },
    { pn: "10.15", desc: "Insulation paper",            lhs: "INS-K-Class-B",rhs: "INS-K-Class-B",status: "same",    note: "" },
    { pn: "10.18", desc: "Slot wedge",                  lhs: "WG-NMX-A",     rhs: "WG-NMX-A",     status: "same",    note: "" },
    { pn: "10.19", desc: "Cable gland",                 lhs: "CG-PG13",      rhs: "CG-PG13",      status: "same",    note: "" },
    { pn: "20.01", desc: "Pump adapter / NRV body",     lhs: "PA-V4-A",      rhs: "PA-V4-A",      status: "same",    note: "" },
    { pn: "20.02", desc: "Pump shaft",                  lhs: "PS-V4-220",    rhs: "PS-V4-260",    status: "swap",    note: "+40mm for 22-stage stack" },
    { pn: "20.04", desc: "NRV (non-return valve)",      lhs: "NRV-86",       rhs: "NRV-100",      status: "swap",    note: "Ø86 → Ø100, S.G.-iron" },
    { pn: "20.05", desc: "Suction strainer",            lhs: "SR-V4-A",      rhs: "SR-V4-A",      status: "same",    note: "" },
    { pn: "20.06", desc: "Impeller stage",              lhs: "IM-V4-S 18×",  rhs: "IM-V4-L 22×",  status: "swap",    note: "stage size up · 22 stages" },
    { pn: "20.07", desc: "Diffuser stage",              lhs: "DF-V4-S 18×",  rhs: "DF-V4-L 22×",  status: "swap",    note: "match impeller" },
    { pn: "20.09", desc: "Coupling",                    lhs: "CP-V4",        rhs: "CP-V4",        status: "same",    note: "" },
    { pn: "20.11", desc: "Pump pipe (delivery)",        lhs: "PP-V4-1\"",    rhs: "PP-V4-1\"",    status: "same",    note: "" },
    { pn: "20.13", desc: "Wear ring",                   lhs: "WR-V4-A",      rhs: "WR-V4-A",      status: "same",    note: "" },
    { pn: "20.17", desc: "Outer sleeve",                lhs: "OS-V4-S",      rhs: "OS-V4-L",      status: "swap",    note: "longer for 22-stage" },
    { pn: "20.20", desc: "Sand guard ring",             lhs: null,           rhs: "SG-V4-A",      status: "added",   note: "field-return mitigation" },
    { pn: "20.99", desc: "Bottom suction cap (legacy)", lhs: "BC-V3-LEG",    rhs: null,           status: "removed", note: "obsoleted in V4 platform" },
    { pn: "30.01", desc: "Cable assembly · 30m",        lhs: "CA-30M-3C",    rhs: "CA-30M-3C",    status: "same",    note: "" },
    { pn: "30.02", desc: "Junction box",                lhs: "JB-V4",        rhs: "JB-V4",        status: "same",    note: "" },
  ];

  const swapCount   = rows.filter((r) => r.status === "swap").length;
  const sameCount   = rows.filter((r) => r.status === "same").length;
  const addedCount  = rows.filter((r) => r.status === "added").length;
  const removedCount= rows.filter((r) => r.status === "removed").length;

  function statusStyle(s) {
    if (s === "swap")    return { bg: "oklch(0.96 0.04 95)", fg: A12_AMBER, label: "swap"   };
    if (s === "added")   return { bg: "oklch(0.95 0.06 145)", fg: A12_GREEN, label: "added"  };
    if (s === "removed") return { bg: "oklch(0.96 0.05 28)", fg: A12_RED, label: "removed"};
    return { bg: A12_PAPER_BG_3, fg: A12_PAPER_INK_3, label: "same" };
  }

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 24 }}>
          <A12Header
            eyebrow="Forge · CARRYOVER"
            title="Design carryover · M-26102 → M-27418"
            subtitle="0.75HP predecessor on left, 1.0HP current on right. 4 swaps · 1 add · 1 remove."
          />
          <div style={{ display: "flex", gap: 10 }}>
            <A12Btn variant="tertiary" onClick={() => { setFlash("Re-derive queued — v2"); if (window.forgeToast) window.forgeToast({ msg: "Re-derive from V5 queued — v2", kind: "info" }); }}>Re-derive from V5 platform</A12Btn>
          </div>
        </div>

        {flash && (
          <div style={{
            marginBottom: 16, padding: 12,
            background: "oklch(0.95 0.06 145)",
            border: `1px solid ${A12_GREEN}`,
            color: A12_GREEN, borderRadius: 8,
            fontFamily: A12_FONT_MONO, fontSize: 12,
          }}>{flash}</div>
        )}

        {/* summary tiles */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 24 }}>
          {[
            { l: "unchanged",  v: sameCount,    tone: "default" },
            { l: "swapped",    v: swapCount,    tone: "amber"   },
            { l: "added",      v: addedCount,   tone: "green"   },
            { l: "removed",    v: removedCount, tone: "red"     },
          ].map((t) => {
            const toneColor = t.tone === "amber" ? A12_AMBER : t.tone === "green" ? A12_GREEN : t.tone === "red" ? A12_RED : A12_PAPER_INK;
            return (
              <A12Card key={t.l} style={{ padding: 16 }}>
                <div style={Object.assign({}, a12Mono(), { marginBottom: 6 })}>{t.l}</div>
                <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 30, color: toneColor }}>{t.v}</div>
              </A12Card>
            );
          })}
        </div>

        {/* diff table */}
        <A12Card style={{ overflow: "auto", padding: 0 }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
            <thead>
              <tr style={{ background: A12_PAPER_BG_2 }}>
                <th style={a12DiffH()}>P/N</th>
                <th style={a12DiffH()}>Description</th>
                <th style={Object.assign({}, a12DiffH(), { background: "oklch(0.94 0.01 30)" })}>M-26102 (predecessor)</th>
                <th style={Object.assign({}, a12DiffH(), { background: "oklch(0.94 0.02 145)" })}>M-27418 (current)</th>
                <th style={a12DiffH()}>status</th>
                <th style={a12DiffH()}>note</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => {
                const s = statusStyle(r.status);
                const dim = r.status === "same";
                const baseColor = dim ? A12_PAPER_INK_3 : A12_PAPER_INK;
                return (
                  <tr key={r.pn} style={{
                    background: s.bg,
                    borderTop: `1px solid ${A12_PAPER_LINE_S}`,
                    color: baseColor,
                  }}>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO })}>{r.pn}</td>
                    <td style={a12DiffC()}>{r.desc}</td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, color: r.status === "removed" ? A12_RED : baseColor })}>
                      {r.lhs || <span style={{ color: A12_PAPER_INK_3 }}>—</span>}
                    </td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, color: r.status === "added" ? A12_GREEN : baseColor })}>
                      {r.rhs || <span style={{ color: A12_PAPER_INK_3 }}>—</span>}
                    </td>
                    <td style={a12DiffC()}>
                      <span style={{
                        fontFamily: A12_FONT_MONO, fontSize: 12,
                        letterSpacing: "0.06em", textTransform: "uppercase",
                        color: s.fg,
                      }}>{s.label}</span>
                    </td>
                    <td style={Object.assign({}, a12DiffC(), { color: A12_PAPER_INK_3, fontSize: 12 })}>{r.note}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </A12Card>

        {/* footer summary */}
        <div style={{
          marginTop: 24, padding: 20,
          background: "oklch(0.96 0.04 95)",
          border: `1px solid ${A12_ACCENT}`,
          borderRadius: 10,
          display: "grid", gridTemplateColumns: "1fr auto", gap: 18, alignItems: "center",
        }}>
          <div>
            <div style={Object.assign({}, a12Mono(), { color: A12_ACCENT, marginBottom: 6 })}>Net effect</div>
            <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 22, color: A12_PAPER_INK, marginBottom: 4 }}>
              Net cost delta: −{_a12_money("280000", "INR", "₹2,800")} / unit
            </div>
            <div style={{ fontSize: 13, color: A12_PAPER_INK_2 }}>
              Routed through ECO-0042 — approved {_a12_date("2025-12-01", "2025-12-01")} by Meera S.
            </div>
          </div>
          <A12Btn variant="primary" onClick={() => a12Nav("/build/eco")}>Open ECO-0042 →</A12Btn>
        </div>
      </div>
    </div>
  );
}

function a12DiffH() {
  return {
    textAlign: "left",
    padding: "12px 14px",
    fontFamily: A12_FONT_MONO,
    fontSize: 12,
    letterSpacing: "0.08em",
    textTransform: "uppercase",
    color: A12_PAPER_INK_3,
    fontWeight: 500,
    borderBottom: `1px solid ${A12_PAPER_LINE}`,
  };
}
function a12DiffC() {
  return { padding: "10px 14px", verticalAlign: "top" };
}

// ════════════════════════════════════════════════════════════════════
// S13 — Material price history
// ════════════════════════════════════════════════════════════════════
function ScreenMaterialPriceHistory() {
  const quarters = ["2024Q1","2024Q2","2024Q3","2024Q4","2025Q1","2025Q2","2025Q3","2025Q4"];

  // per-material prices (₹/kg) — gradual rise then dip pattern
  const materials = [
    { name: "C.I. Casting",          color: A12_BLUE,             unit: "₹/kg", supplier: "Spire Foundry",      lead: 42,
      prices: [78, 80, 84, 88, 92, 95, 91, 89] },
    { name: "SS 410 Bar",            color: A12_GREEN,            unit: "₹/kg", supplier: "Vega Shafts",         lead: 28,
      prices: [220, 228, 235, 240, 248, 255, 250, 245] },
    { name: "Copper Wire (LME-idx)", color: A12_RED,              unit: "₹/kg", supplier: "Indus Copper Mills",  lead: 21,
      prices: [780, 810, 845, 870, 905, 940, 920, 895] },
    { name: "Aluminum Stamping",     color: A12_AMBER,            unit: "₹/kg", supplier: "Elara Stamping",      lead: 30,
      prices: [185, 192, 198, 204, 210, 218, 212, 207] },
    { name: "Kraft Insulation Paper",color: "oklch(0.55 0.12 295)", unit: "₹/kg", supplier: "Halcyon Insulation", lead: 18,
      prices: [62, 64, 66, 68, 70, 72, 70, 68] },
  ];

  const [locks, setLocks] = uSA12(materials.reduce((acc, m) => { acc[m.name] = "current"; return acc; }, {}));

  // chart geometry
  const W = 760, H = 320, P = 50;
  const allVals = materials.flatMap((m) => m.prices);
  // normalize per-material so the lines are comparable on the same chart — use index baseline
  function norm(p, base) { return (p / base) * 100; }
  const yMin = 90, yMax = 130;
  function xC(i) { return P + (i / (quarters.length - 1)) * (W - P * 2); }
  function yC(v) { return H - P - ((v - yMin) / (yMax - yMin)) * (H - P * 2); }

  const lines = materials.map((m) => {
    const base = m.prices[0];
    const pts = m.prices.map((p, i) => ({ x: xC(i), y: yC(norm(p, base)) }));
    return { name: m.name, color: m.color, pts: pts };
  });

  // estimated savings if all locked
  const savingsLakh = 4.2;

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <A12Header
          eyebrow="Plan · MATERIAL-HISTORY"
          title="Material price history · 8-quarter trail"
          subtitle="Lock prices for the 8-week Helios production window. Indexed to 2024Q1 = 100."
        />

        <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 24, marginBottom: 24 }}>
          {/* ───── Line chart ───── */}
          <A12Card style={{ padding: 20 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14 }}>
              <div style={a12Mono()}>indexed price · 8 quarters</div>
              <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
                {materials.map((m) => (
                  <div key={m.name} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 12, height: 2, background: m.color }} />
                    <span style={{ fontSize: 12, color: A12_PAPER_INK_2 }}>{m.name}</span>
                  </div>
                ))}
              </div>
            </div>

            <svg width={W} height={H} style={{ display: "block" }}>
              {/* y grid */}
              {[90, 100, 110, 120, 130].map((v) => (
                <g key={"yh" + v}>
                  <line x1={P} y1={yC(v)} x2={W - P} y2={yC(v)} stroke={A12_PAPER_LINE_S} strokeDasharray="2 4" />
                  <text x={P - 8} y={yC(v) + 4} textAnchor="end" fontFamily={A12_FONT_MONO} fontSize="10" fill={A12_PAPER_INK_3}>{v}</text>
                </g>
              ))}
              {/* x labels */}
              {quarters.map((q, i) => (
                <text key={q} x={xC(i)} y={H - P + 18} textAnchor="middle" fontFamily={A12_FONT_MONO} fontSize="10" fill={A12_PAPER_INK_3}>{q}</text>
              ))}
              {/* baseline 100 */}
              <line x1={P} y1={yC(100)} x2={W - P} y2={yC(100)} stroke={A12_PAPER_INK_4} strokeWidth="1" strokeDasharray="4 3" />
              <text x={W - P + 4} y={yC(100) + 4} fontFamily={A12_FONT_MONO} fontSize="10" fill={A12_PAPER_INK_3}>100</text>

              {/* axes */}
              <line x1={P} y1={H - P} x2={W - P} y2={H - P} stroke={A12_PAPER_LINE} />
              <line x1={P} y1={P} x2={P} y2={H - P} stroke={A12_PAPER_LINE} />

              {/* lines */}
              {lines.map((ln) => {
                const d = ln.pts.map((p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`)).join(" ");
                return (
                  <g key={ln.name}>
                    <path d={d} fill="none" stroke={ln.color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
                    {ln.pts.map((p, i) => (
                      <circle key={i} cx={p.x} cy={p.y} r="3" fill={ln.color} />
                    ))}
                  </g>
                );
              })}
            </svg>
          </A12Card>

          {/* ───── Lock-price affordance ───── */}
          <A12Card>
            <div style={Object.assign({}, a12Mono(), { marginBottom: 14 })}>Lock prices · 8-week window</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 16 }}>
              {materials.map((m) => {
                const mSlug = "material-lock-" + m.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
                return (
                <div key={m.name}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                    <span style={{ fontSize: 12, color: A12_PAPER_INK_2 }}>{m.name}</span>
                    <span style={{ fontFamily: A12_FONT_MONO, fontSize: 12, color: A12_PAPER_INK, fontVariantNumeric: "tabular-nums" }}>
                      ₹{m.prices[m.prices.length - 1]}/kg
                    </span>
                  </div>
                  <select
                    id={mSlug}
                    name={mSlug}
                    aria-label={"Lock price for " + m.name}
                    value={locks[m.name]}
                    onChange={(e) => setLocks(Object.assign({}, locks, { [m.name]: e.target.value }))}
                    style={{
                      width: "100%", height: 30, fontSize: 12,
                      border: `1px solid ${A12_PAPER_LINE}`, borderRadius: 6,
                      background: A12_PAPER_BG, color: A12_PAPER_INK,
                      padding: "0 8px", fontFamily: A12_FONT_MONO,
                    }}>
                    <option value="current">Lock at current ₹{m.prices[7]}/kg</option>
                    <option value="q3">Lock at Q3 ₹{m.prices[6]}/kg</option>
                    <option value="q2">Lock at Q2 ₹{m.prices[5]}/kg</option>
                    <option value="float">Float (do not lock)</option>
                  </select>
                </div>
                );
              })}
            </div>

            <div style={{
              padding: 14,
              background: "oklch(0.95 0.06 145)",
              border: `1px solid ${A12_GREEN}`,
              borderRadius: 8,
            }}>
              <div style={Object.assign({}, a12Mono(), { color: A12_GREEN, marginBottom: 6 })}>Estimated savings</div>
              <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 22, color: A12_PAPER_INK }}>
                ₹{savingsLakh} lakh
              </div>
              <div style={{ fontSize: 12, color: A12_PAPER_INK_3, marginTop: 4 }}>
                if all 5 materials locked at recent low · Helios 500-unit run
              </div>
            </div>
          </A12Card>
        </div>

        {/* ───── Per-material breakdown ───── */}
        <A12Card>
          <div style={Object.assign({}, a12Mono(), { marginBottom: 12 })}>Per-material breakdown</div>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ background: A12_PAPER_BG_2, borderBottom: `1px solid ${A12_PAPER_LINE}` }}>
                {[
                  { c: "Material", num: false },
                  { c: "current ₹/kg", num: true },
                  { c: "4Q ago ₹/kg", num: true },
                  { c: "% Δ", num: true },
                  { c: "lead time", num: true },
                  { c: "supplier", num: false },
                ].map((h) => (
                  <th key={h.c} style={Object.assign({}, a12DiffH(), h.num ? { textAlign: "right" } : null)}>{h.c}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {materials.map((m) => {
                const cur = m.prices[7];
                const past = m.prices[3];
                const pct = ((cur - past) / past) * 100;
                const tone = pct > 5 ? A12_RED : pct > 0 ? A12_AMBER : A12_GREEN;
                return (
                  <tr key={m.name} style={{ borderBottom: `1px solid ${A12_PAPER_LINE_S}` }}>
                    <td style={a12DiffC()}>
                      <span style={{ display: "inline-block", width: 10, height: 10, background: m.color, borderRadius: 2, marginRight: 8, verticalAlign: "middle" }} />
                      {m.name}
                    </td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>₹{cur}</td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, color: A12_PAPER_INK_3, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>₹{past}</td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, color: tone, fontWeight: 600, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>
                      {pct > 0 ? "+" : ""}{pct.toFixed(1)}%
                    </td>
                    <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>{m.lead}d</td>
                    <td style={a12DiffC()}>{m.supplier}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </A12Card>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// S14 — Quote-out builder
// ════════════════════════════════════════════════════════════════════
function ScreenQuoteBuilder() {
  const [marginPct,  setMarginPct]  = uSA12(18);
  const [freightPct, setFreightPct] = uSA12(3);
  const [flash, setFlash] = uSA12("");
  const mountedRef = React.useRef(true);
  uEA12(() => {
    mountedRef.current = true;
    return () => { mountedRef.current = false; };
  }, []);
  uEA12(() => {
    if (!flash) return;
    const t = setTimeout(() => { if (mountedRef.current) setFlash(""); }, 2400);
    return () => clearTimeout(t);
  }, [flash]);

  // base costs
  const RMC      = 7330;     // pump_rmc + motor_rmc
  const conv     = Math.round(RMC * 0.21);
  const freight  = Math.round((RMC + conv) * (freightPct / 100));
  const subtotal = RMC + conv + freight;
  const margin   = Math.round(subtotal * (marginPct / 100));
  const unit     = subtotal + margin;
  const qty      = 500;
  const total    = unit * qty;

  function fmt(n) { return "₹" + n.toLocaleString("en-IN"); }

  function send() {
    setFlash("Quote sent to Helios. Tracked in /auditor/ledger.");
    setTimeout(() => { if (mountedRef.current) a12Nav("/auditor/ledger"); }, 700);
  }

  return (
    <div style={a12Root()}>
      <div style={a12Container()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 24 }}>
          <A12Header
            eyebrow="Forge · QUOTE-BUILDER"
            title="Quote — Helios AgriFlow · 500 × M-27418"
            subtitle="Printable one-page quote. Adjust margin live. Send when sealed."
          />
          <div style={{ display: "flex", gap: 8 }}>
            <A12Btn variant="tertiary" onClick={() => {
              const _q = function (err) { return err && (err.status === 404 || err.status === 400); };
              if (window.forgeApi && typeof window.forgeApi.mutate === "function") {
                window.forgeApi.mutate("quotes", { op: "add", path: "/-", value: { id: "QT-PMP-2026-001", status: "draft", ts: Date.now() } })
                  .then(function () { setFlash("Draft saved · QT-PMP-2026-001"); })
                  .catch(function (err) { setFlash(_q(err) ? "Draft queued · QT-PMP-2026-001" : "Save failed · " + (err && err.message || "unknown")); });
              } else {
                setFlash("Draft queued · QT-PMP-2026-001");
              }
            }}>Save draft</A12Btn>
            <A12Btn variant="tertiary" onClick={() => {
              if (window.forgeApi && typeof window.forgeApi.exportAuditUrl === "function") {
                window.location.href = window.forgeApi.exportAuditUrl("pdf");
                setFlash("PDF download started");
              } else {
                setFlash("PDF download queued — v2");
              }
            }}>Download PDF</A12Btn>
            <A12Btn variant="tertiary" onClick={() => { setFlash("Email send queued — v2"); if (window.forgeToast) window.forgeToast({ msg: "Email send queued — v2", kind: "info" }); }}>Send via email</A12Btn>
          </div>
        </div>

        {flash && (
          <div style={{
            marginBottom: 16, padding: 12,
            background: "oklch(0.95 0.06 145)",
            border: `1px solid ${A12_GREEN}`,
            color: A12_GREEN, borderRadius: 8,
            fontFamily: A12_FONT_MONO, fontSize: 12,
          }}>{flash}</div>
        )}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 24 }}>
          {/* ───── Quote sheet ───── */}
          <A12Card style={{ padding: 36, background: "white" }}>
            {/* letterhead */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", paddingBottom: 18, borderBottom: `2px solid ${A12_PAPER_INK}` }}>
              <div>
                <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 28, letterSpacing: "-0.02em", color: A12_PAPER_INK }}>
                  Tritan Pumps Pvt Ltd
                </div>
                <div style={{ fontSize: 12, color: A12_PAPER_INK_3, marginTop: 4 }}>
                  GIDC Estate, Vadodara, Gujarat 390010 · GST 24AAACT0000T1Z5 · IEC 0823009999
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={Object.assign({}, a12Mono(), { fontSize: 12, marginBottom: 6 })}>Quote</div>
                <div style={{ fontFamily: A12_FONT_MONO, fontSize: 14, color: A12_PAPER_INK }}>QT-2026-0418</div>
                <div style={{ fontSize: 12, color: A12_PAPER_INK_3, marginTop: 4 }}>Issued: 2026-04-29</div>
                <div style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>Valid: 14 days</div>
              </div>
            </div>

            {/* customer block */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, marginTop: 22, marginBottom: 22 }}>
              <div>
                <div style={Object.assign({}, a12Mono(), { marginBottom: 6 })}>BILL TO</div>
                <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 16, color: A12_PAPER_INK }}>Helios AgriFlow Pvt Ltd</div>
                <div style={{ fontSize: 12, color: A12_PAPER_INK_3, lineHeight: 1.6, marginTop: 4 }}>
                  Plot 14, Phase II<br />
                  Sanand GIDC, Ahmedabad 382110<br />
                  Attn: Procurement — Mr. Ankit P.
                </div>
              </div>
              <div>
                <div style={Object.assign({}, a12Mono(), { marginBottom: 6 })}>SHIP TO</div>
                <div style={{ fontFamily: A12_FONT_SERIF, fontSize: 16, color: A12_PAPER_INK }}>Helios AgriFlow · Sanand DC</div>
                <div style={{ fontSize: 12, color: A12_PAPER_INK_3, lineHeight: 1.6, marginTop: 4 }}>
                  Same as billing<br />
                  Mode: FOB Vadodara · Truck<br />
                  Lead time: 8 weeks ARO
                </div>
              </div>
            </div>

            {/* SKU table */}
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, marginBottom: 18 }}>
              <thead>
                <tr style={{ borderBottom: `1px solid ${A12_PAPER_INK}` }}>
                  {[
                    { c: "SKU", num: false },
                    { c: "Description", num: false },
                    { c: "Qty", num: true },
                    { c: "Unit ₹", num: true },
                    { c: "Total ₹", num: true },
                  ].map((h) => (
                    <th key={h.c} style={Object.assign({}, a12DiffH(), { borderBottom: "none" }, h.num ? { textAlign: "right" } : null)}>{h.c}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO })}>M-27418</td>
                  <td style={a12DiffC()}>1.0HP · 4" submersible · 22-stage · Helios private-label rev B</td>
                  <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>{qty}</td>
                  <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" })}>{fmt(unit)}</td>
                  <td style={Object.assign({}, a12DiffC(), { fontFamily: A12_FONT_SERIF, fontSize: 30, letterSpacing: "-0.01em", color: A12_PAPER_INK, textAlign: "right", verticalAlign: "middle", fontVariantNumeric: "tabular-nums" })}>{fmt(total)}</td>
                </tr>
              </tbody>
            </table>

            {/* pricing breakdown */}
            <div style={{ background: A12_PAPER_BG_2, padding: 16, borderRadius: 8, marginBottom: 18 }}>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 10 })}>Unit price breakdown</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", rowGap: 6, fontSize: 13 }}>
                <span style={{ color: A12_PAPER_INK_2 }}>RMC (pump + motor)</span>
                <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmt(RMC)}</span>
                <span style={{ color: A12_PAPER_INK_2 }}>Conversion (21%)</span>
                <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmt(conv)}</span>
                <span style={{ color: A12_PAPER_INK_2 }}>Freight ({freightPct}%)</span>
                <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmt(freight)}</span>
                <span style={{ color: A12_PAPER_INK_2 }}>Margin ({marginPct}%)</span>
                <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmt(margin)}</span>
                <span style={{ color: A12_PAPER_INK, fontWeight: 600, borderTop: `1px solid ${A12_PAPER_LINE}`, paddingTop: 6, marginTop: 4 }}>Quoted unit price</span>
                <span style={{ fontFamily: A12_FONT_MONO, fontWeight: 600, textAlign: "right", fontVariantNumeric: "tabular-nums", borderTop: `1px solid ${A12_PAPER_LINE}`, paddingTop: 6, marginTop: 4 }}>{fmt(unit)}</span>
              </div>
            </div>

            {/* terms */}
            <div style={{ fontSize: 12, color: A12_PAPER_INK_3, lineHeight: 1.7 }}>
              <div style={Object.assign({}, a12Mono(), { color: A12_PAPER_INK_2, marginBottom: 6 })}>Terms</div>
              Payment: LC at sight, opened on a scheduled IN-bank.<br />
              Freight: FOB Vadodara, road transport. Insurance to buyer's account.<br />
              Lead time: 8 weeks from PO + 30% advance + LC opening.<br />
              Branding: Helios artwork rev B; all CAPA on artwork must be closed before pilot.<br />
              Warranty: 18 months from dispatch or 12 months from install, whichever earlier.
            </div>

            <div style={{ marginTop: 28, paddingTop: 18, borderTop: `1px solid ${A12_PAPER_LINE}`, fontSize: 12, color: A12_PAPER_INK_3, textAlign: "right" }}>
              Authorized signatory · Karan V. (Program Lead) · Tritan Pumps Pvt Ltd
            </div>
          </A12Card>

          {/* ───── Right rail margin model ───── */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <A12Card>
              <div style={Object.assign({}, a12Mono(), { marginBottom: 14 })}>Margin model</div>

              <div style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>Margin %</span>
                  <span style={{ fontFamily: A12_FONT_MONO, fontSize: 12, color: A12_PAPER_INK }}>{marginPct}%</span>
                </div>
                <input
                  type="range" min="8" max="32" value={marginPct}
                  id="quote-margin-pct" name="quote-margin-pct"
                  aria-label="Margin (%)"
                  onChange={(e) => setMarginPct(Number(e.target.value))}
                  style={{ width: "100%" }}
                />
              </div>

              <div style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ fontSize: 12, color: A12_PAPER_INK_3 }}>Freight buffer %</span>
                  <span style={{ fontFamily: A12_FONT_MONO, fontSize: 12, color: A12_PAPER_INK }}>{freightPct}%</span>
                </div>
                <input
                  type="range" min="1" max="8" value={freightPct}
                  id="quote-freight-pct" name="quote-freight-pct"
                  aria-label="Freight buffer (%)"
                  onChange={(e) => setFreightPct(Number(e.target.value))}
                  style={{ width: "100%" }}
                />
              </div>

              <div style={{
                marginTop: 16, padding: 14,
                background: A12_PAPER_BG_2,
                border: `1px solid ${A12_PAPER_LINE}`,
                borderRadius: 8,
              }}>
                <div style={Object.assign({}, a12Mono(), { marginBottom: 6 })}>Live recompute</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr auto", rowGap: 4, fontSize: 12 }}>
                  <span style={{ color: A12_PAPER_INK_3 }}>Unit price</span>
                  <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmt(unit)}</span>
                  <span style={{ color: A12_PAPER_INK_3 }}>Order total</span>
                  <span style={{ fontFamily: A12_FONT_MONO, textAlign: "right", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmt(total)}</span>
                </div>
              </div>
            </A12Card>

            <A12Btn variant="primary" onClick={send} style={{ height: 48, fontSize: 14 }}>
              Send to customer →
            </A12Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// register routes
// ════════════════════════════════════════════════════════════════════
if (typeof registerPumpRoute === "function") {
  registerPumpRoute({ path: "/forge/rfq",        mode: "forge", title: "RFQ intake",         renderer: () => React.createElement(ScreenRFQIntake) });
  registerPumpRoute({ path: "/forge/matcher",    mode: "forge", title: "Performance match",  renderer: () => React.createElement(ScreenPerformanceMatcher) });
  registerPumpRoute({ path: "/forge/interchange",mode: "forge", title: "Interchangeability", renderer: () => React.createElement(ScreenInterchangeabilityMatrix) });
  registerPumpRoute({ path: "/forge/carryover",  mode: "forge", title: "Design carryover",   renderer: () => React.createElement(ScreenEBOMDiff) });
  registerPumpRoute({ path: "/plan/material-history", mode: "plan", title: "Material price history", renderer: () => React.createElement(ScreenMaterialPriceHistory) });
  registerPumpRoute({ path: "/forge/quote",      mode: "forge", title: "Quote builder",      renderer: () => React.createElement(ScreenQuoteBuilder) });
}
