/* global window React */
const { useState, useEffect, useRef } = React;
const {
  I, ResultPill,
  CROP_GROUPS, REGIONS, APPLICATION_METHODS, FORMULATION_TYPES,
  REPORT_DATA, SAMPLE_TRIALS, DEMO_PATHS, CSV_COLUMNS,
  TreeView
} = window;

// ─── Page wrapper ───────────────────────────────────────────────────────
function Page({ title, subtitle, kicker, actions, children, narrow }) {
  return (
    <div className={`rac-page ${narrow ? "rac-page--narrow" : ""}`}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 24, marginBottom: 28, flexWrap: "wrap" }}>
        <div style={{ flex: 1, minWidth: 260 }}>
          {kicker && <div style={{ fontSize: 12, fontWeight: 700, color: "var(--rac-primary)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 6 }}>{kicker}</div>}
          <h1 style={{ fontSize: 24, fontWeight: 700 }}>{title}</h1>
          {subtitle && <p style={{ fontSize: 14, color: "var(--rac-muted)", marginTop: 6, maxWidth: 680, width: "680px" }}>{subtitle}</p>}
        </div>
        {actions && <div className="rac-page__actions" style={{ display: "flex", gap: 10 }}>{actions}</div>}
      </div>
      {children}
    </div>);

}

// ─── Registrant Dashboard ───────────────────────────────────────────────
const REGISTRANT_PAST = [
{
  ref: "REG-2025-114", crop: "Sweet Corn", substance: "S-metolachlor",
  type: "Tolerance modification · Group 15", status: "Approved",
  updated: "Mar 02, 2026", started: "Feb 12, 2026", outcome: "pass",
  filename: "sweet_corn_smet_2025.csv", fileSize: "212 KB",
  gap: { applicationRate: "1.27", applicationRateUnit: "lb ai/A", phi: "30",
    numberOfApps: "1", applicationMethod: "Soil banded",
    formulationType: "EC (emulsifiable concentrate)",
    geographicRegions: ["I", "II", "V", "X"], targetPest: "Pre-emergent grasses",
    growthStage: "Pre-plant" },
  decision: { reviewer: "USEPA OPPTS · Dr. K. Reyes", finalized: "Mar 02, 2026",
    note: "Trial data met all count and distribution requirements." }
},
{
  ref: "REG-2025-088", crop: "Sweet Corn", substance: "Mesotrione",
  type: "Tolerance petition · Group 15", status: "Approved",
  updated: "Jan 14, 2026", started: "Dec 03, 2025", outcome: "pass",
  filename: "sweet_corn_meso_2025.csv", fileSize: "188 KB",
  gap: { applicationRate: "0.188", applicationRateUnit: "lb ai/A", phi: "7",
    numberOfApps: "2", applicationMethod: "Foliar broadcast",
    formulationType: "SC (suspension concentrate)",
    geographicRegions: ["I", "II", "V", "X"], targetPest: "Annual broadleaf weeds, grasses",
    growthStage: "V2–V6" },
  decision: { reviewer: "USEPA OPPTS · J. Carter", finalized: "Jan 14, 2026",
    note: "Approved without modification. Crop Subgroup 15-A established." }
},
{
  ref: "REG-2024-301", crop: "Sweet Corn", substance: "Glufosinate",
  type: "Tolerance modification · Group 15", status: "Rejected",
  updated: "Dec 09, 2025", started: "Oct 22, 2025", outcome: "fail",
  filename: "sweet_corn_gluf_2024.csv", fileSize: "152 KB",
  gap: { applicationRate: "0.45", applicationRateUnit: "lb ai/A", phi: "14",
    numberOfApps: "2", applicationMethod: "Foliar broadcast",
    formulationType: "SL (soluble liquid)",
    geographicRegions: ["II", "V"], targetPest: "Post-emergent weeds",
    growthStage: "V4–V8" },
  decision: { reviewer: "USEPA OPPTS · Dr. A. Singh", finalized: "Dec 09, 2025",
    note: "Distribution failed Crop Group threshold. Resubmitted under REG-2026-014." }
}];


function RegistrantDashboard({ user, onNew, onResume, onViewArchive }) {
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  const filtered = REGISTRANT_PAST.filter((r) => {
    if (statusFilter === "submitted") {
      const s = r.status.toLowerCase();
      if (s !== "approved" && s !== "rejected") return false;
    } else if (statusFilter !== "all" && r.status.toLowerCase() !== statusFilter) {
      return false;
    }
    if (search) {
      const q = search.toLowerCase();
      return r.ref.toLowerCase().includes(q) || r.crop.toLowerCase().includes(q) || r.substance.toLowerCase().includes(q) || r.type.toLowerCase().includes(q);
    }
    return true;
  });

  return (
    <Page
      kicker={`Welcome back, ${user.name.split(" ")[0]}`}
      title="Your registration submissions"
      subtitle={`Manage tolerance petitions and trial-data submissions for ${user.company}.`}
      actions={[
      <button key="n" className="rac-btn rac-btn--primary" onClick={onNew}>
          <I.Plus size={14} /> New Tolerance Petition for an Existing Product
        </button>]
      }>
      
      <div className="rac-grid-3" style={{ marginBottom: 28 }}>
        <StatCard label="In progress" value="1" hint="Sweet Corn · Mesotrione"
        active={statusFilter === "pending review"}
        onClick={() => {setStatusFilter(statusFilter === "pending review" ? "all" : "pending review");setSearch("");}} />
        <StatCard label="Submitted" value="3" hint="Past 90 days"
        active={statusFilter === "submitted"}
        onClick={() => {setStatusFilter(statusFilter === "submitted" ? "all" : "submitted");setSearch("");}} />
        <StatCard label="Approved" value="2" hint="of 3 reviewed"
        active={statusFilter === "approved"}
        onClick={() => {setStatusFilter(statusFilter === "approved" ? "all" : "approved");setSearch("");}} />
      </div>

      <div className="rac-card">
        <div className="rac-card__head" style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 10 }}>
          <div>
            <div className="rac-card__title">Submissions</div>
            <div className="rac-card__sub">All registrations under your account</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center", flexShrink: 0 }}>
            <select className="rac-select" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} style={{ height: 32, fontSize: 12, padding: "0 28px 0 10px" }}>
              <option value="all">All statuses</option>
              <option value="submitted">Submitted (Approved + Rejected)</option>
              <option value="approved">Approved</option>
              <option value="rejected">Rejected</option>
              <option value="pending review">Pending</option>
            </select>
            <div style={{ position: "relative", flexShrink: 0 }}>
              <I.Search size={13} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--rac-muted)", pointerEvents: "none", zIndex: 1 }} />
              <input className="rac-input" placeholder="Search…" value={search} onChange={(e) => setSearch(e.target.value)} style={{ height: 32, fontSize: 12, padding: "0 10px 0 30px", width: 180, boxSizing: "border-box" }} />
            </div>
          </div>
        </div>
        <table className="rac-table">
          <thead>
            <tr>
              <th>Reference</th><th>Crop</th><th>Active substance</th><th>Type</th><th>Status</th><th>Last updated</th><th></th>
            </tr>
          </thead>
          <tbody>
            {(statusFilter === "all" || statusFilter === "pending review") && !search &&
            <tr style={{ cursor: "pointer" }} onClick={onResume}>
                <td className="rac-mono" style={{ color: "var(--rac-primary)" }}>DRAFT-001</td>
                <td>Sweet Corn</td>
                <td>Mesotrione</td>
                <td>Tolerance petition · Group 15</td>
                <td><ResultPill value="Pending Review" /></td>
                <td style={{ color: "var(--rac-muted)" }}>Just now</td>
                <td style={{ textAlign: "right" }}><button className="rac-btn rac-btn--ghost rac-btn--sm">Resume <I.ChevronRight size={12} /></button></td>
              </tr>
            }
            {filtered.map((r) =>
            <tr key={r.ref} style={{ cursor: "pointer" }} onClick={() => onViewArchive(r.ref)}>
                <td className="rac-mono">{r.ref}</td>
                <td>{r.crop}</td>
                <td>{r.substance}</td>
                <td>{r.type}</td>
                <td><ResultPill value={r.status} /></td>
                <td style={{ color: "var(--rac-muted)" }}>{r.updated}</td>
                <td style={{ textAlign: "right" }}><button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={(e) => {e.stopPropagation();onViewArchive(r.ref);}}>View <I.ChevronRight size={12} /></button></td>
              </tr>
            )}
            {filtered.length === 0 && (statusFilter !== "all" && statusFilter !== "pending review" || search) &&
            <tr><td colSpan="7" style={{ textAlign: "center", padding: "32px 16px", color: "var(--rac-muted)", fontSize: 13 }}>No submissions match your filters.</td></tr>
            }
          </tbody>
        </table>
      </div>
    </Page>);

}

