/* global React, I, ScreenHeader, Field, Btn, Pill, useState, useEffect, BottomNav, SkeletonCard */

// ============ HOSPITAL LIST ============
function HospitalScreen({ go }) {
  const [selected, setSelected] = useState(null);
  const hospitals = [
    { id: 1, name: "City General Hospital", loc: "Mumbai, Maharashtra", devices: 12, staff: 8, kind: "general" },
    { id: 2, name: "Metro Health Center", loc: "Delhi, NCR", devices: 5, staff: 3, kind: "vaccines" },
    { id: 3, name: "Aarogya Multispeciality", loc: "Bengaluru, Karnataka", devices: 18, staff: 14, kind: "science" },
  ];
  const variants = ["#4ea8de", "#a36cd1", "#e0934a", "#0a6f4d", "#2a6ed9"];
  return (
    <div style={{ flex: 1, padding: "16px 22px 90px", display: "flex", flexDirection: "column", gap: 12, overflow: "auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>Welcome, Dr. Chen</div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Your hospitals</div>
        </div>
        <div className="tap-hot" style={{ width: 38, height: 38, border: "1.2px solid var(--line)", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--paper-2)" }} onClick={() => go("hospital-reg")}>
          <I.plus />
        </div>
      </div>
      <div className="search">
        <I.search /> <span>Search hospitals...</span>
      </div>

      <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 6 }}>
        {hospitals.map((h, i) => (
          <div key={h.id}
            className={"wf-box tap-hot"}
            style={{
              padding: 16,
              borderColor: selected === h.id ? "var(--ink)" : "var(--line)",
              borderWidth: selected === h.id ? 1.6 : 1.2,
              boxShadow: selected === h.id ? "0 0 0 3px rgba(15,20,25,0.04)" : "none",
              transition: "all 0.2s ease",
            }}
            onClick={() => { setSelected(h.id); setTimeout(() => go("devices"), 350); }}
          >
            <div style={{ display: "flex", gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 12, border: "1.2px solid var(--line)", display: "grid", placeItems: "center", color: variants[i % variants.length], background: variants[i % variants.length] + "15" }}>
                <I.building />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 800, fontSize: 15 }}>{h.name}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2, display: "flex", alignItems: "center", gap: 4 }}>
                  <I.pin /> {h.loc}
                </div>
                <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
                  <span className="chip" style={{ fontSize: 10 }}>{h.devices} devices</span>
                  <span className="chip" style={{ fontSize: 10 }}>{h.staff} staff</span>
                  <span className="chip" style={{ fontSize: 10, color: "#0a6f4d" }}><span className="live-dot" style={{ width: 6, height: 6 }} /> Active</span>
                </div>
              </div>
              <div className="dim" style={{ alignSelf: "center" }}><I.forward /></div>
            </div>
          </div>
        ))}
        <div className="wf-box-soft tap-hot" style={{ padding: 16, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, color: "var(--ink-3)" }} onClick={() => go("hospital-reg")}>
          <I.plus /> Add a new hospital
        </div>
      </div>
    </div>
  );
}

// ============ HOSPITAL REGISTRATION ============
function HospitalRegScreen({ go }) {
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14, overflow: "auto" }}>
      <div className="back" onClick={() => go("hospital", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Register hospital</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>Add a new facility to your account</div>
      </div>
      <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>Hospital name</div>
          <Field icon={<I.building />} label="e.g. City General Hospital" value="" />
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>Location</div>
          <Field icon={<I.pin />} label="City, State" value="" />
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>Pincode</div>
          <Field icon={<I.dots />} label="6-digit pincode" value="" />
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>Hospital type</div>
          <div className="dd">Multispeciality <span className="caret" /></div>
        </div>
      </div>
      <div style={{ marginTop: "auto", display: "flex", gap: 10 }}>
        <Btn variant="ghost" full onClick={() => go("hospital", "back")}>Cancel</Btn>
        <Btn variant="primary" full onClick={() => go("hospital", "back")}>Register</Btn>
      </div>
    </div>
  );
}

