/* Hospital — live ward view.
 * Click a ward to open a detail panel with patient list + recommended action.
 */

const hospTheme = {
  card: "#171715",
  cardHi: "#1f1c19",
  cardLine: "#262320",
  ink: "#f0ece4",
  ink2: "#a8a49b",
  ink3: "#6b6862",
  ink4: "#4a4842",
  amber: "#d99350",
  green: "#6aa37d",
  red: "#d35a4a",
  blue: "#6c8db6",
};

const WARDS = [
  { id: "med-w", name: "Medical · West",   occ: 28, cap: 36, alerts: 0,  status: "calm",  doc: "Dr. K. Hassan",
    patients: [["W-401","stable","Day 4 post-op · cleared for discharge"], ["W-402","stable","CHF monitoring · pending echo"], ["W-405","stable","Day 2 antibiotics IV"]],
    action: "2 beds free this morning. Pre-clear W-401 for 11:00 release."
  },
  { id: "med-e", name: "Medical · East",   occ: 24, cap: 32, alerts: 0,  status: "calm",  doc: "Dr. R. Costa",
    patients: [["E-512","stable","Pneumonia · improving"], ["E-518","stable","Diabetes mgmt"], ["E-521","stable","Awaiting MRI"]],
    action: "8 beds free. Capacity is healthy."
  },
  { id: "surg",  name: "Surgical",         occ: 22, cap: 30, alerts: 1,  status: "calm",  doc: "Dr. N. Yusuf",
    patients: [["S-203","watch","Post-laparotomy · day 1"], ["S-207","stable","Cholecystectomy · day 3"], ["S-212","stable","Hernia repair · ready for d/c"]],
    action: "1 watch case. 8 beds free for theatre list tomorrow."
  },
  { id: "ward4", name: "Ward 4 · Cardio",  occ: 30, cap: 33, alerts: 2,  status: "alert", doc: "Dr. A. Müller", note: "Bed pressure",
    patients: [
      ["C-118","ready",  "MI · day 6 · cardiology approved discharge"],
      ["C-122","ready",  "Arrhythmia review · discharge plan signed"],
      ["C-124","watch",  "Post-PCI · 24 hr monitoring"],
      ["C-130","critical","Acute decompensated HF · daily review"],
    ],
    action: "Two patients (C-118, C-122) ready to discharge — pharmacy holds them. Releasing both clears Ward 4 to 84%.",
  },
  { id: "mat",   name: "Maternity",         occ: 14, cap: 22, alerts: 0,  status: "calm",  doc: "Dr. L. Petrescu",
    patients: [["M-301","stable","Antenatal · 38 wk"], ["M-304","stable","Post-partum day 1"]],
    action: "8 beds free. Routine."
  },
  { id: "ped",   name: "Pediatrics",        occ: 16, cap: 24, alerts: 0,  status: "calm",  doc: "Dr. F. Bouazza",
    patients: [["P-108","stable","Bronchiolitis · day 2"], ["P-111","stable","Gastroenteritis · improving"]],
    action: "8 beds free. No isolations active."
  },
];

function HospOccBar({ occ, cap, color }) {
  const pct = (occ / cap) * 100;
  return (
    <div style={{ height: 4, background: "#2a2925", borderRadius: 2, overflow: "hidden", marginTop: 10 }}>
      <div style={{ width: pct + "%", height: "100%", background: color, transition: "width 0.6s ease" }} />
    </div>
  );
}