// ─── Archive viewer ─────────────────────────────────────────────────────
function ArchivedSubmission({ refId, onBack }) {
  const sub = REGISTRANT_PAST.find((r) => r.ref === refId);
  if (!sub) return null;
  const data = window.REPORT_DATA[sub.outcome];
  const path = window.DEMO_PATHS[sub.outcome];
  const trials = window.SAMPLE_TRIALS[sub.outcome] || [];
  const isPass = sub.outcome === "pass";
  const REGIONS = window.REGIONS;
  const cropGroup = window.CROP_GROUPS.find((g) => g.crop === sub.crop);

  const STEPS = [
  { id: "a1", label: "Crop selection", hint: sub.crop, icon: I.Crop },
  { id: "a2", label: "GAP conditions", hint: "Confirmed", icon: I.Form },
  { id: "a3", label: "Trial data", hint: sub.filename, icon: I.Upload },
  { id: "a4", label: "Decision tree", hint: isPass ? "PASS" : "FAIL", icon: I.Tree },
  { id: "a5", label: "Output report", hint: "Reviewed", icon: I.Report },
  { id: "a6", label: "Submitted", hint: sub.updated, icon: I.Send }];


  return (
    <div style={{ display: "flex", width: "100%" }}>
      {/* Read-only timeline sidebar */}
      <aside className="rac-steps">
        <div className="rac-steps__title">Archived submission</div>
        {STEPS.map((s, i) =>
        <div key={s.id} className="rac-step is-complete" style={{ cursor: "default" }}>
            <span className="rac-step__dot"><I.Check size={14} /></span>
            <span className="rac-step__body">
              <span className="rac-step__label">{s.label}</span>
              <span className="rac-step__hint">{s.hint}</span>
            </span>
          </div>
        )}
        <div style={{ padding: "24px 12px 0", borderTop: "1px solid var(--rac-line)", marginTop: 16 }}>
          <div className="rac-steps__title" style={{ padding: "0 0 10px" }}>Submission</div>
          <div style={{ fontSize: 12, color: "var(--rac-muted)", lineHeight: 1.5 }}>
            <div><strong style={{ color: "var(--rac-ink)" }}>Reference</strong></div>
            <div className="rac-mono">{sub.ref}</div>
            <div style={{ marginTop: 8 }}><strong style={{ color: "var(--rac-ink)" }}>Started</strong> {sub.started}</div>
            <div style={{ marginTop: 4 }}><strong style={{ color: "var(--rac-ink)" }}>Finalized</strong> {sub.updated}</div>
          </div>
        </div>
      </aside>

      <main className="rac-content">
    <Page
          kicker={sub.ref}
          title={`${sub.substance} on ${sub.crop}`}
          subtitle={`${sub.type} · Decision finalized ${sub.updated}`}
          actions={[
          <button key="b" className="rac-btn rac-btn--ghost" onClick={onBack}><I.Back size={14} /> Back to submissions</button>,
          <button key="d" className="rac-btn rac-btn--ghost"><I.Download size={14} /> Download PDF</button>]
          }>
          
      {/* Read-only banner */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", background: "var(--rac-surface-alt)", border: "1px solid var(--rac-line)", borderRadius: 8, marginBottom: 18, fontSize: 12.5, color: "var(--rac-muted)" }}>
        <I.Lock size={14} />
        <span>This submission is archived and read-only. All values reflect the state at the time of decision.</span>
      </div>

      {/* Outcome banner */}
      <div className={`rac-banner rac-banner--${isPass ? "pass" : "fail"}`} style={{ marginBottom: 18 }}>
        {isPass ? <I.Check size={20} /> : <I.X size={20} />}
        <div>
          <strong>{isPass ? "Approved" : "Rejected"} by USEPA OPPTS</strong>
          <div style={{ fontSize: 13, marginTop: 2 }}>{sub.decision.note}</div>
          <div style={{ fontSize: 12, marginTop: 4, opacity: 0.8 }}>Reviewer: {sub.decision.reviewer} · {sub.decision.finalized}</div>
        </div>
      </div>

      {/* A1 + A2 - Crop & GAP */}
      <div className="rac-grid-2" style={{ marginBottom: 18 }}>
        <div className="rac-card">
          <div className="rac-card__head"><div className="rac-card__title">Crop selection</div><div className="rac-card__sub">Step 1</div></div>
          <div style={{ padding: "14px 20px 18px" }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--rac-primary)", letterSpacing: "0.05em" }}>GROUP {cropGroup?.id || 15}</div>
            <div style={{ fontSize: 15, fontWeight: 600, marginTop: 2 }}>{cropGroup?.name || "Cereal Grains"}</div>
            <div style={{ fontSize: 13, color: "var(--rac-muted)", marginTop: 2 }}>{sub.crop}</div>
          </div>
        </div>
        <div className="rac-card">
          <div className="rac-card__head"><div className="rac-card__title">GAP conditions</div><div className="rac-card__sub">Step 2 · Active substance: {sub.substance}</div></div>
          <div style={{ padding: "14px 20px 18px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 18px" }}>
            <KV k="Application rate" v={`${sub.gap.applicationRate} ${sub.gap.applicationRateUnit}`} />
            <KV k="PHI" v={`${sub.gap.phi} days`} />
            <KV k="Applications" v={sub.gap.numberOfApps} />
            <KV k="Method" v={sub.gap.applicationMethod} />
            <KV k="Formulation" v={sub.gap.formulationType} />
            <KV k="Growth stage" v={sub.gap.growthStage} />
            <KV k="Target" v={sub.gap.targetPest} span />
            <KV k="Regions" v={sub.gap.geographicRegions.join(", ")} span />
          </div>
        </div>
      </div>

      {/* A3 - Trial data file */}
      <div className="rac-card" style={{ marginBottom: 18 }}>
        <div className="rac-card__head"><div className="rac-card__title">Trial data file</div><div className="rac-card__sub">Step 3 · As uploaded</div></div>
        <div style={{ padding: "14px 20px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", background: "var(--rac-surface-alt)", border: "1px solid var(--rac-line)", borderRadius: 10 }}>
            <div style={{ width: 38, height: 38, borderRadius: 8, background: "#fff", color: "var(--rac-ink-2)", display: "grid", placeItems: "center", border: "1px solid var(--rac-line)" }}>
              <I.File size={18} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="rac-mono" style={{ fontSize: 13, fontWeight: 600 }}>{sub.filename}</div>
              <div style={{ fontSize: 11.5, color: "var(--rac-muted)" }}>{sub.fileSize} · {data.totalTrials} rows · 11 columns · OPPTS 860.1500 schema</div>
            </div>
            <button className="rac-btn rac-btn--ghost rac-btn--sm"><I.Download size={12} /> CSV</button>
          </div>
          {trials.length > 0 &&
              <div style={{ marginTop: 12, maxHeight: 160, overflowY: "auto", overflowX: "auto", border: "1px solid var(--rac-line)", borderRadius: 6, background: "#fff" }}>
              <table style={{ fontSize: 11.5, fontFamily: "var(--font-mono)", borderCollapse: "collapse", whiteSpace: "nowrap" }}>
                <thead style={{ position: "sticky", top: 0, background: "#fafbfd" }}>
                  <tr>{window.CSV_COLUMNS.map((h) => <th key={h} style={{ padding: "6px 10px", textAlign: "left", color: "var(--rac-muted)", borderBottom: "1px solid var(--rac-line)", fontWeight: 600 }}>{h}</th>)}</tr>
                </thead>
                <tbody>
                  {trials.slice(0, 4).map((r) =>
                    <tr key={r.id}>
                      <td style={{ padding: "5px 10px" }}>{r.id}</td><td style={{ padding: "5px 10px" }}>{r.state}</td>
                      <td style={{ padding: "5px 10px" }}>{r.county}</td><td style={{ padding: "5px 10px" }}>{r.region}</td>
                      <td style={{ padding: "5px 10px" }}>{r.crop}</td><td style={{ padding: "5px 10px" }}>{r.variety}</td>
                      <td style={{ padding: "5px 10px" }}>{r.rate}</td><td style={{ padding: "5px 10px" }}>{r.apps}</td>
                      <td style={{ padding: "5px 10px" }}>{r.phi}</td><td style={{ padding: "5px 10px" }}>{r.harvest}</td>
                      <td style={{ padding: "5px 10px" }}>{r.residue}</td>
                    </tr>
                    )}
                  {trials.length > 4 && <tr><td colSpan={window.CSV_COLUMNS.length} style={{ padding: "5px 10px", color: "var(--rac-muted)", fontFamily: "var(--font-sans)", fontStyle: "italic" }}>+ {trials.length - 4} more rows…</td></tr>}
                </tbody>
              </table>
            </div>
              }
        </div>
      </div>

      {/* A4 - Decision tree path */}
      <div className="rac-card" style={{ marginBottom: 18 }}>
        <div className="rac-card__head"><div className="rac-card__title">Decision tree path</div><div className="rac-card__sub">Step 4 · Path traversed during assessment</div></div>
        <div style={{ padding: 18 }}>
          <div style={{ marginBottom: 16 }}>
            <TreeView selectedFile={sub.outcome} />
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 6 }}>
            {path.nodes.map((n, i) => {
                  const isTerminal = n.startsWith("PASS") || n.startsWith("FAIL");
                  const cls = isTerminal && n.startsWith("PASS") ? "pass" : isTerminal ? "fail" : "info";
                  return (
                    <React.Fragment key={n}>
                  <span className={`rac-pill rac-pill--${cls}`} style={{ padding: "4px 10px" }}>{n}</span>
                  {i < path.nodes.length - 1 && <I.ChevronRight size={12} style={{ color: "var(--rac-muted)" }} />}
                </React.Fragment>);

                })}
          </div>
          {path.failingRule &&
              <div style={{ marginTop: 14, padding: "12px 14px", background: "var(--rac-fail-bg)", border: "1px solid var(--rac-fail)", borderRadius: 8, fontSize: 12.5, color: "var(--rac-ink)" }}>
              <strong>Failing rule - {path.failingRule.nodeId}:</strong> {path.failingRule.ruleText}
              <div style={{ marginTop: 4, color: "var(--rac-ink-2)" }}>{path.failingRule.explanation}</div>
            </div>
              }
        </div>
      </div>

      {/* A5 - Trial summary + distribution */}
      <div className="rac-card" style={{ marginBottom: 18 }}>
        <div className="rac-card__head"><div className="rac-card__title">Trial summary</div><div className="rac-card__sub">Step 5 · Output report</div></div>
        <table className="rac-table">
          <thead><tr><th>Criterion</th><th style={{ textAlign: "center" }}>Required</th><th style={{ textAlign: "center" }}>Submitted</th><th style={{ textAlign: "right" }}>Result</th></tr></thead>
          <tbody>
            {data.trialCounts.map((r, i) =>
                <tr key={i}>
                <td>
                  <div>{r.criterion}</div>
                  {r.note && <div style={{ fontSize: 11.5, color: "var(--rac-muted)", marginTop: 2, lineHeight: 1.45 }}>{r.note}</div>}
                </td>
                <td style={{ textAlign: "center" }} className="rac-mono">{r.required}</td>
                <td style={{ textAlign: "center" }} className="rac-mono">{r.submitted}</td>
                <td style={{ textAlign: "right" }}><ResultPill value={r.result} /></td>
              </tr>
                )}
          </tbody>
        </table>
      </div>

      <div className="rac-card">
        <div className="rac-card__head"><div className="rac-card__title">Regional distribution</div><div className="rac-card__sub">USEPA Crop Group 15 required regions</div></div>
        <table className="rac-table">
          <thead><tr><th>Region</th><th>States</th><th style={{ textAlign: "center" }}>Trials</th><th style={{ textAlign: "right" }}>Result</th></tr></thead>
          <tbody>
            {data.distribution.map((r, i) =>
                <tr key={i}>
                <td><strong>{r.region}</strong> - {r.name}</td>
                <td className="rac-mono" style={{ fontSize: 11.5, color: "var(--rac-muted)" }}>{r.states}</td>
                <td style={{ textAlign: "center" }} className="rac-mono">{r.present}</td>
                <td style={{ textAlign: "right" }}><ResultPill value={r.result} /></td>
              </tr>
                )}
          </tbody>
        </table>
      </div>
    </Page>
      </main>
    </div>);

}

