// Reset-password page — rendered when pathname = /reset-password

function ResetPasswordOverlay({ token }) {
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm]   = React.useState('');
  const [status, setStatus]     = React.useState(null); // null | 'loading' | 'error' | 'success'
  const [errMsg, setErrMsg]     = React.useState('');

  async function submit(e) {
    e?.preventDefault?.();
    if (!password || !confirm) { setStatus('error'); setErrMsg('Complete todos los campos.'); return; }
    if (password !== confirm)  { setStatus('error'); setErrMsg('Las contraseñas no coinciden.'); return; }
    if (password.length < 8)   { setStatus('error'); setErrMsg('La contraseña debe tener al menos 8 caracteres.'); return; }

    setStatus('loading'); setErrMsg('');
    try {
      const res = await fetch('/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setStatus('error'); setErrMsg(data.detail || 'Error al restablecer la contraseña.'); return;
      }
      setStatus('success');
      setTimeout(() => { window.location.href = '/'; }, 2200);
    } catch (_) {
      setStatus('error'); setErrMsg('Error de conexión.');
    }
  }

  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:420, 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 }}>Nueva contraseña</div>
        <div style={{ fontSize:11, color:'rgba(255,255,255,.8)', fontFamily:BC.mono, letterSpacing:'.04em' }}>Recuperación de cuenta</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 (!token) {
    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 }}>Este enlace de recuperación no es válido.</div>
            <a href="/" style={{ display:'inline-block', marginTop:18, fontSize:13, color:BC.brand }}>Ir al inicio</a>
          </div>
          {footer}
        </div>
      </div>
    );
  }

  if (status === 'success') {
    return (
      <div style={wrapStyle}>
        <div style={{ ...cardStyle, textAlign:'center' }}>
          {brandStrip}
          <div style={{ padding:'32px 28px 24px' }}>
            <Icon name="check" size={40} color={BC.ok.fg}/>
            <div style={{ fontSize:16, fontWeight:600, marginTop:12, color:BC.ink }}>Contraseña restablecida</div>
            <div style={{ fontSize:13, color:BC.inkMuted, marginTop:8 }}>Todas las sesiones activas fueron cerradas. Redirigiendo al inicio de sesión…</div>
          </div>
          {footer}
        </div>
      </div>
    );
  }

  return (
    <div style={wrapStyle}>
      <div style={bgGlow}/>
      <div className="bc-slide-up" style={cardStyle}>
        {brandStrip}
        <form onSubmit={submit} style={{ padding:'24px 28px 26px' }}>
          <div style={{ fontSize:13, color:BC.inkMuted, marginBottom:18 }}>
            Ingresa tu nueva contraseña. Una vez confirmada, deberás iniciar sesión nuevamente.
          </div>

          <label style={{ display:'block', fontSize:11, fontWeight:600, color:BC.inkSubtle, letterSpacing:'.06em', textTransform:'uppercase', marginBottom:6 }}>Nueva 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" autoFocus type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="mín. 8 caracteres"
              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 }}>Confirmar 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={confirm} onChange={e => setConfirm(e.target.value)} placeholder="repite la contraseña"
              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>
          )}

          <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' ? 'Guardando…' : 'Establecer contraseña'}
          </button>
        </form>
        {footer}
      </div>
    </div>
  );
}

window.ResetPasswordOverlay = ResetPasswordOverlay;