function WardCard({ w, active, onClick }) {
  const pct = Math.round((w.occ / w.cap) * 100);
  const isAlert = w.status === "alert";
  const color = pct >= 90 ? hospTheme.red : pct >= 80 ? hospTheme.amber : hospTheme.green;
  return (
    <button onClick={onClick} style={{
      textAlign: "left",
      background: isAlert ? "#1a1413" : (active ? hospTheme.cardHi : hospTheme.card),
      padding: "16px 18px 18px",
      borderRadius: 10,
      position: "relative",
      boxShadow: isAlert ? "inset 0 0 0 1px rgba(211, 90, 74, 0.35)" : active ? "inset 0 0 0 1px rgba(217,147,80,0.5)" : "inset 0 0 0 1px rgba(255,255,255,0.03)",
      overflow: "hidden",
      cursor: "pointer",
      transition: "background 0.15s ease, box-shadow 0.15s ease",
    }}>
      {isAlert && (
        <div style={{
          position: "absolute", top: 0, left: 0, right: 0,
          height: 3,
          background: hospTheme.red,
        }} />
      )}

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ fontSize: 13, color: hospTheme.ink, fontWeight: 500 }}>{w.name}</div>
        {w.alerts > 0 && (
          <span style={{
            fontSize: 10.5, fontWeight: 600, letterSpacing: "0.06em",
            padding: "2px 7px",
            background: isAlert ? "rgba(211,90,74,0.18)" : "rgba(217,147,80,0.15)",
            color: isAlert ? hospTheme.red : hospTheme.amber,
            borderRadius: 3,
          }}>{w.alerts} alert{w.alerts > 1 ? "s" : ""}</span>
        )}
      </div>

      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 12 }}>
        <div style={{
          fontSize: 26,
          fontWeight: 600,
          color: isAlert ? hospTheme.red : hospTheme.ink,
          letterSpacing: "-0.02em",
          lineHeight: 1,
          fontVariantNumeric: "tabular-nums",
        }}>{pct}<span style={{ fontSize: 14, color: hospTheme.ink3 }}>%</span></div>
        <div style={{ fontSize: 11.5, color: hospTheme.ink3, fontVariantNumeric: "tabular-nums" }}>
          {w.occ} / {w.cap} beds
        </div>
      </div>

      <HospOccBar occ={w.occ} cap={w.cap} color={color} />

      <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", fontSize: 11, color: hospTheme.ink3 }}>
        <span>{w.doc}</span>
        <span>
          {isAlert && <span style={{ color: hospTheme.red }}>● </span>}
          {isAlert ? w.note : "stable"}
        </span>
      </div>
    </button>
  );
}