function KV({ k, v, span }) {
  return (
    <div style={{ gridColumn: span ? "1 / -1" : "auto" }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--rac-muted)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 2 }}>{k}</div>
      <div style={{ fontSize: 13.5, color: "var(--rac-ink)" }}>{v}</div>
    </div>);

}
function StatCard({ label, value, hint, onClick, active }) {
  const clickable = typeof onClick === "function";
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={!clickable}
      className="rac-card"
      style={{
        padding: "18px 22px",
        textAlign: "left",
        cursor: clickable ? "pointer" : "default",
        border: active ? "1.5px solid var(--rac-primary)" : "1px solid var(--rac-line)",
        boxShadow: active ? "0 0 0 3px rgba(28, 70, 168, 0.10)" : undefined,
        background: "#fff",
        font: "inherit",
        color: "inherit",
        transition: "border-color 120ms ease, box-shadow 120ms ease, transform 120ms ease",
        position: "relative"
      }}
      onMouseDown={clickable ? (e) => {e.currentTarget.style.transform = "translateY(1px)";} : undefined}
      onMouseUp={clickable ? (e) => {e.currentTarget.style.transform = "";} : undefined}
      onMouseLeave={clickable ? (e) => {e.currentTarget.style.transform = "";} : undefined}>
      
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <div style={{ fontSize: 11, color: active ? "var(--rac-primary)" : "var(--rac-muted)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em" }}>{label}</div>
        {active &&
        <div style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, fontWeight: 700, color: "var(--rac-primary)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
            <I.Filter size={10} /> Filter on
          </div>
        }
      </div>
      <div style={{ fontSize: 32, fontWeight: 700, fontFamily: "var(--font-display)", marginTop: 6, color: "var(--rac-ink)" }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--rac-muted)", marginTop: 4 }}>{hint}</div>
    </button>);

}

