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

// ============ DEVICE SETUP (WiFi credentials) ============
function DeviceSetupScreen({ go }) {
  const [showPass, setShowPass] = useState(false);
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14, overflow: "auto" }}>
      <div className="back" onClick={() => go("pairing", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>Step 1 of 3</div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Configure device</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>Set up the WiFi network so it can sync to ArogyaSync cloud.</div>
      </div>

      {/* status cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>
        {[
          { i: <I.bluetooth />, l: "Bonded", c: "var(--accent)" },
          { i: <I.device />, l: "Awaiting", c: "var(--warn)" },
          { i: <I.wifi />, l: "Setup WiFi", c: "var(--info)" },
        ].map((s, i) => (
          <div key={i} className="wf-box" style={{ padding: 10, textAlign: "center" }}>
            <div style={{ color: s.c, display: "grid", placeItems: "center", marginBottom: 4 }}>{s.i}</div>
            <div style={{ fontSize: 10, color: "var(--ink-3)", fontWeight: 700, letterSpacing: 0.5, textTransform: "uppercase" }}>{s.l}</div>
          </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" }}>Device name</div>
          <Field icon={<I.device />} label="" value="ICU Bed 4A Monitor" focus />
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>WiFi SSID</div>
          <Field icon={<I.wifi />} label="" value="CityGen-Clinical-5G" />
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 6, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase" }}>WiFi password</div>
          <Field icon={<I.lock />} label="" value={showPass ? "Cl1n1cal#2026" : "•••••••••••"} suffix={<span className="tap-hot dim" onClick={() => setShowPass(s => !s)}><I.eye /></span>} />
        </div>
      </div>

      <div className="wf-box-soft" style={{ padding: 12, fontSize: 11, color: "var(--ink-3)", display: "flex", gap: 8 }}>
        <I.shield />
        <span>Credentials are encrypted in transit and never stored on the unit.</span>
      </div>

      <div style={{ marginTop: "auto" }}>
        <Btn variant="primary" onClick={() => go("check-image")}>Connect to device →</Btn>
      </div>
    </div>
  );
}

// ============ CHECK IMAGE ============
function CheckImageScreen({ go }) {
  const [loaded, setLoaded] = useState(false);
  useEffect(() => { const t = setTimeout(() => setLoaded(true), 1400); return () => clearTimeout(t); }, []);
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="back" onClick={() => go("device-setup", "back")}><I.back /> Back</div>
      <div>
        <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>Step 2 of 3</div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.3px" }}>Check positioning</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>Frame the bedside monitor's display fully in view.</div>
      </div>

      <div className="wf-box" style={{ flex: 1, padding: 14, display: "flex", flexDirection: "column", gap: 10, position: "relative" }}>
        <div style={{ flex: 1, position: "relative", borderRadius: 10, overflow: "hidden", background: "repeating-linear-gradient(45deg, var(--paper) 0 10px, var(--paper-3) 10px 11px)", border: "1.2px dashed var(--line)" }}>
          {!loaded ? (
            <div className="center" style={{ position: "absolute", inset: 0, color: "var(--ink-3)", flexDirection: "column", gap: 8 }}>
              <div className="ripple-wrap" style={{ width: 56, height: 56, position: "relative" }}>
                <span className="ripple" /><span className="ripple r2" />
                <div style={{ width: 56, height: 56, border: "1.4px solid var(--ink-3)", borderRadius: 14, display: "grid", placeItems: "center" }}><I.camera /></div>
              </div>
              <div className="mono" style={{ fontSize: 11 }}>RECEIVING IMAGE…</div>
            </div>
          ) : (
            <div style={{ position: "absolute", inset: 0, padding: 20 }} className="enter-fade">
              {/* mock ECG monitor */}
              <div style={{ width: "100%", height: "100%", background: "var(--ink)", borderRadius: 8, padding: 14, display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", color: "rgba(255,255,255,0.6)", fontSize: 9, fontFamily: "monospace" }}>
                  <span>HR 72 BPM</span><span>SpO₂ 98%</span><span>NIBP 120/80</span>
                </div>
                <div style={{ flex: 1, position: "relative", background: "rgba(255,255,255,0.04)", borderRadius: 4 }}>
                  <svg viewBox="0 0 200 80" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                    <path d="M0 40 L30 40 L36 20 L42 60 L48 14 L54 60 L60 40 L100 40 L106 20 L112 60 L118 14 L124 60 L130 40 L170 40" stroke="#10B77F" strokeWidth="1.4" fill="none"/>
                  </svg>
                </div>
                <div style={{ height: 24, background: "rgba(255,255,255,0.04)", borderRadius: 4, position: "relative" }}>
                  <svg viewBox="0 0 200 24" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                    <path d="M0 12 Q15 4, 30 12 T60 12 T90 12 T120 12 T150 12 T180 12" stroke="#3B82F6" strokeWidth="1.4" fill="none"/>
                  </svg>
                </div>
                <div style={{ color: "rgba(255,255,255,0.4)", fontSize: 8, fontFamily: "monospace", textAlign: "center" }}>BEDSIDE MONITOR — LIVE</div>
              </div>
            </div>
          )}
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "center", padding: "0 12px" }}>
          ✓ Display centered  •  ✓ All vitals visible  •  ✓ Adequate lighting
        </div>
      </div>

      <div style={{ display: "flex", gap: 8 }}>
        <Btn variant="ghost" full sm onClick={() => setLoaded(false) || setTimeout(() => setLoaded(true), 1200)}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><I.refresh /> Retake</span>
        </Btn>
        <Btn variant="primary" full onClick={() => loaded && go("roi")}>Continue →</Btn>
      </div>
      <div style={{ textAlign: "center", fontSize: 11, color: "var(--ink-4)" }} className="tap-hot" onClick={() => go("device-vitals", "fwd")}>Skip ROI setup</div>
    </div>
  );
}

