/* global React, I, Field, Btn, Pill, useState, useEffect, BottomNav, VitalCard, Spark, HeartIcon, ECGTrack */

// ============ DEVICE VITALS DASHBOARD ============
function DeviceVitalsScreen({ go, tab, onTab }) {
  // Animate vital ticks
  const [hr, setHr] = useState(72);
  useEffect(() => {
    const t = setInterval(() => setHr(h => Math.max(64, Math.min(82, h + (Math.random() > 0.5 ? 1 : -1)))), 1300);
    return () => clearInterval(t);
  }, []);

  return (
    <>
      <div style={{ flex: 1, padding: "16px 18px 90px", display: "flex", flexDirection: "column", gap: 14, overflow: "auto" }}>
        {/* header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center", minWidth: 0, flex: 1 }}>
            <div className="avatar" style={{ width: 38, height: 38 }}>SC<span className="online" /></div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 0.6, fontWeight: 700 }}>Good morning</div>
              <div style={{ fontSize: 15, fontWeight: 800, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Dr. Sarah Chen</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 6, flex: "0 0 auto" }}>
            <div className="icon-btn"><I.bluetooth /></div>
            <div className="icon-btn" onClick={() => go("alerts")}><I.bell /><span className="badge" /></div>
          </div>
        </div>

        {/* patient + status card */}
        <div className="wf-box accent-gradient-card" style={{ padding: 14, borderWidth: 1.4 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>Patient · ICU 4A</div>
              <div style={{ fontSize: 16, fontWeight: 800, marginTop: 2 }}>John Doe <span className="mono dim" style={{ fontSize: 11, fontWeight: 600 }}>PT-0042</span></div>
            </div>
            <Pill variant="ok"><span className="dot" /> Stable</Pill>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, paddingTop: 10, borderTop: "1px dashed var(--line)", gap: 8 }}>
            <div style={{ fontSize: 11, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 6, whiteSpace: "nowrap" }}>
              <span className="live-dot" /> Live · <span style={{ color: "var(--ink-4)" }}>2s ago</span>
            </div>
            <div className="tap-hot" style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-2)", display: "inline-flex", alignItems: "center", gap: 4, whiteSpace: "nowrap" }} onClick={() => go("live-vitals")}>
              View live <I.forward />
            </div>
          </div>
        </div>

        {/* vitals grid */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <div className="section-title">Real-time vitals</div>
          <div className="tap-hot" style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-2)" }} onClick={() => go("trends")}>History →</div>
        </div>
        <div className="stagger" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <div className="tap-hot" onClick={() => go("live-vitals")}>
            <VitalCard kind="hr" value={hr} unit="BPM" label="Heart Rate" status="ok" spark={[68, 70, 72, 71, 73, 75, 72, 70, 71, 73, 72]} />
          </div>
          <div className="tap-hot" onClick={() => go("live-vitals")}>
            <VitalCard kind="spo2" value={98} unit="%" label="SpO₂" status="ok" spark={[97, 97, 98, 98, 97, 98, 98, 98, 97, 98, 98]} />
          </div>
          <div className="tap-hot" onClick={() => go("live-vitals")}>
            <VitalCard kind="bp" value="120/80" unit="mmHg" label="NIBP" status="ok" spark={[118, 120, 122, 121, 120, 119, 120, 121, 120, 120, 120]} />
          </div>
          <div className="tap-hot" onClick={() => go("live-vitals")}>
            <VitalCard kind="temp" value="36.8" unit="°C" label="Temperature" status="ok" spark={[36.6, 36.7, 36.8, 36.8, 36.9, 36.8, 36.8, 36.8, 36.8, 36.8, 36.8]} />
          </div>
        </div>
        <div className="tap-hot" onClick={() => go("live-vitals")}>
          <VitalCard kind="rr" value={18} unit="RPM" label="Respiration Rate" status="ok" spark={[16, 17, 18, 17, 18, 19, 18, 17, 18, 19, 18, 18, 17, 18]} large />
        </div>

        {/* mini insights */}
        <div className="wf-box-soft" style={{ padding: 12, display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12, color: "var(--ink-3)" }}>
          <div style={{ width: 22, height: 22, borderRadius: 6, background: "var(--accent-soft)", color: "#0a6f4d", display: "grid", placeItems: "center", flex: "0 0 auto" }}><I.check /></div>
          <div>
            <div style={{ fontWeight: 700, color: "var(--ink-2)" }}>All vitals in range over last 4 hours</div>
            <div style={{ marginTop: 2 }}>No alerts. Cleared shift handover by Dr. R. Iyer at 06:14.</div>
          </div>
        </div>
      </div>
      <BottomNav tab={tab} onTab={onTab} />
    </>
  );
}

