/* ============================================================
   FLOWSHIELD — Login (gated: daynko / !Aa123456789.)
   ============================================================ */
const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

function MatrixRain() {
  const ref = useRefL(null);
  useEffectL(() => {
    const cv = ref.current; if (!cv) return;
    const ctx = cv.getContext('2d');
    let w, h, cols, drops;
    const chars = '01░▒▓<>{}[]/\\|=+*ABCDEF0123456789アカサタナ';
    function resize(){ w = cv.width = cv.offsetWidth; h = cv.height = cv.offsetHeight; cols = Math.floor(w/16); drops = Array(cols).fill(0).map(()=>Math.random()*-50); }
    resize();
    function draw(){
      if (document.hidden) return;
      ctx.fillStyle = 'rgba(5,7,13,0.18)'; ctx.fillRect(0,0,w,h);
      ctx.font = '13px JetBrains Mono';
      for (let i=0;i<cols;i++){
        const ch = chars[Math.floor(Math.random()*chars.length)];
        const x = i*16, y = drops[i]*16;
        ctx.fillStyle = Math.random()>0.96 ? 'rgba(0,245,192,0.9)' : 'rgba(0,245,192,0.32)';
        ctx.fillText(ch, x, y);
        if (y > h && Math.random()>0.975) drops[i]=0;
        drops[i]++;
      }
    }
    const timer = setInterval(draw, 70);
    window.addEventListener('resize', resize);
    return () => { clearInterval(timer); window.removeEventListener('resize', resize); };
  }, []);
  return <canvas ref={ref} style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:.5 }} />;
}