// ─── A1 - Crop Selection ────────────────────────────────────────────────
function A1CropSelection({ submission, onUpdate, onNavigate }) {
  return (
    <Page kicker="Step 1 of 6" title="Select a crop group" subtitle="Choose the USEPA crop classification for this submission. Only Group 15 - Cereal Grains is enabled in this mock-up.">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 14, marginBottom: 24 }}>
        {CROP_GROUPS.map((g) => {
          const isSel = submission.crop === g.crop && g.active;
          return (
            <button
              key={g.id}
              onClick={() => g.active && onUpdate({ crop: g.crop })}
              disabled={!g.active}
              style={{
                background: "#fff", textAlign: "left",
                border: isSel ? "2px solid var(--rac-primary)" : "1px solid var(--rac-line)",
                borderRadius: 12, padding: "16px 18px",
                opacity: g.active ? 1 : 0.55,
                cursor: g.active ? "pointer" : "not-allowed",
                position: "relative",
                boxShadow: isSel ? "0 0 0 4px var(--rac-primary-50)" : "none",
                transition: "all 120ms"
              }}>
              
              <div style={{ fontSize: 11, fontWeight: 700, color: g.active ? "var(--rac-primary)" : "var(--rac-muted)", letterSpacing: "0.05em" }}>GROUP {g.id}</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4, color: "var(--rac-ink)" }}>{g.name}</div>
              <div style={{ fontSize: 12, color: "var(--rac-muted)", marginTop: 4 }}>{g.crop}</div>
              {!g.active && <I.Lock size={13} style={{ position: "absolute", top: 14, right: 14, color: "var(--rac-muted)" }} />}
              {isSel && <span style={{ position: "absolute", top: 12, right: 12, background: "var(--rac-primary)", color: "#fff", borderRadius: "50%", width: 22, height: 22, display: "grid", placeItems: "center" }}><I.Check size={13} /></span>}
            </button>);

        })}
      </div>

      <FooterNav
        onBack={() => onNavigate("registrant.dashboard")} backLabel="Cancel"
        onNext={() => onNavigate("registrant.a2")}
        nextDisabled={!submission.crop}
        nextLabel="Continue to GAP conditions" />
      
    </Page>);

}

