// CronoDato — Auth screens (Login + Registro)

const PLANES = [
  {
    id: 'pack_inicial',
    nombre: 'Pack Inicial',
    facturas: 50,
    precio: 5000,
    costo: 100,
    promo: false,
    desc: 'Ideal para empezar',
  },
  {
    id: 'pack_estandar',
    nombre: 'Pack Estándar',
    facturas: 200,
    precio: 16000,
    costo: 80,
    promo: false,
    desc: 'El más elegido',
    destacado: true,
  },
  {
    id: 'pack_profesional',
    nombre: 'Pack Profesional',
    facturas: 100,
    precio: 9000,
    costoOriginal: 35000,
    facturasOriginal: 500,
    costo: 90,
    promo: true,
    desc: 'Promo por tiempo limitado',
  },
];

const GoogleIcon = () => (
  <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
    <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
    <path d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z" fill="#34A853"/>
    <path d="M3.964 10.707A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.707V4.961H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.039l3.007-2.332z" fill="#FBBC05"/>
    <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.96L3.964 7.293C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
  </svg>
);

// ── ReCaptcha simulado (placeholder visual) ──────────────────
const RecaptchaBox = ({ checked, onCheck }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12,
    border: '1px solid #E2E8F0', borderRadius: 6, padding: '12px 16px',
    background: '#F8FAFC', cursor: 'pointer', userSelect: 'none',
  }} onClick={onCheck}>
    <div style={{
      width: 22, height: 22, borderRadius: 4, border: `2px solid ${checked ? '#059669' : '#CBD5E1'}`,
      background: checked ? '#059669' : 'white', display: 'flex', alignItems: 'center',
      justifyContent: 'center', flexShrink: 0, transition: 'all 150ms',
    }}>
      {checked && (
        <svg width="13" height="10" viewBox="0 0 13 10" fill="none">
          <path d="M1 5l4 4 7-8" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      )}
    </div>
    <span style={{ fontSize: 14, color: '#475569', fontWeight: 500 }}>No soy un robot</span>
    <div style={{ marginLeft: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <svg width="32" height="32" viewBox="0 0 64 64" fill="none">
        <path d="M32 8C18.7 8 8 18.7 8 32s10.7 24 24 24 24-10.7 24-24S45.3 8 32 8z" fill="#4A90D9"/>
        <path d="M32 16c-8.8 0-16 7.2-16 16s7.2 16 16 16 16-7.2 16-16-7.2-16-16-16z" fill="#357ABD"/>
        <path d="M28 26l8 6-8 6V26z" fill="white"/>
      </svg>
      <span style={{ fontSize: 8, color: '#94A3B8', marginTop: 2 }}>reCAPTCHA</span>
    </div>
  </div>
);

// ── Campo de formulario ──────────────────────────────────────
const AuthField = ({ label, type = 'text', value, onChange, placeholder, hint, error, mono }) => (
  <div style={{ marginBottom: 16 }}>
    <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#64748B', marginBottom: 6 }}>{label}</label>
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: '100%', fontFamily: mono ? "'DM Mono',monospace" : "'DM Sans',sans-serif",
        fontSize: 14, padding: '9px 12px',
        border: `1.5px solid ${error ? '#DC2626' : '#E2E8F0'}`,
        borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none',
        transition: 'border-color 150ms, box-shadow 150ms',
      }}
      onFocus={e => { e.target.style.borderColor = error ? '#DC2626' : '#059669'; e.target.style.boxShadow = error ? '0 0 0 3px rgba(220,38,38,0.12)' : '0 0 0 3px rgba(5,150,105,0.12)'; }}
      onBlur={e => { e.target.style.borderColor = error ? '#DC2626' : '#E2E8F0'; e.target.style.boxShadow = 'none'; }}
    />
    {hint && !error && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>{hint}</div>}
    {error && <div style={{ fontSize: 11, color: '#DC2626', marginTop: 4 }}>{error}</div>}
  </div>
);

