/* ============================================================
   Carebridge Portal — Patient Management (list + detail)
   ============================================================ */
const { useState } = React;
const PD = window.CB_DATA;

function PatientsView({ go }) {
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("All");
  const filters = ["All", "New inquiry", "In treatment", "In recovery", "Follow-up", "High priority"];
  const rows = PD.PATIENTS.filter((p) => {
    if (q && !(p.name + p.id + p.condition).toLowerCase().includes(q.toLowerCase())) return false;
    if (filter === "All") return true;
    if (filter === "High priority") return p.priority === "High";
    return p.status.toLowerCase().includes(filter.toLowerCase()) || (filter === "New inquiry" && p.stage === 0) || (filter === "Follow-up" && p.stage === 4);
  });
  return (
    <div className="cb-grid" style={{ gap: "var(--gap-grid)" }}>
      <div className="cb-grid" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
        <StatCard icon="users" chip="navy" value="84" label="Total patients" />
        <StatCard icon="activity" chip="" value="46" label="In active treatment" />
        <StatCard icon="user-plus" chip="sky" value="9" label="New this week" />
        <StatCard icon="flag" chip="warm" value="5" label="High priority" />
      </div>

      <Card pad0>
        <div style={{ padding: "var(--space-5) var(--pad-card)", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", borderBottom: "1px solid var(--border-subtle)" }}>
          <div className="cb-search" style={{ minWidth: 260, flex: 1, maxWidth: 360 }}>
            <Icon name="search" size={17} />
            <input placeholder="Search patients, cases, conditions…" value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
          <div className="cb-tag-list">
            {filters.map((f) => (
              <button key={f} onClick={() => setFilter(f)} className="cb-spec" style={{ cursor: "pointer", border: "none", fontFamily: "var(--font-body)", background: filter === f ? "var(--navy-600)" : "var(--navy-50)", color: filter === f ? "#fff" : "var(--navy-600)" }}>{f}</button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <button className="cb-link" style={{ color: "var(--teal-600)" }}><Icon name="user-plus" size={15} />New patient</button>
        </div>
        <table className="cb-table">
          <thead><tr><th>Patient</th><th>Condition</th><th>Coordinator</th><th>Destination</th><th>Stage</th><th>Progress</th><th>Priority</th><th></th></tr></thead>
          <tbody>
            {rows.map((p) => {
              const dest = PD.destByCode(p.dest), co = PD.coordById(p.coordinator);
              return (
                <tr key={p.id} onClick={() => go("patient", p.id)}>
                  <td>
                    <div className="cb-cellname">
                      <Avatar initials={p.initials} color={co.color} size="sm" />
                      <div><b>{p.name}</b><small>{p.id} · {p.age}{p.gender[0]}</small></div>
                    </div>
                  </td>
                  <td style={{ fontWeight: 500, color: "var(--text-strong)", maxWidth: 200 }}>{p.condition}</td>
                  <td className="cb-muted" style={{ fontSize: 13 }}>{co.name}</td>
                  <td className="cb-muted">{dest.flag} {dest.city}</td>
                  <td><Pill tone="navy">{PD.STAGES[p.stage]}</Pill></td>
                  <td style={{ minWidth: 110 }}>
                    <div className="cb-row" style={{ gap: 9 }}><ProgressBar value={p.progress} /><span style={{ fontSize: 12, fontWeight: 700, color: "var(--text-muted)", width: 32 }}>{p.progress}%</span></div>
                  </td>
                  <td><Pill tone={p.priority === "High" ? "danger" : p.priority === "Medium" ? "warn" : "muted"} dot>{p.priority}</Pill></td>
                  <td><Icon name="chevron-right" size={18} style={{ color: "var(--text-faint)" }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

/* ---------------- Patient detail ---------------- */
function PatientDetail({ id, go }) {
  const [tab, setTab] = useState("Overview");
  const p = PD.PATIENTS.find((x) => x.id === id) || PD.PATIENTS[0];
  const dest = PD.destByCode(p.dest), co = PD.coordById(p.coordinator), hosp = PD.hospitalById(p.hospital);
  const tabs = ["Overview", "Medical history", "Documents", "Timeline", "Communication"];

  return (
    <div className="cb-grid" style={{ gap: "var(--gap-grid)" }}>
      <button className="cb-link" style={{ alignSelf: "flex-start", color: "var(--text-muted)" }} onClick={() => go("patients")}><Icon name="arrow-left" size={15} />Back to patients</button>

      {/* Header */}
      <Card>
        <div className="cb-between" style={{ flexWrap: "wrap", gap: 20 }}>
          <div className="cb-row" style={{ gap: 18 }}>
            <Avatar initials={p.initials} color={co.color} size="lg" />
            <div>
              <div className="cb-row" style={{ gap: 10 }}>
                <h2 style={{ fontSize: 24, fontWeight: 800 }}>{p.name}</h2>
                <Pill tone={p.priority === "High" ? "danger" : "warn"} dot>{p.priority} priority</Pill>
              </div>
              <div className="cb-row" style={{ gap: 16, marginTop: 8, color: "var(--text-muted)", fontSize: 13.5, flexWrap: "wrap" }}>
                <span><b style={{ color: "var(--text-strong)" }}>{p.id}</b></span>
                <span>{p.age} yrs · {p.gender}</span>
                <span className="cb-row" style={{ gap: 5 }}><Icon name="stethoscope" size={15} style={{ color: "var(--teal-600)" }} />{p.specialty}</span>
                <span className="cb-row" style={{ gap: 5 }}><Icon name="map-pin" size={15} style={{ color: "var(--teal-600)" }} />{dest.city}, {dest.country}</span>
              </div>
            </div>
          </div>
          <div className="cb-row" style={{ gap: 10 }}>
            <button className="cb-icon-pill"><Icon name="phone-call" size={18} /></button>
            <button className="cb-icon-pill"><Icon name="message-circle" size={18} /></button>
            <button className="cb-link" style={{ background: "var(--navy-600)", color: "#fff", padding: "11px 18px", borderRadius: 999 }}><Icon name="file-text" size={15} />Open case file</button>
          </div>
        </div>
        <div className="cb-divider" />
        <StageTrack current={p.stage} />
      </Card>

      {/* Tabs */}
      <div className="cb-seg" style={{ alignSelf: "flex-start" }}>
        {tabs.map((t) => <button key={t} className={tab === t ? "is-active" : ""} onClick={() => setTab(t)}>{t}</button>)}
      </div>

      {tab === "Overview" ? <PatientOverview p={p} dest={dest} co={co} hosp={hosp} /> : null}
      {tab === "Medical history" ? <PatientHistory p={p} /> : null}
      {tab === "Documents" ? <PatientDocuments /> : null}
      {tab === "Timeline" ? <PatientTimeline p={p} hosp={hosp} /> : null}
      {tab === "Communication" ? <PatientComms p={p} co={co} /> : null}
    </div>
  );
}

function InfoRow({ label, children }) {
  return (
    <div className="cb-between" style={{ padding: "11px 0", borderBottom: "1px solid var(--border-subtle)" }}>
      <span style={{ fontSize: 13, color: "var(--text-muted)", fontWeight: 600 }}>{label}</span>
      <span style={{ fontSize: 13.5, color: "var(--text-strong)", fontWeight: 600, textAlign: "right" }}>{children}</span>
    </div>
  );
}

function PatientOverview({ p, dest, co, hosp }) {
  const remaining = p.estimate - p.paid;
  return (
    <div className="cb-grid" style={{ gridTemplateColumns: "1.4fr 1fr" }}>
      <div className="cb-grid">
        <Card>
          <CardHead title="Case summary" />
          <p style={{ fontSize: 15, lineHeight: 1.6, color: "var(--text-body)" }}>
            {p.name} is a {p.age}-year-old {p.gender.toLowerCase()} patient referred for <b style={{ color: "var(--text-strong)" }}>{p.condition.toLowerCase()}</b>. Carebridge has coordinated a {p.specialty.toLowerCase()} pathway at {hosp.name} in {dest.city}. The case is currently at the <b style={{ color: "var(--text-strong)" }}>{PD.STAGES[p.stage].toLowerCase()}</b> stage, managed by {co.name}.
          </p>
          <div className="cb-soft-panel" style={{ marginTop: 18, display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
            {[["Treatment progress", p.progress + "%"], ["Care start", p.started], ["Last update", p.updated]].map((k, i) => (
              <div key={i}><div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 600 }}>{k[0]}</div><div style={{ fontSize: 18, fontWeight: 700, color: "var(--text-strong)", fontFamily: "var(--font-display)", marginTop: 3 }}>{k[1]}</div></div>
            ))}
          </div>
        </Card>
        <Card>
          <CardHead title="Treatment & travel" />
          <div className="cb-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 24 }}>
            <div>
              <InfoRow label="Partner hospital">{hosp.name}</InfoRow>
              <InfoRow label="Specialty">{p.specialty}</InfoRow>
              <InfoRow label="Accreditation"><Pill tone="teal" icon="badge-check">{hosp.accreditation}</Pill></InfoRow>
            </div>
            <div>
              <InfoRow label="Visa status"><Pill tone={statusTone(p.visa)} dot>{p.visa}</Pill></InfoRow>
              <InfoRow label="Flight"><Pill tone={statusTone(p.flight)} dot>{p.flight}</Pill></InfoRow>
              <InfoRow label="Coordinator">{co.name}</InfoRow>
            </div>
          </div>
        </Card>
      </div>
      <div className="cb-grid">
        <Card>
          <CardHead title="Financial summary" />
          <div style={{ textAlign: "center", padding: "8px 0 16px" }}>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)", fontWeight: 600 }}>Treatment estimate</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 34, color: "var(--text-strong)", letterSpacing: "-0.02em", marginTop: 4 }}>{p.estimate ? PD.money(p.estimate) : "Pending"}</div>
          </div>
          {p.estimate ? (
            <div>
              <div className="cb-between" style={{ fontSize: 13, marginBottom: 8 }}><span className="cb-muted">Paid {PD.money(p.paid)}</span><span style={{ fontWeight: 700, color: "var(--text-strong)" }}>{Math.round((p.paid / p.estimate) * 100)}%</span></div>
              <ProgressBar value={(p.paid / p.estimate) * 100} />
              <div className="cb-soft-panel" style={{ marginTop: 16, textAlign: "center" }}>
                <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>Remaining balance</div>
                <div style={{ fontSize: 20, fontWeight: 700, color: remaining > 0 ? "var(--warning)" : "var(--teal-700)", fontFamily: "var(--font-display)" }}>{PD.money(remaining)}</div>
              </div>
            </div>
          ) : <p className="cb-muted" style={{ fontSize: 13, textAlign: "center" }}>Estimate prepared after medical review.</p>}
        </Card>
        <Card>
          <CardHead title="Care team" />
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[co, PD.coordById("c2"), PD.coordById("c4")].map((m, i) => (
              <div key={i} className="cb-row" style={{ gap: 11 }}>
                <Avatar initials={m.initials} color={m.color} size="sm" />
                <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>{m.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{m.role}</div></div>
                <button className="cb-icon-pill" style={{ width: 34, height: 34 }}><Icon name="message-circle" size={16} /></button>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function PatientHistory({ p }) {
  const items = [
    { t: "Presenting condition", d: p.condition, meta: "Referred by Carebridge intake" },
    { t: "Allergies", d: "No known drug allergies (sample)", meta: "Self-reported" },
    { t: "Chronic conditions", d: "Hypertension, managed (sample)", meta: "From submitted records" },
    { t: "Previous procedures", d: "None on file (sample)", meta: "—" },
    { t: "Current medication", d: "Per submitted prescription (sample)", meta: "Pending hospital review" },
  ];
  return (
    <Card>
      <CardHead title="Medical history" sub="Compiled from submitted reports — sample data" />
      <div className="cb-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        {items.map((it, i) => (
          <div key={i} className="cb-soft-panel">
            <div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em" }}>{it.t}</div>
            <div style={{ fontSize: 15, color: "var(--text-strong)", fontWeight: 600, margin: "6px 0 4px" }}>{it.d}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-faint)" }}>{it.meta}</div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function PatientDocuments() {
  const docs = [
    { name: "Passport copy", type: "PDF", size: "1.2 MB", icon: "book-user", status: "Verified" },
    { name: "Medical report bundle", type: "PDF", size: "8.4 MB", icon: "file-text", status: "Reviewed" },
    { name: "Visa application", type: "PDF", size: "0.9 MB", icon: "stamp", status: "Submitted" },
    { name: "Insurance letter", type: "PDF", size: "0.4 MB", icon: "shield-check", status: "On file" },
    { name: "Lab results — bloods", type: "PDF", size: "2.1 MB", icon: "flask-conical", status: "Reviewed" },
    { name: "Hospital admission letter", type: "PDF", size: "0.6 MB", icon: "hospital", status: "Received" },
  ];
  return (
    <Card>
      <CardHead title="Document storage" sub="Secure cloud — encrypted at rest" action="Upload document" onAction={() => {}} />
      <div className="cb-grid" style={{ gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
        {docs.map((d, i) => (
          <div key={i} className="cb-row" style={{ gap: 12, padding: 14, border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", cursor: "pointer" }}>
            <div className="cb-chip cb-chip--navy" style={{ width: 40, height: 40 }}><Icon name={d.icon} size={20} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{d.type} · {d.size}</div>
            </div>
            <Pill tone="teal">{d.status}</Pill>
          </div>
        ))}
      </div>
    </Card>
  );
}

function PatientTimeline({ p, hosp }) {
  const events = [
    { icon: "user-plus", tone: "navy", title: "Initial inquiry received", date: p.started, body: "Family contacted Carebridge and shared first medical reports." },
    { icon: "file-search", tone: "teal", title: "Medical reports reviewed", date: "Within 48 hours", body: "Reports organized and shared with " + hosp.name + " for opinion." },
    { icon: "stamp", tone: "warn", title: "Visa & travel arranged", date: "1 week later", body: "Visa application submitted, flights and accommodation coordinated." },
    { icon: "stethoscope", tone: "navy", title: "Treatment commenced", date: "On arrival", body: p.specialty + " pathway started at " + hosp.name + "." },
    { icon: "heart-pulse", tone: "teal", title: "Currently: " + PD.STAGES[p.stage], date: p.updated, body: "Care team monitoring progress — " + p.progress + "% complete." },
  ];
  return (
    <Card>
      <CardHead title="Treatment timeline" sub="Every step, documented" />
      <div style={{ position: "relative", paddingLeft: 8 }}>
        {events.map((e, i) => (
          <div key={i} style={{ display: "flex", gap: 16, paddingBottom: i < events.length - 1 ? 24 : 0 }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
              <div className={"cb-chip cb-chip--" + (e.tone === "teal" ? "" : e.tone)} style={{ width: 40, height: 40, borderRadius: 12 }}><Icon name={e.icon} size={19} /></div>
              {i < events.length - 1 ? <div style={{ width: 2, flex: 1, background: "var(--border-subtle)", marginTop: 6 }} /> : null}
            </div>
            <div style={{ paddingBottom: 4 }}>
              <div className="cb-row" style={{ gap: 10 }}><div style={{ fontSize: 15, fontWeight: 700, color: "var(--text-strong)" }}>{e.title}</div><span style={{ fontSize: 12, color: "var(--text-faint)", fontWeight: 600 }}>{e.date}</span></div>
              <p style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 4, maxWidth: "62ch" }}>{e.body}</p>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function PatientComms({ p, co }) {
  const msgs = [
    { me: false, text: "Assalamu alaikum, we received the hospital letter. Thank you so much for your help.", time: "09:12" },
    { me: true, text: "Wa alaikum salam. You're very welcome. Your admission is confirmed for " + p.started + ". I'll share the travel plan today.", time: "09:20" },
    { me: false, text: "JazakAllah khair. Should we prepare anything before the flight?", time: "09:24" },
    { me: true, text: "Just your passport and the documents I sent. Our team will meet you at the airport. You're in good hands.", time: "09:26" },
  ];
  return (
    <Card>
      <CardHead title="Communication log" sub={"Secure thread with " + p.name} />
      <div style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 680 }}>
        {msgs.map((m, i) => (
          <div key={i} style={{ alignSelf: m.me ? "flex-end" : "flex-start", maxWidth: "78%" }}>
            <div style={{ padding: "11px 15px", borderRadius: m.me ? "16px 16px 4px 16px" : "16px 16px 16px 4px", background: m.me ? "var(--navy-600)" : "var(--sky-100)", color: m.me ? "#fff" : "var(--text-body)", fontSize: 14, lineHeight: 1.5 }}>{m.text}</div>
            <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 4, textAlign: m.me ? "right" : "left" }}>{m.me ? co.name : p.name} · {m.time}</div>
          </div>
        ))}
      </div>
      <div className="cb-row" style={{ gap: 10, marginTop: 18, paddingTop: 18, borderTop: "1px solid var(--border-subtle)" }}>
        <div className="cb-search" style={{ flex: 1, minWidth: 0 }}><input placeholder="Write a secure message…" /></div>
        <button className="cb-icon-pill" style={{ background: "var(--teal-500)", color: "#fff", border: "none" }}><Icon name="send" size={18} /></button>
      </div>
    </Card>
  );
}

Object.assign(window, { PatientsView, PatientDetail });