// ============ DEVICE OVERVIEW ============
function DevicesScreen({ go, tab, onTab }) {
  const [filter, setFilter] = useState("all");
  const [loading, setLoading] = useState(true);
  useEffect(() => { const t = setTimeout(() => setLoading(false), 700); return () => clearTimeout(t); }, []);
  const devices = [
    { id: "ARS-001", name: "Bedside Monitor A", ward: "ICU Bed 4A", patient: "John Doe", online: true, hr: 72, spo2: 98, mins: 1 },
    { id: "ARS-002", name: "Bedside Monitor B", ward: "Ward B, Bed 7", patient: null, online: false, mins: 124 },
    { id: "ARS-003", name: "ER Cart Monitor", ward: "ER Triage 2", patient: "Jane Smith", online: true, hr: 88, spo2: 95, mins: 1 },
    { id: "ARS-004", name: "Recovery Unit 1", ward: "PACU Bay 3", patient: "Robert Patel", online: true, hr: 64, spo2: 99, mins: 2 },
  ];
  const filtered = filter === "online" ? devices.filter(d => d.online) : filter === "offline" ? devices.filter(d => !d.online) : devices;

  return (
    <>
      <div style={{ flex: 1, padding: "16px 18px 90px", display: "flex", flexDirection: "column", gap: 12, overflow: "auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>City General Hospital</div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Devices</div>
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <div className="tap-hot" style={{ width: 36, height: 36, border: "1.2px solid var(--line)", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--paper-2)" }}>
              <I.bluetooth />
            </div>
            <div className="tap-hot" style={{ width: 36, height: 36, border: "1.2px solid var(--line)", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--paper-2)" }} onClick={() => go("pairing")}>
              <I.plus />
            </div>
          </div>
        </div>

        {/* stats carousel */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
          {[
            { l: "Total", v: 12, c: "var(--ink-2)" },
            { l: "Online", v: 8, c: "var(--accent)" },
            { l: "Offline", v: 4, c: "var(--danger)" },
          ].map(s => (
            <div key={s.l} className="wf-box" style={{ padding: 12, borderLeft: `3px solid ${s.c}` }}>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>{s.l}</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 800 }}>{s.v}</div>
            </div>
          ))}
        </div>

        {/* search + filters */}
        <div className="search"><I.search /> Search devices...</div>
        <div className="tab-row">
          {["all", "online", "offline"].map(f => (
            <div key={f} className={"t " + (filter === f ? "on" : "")} onClick={() => setFilter(f)}>
              {f.charAt(0).toUpperCase() + f.slice(1)}
              <span className="mono" style={{ marginLeft: 5, color: "var(--ink-4)" }}>{f === "all" ? 12 : f === "online" ? 8 : 4}</span>
            </div>
          ))}
        </div>

        {/* device list */}
        <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {loading ? <>
            <SkeletonCard /><SkeletonCard /><SkeletonCard />
          </> : filtered.map(d => (
            <div key={d.id} className="wf-box tap-hot" style={{ padding: 14, borderLeft: `3px solid ${d.online ? "var(--accent)" : "var(--danger)"}` }} onClick={() => go("device-vitals")}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div style={{ minWidth: 0 }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)", letterSpacing: 0.5 }}>DEV-{d.id}</div>
                  <div style={{ fontSize: 14, fontWeight: 800, marginTop: 2 }}>{d.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{d.ward}</div>
                </div>
                {d.online ? <Pill variant="ok"><span className="live-dot" style={{ width: 6, height: 6 }} /> Online</Pill> : <Pill variant="danger"><span className="dot" /> Offline</Pill>}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, paddingTop: 10, borderTop: "1px dashed var(--line-soft)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                  <span className="dim"><I.user /></span>
                  <span style={{ color: "var(--ink-2)", fontWeight: 600 }}>{d.patient || "Unassigned"}</span>
                </div>
                {d.online && (
                  <div className="mono" style={{ display: "flex", gap: 10, fontSize: 11, color: "var(--ink-3)" }}>
                    <span><HeartIcon size={10} /> {d.hr}</span>
                    <span style={{ color: "var(--info)" }}>SpO₂ {d.spo2}</span>
                  </div>
                )}
              </div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", marginTop: 6, display: "flex", justifyContent: "space-between" }}>
                <span>Last sync: {d.mins}m ago</span>
                <span style={{ display: "flex", alignItems: "center", gap: 4 }}>View vitals <I.forward /></span>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
          <Btn variant="ghost" full sm onClick={() => go("patient-list")}>Patients</Btn>
          <Btn variant="ghost" full sm onClick={() => go("patient-reg")}>New patient</Btn>
        </div>
      </div>
      <BottomNav tab={tab} onTab={onTab} />
    </>
  );
}

// ============ DEVICE PAIRING ============
function PairingScreen({ go }) {
  const [scanning, setScanning] = useState(true);
  const [selected, setSelected] = useState(null);
  useEffect(() => { const t = setTimeout(() => setScanning(false), 1800); return () => clearTimeout(t); }, []);
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14, overflow: "auto" }}>
      <div className="back" onClick={() => go("devices", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Pair new device</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>Discover nearby ArogyaSync monitors via Bluetooth</div>
      </div>

      {/* radar scan */}
      <div className="wf-box" style={{ padding: 22, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, position: "relative", overflow: "hidden" }}>
        <div className="ripple-wrap" style={{ width: 72, height: 72, position: "relative" }}>
          {scanning && <><span className="ripple" /><span className="ripple r2" /></>}
          <div style={{ width: 72, height: 72, border: "1.5px solid var(--info)", borderRadius: "50%", display: "grid", placeItems: "center", color: "var(--info)" }}>
            <I.bluetooth />
          </div>
        </div>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{scanning ? "Scanning nearby devices…" : "Scan complete"}</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Make sure your device is powered on</div>
        <div className="tap-hot" style={{ fontSize: 11, fontWeight: 800, color: "var(--ink)", padding: "6px 12px", border: "1px solid var(--line)", borderRadius: 999, marginTop: 4, display: "inline-flex", alignItems: "center", gap: 6 }} onClick={() => setScanning(true)}>
          <I.refresh /> Re-scan
        </div>
      </div>

      <div>
        <div className="section-title" style={{ marginBottom: 6 }}>Discovered ({scanning ? 1 : 3})</div>
        <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {(scanning ? [{ name: "ARS-Monitor-002", mac: "A4:23:9C:EE:FF", rssi: -54 }] : [
            { name: "ARS-Monitor-002", mac: "A4:23:9C:EE:FF", rssi: -54 },
            { name: "ARS-Monitor-007", mac: "A4:23:9C:E1:F2", rssi: -72 },
            { name: "ARS-Monitor-012", mac: "A4:23:9C:DC:AA", rssi: -81 },
          ]).map(d => (
            <div key={d.mac} className={"wf-box tap-hot"} style={{ padding: 12, borderColor: selected === d.mac ? "var(--ink)" : "var(--line)" }} onClick={() => { setSelected(d.mac); setTimeout(() => go("device-setup"), 350); }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 32, height: 32, border: "1.2px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center", color: "var(--info)" }}><I.device /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{d.name}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{d.mac}</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--ink-3)" }}>
                  <I.signal /> {d.rssi}
                </div>
                <I.forward />
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 14px", border: "1px dashed var(--line)", borderRadius: 12, background: "var(--paper)", marginTop: "auto" }}>
        <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Mock mode (no hardware)</div>
        <div className="tg" />
      </div>
    </div>
  );
}

Object.assign(window, { HospitalScreen, HospitalRegScreen, DevicesScreen, PairingScreen });