// ============ ROI ============
function RoiScreen({ go, step = 0, setStep }) {
  const vitals = [
    { name: "Heart Rate", color: "var(--danger)", icon: <I.heart /> },
    { name: "SpO₂", color: "var(--info)", icon: <I.drop /> },
    { name: "Respiration", color: "#5a3da3", icon: <I.lung /> },
    { name: "Temperature", color: "var(--warn)", icon: <I.temp /> },
    { name: "Blood Pressure", color: "#0a6f4d", icon: <I.bp /> },
  ];
  const v = vitals[step];
  const [zoom, setZoom] = useState(1);
  const [mode, setMode] = useState("move");
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 12 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
        <div className="back" onClick={() => step > 0 ? setStep(step - 1) : go("check-image", "back")}><I.back /> Back</div>
        <span className="wf-pill" style={{ color: v.color, borderColor: v.color, background: v.color + "12", whiteSpace: "nowrap" }}>
          <span className="dot" /> {v.name.toUpperCase()}
        </span>
      </div>
      <div>
        <div style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: 1, fontWeight: 700 }}>Step {step + 1} of 5</div>
        <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: "-0.3px" }}>Draw region of interest</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>Drag corners to fit the {v.name.toLowerCase()} reading</div>
      </div>

      <div className="dots-prog" style={{ justifyContent: "center" }}>
        {vitals.map((_, i) => (
          <span key={i} className={"d " + (i < step ? "done" : i === step ? "on" : "")} />
        ))}
      </div>

      <div className="roi-canvas" style={{ flex: 1, position: "relative" }}>
        {/* mock monitor inside ROI canvas */}
        <div style={{ position: "absolute", inset: 12, background: "var(--ink)", borderRadius: 10, padding: 14, transform: `scale(${zoom})`, transformOrigin: "center", transition: "transform 0.3s" }}>
          <div style={{ color: "rgba(255,255,255,0.4)", fontSize: 8, fontFamily: "monospace", display: "flex", justifyContent: "space-between" }}>
            <span>HR</span><span>SpO₂</span><span>NIBP</span><span>RR</span><span>TEMP</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 6 }}>
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 3, padding: 6, color: "rgba(255,255,255,0.7)", fontSize: 9, fontFamily: "monospace" }}>HR <strong style={{ fontSize: 18, color: "#10B77F" }}>72</strong></div>
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 3, padding: 6, color: "rgba(255,255,255,0.7)", fontSize: 9, fontFamily: "monospace" }}>SpO₂ <strong style={{ fontSize: 18, color: "#3B82F6" }}>98</strong></div>
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 3, padding: 6, color: "rgba(255,255,255,0.7)", fontSize: 9, fontFamily: "monospace" }}>NIBP <strong style={{ fontSize: 14, color: "#10B77F" }}>120/80</strong></div>
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 3, padding: 6, color: "rgba(255,255,255,0.7)", fontSize: 9, fontFamily: "monospace" }}>RR <strong style={{ fontSize: 18, color: "#8B5CF6" }}>18</strong></div>
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 3, padding: 6, color: "rgba(255,255,255,0.7)", fontSize: 9, fontFamily: "monospace", gridColumn: "span 2" }}>TEMP <strong style={{ fontSize: 14, color: "#F59E0B" }}>36.8°C</strong></div>
          </div>
        </div>
        {/* ROI rect - varies position based on step */}
        <div className="roi-rect" style={{
          top: step === 0 ? 24 : step === 1 ? 24 : step === 2 ? 100 : step === 3 ? 138 : 64,
          left: step === 0 ? 24 : step === 1 ? "55%" : step === 2 ? "55%" : step === 3 ? 24 : 24,
          width: step === 4 ? "60%" : "38%",
          height: step === 4 ? 32 : 44,
          borderColor: v.color,
          background: v.color + "10",
        }}>
          <div className="roi-corner tl" style={{ borderColor: v.color }} />
          <div className="roi-corner tr" style={{ borderColor: v.color }} />
          <div className="roi-corner bl" style={{ borderColor: v.color }} />
          <div className="roi-corner br" style={{ borderColor: v.color }} />
          <div className="mono" style={{ position: "absolute", top: -22, left: 0, fontSize: 10, color: v.color, fontWeight: 800 }}>148 × 44 px</div>
        </div>
        {/* tools */}
        <div style={{ position: "absolute", top: 12, right: 12, display: "flex", flexDirection: "column", gap: 6 }}>
          <div className="tap-hot" style={{ width: 30, height: 30, background: "rgba(255,255,255,0.95)", border: "1px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center", fontSize: 14, fontWeight: 800 }} onClick={() => setZoom(z => Math.min(2, z + 0.2))}>+</div>
          <div className="mono" style={{ fontSize: 9, textAlign: "center", color: "var(--ink-3)" }}>{zoom.toFixed(1)}×</div>
          <div className="tap-hot" style={{ width: 30, height: 30, background: "rgba(255,255,255,0.95)", border: "1px solid var(--line)", borderRadius: 8, display: "grid", placeItems: "center", fontSize: 14, fontWeight: 800 }} onClick={() => setZoom(z => Math.max(1, z - 0.2))}>−</div>
        </div>
      </div>

      <div className="tab-row">
        <div className={"t " + (mode === "move" ? "on" : "")} onClick={() => setMode("move")}>↕ Move</div>
        <div className={"t " + (mode === "resize" ? "on" : "")} onClick={() => setMode("resize")}>⤡ Resize</div>
      </div>

      <Btn variant="primary" onClick={() => go("roi-confirm")}>Confirm region →</Btn>
    </div>
  );
}

