// Protocol generation, AI protocol review, side panels (knowledge, audit, case)
function GeneratingProtocol({ onDone }) {
  const [pct, setPct] = useState(10);
  useEffect(() => {
    const id = setInterval(() => {
      setPct(p => {
        const n = Math.min(100, p + 4 + Math.random() * 6);
        if (n >= 100) { clearInterval(id); setTimeout(onDone, 500); }
        return n;
      });
    }, 260);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="page page-narrow" data-screen-label="07 Generating protocol">
      <div className="page-head">
        <div>
          <div className="page-title">Drafting protocol</div>
          <div className="page-sub">Vykon is synthesising your reviewed labs into a draft protocol</div>
        </div>
      </div>

      <div className="card card-pad" style={{display: "flex", flexDirection: "column", gap: 22}}>
        <div className="row" style={{gap: 16}}>
          <div style={{width: 56, height: 56, borderRadius: "50%", border: "3px solid var(--border)", borderTopColor: "var(--accent)", animation: "spin 1.1s linear infinite"}}></div>
          <div style={{flex: 1}}>
            <div style={{fontSize: 18, fontWeight: 600}}>Generating protocol draft</div>
            <div className="muted">Cross-referencing 12 minerals, 6 ratios, blood panel · {Math.round(pct)}%</div>
          </div>
        </div>
        <div className="progress-bar"><div style={{width: pct + "%"}}></div></div>

        <div className="col" style={{gap: 6}}>
          {[
            ["Building case narrative", pct > 20],
            ["Selecting supplement candidates", pct > 45],
            ["Computing dosing per practitioner defaults", pct > 70],
            ["Running safety checks & flag scoring", pct > 92],
          ].map(([l, ok]) => (
            <div key={l} className="row" style={{gap: 8, padding: "8px 0", color: ok ? "var(--text)" : "var(--text-3)"}}>
              {ok ? <I.checkCircle size={14} style={{color: "var(--accent)"}}/> : <div style={{width: 14, height: 14, borderRadius: 50, border: "1.5px solid var(--border-strong)"}}/>}
              <span style={{fontSize: 13.5}}>{l}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ProtocolReview({ go, openPanel, scenario, setScenario, clientName }) {
  const [yellowAck, setYellowAck] = useState(false);
  const [escalated, setEscalated] = useState(false);
  const [ready, setReady] = useState(false);

  const blocked = scenario === "red" && !escalated;
  const needsAck = scenario === "yellow" && !yellowAck;

  return (
    <div className="page" data-screen-label="08 Protocol review">
      <div className="page-head">
        <div>
          <div className="row" style={{gap: 8, marginBottom: 6}}>
            <span className="chip">Draft v3 · {clientName || "Amelia Hart"}</span>
            <span className="chip">Built {new Date().toLocaleDateString("en-US", { month: "short", day: "numeric" })}, 09:42</span>
            <span className="chip green"><I.sparkle size={11}/> AI-assisted</span>
          </div>
          <div className="page-title">Protocol review</div>
          <div className="page-sub">Review the AI-drafted protocol below. Mark ready when you're satisfied — or escalate if flagged.</div>
        </div>
        <div className="row">
          <button className="btn" onClick={() => openPanel("audit")}><I.shield size={14}/> Audit trace</button>
          <button className="btn" onClick={() => openPanel("case")}><I.doc size={14}/> Case compilation</button>
          <button className="btn" onClick={() => openPanel("knowledge")}><I.brain size={14}/> Ask assistant</button>
        </div>
      </div>

      {/* Scenario toggle (prototype convenience) */}
      <div className="card card-pad" style={{marginBottom: 16, display: "flex", gap: 14, alignItems: "center"}}>
        <div className="muted" style={{fontSize: 12.5}}>Prototype scenario:</div>
        <div className="row" style={{gap: 6}}>
          {[["green", "No blocking issues"], ["yellow", "Yellow flags · acknowledge"], ["red", "Red flags · mentor review"]].map(([k, l]) => (
            <button key={k} className={"btn sm" + (scenario === k ? " primary" : "")} onClick={() => { setScenario(k); setYellowAck(false); setEscalated(false); setReady(false); }}>{l}</button>
          ))}
        </div>
        <div className="spacer"></div>
        <div className="muted" style={{fontSize: 12}}>This toggle is only in the prototype — production drives this from the safety engine.</div>
      </div>

      <div className="grid" style={{gridTemplateColumns: "minmax(0,1fr) 360px", gap: 20}}>
        <div style={{display: "flex", flexDirection: "column", gap: 16}}>
          {/* Narrative */}
          <div className="card">
            <div className="card-head"><div className="card-title">Case narrative</div><button className="btn sm ghost"><I.edit size={12}/> Edit</button></div>
            <div style={{padding: "16px 20px", fontSize: 14, lineHeight: 1.65, color: "var(--text-2)"}}>
              <p style={{margin: "0 0 10px"}}>
                <strong style={{color: "var(--text)"}}>{clientName || "Amelia"}</strong> presents a <strong style={{color: "var(--text)"}}>Slow 2</strong> oxidative pattern with a Ca/Mg ratio of 18.25 (ideal ~6.7), indicating magnesium loss and sympathetic dominance. Sodium and potassium remain low, consistent with adrenal under-function. Copper is mildly elevated relative to zinc; pair with a Cu/Zn ratio of 8.82 — within range but worth monitoring at retest.
              </p>
              <p style={{margin: 0}}>
                The blood panel corroborates: ferritin is sub-optimal (28 ng/mL) and TSH sits at the high-normal edge. Recommend a 90-day mineral balancing phase, then a retest with thyroid panel.
              </p>
            </div>
          </div>

          {/* Supplements & dosing */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Supplements & dosing</div>
              <div className="row"><button className="btn sm"><I.plus size={12}/> Add</button></div>
            </div>
            <table className="tbl">
              <thead><tr><th>Supplement</th><th>Form</th><th>Dose</th><th>Schedule</th><th>Phase</th><th></th></tr></thead>
              <tbody>
                {[
                  ["Magnesium glycinate", "Powder · 200mg/scoop", "1 scoop", "PM, w/ food", "Weeks 1–12"],
                  ["Zinc picolinate", "Capsule · 25mg", "1 cap", "AM, empty stomach", "Weeks 1–8"],
                  ["Adrenal cocktail", "Custom", "1 serving", "Mid-afternoon", "Weeks 1–12"],
                  ["Selenium (selenomethionine)", "Capsule · 200mcg", "1 cap", "AM w/ food", "Weeks 1–12"],
                  ["Vitamin D3 / K2", "Drops · 5000 IU / 100mcg", "1 drop", "AM w/ fat", "Weeks 1–12"],
                ].map(([s, f, d, sch, p], i) => (
                  <tr key={i}>
                    <td style={{fontWeight: 500}}><span className="row" style={{gap: 8}}><I.pill size={14} style={{color: "var(--text-3)"}}/> {s}</span></td>
                    <td className="muted">{f}</td>
                    <td className="mono">{d}</td>
                    <td className="muted">{sch}</td>
                    <td><span className="chip">{p}</span></td>
                    <td><button className="icon-btn"><I.more size={14}/></button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Instructions */}
          <div className="card">
            <div className="card-head"><div className="card-title">Client-facing instructions</div><button className="btn sm ghost"><I.edit size={12}/> Edit</button></div>
            <div style={{padding: "16px 20px", fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.65}}>
              <ul style={{margin: 0, paddingLeft: 18}}>
                <li>Start magnesium glycinate on day 1, taken 30 min before sleep with food.</li>
                <li>Hold off on zinc if any nausea — re-introduce on day 3.</li>
                <li>Hydrate aggressively for the first two weeks (target 80oz/day) to support mineral shifts.</li>
                <li>Re-test HTMA at week 12; book a thyroid panel at week 10.</li>
              </ul>
            </div>
          </div>
        </div>

        {/* RIGHT — safety panel + actions */}
        <div style={{display: "flex", flexDirection: "column", gap: 16, position: "sticky", top: 0, alignSelf: "start"}}>
          <SafetyPanel scenario={scenario} yellowAck={yellowAck} setYellowAck={setYellowAck} escalated={escalated} setEscalated={setEscalated}/>

          <div className="card card-pad">
            <div className="card-title" style={{marginBottom: 10}}>Actions</div>
            <div style={{display: "flex", flexDirection: "column", gap: 8}}>
              <button className="btn primary lg" disabled={blocked || needsAck || ready} onClick={() => setReady(true)}>
                {ready ? <><I.checkCircle size={14}/> Marked ready</> : <>Mark protocol ready <I.check size={14}/></>}
              </button>
              <button className="btn"><I.send size={14}/> Send to client portal</button>
              <button className="btn ghost" onClick={() => go("client")}><I.arrowL size={14}/> Return to client profile</button>
            </div>
          </div>

          <div className="card card-pad">
            <div className="card-title" style={{marginBottom: 10}}>Case-support tools</div>
            <div style={{display: "flex", flexDirection: "column", gap: 6}}>
              <button className="nav-item" onClick={() => openPanel("audit")}><span className="ico"><I.shield size={16}/></span><span>Open audit trace</span><I.chevR size={12} style={{marginLeft: "auto"}}/></button>
              <button className="nav-item" onClick={() => openPanel("case")}><span className="ico"><I.doc size={16}/></span><span>Open case compilation</span><I.chevR size={12} style={{marginLeft: "auto"}}/></button>
              <button className="nav-item" onClick={() => openPanel("knowledge")}><span className="ico"><I.brain size={16}/></span><span>Ask knowledge assistant</span><I.chevR size={12} style={{marginLeft: "auto"}}/></button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function SafetyPanel({ scenario, yellowAck, setYellowAck, escalated, setEscalated }) {
  if (scenario === "green") {
    return (
      <div className="card">
        <div className="card-head">
          <div className="row" style={{gap: 8}}><I.shield size={16} style={{color: "var(--accent)"}}/><div className="card-title">Safety check</div></div>
          <span className="badge green"><span className="dot"></span> Clear</span>
        </div>
        <div style={{padding: "16px 20px", fontSize: 13.5, color: "var(--text-2)"}}>
          No blocking issues detected. All supplements are within practitioner-approved ranges.
          <div className="divider"></div>
          <div className="muted" style={{fontSize: 12.5}}>Last safety run · 2 sec ago · 14 checks passed</div>
        </div>
      </div>
    );
  }
  if (scenario === "yellow") {
    return (
      <div className="card" style={{borderColor: "var(--warn-container)"}}>
        <div className="card-head" style={{borderColor: "var(--warn-container)"}}>
          <div className="row" style={{gap: 8}}><I.warn size={16} style={{color: "var(--warn)"}}/><div className="card-title">Yellow flags · 2</div></div>
          <span className="badge amber"><span className="dot"></span> Acknowledge</span>
        </div>
        <div style={{padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12}}>
          <FlagItem title="Selenium near upper end of personal tolerance" detail="Client previously reported metallic taste on selenium >150mcg. Consider 100mcg." kind="amber"/>
          <FlagItem title="Copper monitoring recommended" detail="Cu/Zn at 8.82 — within range, but trending up across last 2 tests." kind="amber"/>
          <div className="divider" style={{margin: 0}}></div>
          <label className="row" style={{gap: 10, alignItems: "flex-start", cursor: "pointer"}}>
            <input type="checkbox" checked={yellowAck} onChange={e => setYellowAck(e.target.checked)} style={{marginTop: 3}}/>
            <div>
              <div style={{fontWeight: 500}}>I acknowledge both yellow flags</div>
              <div className="muted" style={{fontSize: 12}}>Required before marking ready.</div>
            </div>
          </label>
        </div>
      </div>
    );
  }
  // red
  return (
    <div className="card" style={{borderColor: "var(--danger-container)"}}>
      <div className="card-head" style={{borderColor: "var(--danger-container)"}}>
        <div className="row" style={{gap: 8}}><I.flag size={16} style={{color: "var(--danger)"}}/><div className="card-title">Red flags · 1</div></div>
        <span className="badge red"><span className="dot"></span> Blocking</span>
      </div>
      <div style={{padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12}}>
        <FlagItem title="Lead (Pb) at 0.42 mg% — significantly above safe threshold" detail="Heavy-metal protocols require mentor sign-off per practice policy. Cannot mark ready until cleared." kind="red"/>
        {!escalated ? (
          <button className="btn" style={{background: "var(--danger-container)", borderColor: "transparent", color: "var(--danger-on-container)"}} onClick={() => setEscalated(true)}>
            <I.send size={14}/> Send to mentor for review
          </button>
        ) : (
          <div className="alert info">
            <I.clock size={16} className="alert-icon"/>
            <div>
              <div style={{fontWeight: 600}}>Awaiting mentor review</div>
              <div style={{marginTop: 2}}>Sent to Dr. Lena Park · ETA 6 hours. You'll be notified when cleared or returned with notes.</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function FlagItem({ title, detail, kind }) {
  return (
    <div style={{display: "flex", gap: 10}}>
      <div style={{width: 6, height: 6, borderRadius: 50, background: kind === "red" ? "var(--danger)" : "var(--warn)", marginTop: 7, flex: "none"}}></div>
      <div>
        <div style={{fontWeight: 500, fontSize: 13.5}}>{title}</div>
        <div className="muted" style={{fontSize: 12.5, marginTop: 2}}>{detail}</div>
      </div>
    </div>
  );
}

/* -------- Side panels -------- */
function SidePanel({ kind, onClose, openPanel }) {
  return (
    <div className="modal-backdrop" onClick={onClose} style={{justifyContent: "flex-end", padding: 0}}>
      <div className="side-panel" onClick={e => e.stopPropagation()}>
        <header>
          <div className="row" style={{gap: 10}}>
            {kind === "knowledge" && <><I.brain size={16}/><div style={{fontWeight: 600}}>Knowledge assistant</div></>}
            {kind === "audit" && <><I.shield size={16}/><div style={{fontWeight: 600}}>Audit trace</div></>}
            {kind === "case" && <><I.doc size={16}/><div style={{fontWeight: 600}}>Case compilation</div></>}
          </div>
          <button className="icon-btn" onClick={onClose}><I.x size={16}/></button>
        </header>
        <div className="body">
          {kind === "knowledge" && <KnowledgePanel openPanel={openPanel}/>}
          {kind === "audit" && <AuditPanel openPanel={openPanel} onClose={onClose}/>}
          {kind === "case" && <CasePanel openPanel={openPanel}/>}
        </div>
      </div>
    </div>
  );
}

function KnowledgePanel({ openPanel }) {
  const [thread, setThread] = useState([
    { role: "assistant", text: "Grounded in this case's HTMA, blood panel, and the Slow 2 protocol library. Ask me anything." },
  ]);
  const [input, setInput] = useState("");
  function ask(q) {
    if (!q.trim()) return;
    const next = [...thread, { role: "user", text: q }];
    setThread(next);
    setInput("");
    setTimeout(() => {
      setThread([...next, {
        role: "assistant",
        text: `Magnesium glycinate is well-tolerated for Slow 2 patterns at 200–400mg elemental. For ${"Amelia"} specifically — given her Ca/Mg ratio of 18.25 and reported sleep issues — start at 200mg PM and titrate up after week 4 if tolerated. Avoid magnesium oxide; bioavailability is too low for this case.`,
        citations: [
          { label: "Protocol library · Slow 2 §3.1", onClick: () => openPanel("case") },
          { label: "This case · HTMA #2 ratios", onClick: () => openPanel("audit") },
        ],
      }]);
    }, 400);
  }
  return (
    <div style={{display: "flex", flexDirection: "column", gap: 12, height: "100%"}}>
      <div style={{flex: 1, overflow: "auto", display: "flex", flexDirection: "column", gap: 14}}>
        {thread.map((m, i) => (
          <div key={i} style={{display: "flex", flexDirection: "column", gap: 6}}>
            <div className="muted" style={{fontSize: 11, textTransform: "uppercase", letterSpacing: 0.06}}>
              {m.role === "assistant" ? "Vykon assistant" : "You"}
            </div>
            <div style={{padding: "10px 12px", background: m.role === "assistant" ? "var(--surface)" : "transparent", border: m.role === "assistant" ? "1px solid var(--border)" : "1px solid transparent", borderRadius: 10, fontSize: 13.5, lineHeight: 1.55}}>
              {m.text}
            </div>
            {m.citations && (
              <div className="row" style={{gap: 6, flexWrap: "wrap"}}>
                {m.citations.map((c, j) => (
                  <button key={j} className="chip" onClick={c.onClick}><I.link size={11}/> {c.label}</button>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
      <div style={{borderTop: "1px solid var(--border)", paddingTop: 12}}>
        <div style={{display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 10}}>
          {["Why magnesium glycinate?", "Risk of zinc on copper IUD?", "Slow 2 ferritin targets?"].map(s => (
            <button key={s} className="chip" onClick={() => ask(s)}>{s}</button>
          ))}
        </div>
        <div className="input-wrap">
          <input className="input" placeholder="Ask a grounded question…" value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{ if (e.key === "Enter") ask(input); }}/>
          <button className="icon-btn trail" style={{position: "absolute", right: 4, top: "50%", transform: "translateY(-50%)"}} onClick={() => ask(input)}><I.send size={14}/></button>
        </div>
      </div>
    </div>
  );
}

function AuditPanel({ openPanel, onClose }) {
  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14, height: "100%"}}>
      <div style={{flex: 1, overflow: "auto", display: "flex", flexDirection: "column", gap: 14}}>
        <div className="alert info"><I.shield size={14} className="alert-icon"/>Every value, recommendation, and flag traces back to its source. Provenance below.</div>
        {[
          { k: "Extraction", items: [
            "HTMA_Sundar_Nov_2025.pdf · page 1 · table T2 · 16 minerals extracted",
            "OCR confidence ≥ 0.97 for all values · no manual overrides",
            "Validation: 12/12 values within plausibility envelope",
          ]},
          { k: "Reference ranges", items: [
            "Reference range source · Trace Elements, Inc. 2025 reference set",
            "Practice override: Cu/Zn ideal narrowed to 7.5–8.5 (set Jun 2024)",
          ]},
          { k: "Protocol model", items: [
            "Model: vykon-protocol v1.4 · safety-mode strict",
            "Retrieval: 6 docs from Slow 2 library, 2 client history entries",
            "Outputs reviewed by safety classifier · score 0.91",
          ]},
          { k: "Flags raised", items: [
            "Lead elevated · rule R-PB-001 · escalation required",
            "Cu/Zn trending · rule R-CU-007 · monitor",
          ]},
        ].map((g, i) => (
          <div key={i} className="card card-pad">
            <div className="card-title" style={{marginBottom: 8}}>{g.k}</div>
            <ul style={{margin: 0, paddingLeft: 18, color: "var(--text-2)", fontSize: 13, lineHeight: 1.65}}>
              {g.items.map((it, j) => <li key={j}>{it}</li>)}
            </ul>
          </div>
        ))}
      </div>
      <div style={{borderTop: "1px solid var(--border)", paddingTop: 12, display: "flex", gap: 8}}>
        <button className="btn primary" style={{flex: 1}} onClick={onClose}><I.arrowL size={14}/> Return to protocol</button>
        <button className="btn" style={{flex: 1}} onClick={() => openPanel("knowledge")}><I.brain size={14}/> Ask about this trace</button>
      </div>
    </div>
  );
}

function CasePanel({ openPanel }) {
  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      <div className="muted" style={{fontSize: 13}}>Everything Vykon used to draft this protocol — in one scrollable case file.</div>
      {[
        ["Extracted HTMA", "12 minerals · 7 toxic · 6 ratios"],
        ["Reviewed intake", "Adult · presenting: fatigue + crash · 11 fields confirmed from HIF + snapshot"],
        ["Blood panel", "CBC + comprehensive · 1 ferritin study"],
        ["Client history", "2 prior HTMA · 1 protocol on file · 8 notes"],
        ["Protocol draft", "5 supplements · 4 phases · 1 retest reminder"],
        ["Flags", "0 red · 2 yellow"],
        ["Mentor question (case only)", "Cu trending up across last 2 tests — clinically actionable yet?"],
      ].map(([k, v], i) => (
        <div key={i} className="card card-pad row-between" style={{cursor: "pointer"}}>
          <div>
            <div style={{fontWeight: 500}}>{k}</div>
            <div className="muted" style={{fontSize: 12.5, marginTop: 2}}>{v}</div>
          </div>
          <I.chevR size={14} style={{color: "var(--text-3)"}}/>
        </div>
      ))}
      {openPanel && (
        <div style={{borderTop: "1px solid var(--border)", paddingTop: 12, display: "flex", gap: 8}}>
          <button className="btn" style={{flex: 1}} onClick={() => openPanel("audit")}><I.shield size={14}/> Open audit trace</button>
          <button className="btn" style={{flex: 1}} onClick={() => openPanel("knowledge")}><I.brain size={14}/> Ask about this case</button>
        </div>
      )}
    </div>
  );
}

/* -------- Retest suggestion -------- */
function RetestModal({ onClose, onLink, onSkip, clientName }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row" style={{gap: 10, marginBottom: 12}}>
          <I.refresh size={18}/>
          <h3>Link as retest?</h3>
        </div>
        <p className="muted" style={{margin: "0 0 16px", fontSize: 13.5, lineHeight: 1.55}}>
          {clientName || "Amelia Hart"} has 2 prior HTMA reports on file. Want to link this one as a retest? You'll get a side-by-side comparison with deltas and change indicators.
        </p>
        <div className="card card-pad" style={{marginBottom: 16}}>
          <div className="muted" style={{fontSize: 12, marginBottom: 8}}>Most recent prior</div>
          <div className="row-between">
            <div>
              <div style={{fontWeight: 500}}>HTMA #2 · Aug 14, 2025</div>
              <div className="muted" style={{fontSize: 12}}>Trace Elements · 88 days ago</div>
            </div>
            <span className="chip green">Recommended link</span>
          </div>
        </div>
        <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
          <button className="btn" onClick={onSkip}>Skip for now</button>
          <button className="btn primary" onClick={onLink}><I.link size={14}/> Link as retest</button>
        </div>
      </div>
    </div>
  );
}

function RetestComparison({ go, clientName }) {
  const { HTMA_NUTRITIONAL, PRIOR_TEST } = window.MOCK;
  return (
    <div className="page" data-screen-label="09 Retest comparison">
      <div className="page-head">
        <div>
          <div className="row" style={{gap: 8, marginBottom: 6}}>
            <span className="chip"><I.link size={11}/> Linked retest</span>
            <span className="chip">{clientName || "Amelia Hart"}</span>
          </div>
          <div className="page-title">Retest comparison</div>
          <div className="page-sub">Nov 12, 2025 (current) vs Aug 14, 2025 (prior) · 88 days apart</div>
        </div>
        <div className="row">
          <button className="btn" onClick={() => go("client")}><I.arrowL size={14}/> Client profile</button>
          <button className="btn primary" onClick={() => go("protocol")}>Continue to protocol <I.arrowR size={14}/></button>
        </div>
      </div>

      <div className="grid grid-4" style={{marginBottom: 16}}>
        <div className="kpi"><div className="kpi-label">Improvements</div><div className="kpi-val">6</div><div className="kpi-trend up">↑ trending toward ideal</div></div>
        <div className="kpi"><div className="kpi-label">Regressions</div><div className="kpi-val">2</div><div className="kpi-trend warn">↓ moving away from ideal</div></div>
        <div className="kpi"><div className="kpi-label">New flags</div><div className="kpi-val">1</div><div className="kpi-trend">Pb +0.32</div></div>
        <div className="kpi"><div className="kpi-label">Metabolic type</div><div className="kpi-val" style={{fontSize: 20}}>Slow 2 → Slow 2</div><div className="kpi-trend">Stable</div></div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">Nutritional elements · current vs prior</div>
          <div className="row" style={{gap: 6}}><span className="chip">All</span><span className="chip">Movers only</span></div>
        </div>
        <table className="tbl">
          <thead><tr><th>Element</th><th>Prior · Aug 14</th><th>Current · Nov 12</th><th>Δ</th><th>Ideal range</th><th>Trend</th></tr></thead>
          <tbody>
            {HTMA_NUTRITIONAL.map(b => {
              const prior = PRIOR_TEST.values[b.sym];
              if (prior == null) return null;
              const cur = b.value;
              const d = (cur - prior).toFixed(2);
              const up = cur > prior;
              const ideal = b.ideal ? `${b.ideal[0]}–${b.ideal[1]}` : "—";
              const inRange = b.ideal && cur >= b.ideal[0] && cur <= b.ideal[1];
              return (
                <tr key={b.sym}>
                  <td><span className="mono" style={{color: "var(--text-3)", marginRight: 6}}>{b.sym}</span>{b.name}</td>
                  <td className="mono muted">{prior}</td>
                  <td className="mono">{cur}</td>
                  <td><span className={"delta " + (up ? "up" : d == 0 ? "flat" : "down")}>{up ? "↑" : d == 0 ? "→" : "↓"} {Math.abs(d)}</span></td>
                  <td className="muted mono">{ideal}</td>
                  <td>{inRange ? <span className="badge green"><span className="dot"></span> In range</span> : <span className="badge amber"><span className="dot"></span> Out of range</span>}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { GeneratingProtocol, ProtocolReview, SidePanel, RetestModal, RetestComparison });