// ─── A2 - GAP Conditions ────────────────────────────────────────────────
function A2GAPConditions({ submission, onUpdate, onNavigate }) {
  const [g, setG] = useState(submission.gap);
  const setF = (k, v) => setG((prev) => ({ ...prev, [k]: v }));
  const toggleRegion = (id) => setF("geographicRegions", g.geographicRegions.includes(id) ? g.geographicRegions.filter((x) => x !== id) : [...g.geographicRegions, id]);
  const confirm = () => {onUpdate({ gap: g, gapConfirmed: true });onNavigate("registrant.a3");};

  return (
    <Page kicker="Step 2 of 6" title="Confirm Good Agricultural Practice (GAP)" subtitle="Default values are pre-filled from the active substance's most-recent registration, which can be prepared as a drop-down list based on the registrant's registered products.">
      <div className="rac-card">
        <div className="rac-card__body">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 18 }}>
            <div className="rac-field" style={{ gridColumn: "span 2" }}>
              <label className="rac-label">Active ingredient</label>
              <select className="rac-select" value={g.activeIngredient} onChange={(e) => setF("activeIngredient", e.target.value)}>
                <option value="Mesotrione">Mesotrione</option>
                <option value="S-metolachlor">S-metolachlor</option>
                <option value="Glufosinate">Glufosinate</option>
                <option value="Atrazine">Atrazine</option>
                <option value="Dicamba">Dicamba</option>
                <option value="Glyphosate">Glyphosate</option>
              </select>
              <div className="rac-field-hint">Selected from your registered products for Sweet Corn.</div>
            </div>
            <div className="rac-field">
              <label className="rac-label">Number of applications</label>
              <input className="rac-input" type="number" value={g.numberOfApps} onChange={(e) => setF("numberOfApps", e.target.value)} />
            </div>

            <div className="rac-field">
              <label className="rac-label">Application rate</label>
              <div style={{ display: "flex", gap: 8 }}>
                <input className="rac-input" style={{ flex: 1 }} value={g.applicationRate} onChange={(e) => setF("applicationRate", e.target.value)} />
                <select className="rac-select" style={{ width: 120 }} value={g.applicationRateUnit} onChange={(e) => setF("applicationRateUnit", e.target.value)}>
                  <option>lb ai/A</option><option>kg ai/ha</option><option>oz ai/A</option><option>g ai/ha</option>
                </select>
              </div>
            </div>
            <div className="rac-field">
              <label className="rac-label">Pre-Harvest Interval (PHI)</label>
              <div style={{ display: "flex", gap: 8 }}>
                <input className="rac-input" type="number" style={{ flex: 1 }} value={g.phi} onChange={(e) => setF("phi", e.target.value)} />
                <span style={{ display: "grid", placeItems: "center", background: "var(--rac-surface-alt)", border: "1px solid var(--rac-line)", borderRadius: 8, padding: "0 14px", fontSize: 13, color: "var(--rac-muted)" }}>days</span>
              </div>
            </div>
            <div className="rac-field">
              <label className="rac-label">Application method</label>
              <select className="rac-select" value={g.applicationMethod} onChange={(e) => setF("applicationMethod", e.target.value)}>
                {APPLICATION_METHODS.map((m) => <option key={m}>{m}</option>)}
              </select>
            </div>

            <div className="rac-field">
              <label className="rac-label">Formulation type</label>
              <select className="rac-select" value={g.formulationType} onChange={(e) => setF("formulationType", e.target.value)}>
                {FORMULATION_TYPES.map((m) => <option key={m}>{m}</option>)}
              </select>
            </div>
            <div className="rac-field">
              <label className="rac-label">Target pest(s)</label>
              <input className="rac-input" value={g.targetPest} onChange={(e) => setF("targetPest", e.target.value)} />
            </div>
            <div className="rac-field">
              <label className="rac-label">Crop growth stage</label>
              <input className="rac-input" value={g.growthStage} onChange={(e) => setF("growthStage", e.target.value)} />
            </div>
          </div>

          <div className="rac-divider" />

          <div>
            <label className="rac-label" style={{ marginBottom: 10 }}>Geographic regions (USEPA crop-growing zones)</label>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 8 }}>
              {REGIONS.map((r) => {
                const selected = g.geographicRegions.includes(r.id);
                return (
                  <label key={r.id} style={{
                    display: "flex", alignItems: "center", gap: 10, padding: "8px 12px",
                    border: selected ? "1.5px solid var(--rac-primary)" : "1px solid var(--rac-line)",
                    background: selected ? "var(--rac-primary-50)" : "#fff",
                    borderRadius: 8, cursor: "pointer"
                  }}>
                    <input type="checkbox" checked={selected} onChange={() => toggleRegion(r.id)} style={{ accentColor: "var(--rac-primary)" }} />
                    <span style={{ flex: 1, minWidth: 0 }}>
                      <span style={{ fontSize: 13, fontWeight: 600 }}>Region {r.id}</span>
                      <span style={{ display: "block", fontSize: 11, color: "var(--rac-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.name}</span>
                    </span>
                    {r.required && <span className="rac-pill rac-pill--info" style={{ fontSize: 10, padding: "2px 6px" }}>Required</span>}
                  </label>);

              })}
            </div>
          </div>
        </div>
      </div>

      <FooterNav
        onBack={() => onNavigate("registrant.a1")}
        onNext={confirm}
        nextLabel={submission.gapConfirmed ? "Update & continue" : "Confirm GAP & continue"} />
      
    </Page>);

}

