// Dashboard + Client list + Client profile screens
function Dashboard({ go, openClient, newTest }) {
  const { CLIENTS, RECENT_JOBS, NEEDS_REVIEW } = window.MOCK;

  return (
    <div className="page" data-screen-label="01 Dashboard">
      <div className="page-head">
        <div>
          <div className="page-title">Good morning, Linn</div>
          <div className="page-sub">Tuesday · 12 November 2025 · 4 active cases this week</div>
        </div>
        <div className="row">
          <button className="btn"><I.search size={14}/> Search · <span className="mono muted">⌘K</span></button>
          <button className="btn primary lg" onClick={newTest}><I.plus size={15}/> New Test</button>
        </div>
      </div>

      <div className="grid grid-4" style={{marginBottom: 16}}>
        <div className="kpi">
          <div className="kpi-label">Active clients</div>
          <div className="kpi-val">28</div>
          <div className="kpi-trend up">↑ 3 this month</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Tests in review</div>
          <div className="kpi-val">4</div>
          <div className="kpi-trend">2 awaiting your sign-off</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Retests due</div>
          <div className="kpi-val">6</div>
          <div className="kpi-trend warn">2 overdue</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Red-flag cases</div>
          <div className="kpi-val">1</div>
          <div className="kpi-trend">Awaiting mentor</div>
        </div>
      </div>

      <div className="grid grid-2" style={{marginBottom: 16}}>
        {/* Recent uploads */}
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Recent uploads & jobs</div>
              <div className="card-sub">Live extraction queue</div>
            </div>
            <div className="row" style={{gap: 6}}>
              <button className="btn sm primary" onClick={() => newTest()}><I.plus size={12}/> New upload</button>
              <button className="btn sm">View all</button>
            </div>
          </div>
          <table className="tbl">
            <tbody>
              {RECENT_JOBS.map(j => (
                <tr key={j.id} className="row-click" onClick={() => {
                  if (j.status === "processing") go("processing");
                  else if (j.status === "review") go("scan-review");
                  else if (j.status === "failed") go("upload");
                  else openClient(j.client);
                }}>
                  <td style={{width: 38}}><Avatar name={j.client} initial={j.initial} color={j.color} size={28}/></td>
                  <td>
                    <div style={{fontWeight: 500}}>{j.client}</div>
                    <div className="muted mono" style={{fontSize: 11.5}}>{j.file}</div>
                  </td>
                  <td>
                    {j.status === "processing" && <span className="badge blue"><span className="dot"></span> Processing · {j.progress}%</span>}
                    {j.status === "review" && <span className="badge amber"><span className="dot"></span> Ready to review</span>}
                    {j.status === "complete" && <span className="badge green"><span className="dot"></span> Complete</span>}
                    {j.status === "failed" && <span className="badge red"><span className="dot"></span> Upload failed</span>}
                  </td>
                  <td className="muted" style={{fontSize: 12, textAlign: "right"}}>{j.started}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Protocols needing review */}
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Protocols needing review</div>
              <div className="card-sub">AI-drafted, awaiting practitioner sign-off</div>
            </div>
            <button className="btn sm">All</button>
          </div>
          <div style={{padding: 8}}>
            {NEEDS_REVIEW.map((n, i) => (
              <div key={i} className="row-click" style={{display: "flex", gap: 12, padding: "12px 12px", borderRadius: 8, alignItems: "flex-start", cursor: "pointer"}} onClick={() => go("protocol")}>
                <div style={{width: 6, height: 6, borderRadius: 50, background: n.flag === "red" ? "var(--danger)" : n.flag === "yellow" ? "var(--warn)" : "var(--accent)", marginTop: 7, flex: "none"}}></div>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontWeight: 500}}>{n.client}</div>
                  <div className="muted" style={{fontSize: 12, marginTop: 2}}>{n.reason}</div>
                </div>
                <div className="muted" style={{fontSize: 12}}>{n.date}</div>
                <I.chevR size={14}/>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid grid-2">
        {/* Recent clients */}
        <div className="card">
          <div className="card-head">
            <div className="card-title">Recent clients</div>
            <button className="btn sm" onClick={() => go("clients")}>View all clients</button>
          </div>
          <div style={{padding: 8}}>
            {CLIENTS.slice(0, 5).map(c => (
              <div key={c.id} className="row-click" style={{display: "flex", gap: 12, padding: "10px 12px", alignItems: "center", borderRadius: 8, cursor: "pointer"}} onClick={() => openClient(c.id)}>
                <Avatar initial={c.initial} color={c.color} size={32}/>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontWeight: 500}}>{c.name}</div>
                  <div className="muted" style={{fontSize: 12}}>{c.age} · {c.sex} · {c.tests} HTMA tests · Last {c.lastTest}</div>
                </div>
                {c.flags > 0 && <span className="badge red"><span className="dot"></span> {c.flags} flag{c.flags>1?'s':''}</span>}
              </div>
            ))}
          </div>
        </div>

        <div style={{display: "flex", flexDirection: "column", gap: 16}}>
          {/* Retests due */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Retests due</div>
              <button className="btn sm">Schedule</button>
            </div>
            <div style={{padding: 8}}>
              {CLIENTS.filter(c => c.retest).slice(0, 3).map(c => (
                <div key={c.id} className="row-click" style={{display: "flex", padding: "10px 12px", alignItems: "center", gap: 12, borderRadius: 8, cursor: "pointer"}} onClick={() => openClient(c.id)}>
                  <Avatar initial={c.initial} color={c.color} size={28}/>
                  <div style={{flex: 1}}>
                    <div style={{fontSize: 13.5, fontWeight: 500}}>{c.name}</div>
                    <div className="muted" style={{fontSize: 12}}>Retest scheduled · {c.retest}</div>
                  </div>
                  <button className="btn sm" onClick={(e) => { e.stopPropagation(); newTest(c.id); }}><I.upload size={12}/> Upload</button>
                </div>
              ))}
            </div>
          </div>

          {/* Red flag */}
          <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-flag cases</div>
              </div>
              <span className="badge red"><span className="dot"></span> 1 active</span>
            </div>
            <div style={{padding: "14px 18px"}}>
              <div className="row" style={{gap: 12}}>
                <Avatar name="Marcus Chen" initial="MC" color="oklch(0.62 0.14 158)" size={36}/>
                <div style={{flex: 1}}>
                  <div style={{fontWeight: 600}}>Marcus Chen</div>
                  <div className="muted" style={{fontSize: 12, marginTop: 2}}>Elevated Pb (0.42 mg%), Hg trending up — escalated to mentor review on Aug 02</div>
                </div>
                <button className="btn sm" onClick={() => go("protocol")}>Open case <I.arrowR size={12}/></button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ClientList({ openClient }) {
  const { CLIENTS } = window.MOCK;
  const [q, setQ] = useState("");
  const [adding, setAdding] = useState(false);
  const filtered = CLIENTS.filter(c => c.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="page" data-screen-label="02 Client list">
      <div className="page-head">
        <div>
          <div className="page-title">Clients</div>
          <div className="page-sub">{CLIENTS.length} total · 6 active protocols</div>
        </div>
        <div className="row">
          <div className="input-wrap" style={{width: 280}}>
            <I.search className="lead" size={16}/>
            <input className="input with-icon" placeholder="Search by name, email, case ID…" value={q} onChange={e=>setQ(e.target.value)}/>
          </div>
          <button className="btn"><I.filter size={14}/> Filter</button>
          <button className="btn primary" onClick={() => setAdding(true)}><I.plus size={14}/> Add client</button>
        </div>
      </div>
      {adding && <AddClientModal onClose={() => setAdding(false)} onCreated={(c) => { setAdding(false); openClient(c.id || "c1"); }}/>}

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th style={{width: 30}}></th>
              <th>Client</th>
              <th>Age / Sex</th>
              <th>HTMA tests</th>
              <th>Last test</th>
              <th>Protocol status</th>
              <th>Retest</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(c => (
              <tr key={c.id} className="row-click" onClick={() => openClient(c.id)}>
                <td><Avatar initial={c.initial} color={c.color} size={28}/></td>
                <td><div style={{fontWeight: 500}}>{c.name}</div><div className="muted" style={{fontSize: 11.5}}>case-{c.id.toUpperCase()}</div></td>
                <td className="mono">{c.age} · {c.sex}</td>
                <td>{c.tests}</td>
                <td className="muted">{c.lastTest}</td>
                <td>
                  {c.status === "active" && <span className="badge green"><span className="dot"></span> On protocol</span>}
                  {c.status === "needs-review" && <span className="badge amber"><span className="dot"></span> Awaiting</span>}
                  {c.status === "new" && <span className="badge blue"><span className="dot"></span> New case</span>}
                  {c.status === "flagged" && <span className="badge red"><span className="dot"></span> Mentor review</span>}
                </td>
                <td className="muted">{c.retest || "—"}</td>
                <td style={{textAlign: "right"}}><I.chevR size={14} style={{color: "var(--text-3)"}}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ClientProfile({ clientId, go, newTest }) {
  const c = window.MOCK.CLIENTS.find(x => x.id === clientId) || window.MOCK.CLIENTS[0];
  const [tab, setTab] = useState("timeline");
  const [addingItem, setAddingItem] = useState(null);
  const [editingItem, setEditingItem] = useState(null);
  const [markInactiveItem, setMarkInactiveItem] = useState(null);
  const [viewingSnapshot, setViewingSnapshot] = useState(null);
  return (
    <div className="page" data-screen-label="03 Client profile">
      <div className="page-head" style={{alignItems: "flex-start"}}>
        <div className="row" style={{gap: 16}}>
          <Avatar initial={c.initial} color={c.color} size={56}/>
          <div>
            <div className="page-title">{c.name}</div>
            <div className="page-sub">{c.age} · {c.sex} · case-{c.id.toUpperCase()} · client since Feb 2024</div>
            <div className="row" style={{gap: 6, marginTop: 8}}>
              <span className="badge green"><span className="dot"></span> On protocol</span>
              <span className="badge blue"><span className="dot"></span> Slow 2 metabolic type</span>
              {c.flags > 0 && <span className="badge amber"><span className="dot"></span> {c.flags} open flag</span>}
            </div>
            <div className="row" style={{gap: 6, marginTop: 10}}>
              <button className="btn sm" onClick={() => go("retest-comparison")}><I.refresh size={12}/> Retest comparison</button>
            </div>
          </div>
        </div>
        <div className="row">
          <button className="btn"><I.msg size={14}/> Message</button>
          <button className="btn"><I.doc size={14}/> Notes</button>
          <button className="btn primary" onClick={() => newTest(c.id)}><I.upload size={14}/> Upload new report</button>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns: "1fr 320px", gap: 20}}>
        <div>
          <div className="tabs" style={{marginBottom: 18}}>
            {[["timeline", "HTMA timeline"], ["intake", "Intake history"], ["blood", "Blood panels"], ["protocols", "Protocols"], ["notes", "Notes"], ["retest", "Retest comparison"]].map(([k, l]) => (
              <button key={k} className={"tab" + (tab === k ? " active" : "")} onClick={() => setTab(k)}>{l}</button>
            ))}
          </div>

          {tab === "timeline" && (
            <div className="card card-pad">
              <div className="timeline">
                <div className="timeline-item cur">
                  <div className="row-between">
                    <div>
                      <div style={{fontWeight: 600}}>HTMA #3 — pending upload</div>
                      <div className="muted" style={{fontSize: 12}}>Scheduled for retest window · Nov 2025</div>
                    </div>
                    <button className="btn sm primary" onClick={() => newTest(c.id)}><I.upload size={12}/> Upload</button>
                  </div>
                </div>
                <div className="timeline-item">
                  <div className="row-between">
                    <div>
                      <div style={{fontWeight: 500}}>HTMA #2 — Aug 14, 2025</div>
                      <div className="muted" style={{fontSize: 12}}>Trace Elements · Slow 2 confirmed · Cu trending up</div>
                    </div>
                    <button className="btn sm">View</button>
                  </div>
                </div>
                <div className="timeline-item">
                  <div className="row-between">
                    <div>
                      <div style={{fontWeight: 500}}>Protocol v2 marked ready — Aug 18, 2025</div>
                      <div className="muted" style={{fontSize: 12}}>Mg glycinate, Zn picolinate, adrenal cocktail</div>
                    </div>
                    <button className="btn sm" onClick={() => go("protocol")}>Open</button>
                  </div>
                </div>
                <div className="timeline-item">
                  <div className="row-between">
                    <div>
                      <div style={{fontWeight: 500}}>HTMA #1 — Feb 22, 2024</div>
                      <div className="muted" style={{fontSize: 12}}>Baseline · Fast 4 mistakenly assigned, corrected to Slow 2</div>
                    </div>
                    <button className="btn sm">View</button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {tab === "intake" && (
            <div className="card card-pad">
              <div className="row-between" style={{marginBottom: 12}}>
                <div>
                  <div className="card-title">Case-linked intake history</div>
                  <div className="muted" style={{fontSize: 12.5}}>Each snapshot is bound to its case · edits here don't change canonical client data</div>
                </div>
                <span className="chip">3 snapshots on file</span>
              </div>
              <div className="timeline">
                {INTAKE_SNAPSHOTS.map((s, i) => (
                  <div key={s.id} className={"timeline-item row-click" + (i === 0 ? " cur" : "")}
                       style={{cursor: "pointer"}}
                       onClick={() => setViewingSnapshot(s)}>
                    <div className="row-between">
                      <div style={{fontWeight: i === 0 ? 600 : 500}}>
                        {s.title} {i === 0 && <span className="chip green" style={{marginLeft: 6}}>This case</span>}
                      </div>
                      <I.chevR size={14} style={{color: "var(--text-3)"}}/>
                    </div>
                    <div className="muted" style={{fontSize: 12.5, marginTop: 4}}>{s.summary}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === "blood" && (
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Blood panels</div>
                  <div className="card-sub">2 panels on file</div>
                </div>
                <button className="btn sm" onClick={() => newTest(c.id)}><I.upload size={12}/> Upload new panel</button>
              </div>
              <table className="tbl">
                <thead><tr><th>Date</th><th>Panel</th><th>Markers</th><th>Notable</th><th></th></tr></thead>
                <tbody>
                  <tr className="row-click">
                    <td className="muted">Aug 14, 2025</td>
                    <td>Ferritin / Iron studies</td>
                    <td className="mono">3 markers</td>
                    <td><span className="badge amber"><span className="dot"></span> Ferritin low (28)</span></td>
                    <td style={{textAlign: "right"}}><I.chevR size={14} style={{color: "var(--text-3)"}}/></td>
                  </tr>
                  <tr className="row-click">
                    <td className="muted">Jul 02, 2025</td>
                    <td>CBC + comprehensive metabolic</td>
                    <td className="mono">22 markers</td>
                    <td><span className="badge green"><span className="dot"></span> All in range</span></td>
                    <td style={{textAlign: "right"}}><I.chevR size={14} style={{color: "var(--text-3)"}}/></td>
                  </tr>
                </tbody>
              </table>
            </div>
          )}
          {tab === "protocols" && (
            <div style={{display: "flex", flexDirection: "column", gap: 14}}>
              <div className="card">
                <div className="card-head">
                  <div className="row" style={{gap: 8}}>
                    <div className="card-title">Protocol v2 · Aug 18, 2025</div>
                    <span className="badge green"><span className="dot"></span> Active</span>
                  </div>
                  <button className="btn sm" onClick={() => go("protocol")}>Open</button>
                </div>
                <div style={{padding: "14px 18px", fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.6}}>
                  <div style={{marginBottom: 8}}><strong style={{color: "var(--text)"}}>Phase:</strong> Mineral balancing · weeks 1–12</div>
                  <ul style={{margin: 0, paddingLeft: 18}}>
                    <li>Magnesium glycinate · 200mg PM</li>
                    <li>Zinc picolinate · 25mg AM (weeks 1–8)</li>
                    <li>Adrenal cocktail · 1 serving mid-afternoon</li>
                    <li>Vitamin D3/K2 · 5000 IU AM</li>
                  </ul>
                  <div className="muted" style={{fontSize: 12, marginTop: 10}}>2 yellow flags acknowledged · last reviewed by Linn on Aug 18</div>
                </div>
              </div>
              <div className="card">
                <div className="card-head">
                  <div className="row" style={{gap: 8}}>
                    <div className="card-title">Protocol v1 · Feb 26, 2024</div>
                    <span className="chip">Archived</span>
                  </div>
                  <button className="btn sm">Open</button>
                </div>
                <div style={{padding: "14px 18px", fontSize: 13.5, color: "var(--text-2)"}}>
                  Baseline mineral support · replaced after metabolic type re-classification (Fast 4 → Slow 2).
                </div>
              </div>
              <div className="card card-pad" style={{borderStyle: "dashed"}}>
                <div className="row-between">
                  <div>
                    <div style={{fontWeight: 500}}>Draft Protocol v3 from next HTMA</div>
                    <div className="muted" style={{fontSize: 12.5, marginTop: 2}}>Triggers automatically when next HTMA is reviewed and saved.</div>
                  </div>
                  <button className="btn sm primary" onClick={() => newTest(c.id)}><I.upload size={12}/> Upload retest</button>
                </div>
              </div>
            </div>
          )}
          {tab === "notes" && (
            <div className="card">
              <div className="card-head">
                <div className="card-title">Practitioner notes</div>
                <button className="btn sm" onClick={() => setAddingItem("note")}><I.plus size={12}/> Add note</button>
              </div>
              <div style={{padding: 12}}>
                {[
                  ["Oct 04, 2025", "Sleep improving since adrenal cocktail intro. Reports better AM energy."],
                  ["Sep 10, 2025", "Discussed thyroid panel — will order at week 10 of current protocol."],
                  ["Aug 18, 2025", "Confirmed Slow 2. Started Mg glycinate PM. Hold zinc if nausea."],
                ].map(([d, t], i) => (
                  <div key={i} style={{padding: "10px 12px", borderBottom: i < 2 ? "1px solid var(--border)" : "none"}}>
                    <div className="muted" style={{fontSize: 11.5, marginBottom: 4}}>{d}</div>
                    <div style={{fontSize: 13.5, lineHeight: 1.55}}>{t}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {tab === "retest" && (
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Retest comparison</div>
                  <div className="card-sub">Most recent linked retest</div>
                </div>
                <button className="btn sm" onClick={() => go("retest-comparison")}>Open full comparison</button>
              </div>
              <div style={{padding: "14px 18px"}}>
                <div className="row-between" style={{marginBottom: 10}}>
                  <div style={{fontSize: 13.5}}><strong>HTMA #2</strong> · Aug 14, 2025 → <strong>HTMA #3</strong> · pending upload</div>
                  <span className="chip green">88-day window</span>
                </div>
                <div className="muted" style={{fontSize: 12.5}}>Comparison chart populates once the new HTMA is uploaded, reviewed, and confirmed against this client.</div>
              </div>
            </div>
          )}
        </div>

        <div style={{display: "flex", flexDirection: "column", gap: 16}}>
          <div className="card card-pad">
            <div className="row-between" style={{marginBottom: 10}}>
              <div className="card-title">Essential info</div>
              <button className="btn sm ghost"><I.edit size={11}/> Edit</button>
            </div>
            <div className="muted" style={{fontSize: 11.5, marginBottom: 8}}>Canonical · shared across all cases</div>
            <div style={{display: "grid", gridTemplateColumns: "auto 1fr", gap: "6px 14px", fontSize: 13}}>
              <div className="muted">Email</div><div>amelia.hart@mail.co</div>
              <div className="muted">Phone</div><div>+1 (415) 555-0102</div>
              <div className="muted">Birth year</div><div>1991 (age 34)</div>
              <div className="muted">Sex / gender</div><div>F</div>
              <div className="muted">Weight</div><div>132 lb · 60 kg</div>
              <div className="muted">Height</div><div>5'5" · 165 cm</div>
              <div className="muted">BMI</div><div>22.0</div>
            </div>
          </div>
          <div className="card card-pad">
            <div className="row-between" style={{marginBottom: 8}}><div className="card-title">Allergies & sensitivities</div><button className="btn sm ghost" onClick={() => setAddingItem("allergy")}><I.plus size={11}/> Add</button></div>
            <CanonicalEntry text="Shellfish · mild" from="Profile · Feb 2024"
                            onEdit={() => setEditingItem({kind: "allergy", text: "Shellfish", text2: "mild"})}
                            onInactive={() => setMarkInactiveItem({kind: "allergy", text: "Shellfish · mild"})}/>
            <div className="muted" style={{fontSize: 12, marginTop: 6}}>No supplement reactions reported</div>
          </div>
          <div className="card card-pad">
            <div className="row-between" style={{marginBottom: 8}}><div className="card-title">Standing conditions</div><button className="btn sm ghost" onClick={() => setAddingItem("condition")}><I.plus size={11}/> Add</button></div>
            <CanonicalEntry text="Hashimoto's (sub-clinical) · since 2022" from="Profile · Feb 2024"
                            onEdit={() => setEditingItem({kind: "condition", text: "Hashimoto's", text2: "Sub-clinical · since 2022"})}
                            onInactive={() => setMarkInactiveItem({kind: "condition", text: "Hashimoto's (sub-clinical)"})}/>
          </div>
          <div className="card card-pad">
            <div className="row-between" style={{marginBottom: 8}}><div className="card-title">Current medications & supplements</div><button className="btn sm ghost" onClick={() => setAddingItem("med")}><I.plus size={11}/> Add</button></div>
            <CanonicalEntry text="Sertraline 25mg AM" from="Profile · Feb 2024"
                            onEdit={() => setEditingItem({kind: "med", text: "Sertraline", text2: "25mg AM"})}
                            onInactive={() => setMarkInactiveItem({kind: "med", text: "Sertraline 25mg AM"})}/>
            <CanonicalEntry text="Mg glycinate 200mg PM" from="Promoted from case-c1 · Aug 14, 2025"
                            onEdit={() => setEditingItem({kind: "med", text: "Mg glycinate", text2: "200mg PM"})}
                            onInactive={() => setMarkInactiveItem({kind: "med", text: "Mg glycinate 200mg PM"})}/>
            <CanonicalEntry text="Vitamin D3 5000 IU" from="Promoted from case-c1 · Aug 14, 2025"
                            onEdit={() => setEditingItem({kind: "med", text: "Vitamin D3", text2: "5000 IU"})}
                            onInactive={() => setMarkInactiveItem({kind: "med", text: "Vitamin D3 5000 IU"})}/>
            <CanonicalEntry text="Iron bisglycinate 25mg" inactive from="Stopped · Sep 2025"/>
          </div>
          <div className="card card-pad">
            <div className="row-between" style={{marginBottom: 8}}><div className="card-title">Notes</div><button className="btn sm ghost" onClick={() => setAddingItem("note")}><I.plus size={11}/> Add</button></div>
            <CanonicalEntry text="Sleep improving since adrenal cocktail intro. Wants thyroid panel next visit." from="Profile · Oct 04, 2025"
                            onEdit={() => setEditingItem({kind: "note", text: "Sleep improving since adrenal cocktail intro. Wants thyroid panel next visit."})}
                            onInactive={() => setMarkInactiveItem({kind: "note", text: "Sleep improving since adrenal cocktail intro…"})}/>
          </div>
        </div>
      </div>

      {addingItem && <AddItemModal kind={addingItem} onClose={() => setAddingItem(null)}/>}
      {editingItem && <AddItemModal kind={editingItem.kind} mode="edit" initial={editingItem.text} initial2={editingItem.text2 || ""} onClose={() => setEditingItem(null)}/>}
      {markInactiveItem && <ConfirmInactiveModal item={markInactiveItem} onClose={() => setMarkInactiveItem(null)}/>}
      {viewingSnapshot && <IntakeSnapshotModal snap={viewingSnapshot} onClose={() => setViewingSnapshot(null)}/>}
    </div>
  );
}

function AddClientModal({ onClose, onCreated }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [age, setAge] = useState("");
  const [sex, setSex] = useState("F");
  const [goals, setGoals] = useState("");
  const valid = name.trim().length > 1;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row" style={{gap: 10, marginBottom: 4}}><I.user size={18}/><h3>Add client</h3></div>
        <p className="muted" style={{margin: "0 0 16px", fontSize: 13}}>Create a new client record. You can upload their first HTMA right after.</p>
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12}}>
          <div className="field" style={{gridColumn: "1 / -1"}}>
            <div className="field-label">Full name</div>
            <input className="input" placeholder="e.g. Amelia Hart" value={name} onChange={e=>setName(e.target.value)}/>
          </div>
          <div className="field"><div className="field-label">Email</div><input className="input" placeholder="optional" value={email} onChange={e=>setEmail(e.target.value)}/></div>
          <div className="field"><div className="field-label">Date of birth</div><input className="input" placeholder="MM/DD/YYYY"/></div>
          <div className="field"><div className="field-label">Age</div><input className="input" value={age} onChange={e=>setAge(e.target.value)}/></div>
          <div className="field"><div className="field-label">Sex</div>
            <select className="select" value={sex} onChange={e=>setSex(e.target.value)}>
              <option>F</option><option>M</option><option>Other</option>
            </select>
          </div>
          <div className="field" style={{gridColumn: "1 / -1"}}>
            <div className="field-label">Initial goals (optional)</div>
            <input className="input" placeholder="e.g. energy, sleep, hair" value={goals} onChange={e=>setGoals(e.target.value)}/>
          </div>
        </div>
        <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onCreated({ name })}><I.check size={14}/> Create client</button>
        </div>
      </div>
    </div>
  );
}

const INTAKE_SNAPSHOTS = [
  {
    id: "s3", title: "HIF #3 · Nov 12, 2025", date: "Nov 12, 2025", caseLabel: "case-c1 · HTMA #3",
    summary: "Adult · \"Fatigue, mid-afternoon energy crash\" · Hashimoto's sub-clinical · Sertraline 25mg AM · 1 mentor question logged",
    fields: {
      "Client category / life-stage": "Adult",
      "Presenting complaints": "Fatigue, mid-afternoon energy crash",
      "Retest status": "Retest of 8/14 HTMA",
      "Current symptoms": "Poor sleep onset; brittle nails; cold hands",
      "Client conditions": "Hashimoto's (sub-clinical)",
      "Medications": "Sertraline 25mg AM",
      "Supplements": "Mg glycinate 200mg PM · Vit D3 5000 IU",
      "Question for mentor": "Cu trending up across last 2 tests — clinically actionable yet?",
    },
  },
  {
    id: "s2", title: "HIF #2 · Aug 14, 2025", date: "Aug 14, 2025", caseLabel: "case-c1 · HTMA #2",
    summary: "Adult · \"Hair shedding, poor sleep onset\" · No standing conditions · Mg glycinate added",
    fields: {
      "Client category / life-stage": "Adult",
      "Presenting complaints": "Hair shedding, poor sleep onset",
      "Retest status": "Retest of 2/22 HTMA (baseline)",
      "Current symptoms": "Hair shedding; difficulty falling asleep",
      "Client conditions": "—",
      "Medications": "Sertraline 25mg AM",
      "Supplements": "None at intake (added Mg glycinate after)",
    },
  },
  {
    id: "s1", title: "HIF #1 · Feb 22, 2024 (baseline)", date: "Feb 22, 2024", caseLabel: "case-c1 · HTMA #1",
    summary: "Adult · \"General fatigue\" · No medications · No prior protocols",
    fields: {
      "Client category / life-stage": "Adult",
      "Presenting complaints": "General fatigue",
      "Retest status": "Baseline (no prior tests)",
      "Current symptoms": "Fatigue; mid-day energy crash",
      "Client conditions": "—",
      "Medications": "None",
      "Supplements": "None",
    },
  },
];

function AddItemModal({ kind, mode = "add", initial = "", initial2 = "", onClose }) {
  const config = {
    allergy: { title: "allergy or sensitivity", label: "Allergen / trigger", placeholder: "e.g. Shellfish, dairy, latex", second: { label: "Severity / notes", placeholder: "e.g. Mild — itching only" } },
    condition: { title: "standing condition", label: "Condition name", placeholder: "e.g. Hashimoto's, PCOS", second: { label: "Notes (status, since)", placeholder: "e.g. Sub-clinical · since 2022" } },
    med: { title: "medication or supplement", label: "Name", placeholder: "e.g. Sertraline, Mg glycinate", second: { label: "Dose & schedule", placeholder: "e.g. 25mg AM, w/ food" } },
    note: { title: "client note", label: "Note", placeholder: "What did the client report?", second: null, multiline: true },
  }[kind];
  const isEdit = mode === "edit";
  const [val, setVal] = useState(initial);
  const [val2, setVal2] = useState(initial2);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row" style={{gap: 10, marginBottom: 4}}>
          {isEdit ? <I.edit size={18}/> : <I.plus size={18}/>}
          <h3>{isEdit ? "Edit " : "Add "}{config.title}</h3>
        </div>
        <p className="muted" style={{margin: "0 0 16px", fontSize: 13}}>
          {isEdit ? "Mock — edits aren't persisted in this prototype. Will be marked as a manual canonical edit." : "Mock — entries aren't persisted in this prototype."}
        </p>
        <div className="field" style={{marginBottom: 12}}>
          <div className="field-label">{config.label}</div>
          {config.multiline
            ? <textarea className="input" rows={3} placeholder={config.placeholder} value={val} onChange={e=>setVal(e.target.value)} style={{resize: "vertical", fontFamily: "inherit"}}/>
            : <input className="input" placeholder={config.placeholder} value={val} onChange={e=>setVal(e.target.value)}/>
          }
        </div>
        {config.second && (
          <div className="field" style={{marginBottom: 12}}>
            <div className="field-label">{config.second.label}</div>
            <input className="input" placeholder={config.second.placeholder} value={val2} onChange={e=>setVal2(e.target.value)}/>
          </div>
        )}
        <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!val.trim()} onClick={onClose}>
            <I.check size={14}/> {isEdit ? "Save changes" : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}

function CanonicalEntry({ text, from, inactive, onEdit, onInactive }) {
  return (
    <div style={{display: "flex", alignItems: "flex-start", gap: 6, padding: "8px 0", borderBottom: "1px dashed var(--border)"}}>
      <div style={{flex: 1, minWidth: 0}}>
        <div style={{fontSize: 13, opacity: inactive ? 0.55 : 1, textDecoration: inactive ? "line-through" : "none"}}>{text}</div>
        {(from || inactive) && (
          <div className="row" style={{gap: 4, marginTop: 4, flexWrap: "wrap"}}>
            {from && <span className="chip" style={{fontSize: 10, padding: "1px 6px"}}><I.link size={9}/> {from}</span>}
            {inactive && <span className="chip amber" style={{fontSize: 10, padding: "1px 6px"}}>Inactive</span>}
          </div>
        )}
      </div>
      {!inactive && onEdit && (
        <div className="row" style={{gap: 2, opacity: 0.65}}>
          <button className="icon-btn" style={{padding: 4}} title="Edit" onClick={onEdit}><I.edit size={11}/></button>
          <button className="icon-btn" style={{padding: 4}} title="Mark inactive" onClick={onInactive}><I.x size={11}/></button>
        </div>
      )}
    </div>
  );
}

function ConfirmInactiveModal({ item, onClose }) {
  const labels = { allergy: "allergy", condition: "condition", med: "entry", note: "note" };
  const noun = labels[item.kind] || "entry";
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 460}}>
        <div className="row" style={{gap: 10, marginBottom: 4}}><I.x size={18}/><h3 style={{margin: 0}}>Mark {noun} inactive?</h3></div>
        <p className="muted" style={{margin: "4px 0 16px", fontSize: 13.5, lineHeight: 1.55}}>
          <strong style={{color: "var(--text)"}}>"{item.text}"</strong> will be marked inactive. Historical case intakes that referenced this entry stay intact — only the canonical profile updates.
        </p>
        <div className="alert info" style={{marginBottom: 14, fontSize: 12.5}}>
          <I.shield size={14} className="alert-icon"/>
          Tip: Mark inactive is preferred for medications discontinued mid-care. Use the trash icon (not shown in mock) only for entries added by mistake.
        </div>
        <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={onClose}><I.check size={14}/> Mark inactive</button>
        </div>
      </div>
    </div>
  );
}

function IntakeSnapshotModal({ snap, onClose }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 620}}>
        <div className="row-between" style={{marginBottom: 4}}>
          <div className="row" style={{gap: 10}}><I.user size={18}/><h3 style={{margin: 0}}>{snap.title}</h3></div>
          <button className="icon-btn" onClick={onClose}><I.x size={16}/></button>
        </div>
        <p className="muted" style={{margin: "4px 0 16px", fontSize: 12.5}}>
          {snap.caseLabel} · case-only snapshot · canonical client data not affected
        </p>
        <div style={{display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 16px", fontSize: 13.5, marginBottom: 16}}>
          {Object.entries(snap.fields).map(([k, v]) => (
            <React.Fragment key={k}>
              <div className="muted">{k}</div>
              <div>{v}</div>
            </React.Fragment>
          ))}
        </div>
        <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
          <button className="btn ghost" onClick={onClose}>Close</button>
          <button className="btn"><I.doc size={14}/> Open full case</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, ClientList, ClientProfile, AddClientModal, AddItemModal, IntakeSnapshotModal, CanonicalEntry, ConfirmInactiveModal });