// ============ TRENDS ============
function TrendsScreen({ go, tab, onTab }) {
  const [range, setRange] = useState("24H");
  const [vital, setVital] = useState("HR+SpO₂+RR");
  return (
    <>
      <div style={{ flex: 1, padding: "16px 18px 90px", display: "flex", flexDirection: "column", gap: 14, 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 }}>Patient PT-0042</div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Health trends</div>
          </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)" }}>
            <I.share />
          </div>
        </div>

        <div className="dd">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><I.chart /> {vital}</span>
          <span className="caret" />
        </div>

        <div className="tab-row">
          {["1H", "6H", "24H", "7D", "30D"].map(r => (
            <div key={r} className={"t " + (range === r ? "on" : "")} onClick={() => setRange(r)}>{r}</div>
          ))}
        </div>

        {/* chart */}
        <div className="wf-box" style={{ padding: 14 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 800 }}>Last {range}</div>
            <div style={{ fontSize: 10, color: "var(--ink-4)", letterSpacing: 0.5 }}>UPDATED 9:41 AM</div>
          </div>
          <div style={{ position: "relative", height: 200 }}>
            <svg width="100%" height="200" viewBox="0 0 320 200" preserveAspectRatio="none">
              {/* gridlines */}
              {[40, 80, 120, 160].map(y => <line key={y} x1="0" x2="320" y1={y} y2={y} stroke="var(--line-soft)" strokeDasharray="2 4" />)}
              {/* HR */}
              <path d="M0 100 C20 92, 30 105, 50 98 S80 88, 110 95 S150 105, 180 90 S220 100, 250 85 S290 95, 320 92" stroke="var(--danger)" strokeWidth="1.8" fill="none" className="draw" />
              {/* SpO2 */}
              <path d="M0 55 C30 60, 60 50, 90 55 S150 48, 200 55 S260 50, 320 52" stroke="var(--info)" strokeWidth="1.8" fill="none" className="draw" />
              {/* RR */}
              <path d="M0 145 C40 148, 80 140, 130 144 S200 150, 260 144 S300 142, 320 145" stroke="#5a3da3" strokeWidth="1.8" fill="none" className="draw" />
              {/* threshold lines */}
              <line x1="0" x2="320" y1="68" y2="68" stroke="var(--warn)" strokeDasharray="4 4" strokeWidth="1" opacity="0.6" />
              <line x1="0" x2="320" y1="125" y2="125" stroke="var(--warn)" strokeDasharray="4 4" strokeWidth="1" opacity="0.6" />
            </svg>
            <div style={{ position: "absolute", top: 50, right: 0, fontSize: 9, color: "var(--warn)", background: "var(--paper-2)", padding: "0 4px" }}>upper</div>
            <div style={{ position: "absolute", bottom: 50, right: 0, fontSize: 9, color: "var(--warn)", background: "var(--paper-2)", padding: "0 4px" }}>lower</div>
          </div>
          <div style={{ display: "flex", gap: 12, paddingTop: 10, borderTop: "1px dashed var(--line-soft)", marginTop: 8 }}>
            {[
              { c: "var(--danger)", l: "HR" },
              { c: "var(--info)", l: "SpO₂" },
              { c: "#5a3da3", l: "RR" },
            ].map(l => (
              <div key={l.l} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 700 }}>
                <span style={{ width: 10, height: 10, borderRadius: 2, background: l.c }} /> {l.l}
              </div>
            ))}
          </div>
        </div>

        {/* summary */}
        <div className="section-title">Summary</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }} className="stagger">
          {[
            { l: "Avg HR", v: "73", u: "BPM", t: "+1.2%" },
            { l: "Avg SpO₂", v: "97.8", u: "%", t: "stable" },
            { l: "Max BP", v: "128", u: "mmHg", t: "+4" },
            { l: "Avg RR", v: "17.8", u: "RPM", t: "stable" },
          ].map((s, i) => (
            <div key={i} className="wf-box" style={{ padding: 12 }}>
              <div style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 0.6, fontWeight: 700 }}>{s.l}</div>
              <div className="mono" style={{ fontSize: 18, fontWeight: 800, marginTop: 2 }}>{s.v} <span style={{ fontSize: 10, color: "var(--ink-4)" }}>{s.u}</span></div>
              <div style={{ fontSize: 11, color: "var(--accent)", marginTop: 2, fontWeight: 700 }}>↗ {s.t}</div>
            </div>
          ))}
        </div>

        <div className="wf-box-soft" style={{ padding: 12, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontSize: 12 }}>
            <div style={{ fontWeight: 800 }}>Set custom alert thresholds</div>
            <div style={{ color: "var(--ink-3)", marginTop: 2 }}>Get notified when vitals leave the band</div>
          </div>
          <Btn variant="ghost" sm onClick={() => go("threshold")}>Configure</Btn>
        </div>
      </div>
      <BottomNav tab={tab} onTab={onTab} />
    </>
  );
}