// ─── A3 - Trial data file ──────────────────────────────────────────────
function A3FileSelection({ submission, onUpdate, onNavigate }) {
  const [showSpec, setShowSpec] = useState(false);
  const [showSamples, setShowSamples] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const sel = submission.selectedDemoFile;

  // Upload simulation
  const [phase, setPhase] = useState(sel ? "parsed" : "idle"); // idle | uploading | parsed
  const [progress, setProgress] = useState(sel ? 100 : 0);
  const fileMeta = sel === "pass" ?
  { name: "sweet_corn_residue_2024.csv", size: "184 KB", rows: SAMPLE_TRIALS.pass.length, regions: 4, summary: "8 field trials across 4 USEPA regions" } :
  sel === "fail" ?
  { name: "sweet_corn_residue_2024.csv", size: "142 KB", rows: SAMPLE_TRIALS.fail.length, regions: 2, summary: "6 field trials across 2 USEPA regions" } :
  null;

  const startUpload = (which) => {
    onUpdate({ selectedDemoFile: which, reportViewed: false, submitted: false });
    setPhase("uploading");
    setProgress(0);
    setShowSamples(false);
    let p = 0;
    const t = setInterval(() => {
      p += 14 + Math.random() * 12;
      if (p >= 100) {p = 100;clearInterval(t);setTimeout(() => setPhase("parsed"), 280);}
      setProgress(p);
    }, 90);
  };

  const reset = () => {
    onUpdate({ selectedDemoFile: null, reportViewed: false, submitted: false });
    setPhase("idle");setProgress(0);
  };

  const triggerPicker = () => {
    // No real file picker in the demo - open the sample picker as the realistic substitute.
    setShowSamples(true);
  };

  return (
    <Page
      kicker="Step 3 of 6"
      title="Upload trial data"
      subtitle="Provide a CSV containing the residue trial dataset. Files are validated against the OPPTS 860.1500 schema before processing.">
      
      {phase === "idle" &&
      <div
        onClick={triggerPicker}
        onDragOver={(e) => {e.preventDefault();setDragOver(true);}}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => {e.preventDefault();setDragOver(false);triggerPicker();}}
        style={{
          border: `2px dashed ${dragOver ? "var(--rac-primary)" : "var(--rac-line-strong, #cbd5e1)"}`,
          background: dragOver ? "var(--rac-primary-bg)" : "var(--rac-surface-alt)",
          borderRadius: 14, padding: "48px 32px", textAlign: "center", cursor: "pointer",
          transition: "all 140ms"
        }}>
        
          <div style={{ width: 56, height: 56, margin: "0 auto 16px", borderRadius: 12, background: "#fff", border: "1px solid var(--rac-line)", display: "grid", placeItems: "center", color: "var(--rac-primary)" }}>
            <I.Upload size={26} />
          </div>
          <div style={{ fontSize: 16, fontWeight: 600, color: "var(--rac-ink)", marginBottom: 4 }}>Drop your trial-data CSV here</div>
          <div style={{ fontSize: 13, color: "var(--rac-muted)", marginBottom: 16 }}>or click to browse · accepts .csv up to 25 MB</div>
          <button className="rac-btn rac-btn--primary rac-btn--sm" onClick={(e) => {e.stopPropagation();triggerPicker();}}>
            <I.Folder size={13} /> Choose file
          </button>
        </div>
      }

      {phase === "uploading" &&
      <div className="rac-card" style={{ padding: 24 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--rac-primary-bg)", color: "var(--rac-primary)", display: "grid", placeItems: "center" }}>
              <I.File size={22} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="rac-mono" style={{ fontSize: 13.5, fontWeight: 600, color: "var(--rac-ink)" }}>{fileMeta?.name}</div>
              <div style={{ fontSize: 12, color: "var(--rac-muted)" }}>{fileMeta?.size} · uploading…</div>
            </div>
            <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={reset}><I.X size={13} /></button>
          </div>
          <div style={{ height: 6, borderRadius: 3, background: "var(--rac-line)", overflow: "hidden" }}>
            <div style={{ height: "100%", width: `${progress}%`, background: "var(--rac-primary)", transition: "width 90ms" }} />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11.5, color: "var(--rac-muted)" }}>
            <span>Streaming to OPPTS validator…</span>
            <span>{Math.round(progress)}%</span>
          </div>
        </div>
      }

      {phase === "parsed" && fileMeta &&
      <div className="rac-card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--rac-line)", display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--rac-pass-bg)", color: "var(--rac-pass)", display: "grid", placeItems: "center" }}>
              <I.Check size={22} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="rac-mono" style={{ fontSize: 13.5, fontWeight: 600, color: "var(--rac-ink)" }}>{fileMeta.name}</div>
              <div style={{ fontSize: 12, color: "var(--rac-muted)" }}>{fileMeta.size} · {fileMeta.rows} rows · 11 columns · schema valid</div>
            </div>
            <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={reset}>
              <I.RefreshCw size={12} /> Replace file
            </button>
          </div>

          <div style={{ padding: "16px 22px", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, borderBottom: "1px solid var(--rac-line)", background: "var(--rac-surface-alt)" }}>
            <Stat label="Field trials" value={fileMeta.rows} />
            <Stat label="USEPA regions" value={fileMeta.regions} />
            <Stat label="Crop" value="Sweet Corn" />
            <Stat label="Schema" value="OPPTS 860.1500" />
          </div>

          <div style={{ padding: "16px 22px" }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--rac-muted)", letterSpacing: "0.04em", textTransform: "uppercase", marginBottom: 8 }}>Preview · all 11 schema columns</div>
            <div style={{ maxHeight: 200, overflowY: "auto", overflowX: "auto", border: "1px solid var(--rac-line)", borderRadius: 6, background: "#fff" }}>
              <table style={{ fontSize: 11.5, fontFamily: "var(--font-mono)", borderCollapse: "collapse", whiteSpace: "nowrap" }}>
                <thead style={{ position: "sticky", top: 0, background: "#fafbfd" }}>
                  <tr>
                    {CSV_COLUMNS.map((h) =>
                  <th key={h} style={{ padding: "7px 10px", textAlign: "left", color: "var(--rac-muted)", borderBottom: "1px solid var(--rac-line)", fontWeight: 600 }}>{h}</th>
                  )}
                  </tr>
                </thead>
                <tbody>
                  {(SAMPLE_TRIALS[sel] || []).slice(0, 5).map((r) =>
                <tr key={r.id}>
                      <td style={{ padding: "6px 10px" }}>{r.id}</td>
                      <td style={{ padding: "6px 10px" }}>{r.state}</td>
                      <td style={{ padding: "6px 10px" }}>{r.county}</td>
                      <td style={{ padding: "6px 10px" }}>{r.region}</td>
                      <td style={{ padding: "6px 10px" }}>{r.crop}</td>
                      <td style={{ padding: "6px 10px" }}>{r.variety}</td>
                      <td style={{ padding: "6px 10px" }}>{r.rate}</td>
                      <td style={{ padding: "6px 10px" }}>{r.apps}</td>
                      <td style={{ padding: "6px 10px" }}>{r.phi}</td>
                      <td style={{ padding: "6px 10px" }}>{r.harvest}</td>
                      <td style={{ padding: "6px 10px" }}>{r.residue}</td>
                    </tr>
                )}
                  {(SAMPLE_TRIALS[sel]?.length || 0) > 5 &&
                <tr><td colSpan={CSV_COLUMNS.length} style={{ padding: "6px 10px", color: "var(--rac-muted)", fontFamily: "var(--font-sans)", fontStyle: "italic" }}>+ {SAMPLE_TRIALS[sel].length - 5} more rows…</td></tr>
                }
                </tbody>
              </table>
            </div>
          </div>
        </div>
      }

      {/* Discreet sample picker - for the demo only */}
      {phase === "idle" &&
      <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--rac-muted)", textAlign: "center" }}>
          Don't have a file handy? <button onClick={() => setShowSamples(true)} style={{ background: "none", border: "none", color: "var(--rac-primary)", cursor: "pointer", fontSize: "inherit", padding: 0, textDecoration: "underline" }}>Use a sample dataset</button> to walk through the flow.
        </div>
      }

      {showSamples &&
      <div onClick={() => setShowSamples(false)} style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.45)", zIndex: 200, display: "grid", placeItems: "center", padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} className="rac-card" style={{ width: 520, maxWidth: "100%", padding: 0 }}>
            <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--rac-line)" }}>
              <div style={{ fontSize: 15, fontWeight: 600, color: "var(--rac-ink)" }}>Choose a sample file</div>
              <div style={{ fontSize: 12.5, color: "var(--rac-muted)", marginTop: 2 }}>Pre-built datasets used to demonstrate the workflow end-to-end.</div>
            </div>
            <div style={{ padding: 14, display: "grid", gap: 10 }}>
              <SampleRow
              filename="sweet_corn_residue_2024.csv"
              meta="184 KB · 8 trials · 4 regions"
              desc="Multi-region dataset, residues within tolerance"
              onClick={() => startUpload("pass")} />
            
              <SampleRow
              filename="sweet_corn_residue_2024.csv"
              meta="142 KB · 6 trials · 2 regions"
              desc="Limited geography, elevated residues"
              onClick={() => startUpload("fail")} />
            
            </div>
            <div style={{ padding: "12px 22px", borderTop: "1px solid var(--rac-line)", display: "flex", justifyContent: "flex-end" }}>
              <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={() => setShowSamples(false)}>Cancel</button>
            </div>
          </div>
        </div>
      }

      <div className="rac-card" style={{ marginTop: 18 }}>
        <div className="rac-card__head" style={{ display: "flex", alignItems: "center", cursor: "pointer" }} onClick={() => setShowSpec((s) => !s)}>
          <div>
            <div className="rac-card__title">Expected file format</div>
            <div className="rac-card__sub">11-column CSV per the OPPTS 860.1500 trial-data schema</div>
          </div>
          <I.ChevronDown size={16} style={{ marginLeft: "auto", transform: showSpec ? "rotate(180deg)" : "none", transition: "transform 120ms" }} />
        </div>
        {showSpec &&
        <div className="rac-card__body" style={{ paddingTop: 0 }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
              {CSV_COLUMNS.map((c) =>
            <code key={c} className="rac-mono" style={{ background: "var(--rac-surface-alt)", padding: "6px 10px", borderRadius: 6, border: "1px solid var(--rac-line)" }}>{c}</code>
            )}
            </div>
          </div>
        }
      </div>

      <FooterNav
        onBack={() => onNavigate("registrant.a2")}
        onNext={() => onNavigate("registrant.a4")}
        nextDisabled={phase !== "parsed"}
        nextLabel="Continue to decision tree" />
      
    </Page>);

}

function Stat({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: "var(--rac-muted)", textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 600, marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--rac-ink)" }}>{value}</div>
    </div>);

}

