// Login — split panel: oscuro brand izquierda + formulario derecha.
const { useState } = React;

function LoginScreen({ onEnter }) {
  const [email, setEmail]     = useState("");
  const [pass, setPass]       = useState("");
  const [show, setShow]       = useState(false);
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError]     = useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const { user } = await API.Auth.login(email, pass, remember);
      onEnter(user);
    } catch (err) {
      setError(err.message || "Credenciales incorrectas. Intente de nuevo.");
    } finally {
      setLoading(false);
    }
  };

  const today = new Date().toLocaleDateString("es-MX", { day: "2-digit", month: "long", year: "numeric" });

  return (
    <div className="login-shell" data-screen-label="01 Login">
      {/* === Panel brand === */}
      <aside className="login-brand">
        <div className="lb-top">
          <div className="lb-mark">B</div>
          <div>
            <div className="lb-name">Biblioteca</div>
            <div className="lb-tag">Acervo digital corporativo</div>
          </div>
        </div>

        <div className="lb-center">
          <div className="lb-eyebrow">Acceso institucional</div>
          <h1 className="headline">
            El conocimiento<br/>
            de la empresa,<br/>
            <em>en un solo lugar.</em>
          </h1>
          <p className="lb-deck">
            Galería, documentos y archivo histórico — organizados, buscables y disponibles para cada colaborador.
          </p>

          <div className="lb-stats">
            <div className="lb-stat">
              <div className="n">7,461</div>
              <div className="l">Archivos vivos</div>
            </div>
            <div className="lb-stat">
              <div className="n">38</div>
              <div className="l">Áreas conectadas</div>
            </div>
            <div className="lb-stat">
              <div className="n">99.98<span style={{fontSize: 16}}>%</span></div>
              <div className="l">Disponibilidad</div>
            </div>
          </div>
        </div>

        <div className="lb-foot">
          <span>{today}</span>
          <span>v 4.2 · MX</span>
        </div>
      </aside>

      {/* === Formulario === */}
      <main className="login-form-wrap">
        <form className="login-form" onSubmit={submit}>
          <div className="eyebrow">Iniciar sesión</div>
          <h2>Bienvenida<br/>de regreso.</h2>
          <p className="subtitle lf-sub">Ingrese con sus credenciales corporativas.</p>

          {error && (
            <div style={{
              background: "#FEF2F2", border: "1px solid #FECACA",
              color: "#B91C1C", borderRadius: 6, padding: "10px 14px",
              fontSize: 13, marginBottom: 16,
            }}>
              {error}
            </div>
          )}

          <div className="field">
            <label htmlFor="email">Correo institucional</label>
            <div className="input">
              <Icon name="mail" size={16} stroke={1.6} style={{color: "var(--muted)"}}/>
              <input
                id="email" type="email"
                value={email} onChange={(e)=>setEmail(e.target.value)}
                autoComplete="email"
                placeholder="nombre@empresa.com"
                required
              />
            </div>
          </div>

          <div className="field">
            <label htmlFor="pass">Contraseña</label>
            <div className="input">
              <Icon name="lock" size={16} stroke={1.6} style={{color: "var(--muted)"}}/>
              <input
                id="pass" type={show ? "text" : "password"}
                value={pass} onChange={(e)=>setPass(e.target.value)}
                autoComplete="current-password"
                required
              />
              <button type="button" className="peek" onClick={()=>setShow(!show)} aria-label="Mostrar/Ocultar">
                <Icon name={show ? "eyeOff" : "eye"} size={16}/>
              </button>
            </div>
          </div>

          <div className="checkrow">
            <label>
              <input type="checkbox" checked={remember} onChange={(e)=>setRemember(e.target.checked)}/>
              Mantener sesión iniciada
            </label>
            <a href="#" onClick={(e)=>e.preventDefault()}>¿Olvidó su contraseña?</a>
          </div>

          <button type="submit" className="btn-primary" disabled={loading}>
            {loading ? "Verificando…" : "Ingresar"}
            <Icon name="arrowRight" size={16} className="arr"/>
          </button>

          <div className="or-row">o continúe con</div>

          <button type="button" className="sso" onClick={() => alert("SSO corporativo no disponible en este entorno. Contacta a TI.")}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M3 3h8v8H3z" fill="#00B147"/>
              <path d="M13 3h8v8h-8z" fill="#1B1A1A"/>
              <path d="M3 13h8v8H3z" fill="#1B1A1A"/>
              <path d="M13 13h8v8h-8z" fill="#7A6E55"/>
            </svg>
            Single Sign-On corporativo
          </button>

          <p className="footnote">
            ¿No tiene cuenta? Solicite acceso a su <a href="#" onClick={(e)=>e.preventDefault()} style={{color: "var(--ink)", fontWeight: 600}}>administrador de área</a>.
          </p>
        </form>
      </main>
    </div>
  );
}

window.LoginScreen = LoginScreen;