// ============ LIVE VITALS ============
function LiveVitalsScreen({ go }) {
  const [hr, setHr] = useState(72);
  const [windowSize, setWindowSize] = useState("30min");
  useEffect(() => {
    const t = setInterval(() => setHr(h => Math.max(68, Math.min(80, h + (Math.random() > 0.5 ? 1 : -1)))), 900);
    return () => clearInterval(t);
  }, []);

  return (
    <div style={{ flex: 1, padding: "16px 18px 18px", display: "flex", flexDirection: "column", gap: 12, overflow: "auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div className="back" onClick={() => go("device-vitals", "back")}><I.back /> Back</div>
        <div style={{ display: "flex", gap: 6 }}>
          <div className="tap-hot" style={{ width: 32, height: 32, border: "1.2px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center", background: "var(--paper-2)" }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
          </div>
          <div className="tap-hot" style={{ width: 32, height: 32, border: "1.2px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center", background: "var(--paper-2)" }} onClick={() => go("alerts")}>
            <I.bell />
          </div>
        </div>
      </div>
      <div>
        <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 0.6, fontWeight: 700, display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
          <span className="live-dot" /> Live · John Doe · ICU 4A
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px", marginTop: 2 }}>Patient vitals</div>
      </div>

      {/* hero HR card with ECG */}
      <div className="wf-box danger-gradient-card" style={{ padding: 14, borderWidth: 1.4 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 0.8, fontWeight: 700 }}>Heart Rate</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 2 }}>
              <span className="beat" style={{ display: "inline-grid", placeItems: "center", color: "var(--danger)" }}><I.heart /></span>
              <span className="mono tick up" key={String(hr)} style={{ fontSize: 56, fontWeight: 900, letterSpacing: "-2px", lineHeight: 1, color: "var(--ink)" }}>{hr}</span>
              <span style={{ color: "var(--ink-4)", fontSize: 12, fontWeight: 700, letterSpacing: 1, textTransform: "uppercase" }}>BPM</span>
            </div>
          </div>
          <div style={{ textAlign: "right", display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
            <Pill variant="ok"><span className="dot" /> Normal</Pill>
            <div style={{ fontSize: 11, color: "var(--accent)", fontWeight: 700 }}>↗ +3 from avg</div>
          </div>
        </div>
        <div style={{ marginTop: 10 }}><ECGTrack /></div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "var(--ink-4)", marginTop: 6 }}>
          <span className="mono">60-100 bpm range</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><span className="live-dot" /> Streaming</span>
        </div>
      </div>

      {/* mini vitals pills */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
        {[
          { k: "SpO₂", v: 98, u: "%", c: "var(--info)" },
          { k: "NIBP", v: "120/80", u: "mmHg", c: "#0a6f4d" },
          { k: "Temp", v: "36.8", u: "°C", c: "var(--warn)" },
        ].map(m => (
          <div key={m.k} className="wf-box" style={{ padding: 10, textAlign: "center" }}>
            <div style={{ fontSize: 9, color: m.c, fontWeight: 800, letterSpacing: 0.6, textTransform: "uppercase" }}>{m.k}</div>
            <div className="mono" style={{ fontSize: 17, fontWeight: 800, marginTop: 2 }}>{m.v}</div>
            <div style={{ fontSize: 9, color: "var(--ink-4)" }}>{m.u}</div>
          </div>
        ))}
      </div>

      {/* time window pills */}
      <div>
        <div className="section-title" style={{ marginBottom: 6 }}>Window</div>
        <div style={{ display: "flex", gap: 6, overflowX: "auto" }}>
          {["15min", "30min", "1hr", "2hr", "4hr", "8hr"].map(w => (
            <div key={w} className={"chip tap-hot " + (windowSize === w ? "on" : "")} onClick={() => setWindowSize(w)}>{w}</div>
          ))}
        </div>
      </div>

      {/* 3-vital chart */}
      <div className="wf-box" style={{ padding: 14 }}>
        <div style={{ fontSize: 12, color: "var(--ink-3)", display: "flex", justifyContent: "space-between" }}>
          <span style={{ fontWeight: 700 }}>{windowSize} trend</span>
          <span style={{ fontSize: 10 }}>9:11 → 9:41</span>
        </div>
        <svg viewBox="0 0 320 130" style={{ width: "100%", height: 130, marginTop: 6 }}>
          {[30, 60, 90].map(y => <line key={y} x1="0" x2="320" y1={y} y2={y} stroke="var(--line-soft)" strokeDasharray="2 4" />)}
          <path d="M0 70 C30 65, 60 75, 90 70 S150 60, 200 70 S260 65, 320 70" stroke="var(--danger)" strokeWidth="1.8" fill="none" className="draw" />
          <path d="M0 30 C40 32, 90 28, 150 30 S250 32, 320 30" stroke="var(--info)" strokeWidth="1.8" fill="none" className="draw" />
          <path d="M0 100 C40 102, 80 98, 130 100 S200 105, 260 100 S300 100, 320 100" stroke="#5a3da3" strokeWidth="1.8" fill="none" className="draw" />
        </svg>
      </div>

      <div className="wf-box-soft tap-hot" style={{ padding: 12, display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12 }} onClick={() => go("trends")}>
        <span>View full history & comparisons</span>
        <I.forward />
      </div>
    </div>
  );
}

Object.assign(window, { DeviceVitalsScreen, TrendsScreen, LiveVitalsScreen });
