// Login overlay for BControl v0.5

function LoginOverlay({ onLogin }) {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [status, setStatus]     = React.useState(null); // null | 'loading' | 'error' | 'success'
  const [errMsg, setErrMsg]     = React.useState('');

  async function submit(e) {
    e?.preventDefault?.();
    if (!username || !password) {
      setStatus('error'); setErrMsg('Ingrese usuario y contraseña.'); return;
    }
    setStatus('loading'); setErrMsg('');
    try {
      const res = await fetch('/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      });
      if (!res.ok) {
        setStatus('error');
        setErrMsg('Usuario o contraseña incorrectos.');
        return;
      }
      const meRes = await fetch('/auth/me');
      if (!meRes.ok) {
        setStatus('error');
        setErrMsg('Error al obtener sesión.');
        return;
      }
      const user = await meRes.json();
      setStatus('success');
      setTimeout(() => onLogin(user), 350);
    } catch (err) {
      setStatus('error');
      setErrMsg('Error de conexión con el servidor.');
    }
  }

  return (
    <div style={{ position:'fixed', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(135deg,#0F1524 0%, #142036 50%, #0A0E1A 100%)', zIndex:9999 }}>
      <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(circle at 20% 30%, rgba(34,144,206,.18) 0%, transparent 40%), radial-gradient(circle at 80% 70%, rgba(220,38,38,.10) 0%, transparent 40%)', pointerEvents:'none' }}/>
      <div style={{ position:'absolute', inset:0, backgroundImage:'linear-gradient(rgba(255,255,255,.03) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.03) 1px, transparent 1px)', backgroundSize:'40px 40px', pointerEvents:'none' }}/>

      <div className="bc-slide-up" style={{ width:420, background:BC.surface, borderRadius:12, padding:0, boxShadow:'0 30px 80px rgba(0,0,0,.5), 0 8px 24px rgba(0,0,0,.3)', overflow:'hidden', position:'relative', zIndex:1 }}>
        {/* Brand strip */}
        <div style={{ background:BC.brand, padding:'22px 28px 18px', color:'#fff', display:'flex', alignItems:'center', gap:14 }}>
          <img src="/frontend/logo.png" alt="BControl" style={{ height:44, objectFit:'contain' }}/>
          <div style={{ fontSize:11, color:'rgba(255,255,255,.8)', fontFamily:BC.mono, letterSpacing:'.04em' }}>{APP_TITLE} · {APP_VERSION}</div>
        </div>

        <form onSubmit={submit} style={{ padding:'24px 28px 26px' }}>
          <div style={{ fontSize:13, color:BC.inkMuted, marginBottom:18 }}>
            Ingrese sus credenciales para acceder al monitor de eventos.
          </div>

          <label style={{ display:'block', fontSize:11, fontWeight:600, color:BC.inkSubtle, letterSpacing:'.06em', textTransform:'uppercase', marginBottom:6 }}>Usuario</label>
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 12px', border:'1px solid '+BC.border, borderRadius:6, background:BC.surfaceAlt, marginBottom:14 }}>
            <Icon name="user" size={15} color={BC.inkFaint}/>
            <input className="bc-input" autoFocus value={username} onChange={e => setUsername(e.target.value)} placeholder="usuario"
              style={{ flex:1, border:'none', background:'transparent', fontSize:14, color:BC.ink }}/>
          </div>

          <label style={{ display:'block', fontSize:11, fontWeight:600, color:BC.inkSubtle, letterSpacing:'.06em', textTransform:'uppercase', marginBottom:6 }}>Contraseña</label>
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 12px', border:'1px solid '+BC.border, borderRadius:6, background:BC.surfaceAlt, marginBottom:14 }}>
            <Icon name="power" size={15} color={BC.inkFaint}/>
            <input className="bc-input" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••"
              style={{ flex:1, border:'none', background:'transparent', fontSize:14, color:BC.ink }}/>
          </div>

          {status === 'error' && (
            <div style={{ padding:'8px 12px', background:BC.fire.bg, color:BC.fire.fg, border:'1px solid '+BC.fire.bar, borderRadius:6, fontSize:12, marginBottom:12, display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="warning" size={14}/> {errMsg}
            </div>
          )}
          {status === 'success' && (
            <div style={{ padding:'8px 12px', background:BC.ok.bg, color:BC.ok.fg, border:'1px solid '+BC.ok.bar, borderRadius:6, fontSize:12, marginBottom:12, display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="check" size={14}/> Conexión exitosa
            </div>
          )}

          <button type="submit" disabled={status==='loading'} className="bc-btn" style={{ width:'100%', padding:'11px 14px', background:BC.brand, color:'#fff', border:'none', borderRadius:6, fontSize:14, fontWeight:600, display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
            {status==='loading' && <Icon name="refresh" size={14} style={{ animation:'bc-spin .7s linear infinite' }}/>}
            {status==='loading' ? 'Accediendo…' : 'Acceder'}
          </button>
        </form>

        <div style={{ padding:'10px 28px', borderTop:'1px solid '+BC.divider, background:BC.surfaceAlt, fontSize:10, color:BC.inkFaint, fontFamily:BC.mono, letterSpacing:'.04em', display:'flex', justifyContent:'space-between' }}>
          <span>CARLOS INCENDIO SPA</span>
          <span>SANTIAGO · CHILE · 2026</span>
        </div>
      </div>
    </div>
  );
}

window.LoginOverlay = LoginOverlay;
