/* global React, I, Field, Btn, Pill, useState, useEffect, HeartIcon */

// ============ PATIENT REGISTRATION ============
function PatientRegScreen({ go }) {
  const [gender, setGender] = useState("M");
  const [consent, setConsent] = useState(false);
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 12, overflow: "auto" }}>
      <div className="back" onClick={() => go("devices", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>New patient</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 2 }}>Register a patient to start monitoring</div>
      </div>

      <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>First name</div>
            <Field icon={<I.user />} label="" value="John" />
          </div>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Last name</div>
            <Field label="" value="Doe" />
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Age</div>
            <Field label="" value="58" />
          </div>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Date of birth</div>
            <Field label="DD / MM / YYYY" value="14 / 03 / 1968" />
          </div>
        </div>

        <div>
          <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Gender</div>
          <div className="tab-row">
            {["M", "F", "Other"].map(g => (
              <div key={g} className={"t " + (gender === g ? "on" : "")} onClick={() => setGender(g)}>{g === "M" ? "Male" : g === "F" ? "Female" : "Other"}</div>
            ))}
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Bed</div>
            <div className="dd">ICU 4A <span className="caret" /></div>
          </div>
          <div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Insurance</div>
            <div className="dd" style={{ color: "var(--ink-4)" }}>Select… <span className="caret" /></div>
          </div>
        </div>

        <div>
          <div style={{ fontSize: 10, color: "var(--ink-4)", fontWeight: 700, marginBottom: 4, textTransform: "uppercase" }}>Insurance ID (optional)</div>
          <Field label="INS-12345" value="" />
        </div>

        <div className="tap-hot" style={{ display: "flex", gap: 10, padding: 4 }} onClick={() => setConsent(c => !c)}>
          <span className={"cb" + (consent ? " on" : "")}>{consent && <I.check />}</span>
          <span style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5 }}>I confirm patient has given verbal consent to register and that data handling complies with HIPAA.</span>
        </div>
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
        <Btn variant="ghost" full onClick={() => go("devices", "back")}>Cancel</Btn>
        <Btn variant={consent ? "primary" : "ghost"} full onClick={() => consent && go("consent")}>Register & Configure</Btn>
      </div>
    </div>
  );
}