// ── PANTALLA LOGIN ────────────────────────────────────────────
const LoginScreen = ({ onLogin, onGoRegister }) => {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [captcha, setCaptcha] = React.useState(false);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const handleLogin = () => {
    setError('');
    if (!email || !pass) { setError('Completá todos los campos'); return; }
    if (!captcha) { setError('Confirmá que no sos un robot'); return; }
    setLoading(true);
    setTimeout(() => {
      // Admin hardcodeado
      if (email === 'admin@cronodato.com' && pass === 'cronodato2024') {
        window.__cronodatoRole = 'admin';
        window.__cronodatoUser = 'Admin';
        onLogin('admin');
      } else if (email && pass.length >= 6) {
        window.__cronodatoRole = 'cliente';
        window.__cronodatoUser = email.split('@')[0];
        onLogin('cliente');
      } else {
        setError('Email o contraseña incorrectos');
        setLoading(false);
      }
    }, 900);
  };

  return (
    <div style={{ minHeight: '100vh', background: '#0F172A', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      {/* Fondo decorativo */}
      <div style={{ position: 'fixed', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
        <div style={{ position: 'absolute', top: -200, right: -200, width: 600, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(5,150,105,0.15) 0%, transparent 70%)' }} />
        <div style={{ position: 'absolute', bottom: -200, left: -200, width: 500, height: 500, borderRadius: '50%', background: 'radial-gradient(circle, rgba(5,150,105,0.08) 0%, transparent 70%)' }} />
      </div>

      <div style={{ width: '100%', maxWidth: 420, position: 'relative' }}>
        {/* Logo */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 32 }}>
          <CDLogo size={48} showName nameColor="white" />
        </div>

        {/* Card */}
        <div style={{ background: 'white', borderRadius: 14, padding: '36px 32px', boxShadow: '0 24px 48px rgba(0,0,0,0.3)' }}>
          <div style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', marginBottom: 4, letterSpacing: '-0.02em' }}>Bienvenido</div>
          <div style={{ fontSize: 14, color: '#64748B', marginBottom: 28 }}>Ingresá a tu panel de CronoDato</div>

          {error && (
            <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#B91C1C', marginBottom: 16 }}>
              {error}
            </div>
          )}

          {/* Google login */}
          <button
            onClick={() => { setCaptcha(true); setTimeout(() => { window.__cronodatoRole = 'cliente'; window.__cronodatoUser = 'Usuario Google'; onLogin('cliente'); }, 600); }}
            style={{
              width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 500,
              padding: '10px 16px', background: 'white', color: '#0F172A',
              border: '1.5px solid #E2E8F0', borderRadius: 8, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              marginBottom: 20, transition: 'background 150ms, border-color 150ms',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = '#F8FAFC'; e.currentTarget.style.borderColor = '#CBD5E1'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.borderColor = '#E2E8F0'; }}
          >
            <GoogleIcon /> Continuar con Google
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
            <div style={{ flex: 1, height: 1, background: '#F1F5F9' }} />
            <span style={{ fontSize: 12, color: '#94A3B8' }}>o ingresá con email</span>
            <div style={{ flex: 1, height: 1, background: '#F1F5F9' }} />
          </div>

          <AuthField label="Email" type="email" value={email} onChange={setEmail} placeholder="tu@email.com" />
          <AuthField label="Contraseña" type="password" value={pass} onChange={setPass} placeholder="••••••••" />

          <div style={{ marginBottom: 20 }}>
            <RecaptchaBox checked={captcha} onCheck={() => setCaptcha(c => !c)} />
          </div>

          <button
            onClick={handleLogin}
            disabled={loading}
            style={{
              width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 600,
              padding: '11px 16px', background: loading ? '#A7F3D0' : '#059669', color: 'white',
              border: 'none', borderRadius: 8, cursor: loading ? 'not-allowed' : 'pointer',
              transition: 'background 150ms', marginBottom: 16,
            }}
          >
            {loading ? 'Ingresando…' : 'Ingresar'}
          </button>

          <div style={{ textAlign: 'center', fontSize: 13, color: '#64748B' }}>
            ¿No tenés cuenta?{' '}
            <span onClick={onGoRegister} style={{ color: '#059669', fontWeight: 600, cursor: 'pointer' }}>
              Registrate
            </span>
          </div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: '#475569' }}>
          Al ingresar aceptás los{' '}
          <span style={{ color: '#64748B', textDecoration: 'underline', cursor: 'pointer' }}>términos de uso</span>
          {' '}y la{' '}
          <span style={{ color: '#64748B', textDecoration: 'underline', cursor: 'pointer' }}>política de privacidad</span>
        </div>
      </div>
    </div>
  );
};

// ── PANTALLA REGISTRO ─────────────────────────────────────────
const RegisterScreen = ({ onLogin, onGoLogin }) => {
  const [step, setStep] = React.useState(1); // 1: plan, 2: datos
  const [planId, setPlanId] = React.useState('pack_estandar');
  const [nombre, setNombre] = React.useState('');
  const [emailContacto, setEmailContacto] = React.useState('');
  const [emailFacturas, setEmailFacturas] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [pass2, setPass2] = React.useState('');
  const [captcha, setCaptcha] = React.useState(false);
  const [aceptaTerminos, setAceptaTerminos] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  const planSeleccionado = PLANES.find(p => p.id === planId);

  const validarDatos = () => {
    const e = {};
    if (!nombre.trim()) e.nombre = 'Requerido';
    if (!emailContacto.trim()) e.emailContacto = 'Requerido';
    if (!emailFacturas.trim()) e.emailFacturas = 'Requerido';
    if (pass.length < 6) e.pass = 'Mínimo 6 caracteres';
    if (pass !== pass2) e.pass2 = 'Las contraseñas no coinciden';
    if (!captcha) e.captcha = 'Confirmá que no sos un robot';
    if (!aceptaTerminos) e.terminos = 'Debés leer y aceptar los términos y condiciones para continuar';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleRegister = () => {
    if (!validarDatos()) return;
    setLoading(true);
    setTimeout(() => {
      setSuccess(true);
      setLoading(false);
    }, 1200);
  };

  if (success) {
    return (
      <div style={{ minHeight: '100vh', background: '#0F172A', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
        <div style={{ width: '100%', maxWidth: 420 }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 32 }}>
            <CDLogo size={48} showName nameColor="white" />
          </div>
          <div style={{ background: 'white', borderRadius: 14, padding: '40px 32px', textAlign: 'center', boxShadow: '0 24px 48px rgba(0,0,0,0.3)' }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: '#ECFDF5', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
              <svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M5 14l6 6 12-12" stroke="#059669" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', marginBottom: 8, letterSpacing: '-0.02em' }}>¡Registro recibido!</div>
            <div style={{ fontSize: 14, color: '#64748B', lineHeight: 1.6, marginBottom: 28 }}>
              Te enviamos un email de confirmación a <strong>{emailContacto}</strong>. En breve activamos tu cuenta con el <strong>{planSeleccionado?.nombre}</strong>.
            </div>
            <button
              onClick={() => onGoLogin()}
              style={{ fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 600, padding: '11px 32px', background: '#059669', color: 'white', border: 'none', borderRadius: 8, cursor: 'pointer' }}
            >
              Ir al login
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: '#0F172A', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div style={{ position: 'fixed', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
        <div style={{ position: 'absolute', top: -200, right: -200, width: 600, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(5,150,105,0.15) 0%, transparent 70%)' }} />
      </div>

      <div style={{ width: '100%', maxWidth: step === 1 ? 680 : 480, position: 'relative' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
          <CDLogo size={40} showName nameColor="white" />
        </div>

        {/* Pasos */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 24 }}>
          {[1,2].map(s => (
            <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                width: 28, height: 28, borderRadius: '50%',
                background: step >= s ? '#059669' : '#1E293B',
                border: `2px solid ${step >= s ? '#059669' : '#334155'}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: 700, color: step >= s ? 'white' : '#475569',
                transition: 'all 200ms',
              }}>{s}</div>
              {s < 2 && <div style={{ width: 40, height: 2, background: step > s ? '#059669' : '#1E293B', borderRadius: 1, transition: 'background 200ms' }} />}
            </div>
          ))}
        </div>

        <div style={{ background: 'white', borderRadius: 14, padding: '32px', boxShadow: '0 24px 48px rgba(0,0,0,0.3)' }}>

          {/* PASO 1 — Elegir plan */}
          {step === 1 && (
            <>
              <div style={{ fontSize: 20, fontWeight: 700, color: '#0F172A', marginBottom: 4, letterSpacing: '-0.02em' }}>Elegí tu plan</div>
              <div style={{ fontSize: 14, color: '#64748B', marginBottom: 24 }}>Todos los planes son prepago — pagás por lo que usás</div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 24 }}>
                {PLANES.map(plan => (
                  <div
                    key={plan.id}
                    onClick={() => setPlanId(plan.id)}
                    style={{
                      border: `2px solid ${planId === plan.id ? '#059669' : plan.destacado ? '#E2E8F0' : '#E2E8F0'}`,
                      borderRadius: 10, padding: '18px 16px', cursor: 'pointer',
                      background: planId === plan.id ? '#F0FDF4' : 'white',
                      position: 'relative', transition: 'all 150ms',
                      boxShadow: plan.destacado && planId !== plan.id ? '0 0 0 2px #E2E8F0' : 'none',
                    }}
                  >
                    {plan.destacado && (
                      <div style={{ position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)', background: '#0F172A', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 10px', borderRadius: 9999, whiteSpace: 'nowrap', letterSpacing: '0.05em' }}>
                        MÁS ELEGIDO
                      </div>
                    )}
                    {plan.promo && (
                      <div style={{ position: 'absolute', top: -10, right: 12, background: '#059669', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 9999, letterSpacing: '0.04em' }}>
                        PROMO
                      </div>
                    )}
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A' }}>{plan.nombre}</div>
                      <div style={{ width: 18, height: 18, borderRadius: '50%', border: `2px solid ${planId === plan.id ? '#059669' : '#CBD5E1'}`, background: planId === plan.id ? '#059669' : 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 150ms' }}>
                        {planId === plan.id && <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'white' }} />}
                      </div>
                    </div>
                    {plan.promo ? (
                      <>
                        <div style={{ fontSize: 22, fontWeight: 800, color: '#059669', fontFamily: "'DM Mono',monospace", letterSpacing: '-0.02em' }}>${plan.precio.toLocaleString('es-AR')}</div>
                        <div style={{ fontSize: 11, color: '#94A3B8', textDecoration: 'line-through', fontFamily: "'DM Mono',monospace" }}>${plan.costoOriginal.toLocaleString('es-AR')}</div>
                        <div style={{ fontSize: 12, color: '#64748B', marginTop: 6 }}>{plan.facturas} facturas incluidas</div>
                        <div style={{ fontSize: 11, color: '#94A3B8', fontFamily: "'DM Mono',monospace" }}>${plan.costo} / factura</div>
                      </>
                    ) : (
                      <>
                        <div style={{ fontSize: 22, fontWeight: 800, color: '#0F172A', fontFamily: "'DM Mono',monospace", letterSpacing: '-0.02em' }}>${plan.precio.toLocaleString('es-AR')}</div>
                        <div style={{ fontSize: 12, color: '#64748B', marginTop: 6 }}>{plan.facturas} facturas incluidas</div>
                        <div style={{ fontSize: 11, color: '#94A3B8', fontFamily: "'DM Mono',monospace" }}>${plan.costo} / factura</div>
                      </>
                    )}
                    <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 8 }}>{plan.desc}</div>
                  </div>
                ))}
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span onClick={onGoLogin} style={{ fontSize: 13, color: '#64748B', cursor: 'pointer' }}>
                  ¿Ya tenés cuenta? <span style={{ color: '#059669', fontWeight: 600 }}>Ingresá</span>
                </span>
                <button
                  onClick={() => setStep(2)}
                  style={{ fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 600, padding: '10px 24px', background: '#059669', color: 'white', border: 'none', borderRadius: 8, cursor: 'pointer' }}
                >
                  Continuar →
                </button>
              </div>
            </>
          )}

          {/* PASO 2 — Datos */}
          {step === 2 && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24, background: '#F0FDF4', border: '1px solid #A7F3D0', borderRadius: 8, padding: '12px 14px' }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#047857' }}>Plan seleccionado: {planSeleccionado?.nombre}</div>
                  <div style={{ fontSize: 12, color: '#059669' }}>{planSeleccionado?.facturas} facturas — ${planSeleccionado?.precio.toLocaleString('es-AR')} ARS</div>
                </div>
                <span onClick={() => setStep(1)} style={{ marginLeft: 'auto', fontSize: 12, color: '#059669', cursor: 'pointer', fontWeight: 500 }}>Cambiar</span>
              </div>

              <div style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', marginBottom: 20, letterSpacing: '-0.01em' }}>Tus datos</div>

              {/* Google */}
              <button
                onClick={() => { setCaptcha(true); setTimeout(() => { window.__cronodatoRole = 'cliente'; window.__cronodatoUser = 'Usuario Google'; onLogin('cliente'); }, 600); }}
                style={{
                  width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 500,
                  padding: '10px 16px', background: 'white', color: '#0F172A',
                  border: '1.5px solid #E2E8F0', borderRadius: 8, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                  marginBottom: 20, transition: 'background 150ms',
                }}
                onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
                onMouseLeave={e => e.currentTarget.style.background = 'white'}
              >
                <GoogleIcon /> Registrarme con Google
              </button>

              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
                <div style={{ flex: 1, height: 1, background: '#F1F5F9' }} />
                <span style={{ fontSize: 12, color: '#94A3B8' }}>o con email y contraseña</span>
                <div style={{ flex: 1, height: 1, background: '#F1F5F9' }} />
              </div>

              <AuthField label="Nombre o razón social" value={nombre} onChange={setNombre} placeholder="Estudio Contable López" error={errors.nombre} />

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <AuthField label="Email de contacto" type="email" value={emailContacto} onChange={setEmailContacto} placeholder="admin@empresa.com" hint="Para notificaciones" error={errors.emailContacto} />
                <AuthField label="Email que envía facturas" type="email" value={emailFacturas} onChange={setEmailFacturas} placeholder="facturas@empresa.com" hint="Desde donde nos mandás los PDF" error={errors.emailFacturas} />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <AuthField label="Contraseña" type="password" value={pass} onChange={setPass} placeholder="Mínimo 6 caracteres" error={errors.pass} />
                <AuthField label="Repetir contraseña" type="password" value={pass2} onChange={setPass2} placeholder="Repetí la contraseña" error={errors.pass2} />
              </div>

              <div style={{ marginBottom: 16 }}>
                <RecaptchaBox checked={captcha} onCheck={() => { setCaptcha(c => !c); setErrors(e => ({ ...e, captcha: undefined })); }} />
                {errors.captcha && <div style={{ fontSize: 11, color: '#DC2626', marginTop: 4 }}>{errors.captcha}</div>}
              </div>

              {/* Checkbox obligatorio de términos y condiciones */}
              <div style={{ marginBottom: 20 }}>
                <div
                  onClick={() => { setAceptaTerminos(t => !t); setErrors(e => ({ ...e, terminos: undefined })); }}
                  style={{
                    display: 'flex', alignItems: 'flex-start', gap: 12, cursor: 'pointer',
                    padding: '12px 14px', borderRadius: 8,
                    border: `1.5px solid ${errors.terminos ? '#DC2626' : aceptaTerminos ? '#059669' : '#E2E8F0'}`,
                    background: aceptaTerminos ? '#F0FDF4' : errors.terminos ? '#FEF2F2' : '#F8FAFC',
                    transition: 'all 150ms', userSelect: 'none',
                  }}
                >
                  <div style={{
                    width: 20, height: 20, borderRadius: 5, flexShrink: 0, marginTop: 1,
                    border: `2px solid ${aceptaTerminos ? '#059669' : errors.terminos ? '#DC2626' : '#CBD5E1'}`,
                    background: aceptaTerminos ? '#059669' : 'white',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'all 150ms',
                  }}>
                    {aceptaTerminos && (
                      <svg width="11" height="9" viewBox="0 0 11 9" fill="none">
                        <path d="M1 4.5l3 3 6-7" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    )}
                  </div>
                  <div style={{ fontSize: 13, color: '#475569', lineHeight: 1.5 }}>
                    He leído y acepto los{' '}
                    <span
                      onClick={e => { e.stopPropagation(); window.__showTyC && window.__showTyC(); }}
                      style={{ color: '#059669', fontWeight: 600, textDecoration: 'underline', cursor: 'pointer' }}
                    >
                      Términos y Condiciones de Uso
                    </span>
                    {' '}y la{' '}
                    <span
                      onClick={e => { e.stopPropagation(); window.__showTyC && window.__showTyC(); }}
                      style={{ color: '#059669', fontWeight: 600, textDecoration: 'underline', cursor: 'pointer' }}
                    >
                      Política de Privacidad
                    </span>
                    {' '}de CronoDato.
                  </div>
                </div>
                {errors.terminos && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#DC2626', marginTop: 5 }}>
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><circle cx="6" cy="6" r="5.5" stroke="#DC2626"/><path d="M6 4v3M6 8.5v.5" stroke="#DC2626" strokeLinecap="round"/></svg>
                    {errors.terminos}
                  </div>
                )}
              </div>

              <div style={{ display: 'flex', gap: 10 }}>
                <button
                  onClick={() => setStep(1)}
                  style={{ fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 500, padding: '10px 20px', background: 'white', color: '#475569', border: '1.5px solid #E2E8F0', borderRadius: 8, cursor: 'pointer' }}
                >
                  ← Volver
                </button>
                <button
                  onClick={handleRegister}
                  disabled={loading}
                  style={{
                    flex: 1, fontFamily: "'DM Sans',sans-serif", fontSize: 14, fontWeight: 600,
                    padding: '11px 16px', background: loading ? '#A7F3D0' : '#059669', color: 'white',
                    border: 'none', borderRadius: 8, cursor: loading ? 'not-allowed' : 'pointer', transition: 'background 150ms',
                  }}
                >
                  {loading ? 'Registrando…' : 'Solicitar acceso'}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoginScreen, RegisterScreen });