function SampleRow({ filename, meta, desc, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", border: "1px solid var(--rac-line)",
      borderRadius: 10, background: "#fff", textAlign: "left", cursor: "pointer", width: "100%"
    }}>
      <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--rac-surface-alt)", color: "var(--rac-ink-2)", display: "grid", placeItems: "center", flexShrink: 0 }}>
        <I.File size={18} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="rac-mono" style={{ fontSize: 12.5, fontWeight: 600, color: "var(--rac-ink)" }}>{filename}</div>
        <div style={{ fontSize: 11.5, color: "var(--rac-muted)" }}>{desc} · {meta}</div>
      </div>
      <I.ChevronRight size={14} style={{ color: "var(--rac-muted)" }} />
    </button>);

}

// ─── A4 - Decision Tree ────────────────────────────────────────────────
function A4DecisionTree({ submission, onNavigate }) {
  return (
    <Page
      kicker="Step 4 of 6"
      title="Decision tree - Post-Season Assessment"
      subtitle="The cascading number/distribution checks for OPPTS 860.1500 Group 15 crops. The path for your selected demo file is highlighted.">
      
      <TreeView selectedFile={submission.selectedDemoFile} />
      <FooterNav
        onBack={() => onNavigate("registrant.a3")}
        onNext={() => onNavigate("registrant.a5")}
        nextLabel="Continue to report" />
      
    </Page>);

}

// ─── A5 - Output Report ────────────────────────────────────────────────
function A5OutputReport({ submission, user, onUpdate, onNavigate }) {
  useEffect(() => {if (!submission.reportViewed) onUpdate({ reportViewed: true });}, []);
  const sc = window.stepCompletion(submission);

  if (!sc.a5_unlocked) {
    return (
      <Page kicker="Step 5 of 6" title="Output report" subtitle="Complete crop selection, GAP conditions, and trial-data upload to generate the report.">
        <div className="rac-banner rac-banner--info">
          <I.Info />
          <div>
            <strong>Prerequisites incomplete</strong>
            <div style={{ fontSize: 13, marginTop: 4 }}>The assessment report becomes available once steps 1–3 are confirmed.</div>
            <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
              {!submission.crop && <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={() => onNavigate("registrant.a1")}>Go to crop selection</button>}
              {!submission.gapConfirmed && <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={() => onNavigate("registrant.a2")}>Confirm GAP</button>}
              {!submission.selectedDemoFile && <button className="rac-btn rac-btn--ghost rac-btn--sm" onClick={() => onNavigate("registrant.a3")}>Upload trial data</button>}
            </div>
          </div>
        </div>
      </Page>);

  }

  const data = REPORT_DATA[submission.selectedDemoFile];
  const path = DEMO_PATHS[submission.selectedDemoFile];
  const isPass = data.overallResult === "PASS";

  return (
    <Page
      kicker="Step 5 of 6"
      title="Assessment report"
      subtitle={`Pre-computed for ${data.submissionRef}. In production this report is generated by executing the OPPTS 860.1500 rules against your trial data.`}
      actions={[
      <button key="d" className="rac-btn rac-btn--ghost"><I.Download size={14} /> Download PDF</button>]
      }>
      
      <div className={`rac-banner rac-banner--${isPass ? "pass" : "fail"}`} style={{ marginBottom: 24 }}>
        {isPass ? <I.Check size={20} /> : <I.X size={20} />}
        <div style={{ flex: 1 }}>
          <strong style={{ fontSize: 15 }}>
            {isPass ? "PASS - Trial data meets USEPA OPPTS 860.1500 requirements" : "FAIL - Trial data does NOT meet OPPTS 860.1500 requirements"}
          </strong>
          <div style={{ fontSize: 13, marginTop: 4 }}>
            Sweet Corn (Group 15 - Cereal Grains) · {data.totalTrials} trials
            {!isPass && " · Geographic distribution insufficient at Crop Group level"}
          </div>
        </div>
      </div>

      <SummaryHeader submission={submission} user={user} data={data} />
      <ReportSection title="1 · Trial count assessment">
        <ResultTable
          rows={data.trialCounts}
          columns={[
          { key: "criterion", label: "Criterion", flex: 2, render: (v, r) =>
            <div>
                <div>{v}</div>
                {r.note && <div style={{ fontSize: 11.5, color: "var(--rac-muted)", marginTop: 2, lineHeight: 1.45 }}>{r.note}</div>}
              </div>
          },
          { key: "required", label: "Required", align: "center" },
          { key: "submitted", label: "Submitted", align: "center" },
          { key: "result", label: "Result", align: "right", render: (v) => <ResultPill value={v} /> }]
          } />
        
      </ReportSection>

      <ReportSection title="2 · Geographic distribution assessment">
        <ResultTable
          rows={data.distribution}
          columns={[
          { key: "region", label: "Region", render: (v, r) => `${v} - ${r.name}`, flex: 2 },
          { key: "states", label: "States", render: (v) => <span className="rac-mono" style={{ fontSize: 11.5, color: "var(--rac-muted)" }}>{v}</span> },
          { key: "present", label: "Trials present", align: "center" },
          { key: "result", label: "Result", align: "right", render: (v) => <ResultPill value={v} /> }]
          } />
        
      </ReportSection>

      <ReportSection title="3 · Decision tree path">
        <div style={{ marginBottom: 16 }}>
          <TreeView selectedFile={submission.selectedDemoFile} />
        </div>
        <div style={{ padding: 18, background: "var(--rac-surface-alt)", borderRadius: 8 }}>
          <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 6, marginBottom: path.failingRule ? 16 : 0 }}>
            {path.nodes.map((n, i) => {
              const isFailNode = path.failingNode === n;
              const isTerminal = n.startsWith("PASS") || n.startsWith("FAIL");
              const cls = isTerminal && n.startsWith("PASS") ? "pass" : isTerminal ? "fail" : isFailNode ? "fail" : "info";
              return (
                <React.Fragment key={n}>
                  <span className={`rac-pill rac-pill--${cls}`} style={{ padding: "4px 10px" }}>{n}</span>
                  {i < path.nodes.length - 1 && <I.ChevronRight size={12} style={{ color: "var(--rac-muted)" }} />}
                </React.Fragment>);

            })}
          </div>
          {path.failingRule &&
          <div style={{ borderTop: "1px solid #f1c1c8", paddingTop: 14, fontSize: 13, color: "#832231" }}>
              <strong>Failing rule ({path.failingRule.nodeId}):</strong> {path.failingRule.ruleText} - <strong>NO.</strong> {path.failingRule.explanation}
            </div>
          }
        </div>
      </ReportSection>

      <FooterNav
        onBack={() => onNavigate("registrant.a4")}
        onNext={() => onNavigate("registrant.a6")}
        nextLabel="Continue to submit" />
      
    </Page>);

}

function SummaryHeader({ submission, user, data }) {
  const g = submission.gap;
  return (
    <div className="rac-card" style={{ marginBottom: 20 }}>
      <div className="rac-card__body">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
          <SummaryItem label="Crop" value="Sweet Corn" sub="Group 15 · Cereal Grains" />
          <SummaryItem label="Active ingredient" value={g.activeIngredient} sub={`${g.applicationRate} ${g.applicationRateUnit} · ${g.numberOfApps} apps · ${g.phi}-day PHI`} />
          <SummaryItem label="Submission ref." value={data.submissionRef} sub={`Submitted by ${user?.company || "-"}`} />
          <SummaryItem label="Assessment date" value="May 1, 2026" sub="OPPTS 860.1500 v1996" />
        </div>
      </div>
    </div>);

}
function SummaryItem({ label, value, sub }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: "var(--rac-muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--rac-ink)", marginTop: 4 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: "var(--rac-muted)", marginTop: 2 }}>{sub}</div>}
    </div>);

}