// ============ PATIENT LIST ============
function PatientListScreen({ go }) {
  const patients = [
    { id: "PT-0042", name: "John Doe", age: 58, gender: "M", insurance: "ABHA-12345", active: true },
    { id: "PT-0067", name: "Jane Smith", age: 64, gender: "F", insurance: "ABHA-67891", active: true },
    { id: "PT-0089", name: "Robert Patel", age: 42, gender: "M", insurance: "STAR-44210", active: true },
    { id: "PT-0091", name: "Maya Krishnan", age: 71, gender: "F", insurance: "—", active: false },
  ];
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 12, overflow: "auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div className="back" onClick={() => go("devices", "back")}><I.back /> Back</div>
        <div className="tap-hot" style={{ width: 34, height: 34, border: "1.2px solid var(--line)", borderRadius: 9, display: "grid", placeItems: "center", background: "var(--paper-2)" }} onClick={() => go("patient-reg")}>
          <I.plus />
        </div>
      </div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Patients</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{patients.length} total · {patients.filter(p => p.active).length} active</div>
      </div>
      <div className="search"><I.search /> Search by name or ID…</div>
      <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {patients.map(p => (
          <div key={p.id} className="wf-box tap-hot" style={{ padding: 14 }} onClick={() => go("device-vitals")}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div style={{ display: "flex", gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: 50, border: "1.2px solid var(--line)", display: "grid", placeItems: "center", background: "var(--paper)", color: p.active ? "var(--accent)" : "var(--ink-4)", fontSize: 12, fontWeight: 800 }}>
                  {p.name.split(" ").map(n => n[0]).join("")}
                </div>
                <div>
                  <div style={{ fontWeight: 800, fontSize: 14 }}>{p.name}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{p.id}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{p.gender} · {p.age} yrs</div>
                </div>
              </div>
              <Pill variant={p.active ? "ok" : ""}>{p.active ? <><span className="dot" /> Active</> : <><span className="dot" /> Inactive</>}</Pill>
            </div>
            <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
              <span className="chip" style={{ fontSize: 10 }}>{p.insurance}</span>
              <span className="chip tap-hot" style={{ fontSize: 10 }} onClick={(e) => { e.stopPropagation(); go("move-patient"); }}>Move →</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ MOVE PATIENT ============
function MovePatientScreen({ go }) {
  const [selected, setSelected] = useState("PT-0042");
  const [dest, setDest] = useState(null);
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="back" onClick={() => go("patient-list", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Move patient</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 2 }}>Transfer monitoring to a different device</div>
      </div>

      <div>
        <div className="section-title" style={{ marginBottom: 6 }}>Patient</div>
        <div className="dd">John Doe <span className="mono dim" style={{ marginLeft: "auto", marginRight: 8, fontSize: 11 }}>PT-0042</span><span className="caret" /></div>
      </div>

      <div>
        <div className="section-title" style={{ marginBottom: 6 }}>Currently on</div>
        <div className="wf-box" style={{ padding: 12, display: "flex", alignItems: "center", gap: 10, background: "var(--paper)" }}>
          <div style={{ width: 30, height: 30, border: "1.2px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center" }}><I.device /></div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 13 }}>ICU 4A Monitor</div>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>ARS-001</div>
          </div>
          <span className="wf-pill ok" style={{ marginLeft: "auto" }}><span className="live-dot" style={{ width: 6, height: 6 }} /> Online</span>
        </div>
      </div>

      <div>
        <div className="section-title" style={{ marginBottom: 6 }}>Move to</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }} className="stagger">
          {[
            { id: "ARS-005", n: "Ward A Bed 12", on: true },
            { id: "ARS-008", n: "Recovery Bay 2", on: true },
            { id: "ARS-011", n: "Step-down 5", on: false },
          ].map(d => (
            <div key={d.id} className="wf-box tap-hot" style={{ padding: 12, borderColor: dest === d.id ? "var(--ink)" : "var(--line)" }} onClick={() => setDest(d.id)}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className={"cb" + (dest === d.id ? " on" : "")} style={{ borderRadius: 50 }}>{dest === d.id && <I.check />}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{d.n}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{d.id}</div>
                </div>
                {d.on ? <Pill variant="ok"><span className="dot" />Online</Pill> : <Pill variant="danger"><span className="dot" />Offline</Pill>}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: "auto" }}>
        <Btn variant="ghost" full onClick={() => go("patient-list", "back")}>Cancel</Btn>
        <Btn variant={dest ? "primary" : "ghost"} full onClick={() => dest && go("patient-list", "back")}>Move patient</Btn>
      </div>
    </div>
  );
}

