// Accept-invite page — rendered when pathname = /accept-invite

function InviteOverlay({ token, onLogin }) {
  const [inviteInfo, setInviteInfo] = React.useState(null);
  const [tokenError, setTokenError] = React.useState(null);
  const [status, setStatus]         = React.useState(null); // null | 'loading' | 'error' | 'success'
  const [errMsg, setErrMsg]         = React.useState('');

  // Email/password Firebase form state
  const [emailPw, setEmailPw]       = React.useState('');
  const [confirmPw, setConfirmPw]   = React.useState('');
  const [showPwForm, setShowPwForm] = React.useState(false);

  React.useEffect(() => {
    if (!token) { setTokenError('Enlace inválido.'); return; }
    fetch(`/auth/invite-info?token=${encodeURIComponent(token)}`)
      .then(r => r.ok ? r.json() : r.json().then(e => Promise.reject(e.detail || 'Enlace inválido o expirado.')))
      .then(info => setInviteInfo(info))
      .catch(e => setTokenError(typeof e === 'string' ? e : 'Enlace inválido o expirado.'));
  }, [token]);

  async function _finishLogin(idToken) {
    const res = await fetch('/auth/firebase-login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id_token: idToken, invite_token: token }),
    });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      throw new Error(data.detail || 'Error al crear la cuenta.');
    }
    const meRes = await fetch('/auth/me');
    if (!meRes.ok) throw new Error('Cuenta creada pero error al obtener sesión.');
    return await meRes.json();
  }

  async function signInWithGoogle() {
    setStatus('loading'); setErrMsg('');
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      provider.setCustomParameters({ login_hint: inviteInfo.email });
      const result = await window.fbAuth.signInWithPopup(provider);
      const idToken = await result.user.getIdToken();
      const user = await _finishLogin(idToken);
      setStatus('success');
      try { await result.user.updateProfile({ displayName: user.username }); } catch (_) {}
      setTimeout(() => { window.history.replaceState({}, '', '/'); onLogin(user); }, 600);
    } catch (err) {
      setStatus('error'); setErrMsg(err.message || 'Error al iniciar sesión.');
    }
  }

  async function signInWithEmail(e) {
    e?.preventDefault?.();
    if (!emailPw || !confirmPw) { setStatus('error'); setErrMsg('Complete todos los campos.'); return; }
    if (emailPw !== confirmPw)  { setStatus('error'); setErrMsg('Las contraseñas no coinciden.'); return; }
    if (emailPw.length < 6)     { setStatus('error'); setErrMsg('Mín. 6 caracteres.'); return; }

    setStatus('loading'); setErrMsg('');
    try {
      // Try create account, fall back to sign in if already exists
      let result;
      try {
        result = await window.fbAuth.createUserWithEmailAndPassword(inviteInfo.email, emailPw);
      } catch (createErr) {
        if (createErr.code === 'auth/email-already-in-use') {
          result = await window.fbAuth.signInWithEmailAndPassword(inviteInfo.email, emailPw);
        } else {
          throw createErr;
        }
      }
      const idToken = await result.user.getIdToken();
      const user = await _finishLogin(idToken);
      setStatus('success');
      try { await result.user.updateProfile({ displayName: user.username }); } catch (_) {}
      setTimeout(() => { window.history.replaceState({}, '', '/'); onLogin(user); }, 600);
    } catch (err) {
      setStatus('error');
      const msg = err.code === 'auth/wrong-password' ? 'Contraseña incorrecta para ese correo en Firebase.'
                : err.code === 'auth/weak-password'  ? 'Contraseña muy débil (mín. 6 caracteres).'
                : err.message || 'Error al crear cuenta.';
      setErrMsg(msg);
    }
  }

  const wrapStyle = { position:'fixed', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(135deg,#0F1524 0%, #142036 50%, #0A0E1A 100%)', zIndex:9999 };
  const cardStyle = { width:440, background:BC.surface, borderRadius:12, boxShadow:'0 30px 80px rgba(0,0,0,.5)', overflow:'hidden', position:'relative', zIndex:1 };
  const bgGlow    = { position:'absolute', inset:0, backgroundImage:'radial-gradient(circle at 20% 30%, rgba(34,144,206,.18) 0%, transparent 40%)', pointerEvents:'none' };

  const brandStrip = (
    <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>
        <div style={{ fontWeight:600, fontSize:15 }}>Crear cuenta</div>
        <div style={{ fontSize:11, color:'rgba(255,255,255,.8)', fontFamily:BC.mono, letterSpacing:'.04em' }}>Invitación de BControl</div>
      </div>
    </div>
  );

  const footer = (
    <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>
  );

  if (tokenError) {
    return (
      <div style={wrapStyle}>
        <div style={{ ...cardStyle, textAlign:'center' }}>
          {brandStrip}
          <div style={{ padding:'32px 28px 24px' }}>
            <Icon name="warning" size={36} color={BC.fire.fg}/>
            <div style={{ fontSize:16, fontWeight:600, marginTop:12, color:BC.ink }}>Enlace inválido</div>
            <div style={{ fontSize:13, color:BC.inkMuted, marginTop:8 }}>{tokenError}</div>
            <div style={{ fontSize:12, color:BC.inkSubtle, marginTop:6 }}>Contacte al administrador para solicitar una nueva invitación.</div>
            <a href="/" style={{ display:'inline-block', marginTop:18, fontSize:13, color:BC.brand }}>Ir al inicio</a>
          </div>
          {footer}
        </div>
      </div>
    );
  }

  if (!inviteInfo) {
    return (
      <div style={wrapStyle}>
        <Icon name="refresh" size={24} color={BC.brand} style={{ animation:'bc-spin .7s linear infinite' }}/>
      </div>
    );
  }

  return (
    <div style={wrapStyle}>
      <div style={bgGlow}/>
      <div className="bc-slide-up" style={cardStyle}>
        {brandStrip}
        <div style={{ padding:'24px 28px 26px' }}>

          {/* Invite info banner */}
          <div style={{ padding:'10px 14px', background:BC.brandTint, border:'1px solid #B3D9F0', borderRadius:6, fontSize:12, color:BC.brandDeep, marginBottom:20, display:'flex', alignItems:'center', gap:8 }}>
            <Icon name="user" size={14} color={BC.brand}/>
            Invitado como <strong style={{ marginLeft:3 }}>{inviteInfo.role}</strong>&nbsp;·&nbsp;{inviteInfo.email}
          </div>

          {/* Google sign-in */}
          <button type="button" onClick={signInWithGoogle} disabled={status==='loading' || status==='success'} 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:12, boxShadow:'0 1px 3px rgba(0,0,0,.08)' }}>
            <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>
            Continuar con Google
          </button>

          {/* Divider */}
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12, color:BC.inkFaint, fontSize:11 }}>
            <div style={{ flex:1, height:1, background:BC.border }}/>
            <span>o con correo y contraseña</span>
            <div style={{ flex:1, height:1, background:BC.border }}/>
          </div>

          {/* Email/password Firebase form */}
          {!showPwForm ? (
            <button type="button" onClick={() => setShowPwForm(true)} className="bc-btn"
              style={{ width:'100%', padding:'10px 14px', background:BC.surfaceAlt, color:BC.inkMuted, border:'1px solid '+BC.border, borderRadius:6, fontSize:13 }}>
              Usar correo y contraseña
            </button>
          ) : (
            <form onSubmit={signInWithEmail}>
              <div style={{ padding:'8px 12px', background:BC.surfaceAlt, border:'1px solid '+BC.border, borderRadius:5, fontSize:12, color:BC.inkSubtle, marginBottom:10 }}>
                {inviteInfo.email}
              </div>
              <input type="password" value={emailPw} onChange={e => setEmailPw(e.target.value)} placeholder="Contraseña (mín. 6 caracteres)"
                style={{ width:'100%', padding:'9px 12px', border:'1px solid '+BC.border, borderRadius:5, background:BC.surfaceAlt, fontSize:13, color:BC.ink, marginBottom:8 }}/>
              <input type="password" value={confirmPw} onChange={e => setConfirmPw(e.target.value)} placeholder="Confirmar contraseña"
                style={{ width:'100%', padding:'9px 12px', border:'1px solid '+BC.border, borderRadius:5, background:BC.surfaceAlt, fontSize:13, color:BC.ink, marginBottom:10 }}/>
              <button type="submit" disabled={status==='loading' || status==='success'} className="bc-btn"
                style={{ width:'100%', padding:'10px', background:BC.brand, color:'#fff', border:'none', borderRadius:5, fontSize:13, fontWeight:600 }}>
                {status==='loading' ? 'Creando cuenta…' : 'Crear cuenta'}
              </button>
            </form>
          )}

          {/* Status messages */}
          {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, marginTop: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, marginTop:12, display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="check" size={14}/> Cuenta creada. Iniciando sesión…
            </div>
          )}
          {status === 'loading' && (
            <div style={{ textAlign:'center', marginTop:12, color:BC.inkFaint, fontSize:12, display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
              <Icon name="refresh" size={14} style={{ animation:'bc-spin .7s linear infinite' }}/> Verificando…
            </div>
          )}
        </div>
        {footer}
      </div>
    </div>
  );
}

window.InviteOverlay = InviteOverlay;
