// ── Oasis HMS · New Alert modal + success toast ─────────────────────────────
const Om = window.OASIS;
const useOutsideClose = window.useOutsideClose;

function Field({ label, required, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <label style={{ fontFamily: Om.font, fontWeight: 500, fontSize: 16, color: Om.navy }}>
        {label} {required && <span style={{ color: Om.navy }}>*</span>}
      </label>
      {children}
    </div>
  );
}

const inputStyle = {
  width: "100%", height: 56, padding: "0 18px", borderRadius: 12, boxSizing: "border-box",
  border: "1px solid #E2EAF4", background: "#fff", outline: "none",
  fontFamily: Om.font, fontSize: 15, color: Om.navy,
};

function NewAlertModal({ open, editing, onClose, onSubmit }) {
  const [title, setTitle] = useState("");
  const [loc, setLoc] = useState("");
  const [floor, setFloor] = useState("");
  const [floorOpen, setFloorOpen] = useState(false);
  const floorRef = React.useRef(null);
  useOutsideClose(floorRef, floorOpen, () => setFloorOpen(false));
  const [dept, setDept] = useState(null);
  const [priority, setPriority] = useState("low");
  const [notes, setNotes] = useState("");

  React.useEffect(() => {
    if (open) {
      setTitle(editing ? editing.title : "");
      setLoc(editing ? editing.where : "");
      setFloor("");
      setFloorOpen(false);
      setDept(editing ? editing.dept : null);
      setPriority(editing ? editing.priority : "low");
      setNotes("");
    }
  }, [open, editing]);

  if (!open) return null;
  const depts = Object.keys(window.DEPARTMENTS);
  const prios = [["low", Om.primary, "Low"], ["medium", "#E79A1A", "Medium"], ["high", Om.red, "High"]];
  const valid = title.trim() && loc.trim() && dept;

  const submit = () => {
    if (!valid) return;
    onSubmit({
      id: editing ? editing.id : "n" + Date.now(),
      title: title.trim(), where: loc.trim(), time: "now", dept,
      priority, color: priority === "medium" ? "#DB9318" : priority === "high" ? "#DE4343" : "#DE4343",
    }, !!editing);
  };

  return (
    <div onMouseDown={onClose} style={{
      position: "absolute", inset: 0, background: "rgba(31,42,68,.32)", backdropFilter: "blur(2px)",
      display: "flex", alignItems: "center", justifyContent: "center", zIndex: 60, animation: "oasisFade .2s ease",
    }}>
      <div onMouseDown={(e) => e.stopPropagation()} style={{
        width: 760, maxHeight: "86%", background: "#fff", borderRadius: 24, boxShadow: "0 40px 90px rgba(31,42,68,.3)",
        display: "flex", flexDirection: "column", overflow: "hidden", animation: "oasisPop .22s cubic-bezier(.2,.8,.3,1.1)",
      }}>
        <div style={{ padding: "32px 40px 0", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontFamily: Om.font, fontWeight: 500, fontSize: 24, color: Om.navy }}>{editing ? "Edit Alert" : "New Alert"}</div>
            <div style={{ fontFamily: Om.font, fontSize: 15, color: "#AEB6C4", marginTop: 8 }}>Create new alert and assign it to the right department.</div>
          </div>
          <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", padding: 4 }}><Icon name="x" size={22} color={Om.navy} /></button>
        </div>

        <div className="oasis-scroll" style={{ flex: 1, overflowY: "auto", padding: "28px 40px", display: "flex", flexDirection: "column", gap: 26 }}>
          <Field label="Alert Title" required>
            <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Describe the issue..." style={inputStyle} />
          </Field>

          <div style={{ display: "flex", gap: 24 }}>
            <div style={{ flex: 1 }}>
              <Field label="Location" required>
                <div style={{ ...inputStyle, display: "flex", alignItems: "center", gap: 12 }}>
                  <Icon name="search" size={18} color="#AEB6C4" />
                  <input value={loc} onChange={(e) => setLoc(e.target.value)} placeholder="Search room, area, etc..." style={{ border: "none", outline: "none", flex: 1, fontFamily: Om.font, fontSize: 15, color: Om.navy, background: "transparent" }} />
                  <Icon name="chevron-down" size={16} color="#AEB6C4" />
                </div>
              </Field>
            </div>
            <div style={{ flex: 1 }}>
              <Field label="Floor">
                <div ref={floorRef} style={{ position: "relative" }}>
                  <button type="button" onClick={() => setFloorOpen((o) => !o)}
                    style={{ ...inputStyle, display: "flex", alignItems: "center", justifyContent: "space-between", cursor: "pointer",
                      borderColor: floorOpen ? Om.primary : "#E2EAF4", color: floor ? Om.navy : "#AEB6C4", textAlign: "left" }}>
                    {floor ? `Floor ${floor}` : "Select floor"}
                    <span style={{ display: "inline-flex", transform: floorOpen ? "rotate(180deg)" : "none", transition: "transform .15s ease" }}>
                      <Icon name="chevron-down" size={16} color={floorOpen ? Om.primary : "#AEB6C4"} />
                    </span>
                  </button>
                  {floorOpen && (
                    <div style={{ position: "absolute", top: 64, left: 0, right: 0, background: "#fff", borderRadius: 12,
                      boxShadow: "0 14px 34px rgba(31,42,68,.16)", border: `1px solid ${Om.hairline}`, zIndex: 30, overflow: "hidden", padding: 6 }}>
                      {[1, 2, 3, 4, 5].map((f) => {
                        const sel = String(floor) === String(f);
                        return (
                          <div key={f} onMouseDown={() => { setFloor(f); setFloorOpen(false); }} style={{
                            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                            padding: "11px 12px", borderRadius: 8, cursor: "pointer",
                            fontFamily: Om.font, fontSize: 14.5, fontWeight: sel ? 600 : 400,
                            color: sel ? Om.primary : Om.navy, background: sel ? "#F2F8FF" : "#fff" }}
                            onMouseEnter={(e) => { if (!sel) e.currentTarget.style.background = "#F6FAFF"; }}
                            onMouseLeave={(e) => { e.currentTarget.style.background = sel ? "#F2F8FF" : "#fff"; }}>
                            <span style={{ whiteSpace: "nowrap" }}>Floor {f}</span>
                            {sel && <Icon name="check" size={15} color={Om.primary} />}
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </Field>
            </div>
          </div>

          <Field label="Assign to Department" required>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
              {depts.map((d) => {
                const on = dept === d, meta = window.DEPARTMENTS[d];
                return (
                  <button key={d} onClick={() => setDept(d)} style={{
                    flex: 1, minWidth: 0, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, padding: "12px 4px",
                    border: `1.5px solid ${on ? Om.primary : "#E2EAF4"}`, borderRadius: 12, cursor: "pointer",
                    background: on ? "#F2F8FF" : "#fff", transition: "all .15s ease",
                  }}>
                    <Icon name={meta.icon} size={26} color={on ? Om.primary : "#9DCBF5"} />
                    <span style={{ fontFamily: Om.font, fontSize: 12.5, color: on ? Om.primary : "#9AA3B2", fontWeight: 500 }}>{d}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 4 }}>
              <Icon name="info" size={18} color={Om.primary} />
              <span style={{ fontFamily: Om.font, fontSize: 14.5, color: "#AEB6C4" }}>The assigned department manager will receive a notification.</span>
            </div>
          </Field>

          <Field label="Priority" required>
            <div style={{ display: "flex", gap: 16 }}>
              {prios.map(([k, c, l]) => {
                const on = priority === k;
                return (
                  <button key={k} onClick={() => setPriority(k)} style={{
                    flex: 1, height: 56, display: "flex", alignItems: "center", justifyContent: "center", gap: 12, cursor: "pointer",
                    border: `1.5px solid ${on ? c : "#E2EAF4"}`, borderRadius: 12, background: on ? `${c}0F` : "#fff", transition: "all .15s ease",
                  }}>
                    <span style={{ width: 14, height: 14, borderRadius: "50%", background: c }} />
                    <span style={{ fontFamily: Om.font, fontWeight: 500, fontSize: 16, color: on ? Om.navy : "#9AA3B2" }}>{l}</span>
                  </button>
                );
              })}
            </div>
          </Field>

          <Field label="Notes (Optional)">
            <textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Add additional details..." style={{ ...inputStyle, height: 96, padding: "16px 18px", resize: "none", lineHeight: 1.5 }} />
          </Field>
        </div>

        <div style={{ padding: "20px 40px", borderTop: `1px solid ${Om.hairline}`, display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 18 }}>
          <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", fontFamily: Om.font, fontWeight: 500, fontSize: 16, color: Om.navy, padding: "12px 20px" }}>Cancel</button>
          <PillButton tone="blue" variant="solid" onClick={submit} style={{ opacity: valid ? 1 : .5, pointerEvents: valid ? "auto" : "none" }}>
            <Icon name="send" size={18} color="#fff" /> {editing ? "Save Changes" : "Save and Send Alert"}
          </PillButton>
        </div>
      </div>
    </div>
  );
}

function SuccessToast({ show, message }) {
  if (!show) return null;
  return (
    <div style={{
      position: "absolute", top: 28, left: "50%", transform: "translateX(-50%)", zIndex: 80,
      width: 311, background: "#fff", borderRadius: 20, boxShadow: "0 20px 50px rgba(31,42,68,.22)",
      padding: 20, display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
      animation: "oasisDrop .3s cubic-bezier(.2,.8,.3,1.1)",
    }}>
      <Icon name="check-circle" size={28} color={Om.green} />
      <div style={{ fontFamily: Om.font, fontWeight: 500, fontSize: 16, color: Om.navy }}>Success!</div>
      <div style={{ fontFamily: Om.font, fontWeight: 500, fontSize: 14, color: Om.muted, textAlign: "center", lineHeight: 1.4 }}>{message}</div>
    </div>
  );
}

Object.assign(window, { NewAlertModal, SuccessToast });