// ============ CONSENT ============
function ConsentScreen({ go }) {
  const [vital, setVital] = useState(false);
  const [share, setShare] = useState(false);
  const [research, setResearch] = useState(false);
  const [sheet, setSheet] = useState(false);
  return (
    <div style={{ flex: 1, position: "relative" }}>
      <div style={{ padding: "16px 22px 110px", display: "flex", flexDirection: "column", gap: 14, height: "100%", overflow: "auto" }}>
        <div className="back" onClick={() => go("patient-reg", "back")}><I.back /> Back</div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>HIPAA · Patient Consent</div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Consent management</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Patient: <strong style={{ color: "var(--ink-2)" }}>John Doe</strong> · Today, 11:38</div>
        </div>

        <ConsentCard
          icon={<I.heart />}
          color="var(--danger)"
          title="Vital monitoring"
          desc="Required to receive and store vitals from the bedside device."
          mandatory
          on={vital} onToggle={() => setVital(v => !v)}
        />
        <ConsentCard
          icon={<I.share />}
          color="var(--info)"
          title="Data sharing"
          desc="Share de-identified vitals with affiliated specialists."
          on={share} onToggle={() => setShare(s => !s)}
        />
        <ConsentCard
          icon={<I.flask />}
          color="#5a3da3"
          title="Research participation"
          desc="Anonymized data may be used for clinical research."
          on={research} onToggle={() => setResearch(r => !r)}
        />

        <div className="tap-hot wf-box-soft" style={{ padding: 12, display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }} onClick={() => setSheet(true)}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><I.doc /> View HIPAA authorization details</span>
          <I.forward />
        </div>
      </div>

      <div style={{ position: "absolute", left: 12, right: 12, bottom: 14, background: "var(--paper-2)", border: "1.2px solid var(--line)", borderRadius: 16, padding: 12 }}>
        <Btn variant={vital ? "primary" : "ghost"} onClick={() => vital && go("device-vitals", "fwd")}>
          {vital ? "Confirm & continue →" : "Vital consent required"}
        </Btn>
      </div>

      {/* HIPAA bottom sheet */}
      {sheet && (
        <>
          <div style={{ position: "absolute", inset: 0, background: "rgba(15,20,25,0.5)", backdropFilter: "blur(4px)", animation: "enterFade 200ms ease" }} onClick={() => setSheet(false)} />
          <div className="enter-up" style={{ position: "absolute", left: 0, right: 0, bottom: 0, background: "var(--paper-2)", borderRadius: "20px 20px 0 0", padding: 18, maxHeight: "85%", overflow: "auto", boxShadow: "0 -20px 40px -10px rgba(15,20,25,0.2)" }}>
            <div style={{ width: 40, height: 4, background: "var(--line)", borderRadius: 999, margin: "0 auto 14px" }} />
            <div style={{ fontSize: 18, fontWeight: 800 }}>HIPAA Authorization</div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2, letterSpacing: 0.5 }}>VERSION 2.4 · LAST REVISED 2026-01-12</div>

            {[
              { t: "Authorization disclosure", b: "Patient authorizes ArogyaSync to receive, store, and process protected health information (PHI) for purposes specified herein." },
              { t: "Data collection & use", b: "Vitals are encrypted in transit and at rest. Access is limited to authorized care providers within affiliated hospitals." },
              { t: "Recipient information", b: "Care team at City General Hospital. Affiliated specialists if data sharing is granted." },
              { t: "Duration & rights", b: "Authorization remains in effect for the duration of care. Patient may revoke at any time." },
            ].map((s, i) => (
              <div key={i} style={{ marginTop: 14, padding: "12px 0", borderTop: i === 0 ? "1px dashed var(--line)" : "1px dashed var(--line-soft)" }}>
                <div style={{ fontSize: 13, fontWeight: 800, marginBottom: 4 }}>{s.t}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55 }}>{s.b}</div>
              </div>
            ))}

            <div style={{ marginTop: 18 }}>
              <Btn variant="primary" onClick={() => setSheet(false)}>Acknowledge & close</Btn>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function ConsentCard({ icon, color, title, desc, mandatory, on, onToggle }) {
  return (
    <div className="wf-box" style={{ padding: 14, display: "flex", gap: 12, alignItems: "flex-start" }}>
      <div style={{ width: 36, height: 36, borderRadius: 10, display: "grid", placeItems: "center", border: `1.2px solid ${color}`, color, background: color + "12", flex: "0 0 auto" }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ fontSize: 14, fontWeight: 800, flex: 1, minWidth: 0 }}>{title}</div>
          {mandatory && <Pill variant="warn">Required</Pill>}
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6, lineHeight: 1.45 }}>{desc}</div>
        {on && <div className="mono" style={{ fontSize: 10, color: "var(--accent)", marginTop: 6, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 4 }}><I.check /> GRANTED · Today 11:38</div>}
      </div>
      <div className={"tg" + (on ? " on" : "")} onClick={onToggle} style={{ marginTop: 4 }} />
    </div>
  );
}

Object.assign(window, { PatientRegScreen, PatientListScreen, MovePatientScreen, ConsentScreen });
