// screens_auth.jsx — Pantalla de acceso (login) — autenticación contra API real
const { useState: useStateAuth } = React;

function Login({ onLogin }) {
  const [email, setEmail] = useStateAuth("");
  const [pass, setPass] = useStateAuth("");
  const [show, setShow] = useStateAuth(false);
  const [err, setErr] = useStateAuth("");
  const [loading, setLoading] = useStateAuth(false);

  const submit = async (e) => {
    e && e.preventDefault();
    setErr("");
    if (!email.trim() || !pass) { setErr("Ingrese usuario y contraseña."); return; }
    setLoading(true);
    try {
      const res = await fetch(`${window.API_BASE}/api/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim().toLowerCase(), password: pass }),
      });
      const json = await res.json();
      if (!res.ok) {
        setErr(json.error || "Credenciales inválidas. Verifique su usuario y contraseña.");
        setLoading(false);
        return;
      }
      localStorage.setItem("ciecav_token", json.data.token);
      onLogin(window.mapApiUser(json.data.user, json.data.token));
    } catch (ex) {
      setErr("No se pudo conectar con el servidor. Intente nuevamente.");
      setLoading(false);
    }
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1.05fr 1fr", background: "var(--bg)" }} className="g-login-grid">
      {/* Panel de marca */}
      <div className="g-login-brand" style={{ position: "relative", background: "linear-gradient(150deg, #2a1a10 0%, #4a2f1c 45%, #1a3550 100%)", display: "flex", flexDirection: "column", justifyContent: "center", padding: "56px 60px", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 30% 25%, rgba(200,140,90,.28), transparent 55%), radial-gradient(circle at 80% 80%, rgba(60,120,180,.3), transparent 50%)" }} />
        <div style={{ position: "relative", zIndex: 1, maxWidth: 420 }}>
          <div style={{ background: "rgba(255,255,255,.96)", borderRadius: 18, padding: "20px 22px", display: "inline-flex", boxShadow: "0 20px 50px -20px rgba(0,0,0,.6)" }}>
            <img src="assets/ciecav-full.svg" alt="CIECAV" style={{ height: 168, width: "auto", display: "block" }} />
          </div>
          <h1 style={{ color: "#fff", fontSize: 30, fontWeight: 800, letterSpacing: "-.02em", lineHeight: 1.15, margin: "34px 0 0" }}>Historia Clínica<br />Electrónica</h1>
          <p style={{ color: "rgba(255,255,255,.78)", fontSize: 15, lineHeight: 1.6, margin: "14px 0 0" }}>Plataforma integral del Centro Integral de Enfermedades Cardiovasculares. Digitaliza el proceso clínico completo con formularios MSP, firma digital y trazabilidad total.</p>
          <div style={{ display: "flex", gap: 22, marginTop: 30 }}>
            {[["Formularios MSP", "doc"], ["Firma digital", "sign"], ["Auditoría total", "shield"]].map(([t, ic]) => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 8, color: "rgba(255,255,255,.9)", fontSize: 12.5, fontWeight: 600 }}>
                <Icon name={ic} size={16} /> {t}
              </div>
            ))}
          </div>
        </div>
        <div style={{ position: "absolute", bottom: 24, left: 60, color: "rgba(255,255,255,.5)", fontSize: 11.5, zIndex: 1 }}>© 2026 CIECAV · Guayaquil, Ecuador · Sistema conforme a normativa SNS-MSP</div>
      </div>

      {/* Panel de formulario */}
      <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", padding: "40px 56px", overflowY: "auto" }} className="g-login-form">
        <div style={{ width: "100%", maxWidth: 380, margin: "0 auto" }}>
          <div className="g-login-mobilelogo" style={{ display: "none", justifyContent: "center", marginBottom: 24 }}>
            <img src="assets/ciecav-logo.svg" alt="CIECAV" style={{ width: 180, height: "auto" }} />
          </div>
          <h2 style={{ margin: 0, fontSize: 24, fontWeight: 800, letterSpacing: "-.02em", color: "var(--ink)" }}>Iniciar sesión</h2>
          <p style={{ margin: "6px 0 28px", fontSize: 14, color: "var(--ink-3)" }}>Ingrese sus credenciales institucionales para acceder al sistema.</p>

          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Field label="Usuario">
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", display: "flex" }}><Icon name="user" size={17} /></span>
                <input value={email} onChange={(e) => setEmail(e.target.value)} type="text" placeholder="usuario o correo" autoFocus autoComplete="username"
                  className="g-input" style={{ ...window.inputStyle, paddingLeft: 38, paddingTop: 11, paddingBottom: 11 }} />
              </div>
            </Field>
            <Field label="Contraseña">
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", display: "flex" }}><Icon name="shield" size={17} /></span>
                <input value={pass} onChange={(e) => setPass(e.target.value)} type={show ? "text" : "password"} placeholder="••••••••" autoComplete="current-password"
                  className="g-input" style={{ ...window.inputStyle, paddingLeft: 38, paddingRight: 64, paddingTop: 11, paddingBottom: 11 }} />
                <button type="button" onClick={() => setShow(!show)} style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", border: "none", background: "transparent", color: "var(--accent-ink)", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "inherit" }}>{show ? "Ocultar" : "Ver"}</button>
              </div>
            </Field>

            {err && (
              <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 13px", borderRadius: 10, background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13, fontWeight: 600 }}>
                <Icon name="alert" size={16} /> {err}
              </div>
            )}

            <Btn type="submit" size="lg" disabled={loading} style={{ marginTop: 4, width: "100%", padding: "13px" }}>
              {loading
                ? <><span className="g-spin" style={{ width: 16, height: 16, border: "2px solid rgba(255,255,255,.4)", borderTopColor: "#fff", borderRadius: 99, display: "inline-block", marginRight: 8 }} /> Verificando…</>
                : <><Icon name="logout" size={18} style={{ transform: "scaleX(-1)" }} /> Ingresar</>}
            </Btn>
          </form>

          <div style={{ marginTop: 28, paddingTop: 20, borderTop: "1px solid var(--line)", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.6, textAlign: "center" }}>
            <Icon name="shield" size={13} style={{ verticalAlign: "middle", marginRight: 5 }} />
            Acceso restringido a personal autorizado de CIECAV.<br />Las credenciales son administradas por el área de sistemas.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