// ============ ROI CONFIRMATION ============
function RoiConfirmScreen({ go, step = 0, setStep }) {
  const vitals = [
    { name: "Heart Rate", color: "var(--danger)", icon: <I.heart /> },
    { name: "SpO₂", color: "var(--info)", icon: <I.drop /> },
    { name: "Respiration", color: "#5a3da3", icon: <I.lung /> },
    { name: "Temperature", color: "var(--warn)", icon: <I.temp /> },
    { name: "Blood Pressure", color: "#0a6f4d", icon: <I.bp /> },
  ];
  const v = vitals[step];
  const last = step === vitals.length - 1;
  return (
    <div style={{ flex: 1, padding: "16px 22px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="back" onClick={() => go("roi", "back")}><I.back /> Back</div>

      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <span className="wf-pill" style={{ color: v.color, borderColor: v.color, background: v.color + "12" }}>STEP {step + 1} / 5</span>
        <span className="wf-pill"><I.check /> Saved</span>
      </div>

      <div className="dots-prog" style={{ justifyContent: "center" }}>
        {vitals.map((_, i) => (
          <span key={i} className={"d " + (i < step ? "done" : i === step ? "on" : "")} />
        ))}
      </div>

      <div className="wf-box" style={{ flex: 1, padding: 20, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14, background: "var(--ink)", color: "white", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(0deg, transparent 0 18px, rgba(255,255,255,0.04) 18px 19px)" }} />
        <div className="ripple-wrap beat" style={{ width: 88, height: 88, borderRadius: "50%", border: `2px solid ${v.color}`, background: v.color + "20", display: "grid", placeItems: "center", color: v.color, zIndex: 1 }}>
          <div style={{ transform: "scale(2)" }}>{v.icon}</div>
        </div>
        <div style={{ textAlign: "center", zIndex: 1 }}>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 2, textTransform: "uppercase", fontWeight: 700 }}>Region captured</div>
          <div style={{ fontSize: 22, fontWeight: 800, marginTop: 4 }}>{v.name}</div>
        </div>
        <div style={{ display: "flex", gap: 6, zIndex: 1 }}>
          <div className="mono wf-pill" style={{ background: "rgba(255,255,255,0.06)", color: "rgba(255,255,255,0.8)", borderColor: "rgba(255,255,255,0.12)" }}>TOP 100</div>
          <div className="mono wf-pill" style={{ background: "rgba(255,255,255,0.06)", color: "rgba(255,255,255,0.8)", borderColor: "rgba(255,255,255,0.12)" }}>LEFT 50</div>
          <div className="mono wf-pill" style={{ background: "rgba(255,255,255,0.06)", color: "rgba(255,255,255,0.8)", borderColor: "rgba(255,255,255,0.12)" }}>148×44</div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 10 }}>
        <Btn variant="ghost" full onClick={() => go("roi", "back")}>Redraw</Btn>
        <Btn variant="primary" full onClick={() => {
          if (last) { go("patient-reg", "fwd"); setStep(0); }
          else { setStep(step + 1); go("roi", "fwd"); }
        }}>
          {last ? "Complete setup →" : "Confirm & Next →"}
        </Btn>
      </div>
    </div>
  );
}

Object.assign(window, { DeviceSetupScreen, CheckImageScreen, RoiScreen, RoiConfirmScreen });