function Login({ onAuth }) {
  const [u, setU] = useStateL('');
  const [p, setP] = useStateL('');
  const [show, setShow] = useStateL(false);
  const [err, setErr] = useStateL('');
  const [busy, setBusy] = useStateL(false);
  const [boot, setBoot] = useStateL([]);

  const BOOT = [
    '> flowshield secure-shell v3.4.1',
    '> inicializando módulo criptográfico … OK',
    '> verificando integridad del kernel … OK',
    '> red team / blue team / normativa … cargados',
    '> esperando autenticación del operador_',
  ];
  useEffectL(() => {
    let i = 0;
    const t = setInterval(() => { const cur = BOOT[i]; setBoot(b => [...b, cur]); i++; if (i >= BOOT.length) clearInterval(t); }, 380);
    return () => clearInterval(t);
  }, []);

  const submit = async (e) => {
    e.preventDefault(); setErr(''); setBusy(true);
    try {
      const data = await window.fsAuth.login(u.trim(), p);
      setBoot(b => [...b, '> credenciales válidas · acceso concedido ✓']);
      setTimeout(() => onAuth(data), 600);
    } catch (ex) {
      setErr((ex && ex.status === 401)
        ? 'ACCESO DENEGADO · credenciales no válidas'
        : ('ERROR · ' + (ex && ex.message ? ex.message : 'no se pudo autenticar')));
      setBusy(false);
    }
  };

  return (
    <div className="theme-fs" style={{ position:'fixed', inset:0, display:'grid', placeItems:'center', overflow:'hidden', background:'var(--bg-void)' }}>
      <MatrixRain />
      <div style={{ position:'absolute', inset:0, background:'radial-gradient(700px 500px at 50% 42%, transparent, rgba(5,7,13,.86) 72%)' }} />

      <div className="enter" style={{ position:'relative', width:'min(880px, 92vw)', display:'grid', gridTemplateColumns:'1.1fr 1fr', gap:0, border:'1px solid var(--line-bright)', borderRadius:16, overflow:'hidden', boxShadow:'0 40px 120px -30px rgba(0,245,192,.25), 0 0 0 1px rgba(0,245,192,.08)' }}>

        {/* Left: brand + boot terminal */}
        <div style={{ padding:'40px 36px', background:'linear-gradient(160deg, #0A1119, #070A11)', borderRight:'1px solid var(--line)', position:'relative' }}>
          <Logo size={44} />
          <div style={{ marginTop:30, fontSize:13, lineHeight:1.7, color:'var(--txt-dim)', maxWidth:320 }}>
            Plataforma unificada de operaciones de seguridad ofensiva, defensiva y cumplimiento normativo.
          </div>
          <div className="terminal" style={{ marginTop:26, minHeight:148, background:'transparent', border:'none', padding:0 }}>
            {boot.map((l, i) => (
              <div key={i} className={l.includes('✓') ? 't-ok' : l.includes('DENEG') ? 't-err' : 't-dim'} style={{ animation:'enter .3s forwards' }}>{l}</div>
            ))}
          </div>
          <div style={{ position:'absolute', bottom:18, left:36, display:'flex', gap:8, alignItems:'center' }}>
            <span className="dot pulse" style={{ background:'var(--fs)', width:8, height:8, borderRadius:99, color:'var(--fs)' }} />
            <span className="mono" style={{ fontSize:10.5, color:'var(--txt-mute)', letterSpacing:'.1em' }}>NODO SEGURO · ES-MAD-01</span>
          </div>
        </div>

        {/* Right: login form */}
        <div style={{ padding:'44px 38px', background:'var(--bg-panel)', display:'flex', flexDirection:'column', justifyContent:'center' }}>
          <div className="mono upper" style={{ fontSize:11, color:'var(--fs)', letterSpacing:'.2em', marginBottom:10 }}>// acceso restringido</div>
          <h2 className="disp" style={{ fontSize:24, fontWeight:700, color:'var(--txt-hi)', marginBottom:6 }}>Autenticación</h2>
          <p style={{ fontSize:12.5, color:'var(--txt-dim)', marginBottom:26 }}>Sólo operadores autorizados. Modelo base.</p>

          <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <div className="field">
              <Icon name="user" size={16} style={{ position:'absolute', left:14, top:13, color:'var(--txt-mute)' }} />
              <input className="input input-prefix" type="email" autoComplete="username" placeholder="correo del operador" value={u} onChange={e=>setU(e.target.value)} autoFocus />
            </div>
            <div className="field">
              <Icon name="lock" size={16} style={{ position:'absolute', left:14, top:13, color:'var(--txt-mute)' }} />
              <input className="input input-prefix" type={show?'text':'password'} placeholder="contraseña" value={p} onChange={e=>setP(e.target.value)} style={{ paddingRight:42 }} />
              <button type="button" onClick={()=>setShow(s=>!s)} style={{ position:'absolute', right:10, top:11, background:'none', border:'none', color:'var(--txt-mute)', cursor:'pointer' }}>
                <Icon name={show?'eyeoff':'eye'} size={16} />
              </button>
            </div>

            {err && (
              <div className="mono" style={{ fontSize:11.5, color:'var(--red)', background:'var(--red-soft)', border:'1px solid color-mix(in srgb,var(--red) 35%,transparent)', borderRadius:6, padding:'9px 12px', display:'flex', gap:8, alignItems:'center' }}>
                <Icon name="alert" size={15} />{err}
              </div>
            )}

            <Btn type="submit" variant="solid" size="block" style={{ marginTop:6, opacity: busy?0.8:1 }} iconR={busy?null:'chevron'}>
              {busy ? 'AUTENTICANDO…' : 'INICIAR SESIÓN'}
            </Btn>
          </form>

          <div style={{ marginTop:22, paddingTop:18, borderTop:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <span className="mono" style={{ fontSize:10, color:'var(--txt-mute)' }}>2FA · cifrado AES-256</span>
            <span className="mono" style={{ fontSize:10, color:'var(--txt-mute)' }}>v3.4.1</span>
          </div>
        </div>
      </div>

      <div className="mono" style={{ position:'absolute', bottom:16, fontSize:10.5, color:'var(--txt-mute)', letterSpacing:'.1em' }}>
        FLOWSHIELD © 2026 · uso autorizado únicamente
      </div>

      <style>{`@media (max-width:680px){.enter{grid-template-columns:1fr !important}}`}</style>
    </div>
  );
}

Object.assign(window, { Login });
