// Login overlay for BControl v0.5

function LoginOverlay({ onLogin, successBanner }) {
  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('');

  const [fbStatus, setFbStatus] = React.useState(null); // null | 'loading' | 'error'
  const [fbErr, setFbErr]       = React.useState('');

  async function signInWithGoogle() {
    setFbStatus('loading'); setFbErr('');
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      const result = await window.fbAuth.signInWithPopup(provider);
      const idToken = await result.user.getIdToken();
      const res = await fetch('/auth/firebase-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id_token: idToken }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setFbStatus('error'); setFbErr(data.detail || 'Acceso denegado.'); return;
      }
      const meRes = await fetch('/auth/me');
      const user = await meRes.json();
      setFbStatus(null);
      onLogin(user);
    } catch (err) {
      setFbStatus('error'); setFbErr(err.message || 'Error al iniciar sesión con Google.');
    }
  }

  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' }}>

          {/* Firebase sign-in */}
          <button type="button" onClick={signInWithGoogle} disabled={fbStatus==='loading'} className="bc-btn"
            style={{ width:'100%', padding:'10px 14px', background:'#fff', color:'#3c4043', border:'1px solid #dadce0', borderRadius:6, fontSize:14, fontWeight:500, display:'flex', alignItems:'center', justifyContent:'center', gap:10, marginBottom:10, boxShadow:'0 1px 3px rgba(0,0,0,.08)' }}>
            {fbStatus==='loading'
              ? <Icon name="refresh" size={16} style={{ animation:'bc-spin .7s linear infinite' }}/>
              : <svg width="18" height="18" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.31-8.16 2.31-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/><path fill="none" d="M0 0h48v48H0z"/></svg>
            }
            {fbStatus==='loading' ? 'Iniciando sesión…' : 'Continuar con Google'}
          </button>

          {fbStatus === '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:10, display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="warning" size={13}/> {fbErr}
            </div>
          )}

          <div style={{ display:'flex', alignItems:'center', gap:10, margin:'14px 0', color:BC.inkFaint, fontSize:11 }}>
            <div style={{ flex:1, height:1, background:BC.border }}/>
            <span>o con usuario y contraseña</span>
            <div style={{ flex:1, height:1, background:BC.border }}/>
          </div>

          <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>

        {successBanner && (
          <div style={{ margin:'0 28px 12px', padding:'8px 12px', background:BC.ok.bg, color:BC.ok.fg, border:'1px solid '+BC.ok.bar, borderRadius:6, fontSize:12, display:'flex', alignItems:'center', gap:8 }}>
            <Icon name="check" size={13}/> {successBanner}
          </div>
        )}

        <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;
