// ─── Login screen ────────────────────────────────────────────────────────────

function LoginPage({ onLogin }) {
  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError]       = React.useState('');
  const [loading, setLoading]   = React.useState(false);
  const wordmarkRef = React.useRef(null);

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${API_BASE}/api/auth/login`, {
        method:      'POST',
        credentials: 'include',
        headers:     { 'Content-Type': 'application/json' },
        body:        JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Error al iniciar sesión'); return; }
      const fromRect = wordmarkRef.current?.getBoundingClientRect() ?? null;
      onLogin(data.user, fromRect);
    } catch {
      setError('No se pudo conectar con el servidor.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-canvas flex items-center justify-center">
      <div className="w-full max-w-sm">
        <div className="text-center mb-10">
          <div ref={wordmarkRef} className="inline-block font-serif text-[40px] text-ink leading-none">
            {'LANVEN'.split('').map((ch, i) => (
              <span key={i} className="lv-letter" style={{ animationDelay: `${i * 0.085}s` }}>{ch}</span>
            ))}
          </div>
          <div className="lv-rule w-[54px] mx-auto my-3 h-px bg-ink" style={{ opacity: 0.5 }} />
          <p className="lv-fadein text-[12px] text-slate-400 tracking-widest uppercase" style={{ animationDelay: '0.85s' }}>
            Sistema de gestión interna
          </p>
        </div>
        <div className="lv-fadein bg-white border border-slate-100 rounded-xl shadow-card p-8" style={{ animationDelay: '1.0s' }}>
          <h2 className="font-serif text-[22px] text-ink mb-6">Iniciar sesión</h2>
          {error && <div className="mb-4 text-[13px] text-bad bg-red-50 border border-red-100 rounded-lg px-4 py-3">{error}</div>}
          <div className="space-y-4">
            <div>
              <label className="block text-[12px] text-slate-500 mb-1">Email</label>
              <input
                type="email" value={email} onChange={e => setEmail(e.target.value)}
                className="w-full border border-slate-200 rounded-lg px-3 py-2 text-[14px] focus:outline-none focus:border-gold"
                placeholder="tu@lanven.com"
              />
            </div>
            <div>
              <label className="block text-[12px] text-slate-500 mb-1">Contraseña</label>
              <input
                type="password" value={password} onChange={e => setPassword(e.target.value)}
                className="w-full border border-slate-200 rounded-lg px-3 py-2 text-[14px] focus:outline-none focus:border-gold"
                placeholder="••••••••"
              />
            </div>
            <button
              onClick={handleSubmit}
              disabled={loading}
              className="w-full bg-ink text-canvas rounded-lg py-2.5 text-[14px] font-medium hover:bg-slate-800 transition-colors mt-2"
            >
              {loading ? 'Ingresando...' : 'Ingresar'}
            </button>
          </div>
        </div>
        <p className="lv-fadein text-center text-[11px] text-slate-400 mt-6" style={{ animationDelay: '1.25s' }}>by NODEXIS · Lanven v0.2</p>
      </div>
    </div>
  );
}