function ReportSection({ title, children }) {
  return (
    <div className="rac-card" style={{ marginBottom: 18 }}>
      <div className="rac-card__head"><div className="rac-card__title" style={{ fontSize: 14 }}>{title}</div></div>
      <div style={{ padding: 0 }}>{children}</div>
    </div>);

}

function ResultTable({ rows, columns }) {
  return (
    <table className="rac-table">
      <thead>
        <tr>
          {columns.map((c) => <th key={c.key} style={{ textAlign: c.align || "left" }}>{c.label}</th>)}
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) =>
        <tr key={i}>
            {columns.map((c) =>
          <td key={c.key} style={{ textAlign: c.align || "left" }}>
                {c.render ? c.render(r[c.key], r) : r[c.key]}
              </td>
          )}
          </tr>
        )}
      </tbody>
    </table>);

}

// ─── A6 - Submit ────────────────────────────────────────────────────────
function A6Submit({ submission, user, onUpdate, onNavigate, onHome }) {
  const [showConfirm, setShowConfirm] = useState(false);
  const [confirmAccurate, setConfirmAccurate] = useState(false);
  const [confirmBound, setConfirmBound] = useState(false);
  const data = REPORT_DATA[submission.selectedDemoFile];
  const isPass = data.overallResult === "PASS";

  const submit = () => {onUpdate({ submitted: true });setShowConfirm(true);};
  const canSubmit = confirmAccurate && confirmBound && !submission.submitted;

  return (
    <Page kicker="Step 6 of 6" title="Submit for regulatory review" subtitle="Send your assessment and trial data to the USEPA RaC Platform for regulator review.">
      <div className="rac-card" style={{ marginBottom: 18 }}>
        <div className="rac-card__head"><div className="rac-card__title">Submission summary</div></div>
        <div className="rac-card__body" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
          <div>
            <SummaryItem label="Crop" value="Sweet Corn - Group 15" />
            <div style={{ height: 14 }} />
            <SummaryItem label="Active ingredient" value={submission.gap.activeIngredient} sub={`${submission.gap.applicationRate} ${submission.gap.applicationRateUnit}`} />
            <div style={{ height: 14 }} />
            <SummaryItem label="Application" value={submission.gap.applicationMethod} sub={`${submission.gap.numberOfApps} applications · PHI ${submission.gap.phi} days`} />
          </div>
          <div>
            <SummaryItem label="Trial data" value={submission.selectedDemoFile === "pass" ? "sweet_corn_trials_PASS.csv" : "sweet_corn_trials_FAIL.csv"} sub={`${data.totalTrials} trials · ${submission.selectedDemoFile === "pass" ? 4 : 2} regions`} />
            <div style={{ height: 14 }} />
            <SummaryItem label="Submitter" value={user?.name} sub={user?.company} />
            <div style={{ height: 14 }} />
            <SummaryItem label="Submission ref." value={data.submissionRef} />
          </div>
        </div>
      </div>

      <div className={`rac-banner rac-banner--${isPass ? "pass" : "fail"}`} style={{ marginBottom: 18 }}>
        {isPass ? <I.Check size={20} /> : <I.X size={20} />}
        <div>
          <strong>Pre-computed result: {isPass ? "PASS" : "FAIL"}</strong>
          <div style={{ fontSize: 13, marginTop: 2 }}>
            {isPass ?
            "All count and distribution checks satisfied. Ready for submission." :
            "Failing rule N8 - distribution does not qualify at Crop Subgroup (fallback) level. You may still submit for regulator feedback."}
          </div>
        </div>
      </div>

      <div className="rac-card" style={{ marginBottom: 18 }}>
        <div className="rac-card__head"><div className="rac-card__title">Confirm and submit</div></div>
        <div className="rac-card__body">
          <label className="rac-check" style={{ marginBottom: 10 }}>
            <input type="checkbox" checked={confirmAccurate} onChange={(e) => setConfirmAccurate(e.target.checked)} />
            <span style={{ fontSize: 13 }}>I confirm the GAP conditions and trial data above are accurate.</span>
          </label>
          <label className="rac-check">
            <input type="checkbox" checked={confirmBound} onChange={(e) => setConfirmBound(e.target.checked)} />
            <span style={{ fontSize: 13 }}>I understand this submission is bound by 40 CFR §158 and PRIA 5.</span>
          </label>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 18 }}>
            <button className="rac-btn rac-btn--ghost" onClick={() => onNavigate("registrant.a5")}>Back to report</button>
            <button className="rac-btn rac-btn--primary" onClick={submit} disabled={!canSubmit}>
              <I.Send size={14} />
              {submission.submitted ? "Submitted" : "Submit to regulator"}
            </button>
          </div>
        </div>
      </div>

      <window.Modal open={showConfirm} onClose={() => setShowConfirm(false)}>
        <div style={{ padding: "32px 28px" }}>
          <div style={{ width: 48, height: 48, borderRadius: "50%", background: "var(--rac-pass-bg)", color: "var(--rac-pass)", display: "grid", placeItems: "center", marginBottom: 14 }}>
            <I.Check size={24} />
          </div>
          <h2 style={{ fontSize: 20, marginBottom: 6 }}>Submission sent</h2>
          <p style={{ fontSize: 14, color: "var(--rac-muted)", marginBottom: 18 }}>
            <strong style={{ color: "var(--rac-ink)" }}>{data.submissionRef}</strong> has been routed to USEPA OPPTS for review. You'll receive email updates as the regulator progresses through file validation and assessment review.
          </p>
          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
            <button className="rac-btn rac-btn--ghost" onClick={() => {setShowConfirm(false);onHome();}}>Back to dashboard</button>
            <button className="rac-btn rac-btn--primary" onClick={() => setShowConfirm(false)}>Stay on page</button>
          </div>
        </div>
      </window.Modal>
    </Page>);

}

// ─── Common footer nav ─────────────────────────────────────────────────
function FooterNav({ onBack, onNext, backLabel = "Back", nextLabel = "Continue", nextDisabled }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--rac-line)" }}>
      <button className="rac-btn rac-btn--ghost" onClick={onBack}><I.Back size={14} /> {backLabel}</button>
      <button className="rac-btn rac-btn--primary" onClick={onNext} disabled={nextDisabled}>{nextLabel} <I.Forward size={14} /></button>
    </div>);

}

Object.assign(window, {
  RegistrantDashboard, A1CropSelection, A2GAPConditions, A3FileSelection,
  A4DecisionTree, A5OutputReport, A6Submit, ArchivedSubmission
});