/* MedBridge patient view — section views: timeline, meds, imaging, labs, allergies + shared bits */

const { useState: usePS, useEffect: usePE, useRef: usePR } = React;

/* ---- source tag / pill helpers ---- */
function SourcePill({ id, withOrg }) {
  const s = window.PT.sources[id];
  if (!s) return null;
  return (
    <span className="src-pill" style={{ background: s.bg, color: s.color }}>
      <i style={{ background: s.color }} />{s.name}{withOrg ? ` · ${s.org}` : ""}
    </span>
  );
}

function SectionHead({ children }) {
  return <div className="pt-shead"><h2>{children}</h2><span className="line" /></div>;
}

function EmptySection({ icon, title, note }) {
  return (
    <div className="pt-empty">
      <span className="pe-ic"><Icon name={icon} size={26} /></span>
      <div className="pe-title">{title}</div>
      <div className="pe-note">{note}</div>
    </div>
  );
}

/* ============================================================
   Timeline
   ============================================================ */
function TimelineView({ p, data }) {
  const rows = data || p.timeline;
  if (!rows || !rows.length) return <EmptySection icon="clock" title="No timeline events transferred" note="No connected system returned dated encounters for this patient. Obtain collateral history from the sending site." />;
  return (
    <div>
      <p className="pt-lead">Every encounter MedBridge could assemble across the four connected systems, most recent first. Source shown on each event.</p>
      <div className="tl">
        {rows.map((e, i) => (
          <div className="tl-item" key={i}>
            <div className="tl-rail">
              <span className={`tl-node ${e.flag || ""}`} />
              {i < rows.length - 1 && <span className="tl-line" />}
            </div>
            <div className="tl-card">
              <div className="tl-row1">
                <span className="tl-date">{e.date}</span>
                <span className="tl-title">{e.title}</span>
                {e.flag === "critical" && <Badge kind="critical" icon="alert">Critical</Badge>}
                {e.flag === "active" && <Badge kind="info">In transit</Badge>}
                {e.flag === "warn" && <Badge kind="warn" icon="flag">Unstructured</Badge>}
              </div>
              <div className="tl-detail">{e.detail}</div>
              {e.src && <SourcePill id={e.src} withOrg />}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   Medications
   ============================================================ */
function MedsView({ p }) {
  const meds = p.meds || [];
  if (!meds.length) return <EmptySection icon="pill" title="No active medication list on record" note="No connected system returned a structured medication list. Confirm current medications verbally before ordering." />;
  return (
    <div>
      <p className="pt-lead">{meds.length} active medication{meds.length !== 1 ? "s" : ""}, reconciled from {new Set(meds.map((m) => m.src)).size} source{new Set(meds.map((m) => m.src)).size !== 1 ? "s" : ""}. Anticoagulant / antiplatelet therapy is flagged — do not interrupt.</p>
      {meds.map((m, i) => (
        <div className={`rec ${m.critical ? "crit" : ""}`} key={i}>
          <div className="rec-ic"><Icon name="pill" size={18} /></div>
          <div className="rec-main">
            <div className="rec-name">
              {m.name}
              {m.critical && <Badge kind="critical" icon="alert">Do not interrupt</Badge>}
            </div>
            <div className="rec-sub">{m.dose} · {m.route} · {m.cls}</div>
            <div className="rec-note">{m.note}</div>
          </div>
          <div className="rec-right"><SourcePill id={m.src} /></div>
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   Imaging & reports
   ============================================================ */
function ImagingView({ p }) {
  const imaging = p.imaging || [];
  if (!imaging.length) return <EmptySection icon="file" title="No imaging or reports transferred" note="No diagnostic reports were returned by any connected system. Prior imaging may exist at the sending site." />;
  return (
    <div>
      <p className="pt-lead">Imaging and diagnostic reports pulled live from each source — nothing is copied or stored centrally.</p>
      {imaging.map((r, i) => (
        <div className="rec" key={i}>
          <div className="rec-ic"><Icon name="activity" size={18} /></div>
          <div className="rec-main">
            <div className="rec-name">{r.title}<Badge kind="neutral">{r.mod}</Badge></div>
            <div className="rec-sub">{r.read}</div>
            <div className="rec-note">{r.site}</div>
          </div>
          <div className="rec-right">
            <span className="rec-date">{r.date}</span>
            <SourcePill id={r.src} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   Labs
   ============================================================ */
function LabsView({ p }) {
  const labs = p.labs || [];
  if (!labs.length) return <EmptySection icon="flask" title="No recent labs transferred" note="No connected system returned laboratory results. Repeat a full panel on arrival." />;
  return (
    <div>
      <p className="pt-lead">Most recent result for each test across all sources. Out-of-range values flagged.</p>
      {labs.map((l, i) => (
        <div className={`rec ${l.flag === "HH" ? "crit" : ""}`} key={i}>
          <div className="rec-ic" style={l.flag ? null : { background: "var(--surface-3)", color: "var(--text-3)" }}><Icon name="flask" size={17} /></div>
          <div className="rec-main">
            <div className="rec-name">{l.name}{l.flag && <span className={`flag-pill ${l.flag}`}>{l.flag === "HH" ? "CRITICAL HIGH" : "HIGH"}</span>}</div>
            <div className="rec-sub">Reference {l.ref} {l.unit}</div>
            <div style={{ marginTop: 6 }}><SourcePill id={l.src} /></div>
          </div>
          <div className="rec-right">
            <span className={`rec-val ${l.flag ? "hi" : ""}`}>{l.val}<span style={{ fontSize: 12, fontWeight: 600, color: "var(--text-3)", marginLeft: 3 }}>{l.unit}</span></span>
            <span className="rec-date">{l.date}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   Allergies (reconciliation case)
   ============================================================ */
function AllergiesView({ p }) {
  const allergies = p.allergies || [];
  const [reconciled, setReconciled] = usePS({});
  const anyUnconfirmed = allergies.some((a) => a.status !== "confirmed");
  return (
    <div>
      {(!allergies.length || anyUnconfirmed) && (
        <div className="alert-bar" style={{ marginTop: 0, marginBottom: 18 }}>
          <span className="ab-ic"><Icon name="alert" size={19} /></span>
          <div className="ab-txt">
            {allergies.length === 0
              ? <><b>No structured allergy record exists in any connected system.</b> Confirm allergies verbally with the patient or sending site before ordering any new medication, especially antibiotics.</>
              : <><b>An allergy was found only in unstructured data.</b> It must be formally reconciled before antibiotic orders at {window.PT.clinic.facility}.</>}
          </div>
        </div>
      )}
      {allergies.length === 0
        ? <EmptySection icon="check" title="No allergies on the active list" note="This is an absence of data, not a confirmed absence of allergies. Reconcile manually." />
        : allergies.map((a, i) => (
          <div className={`rec ${a.status !== "confirmed" ? "crit" : ""}`} key={i}>
            <div className="rec-ic"><Icon name={a.status === "confirmed" ? "shield" : "alert"} size={18} /></div>
            <div className="rec-main">
              <div className="rec-name">
                {a.agent}
                {a.status === "confirmed" ? <Badge kind="good" icon="check">Confirmed</Badge> : <Badge kind="warn" icon="flag">Unconfirmed</Badge>}
                {!a.coded && <Badge kind="neutral">Not coded</Badge>}
              </div>
              <div className="rec-sub">Reaction: {a.reaction} · Severity: {a.severity}</div>
              <div className="rec-note">{a.note}</div>
              <div style={{ marginTop: 9, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                <SourcePill id={a.src} withOrg />
                {a.status === "confirmed" ? null : reconciled[i] ? (
                  <span className="sum-act accepted"><Icon name="check" size={14} />Reconciled to active list</span>
                ) : (
                  <button className="ab-act" onClick={() => setReconciled((o) => ({ ...o, [i]: true }))}><Icon name="check" size={14} />Reconcile to active allergy list</button>
                )}
              </div>
            </div>
          </div>
        ))}
    </div>
  );
}

Object.assign(window, { SourcePill, SectionHead, EmptySection, TimelineView, MedsView, ImagingView, LabsView, AllergiesView });
