/* twofa.jsx — flujo de configuración de 2FA (reutilizable: pantalla obligatoria y modal de settings) */

/* Pasos de configuración (elegir método → verificar). Sin chrome de página. */
function TwoFAConfig({ onDone, onCancel }) {
  var [method,  setMethod]  = React.useState(null);   // 'email' | 'totp'
  var [step,    setStep]    = React.useState('choose');
  var [totp,    setTotp]    = React.useState(null);   // { secret, qr, otpauthUri }
  var [code,    setCode]    = React.useState('');
  var [loading, setLoading] = React.useState(false);
  var [error,   setError]   = React.useState('');
  var [emailTo, setEmailTo] = React.useState('');
  var toast = useToast();

  function choose(m) {
    setMethod(m); setError(''); setLoading(true);
    API.twofaSetup(m).then(function(d) {
      if (m === 'totp') { setTotp({ secret: d.secret, qr: d.qr, otpauthUri: d.otpauthUri }); }
      else { setEmailTo(d.email || ''); }
      setStep('verify');
    }).catch(function(e) { setError(e.message || 'No se pudo iniciar la configuración'); setMethod(null); })
     .finally(function() { setLoading(false); });
  }

  function activate() {
    if (!code) { setError('Ingresa el código'); return; }
    setLoading(true); setError('');
    API.twofaActivate(method, code).then(function() {
      toast({ title: 'Verificación en dos pasos activada' });
      onDone();
    }).catch(function(e) { setError(e.message || 'Código incorrecto'); })
     .finally(function() { setLoading(false); });
  }

  if (step === 'choose') {
    return (
      <div className="space-y-3">
        <button disabled={loading} onClick={function() { choose('totp'); }}
          className="w-full text-left flex items-center gap-3.5 p-4 rounded-[var(--radius)] border border-input hover:border-primary hover:bg-primary-soft/40 transition-colors disabled:opacity-50">
          <div className="grid place-items-center h-10 w-10 rounded-[var(--radius)] bg-primary text-primary-foreground shrink-0"><Icon name="shield" size={18} /></div>
          <div><div className="font-bold text-[14px]">App autenticadora <span className="text-primary text-[11px] font-bold">RECOMENDADO</span></div><div className="text-[12.5px] text-muted-foreground">Google Authenticator, Authy, etc. Funciona sin internet.</div></div>
        </button>
        <button disabled={loading} onClick={function() { choose('email'); }}
          className="w-full text-left flex items-center gap-3.5 p-4 rounded-[var(--radius)] border border-input hover:border-primary hover:bg-primary-soft/40 transition-colors disabled:opacity-50">
          <div className="grid place-items-center h-10 w-10 rounded-[var(--radius)] bg-muted text-muted-foreground shrink-0"><Icon name="building" size={18} /></div>
          <div><div className="font-bold text-[14px]">Código por correo</div><div className="text-[12.5px] text-muted-foreground">Te enviamos un código a tu email en cada inicio de sesión.</div></div>
        </button>
        {error && <div className="text-[12.5px] text-danger">{error}</div>}
        {loading && <div className="text-[12.5px] text-muted-foreground flex items-center gap-2"><Icon name="refresh" size={14} className="spin" />Preparando…</div>}
        {onCancel && <button onClick={onCancel} className="text-[13px] text-muted-foreground hover:text-foreground mx-auto block pt-1">Cancelar</button>}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {method === 'totp' && totp && (
        <div className="text-center">
          <p className="text-[13px] text-muted-foreground mb-3">Escanea este código con tu app autenticadora:</p>
          {totp.qr && <img src={totp.qr} alt="QR 2FA" className="mx-auto rounded-[var(--radius)] border border-border" width="180" height="180" />}
          <div className="mt-3 text-[11.5px] text-muted-foreground">¿No puedes escanear? Ingresa esta clave:</div>
          <code className="block font-mono text-[12.5px] bg-muted rounded-[var(--radius)] px-3 py-2 mt-1 tracking-wider break-all">{totp.secret}</code>
        </div>
      )}
      {method === 'email' && (
        <p className="text-[13px] text-muted-foreground">Enviamos un código a <strong className="text-foreground">{emailTo}</strong>. Ingrésalo abajo.</p>
      )}
      <Field label="Código de 6 dígitos" error={error || null}>
        <Input icon="shield" inputMode="numeric" maxLength={6} placeholder="000000" value={code}
          error={!!error}
          onChange={function(e) { setCode(e.target.value.replace(/\D/g, '')); setError(''); }}
          onKeyDown={function(e) { if (e.key === 'Enter') activate(); }} />
      </Field>
      <Button className="w-full" size="lg" loading={loading} onClick={activate}>{loading ? 'Activando…' : 'Activar 2FA'}</Button>
      <button onClick={function() { setStep('choose'); setMethod(null); setCode(''); setError(''); }} className="text-[13px] text-muted-foreground hover:text-foreground mx-auto block">← Elegir otro método</button>
    </div>
  );
}

/* Pantalla obligatoria a pantalla completa (post-registro). */
function TwoFASetup({ onDone }) {
  return (
    <div className="min-h-screen grid place-items-center bg-background p-4">
      <Card className="p-7 max-w-md w-full anim-in">
        <div className="grid place-items-center h-12 w-12 rounded-[var(--radius)] bg-primary-soft text-primary mb-4"><Icon name="shield" size={24} /></div>
        <h1 className="text-[22px] font-extrabold tracking-tight">Protege tu cuenta</h1>
        <p className="text-[13.5px] text-muted-foreground mt-1 mb-5">Configura la verificación en dos pasos (2FA). Es obligatoria para emitir comprobantes.</p>
        <TwoFAConfig onDone={onDone} />
      </Card>
    </div>
  );
}

/* Modal de configuración de 2FA (desde Configuración / settings). */
function TwoFAModal({ onClose, onDone }) {
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 backdrop-blur-sm p-4" onClick={onClose}>
      <Card className="p-6 max-w-md w-full anim-in" onClick={function(e) { e.stopPropagation(); }}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-[18px] font-extrabold">Verificación en dos pasos</h3>
          <button onClick={onClose} className="grid place-items-center h-8 w-8 rounded-md hover:bg-accent"><Icon name="x" size={18} /></button>
        </div>
        <TwoFAConfig onDone={onDone} onCancel={onClose} />
      </Card>
    </div>,
    document.body
  );
}

Object.assign(window, { TwoFASetup, TwoFAConfig, TwoFAModal });