function HospitalPreview() {
  const [pickId, setPick] = React.useState("ward4");
  const sel = WARDS.find(w => w.id === pickId) || WARDS[3];
  const totalOcc = WARDS.reduce((a, b) => a + b.occ, 0);
  const totalCap = WARDS.reduce((a, b) => a + b.cap, 0);

  const statusColor = (s) => ({
    critical: hospTheme.red,
    watch:    hospTheme.amber,
    ready:    hospTheme.green,
    stable:   hospTheme.blue,
  }[s] || hospTheme.ink3);

  return (
    <div style={{
      background: "#0e0e0c",
      color: hospTheme.ink,
      borderRadius: 14,
      padding: "24px 28px 26px",
      boxShadow: "0 30px 60px -25px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04)",
      maxWidth: 800,
    }}>
      {/* header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.16em", color: hospTheme.ink3, textTransform: "uppercase" }}>Live ward view</div>
          <div style={{ fontSize: 20, fontWeight: 600, marginTop: 4, letterSpacing: "-0.01em" }}>Hôpital Central · 18 May, 14:42</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontSize: 11, letterSpacing: "0.16em", color: hospTheme.ink3, textTransform: "uppercase" }}>Total occupancy</div>
          <div style={{
            fontSize: 26, fontWeight: 600, marginTop: 2, letterSpacing: "-0.02em",
            color: hospTheme.amber, lineHeight: 1,
          }}>
            {Math.round((totalOcc / totalCap) * 100)}<span style={{ fontSize: 15, color: hospTheme.ink3 }}>%</span>
          </div>
          <div style={{ fontSize: 11, color: hospTheme.ink3, marginTop: 4 }}>{totalOcc} of {totalCap} beds</div>
        </div>
      </div>

      {/* alert strip */}
      <div style={{
        marginTop: 18,
        padding: "10px 14px",
        background: "rgba(211, 90, 74, 0.08)",
        borderRadius: 8,
        display: "flex", alignItems: "center", gap: 12,
        animation: "amber-glow 2.6s ease-in-out infinite",
      }}>
        <span style={{
          width: 8, height: 8, borderRadius: "50%",
          background: hospTheme.red,
          boxShadow: "0 0 8px rgba(211,90,74,0.7)",
          flexShrink: 0,
        }} />
        <div style={{ flex: 1, fontSize: 12.5, color: hospTheme.ink }}>
          <span style={{ color: hospTheme.red, fontWeight: 600 }}>Ward 4 · Cardio</span> <span style={{ color: hospTheme.ink2 }}>is at 91%. Two patients pending discharge — recommend prioritising.</span>
        </div>
        <button onClick={() => setPick("ward4")} style={{
          fontSize: 11, color: hospTheme.ink2,
          padding: "5px 12px",
          background: "rgba(255,255,255,0.05)",
          borderRadius: 5,
        }}>Open ward</button>
      </div>

      {/* ward grid + detail */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 18 }}>
        {/* left: 2 cols × 3 rows of wards */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, alignContent: "start" }}>
          {WARDS.map(w => (
            <WardCard key={w.id} w={w} active={w.id === pickId} onClick={() => setPick(w.id)} />
          ))}
        </div>

        {/* right: detail */}
        <div style={{
          background: hospTheme.card,
          borderRadius: 10,
          padding: "16px 18px",
          alignSelf: "start",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div>
              <div style={{ fontSize: 11, letterSpacing: "0.14em", color: hospTheme.ink3, textTransform: "uppercase" }}>{sel.name}</div>
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 3 }}>
                {Math.round((sel.occ / sel.cap) * 100)}% · {sel.occ}/{sel.cap} beds
              </div>
            </div>
            <div style={{ fontSize: 11, color: hospTheme.ink3, textAlign: "right" }}>
              {sel.doc}<br/>
              {sel.alerts > 0 ? <span style={{ color: hospTheme.amber }}>{sel.alerts} alert{sel.alerts > 1 ? "s" : ""}</span> : "no alerts"}
            </div>
          </div>

          <div style={{ marginTop: 14, fontSize: 10.5, letterSpacing: "0.14em", color: hospTheme.ink3, textTransform: "uppercase" }}>Patients</div>
          <div style={{ marginTop: 6, display: "flex", flexDirection: "column", gap: 6 }}>
            {sel.patients.map((p, i) => (
              <div key={i} style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                <span className="mono" style={{ fontSize: 11.5, color: hospTheme.ink3, minWidth: 44 }}>{p[0]}</span>
                <span style={{
                  fontSize: 10.5, padding: "1px 6px",
                  background: statusColor(p[1]) + "1a",
                  color: statusColor(p[1]),
                  borderRadius: 3, fontWeight: 600,
                  letterSpacing: "0.04em", textTransform: "uppercase",
                  minWidth: 60, textAlign: "center",
                }}>{p[1]}</span>
                <span style={{ flex: 1, fontSize: 12, color: hospTheme.ink2 }}>{p[2]}</span>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 14,
            paddingTop: 12,
            borderTop: "1px solid " + hospTheme.cardLine,
          }}>
            <div style={{ fontSize: 10.5, letterSpacing: "0.14em", color: hospTheme.amber, textTransform: "uppercase", marginBottom: 6 }}>Recommended action</div>
            <div style={{ fontSize: 12.5, color: hospTheme.ink2, lineHeight: 1.5 }}>{sel.action}</div>
            <div style={{ marginTop: 10, display: "flex", gap: 6 }}>
              <button style={{
                fontSize: 11, color: "#0a0a0a", fontWeight: 600,
                background: hospTheme.amber,
                padding: "6px 12px", borderRadius: 5,
              }}>Send to duty manager</button>
              <button style={{
                fontSize: 11, color: hospTheme.ink2,
                background: "rgba(255,255,255,0.05)",
                padding: "6px 12px", borderRadius: 5,
              }}>Mute 1 hr</button>
            </div>
          </div>
        </div>
      </div>

      {/* footer */}
      <div style={{
        marginTop: 18,
        paddingTop: 14,
        borderTop: "1px solid " + hospTheme.cardLine,
        display: "flex", justifyContent: "space-between", fontSize: 11, color: hospTheme.ink3,
      }}>
        <span>Refreshes every 30 seconds from admissions</span>
        <span>3 alerts open · 2 P1 · 1 P2</span>
      </div>
    </div>
  );
}

window.HospitalPreview = HospitalPreview;
