/* ============================================================
   LIA · Auth — Login/Register con Supabase
   ============================================================ */

/* Inicializar Supabase una sola vez */
const _sb = window.LIA_CONFIG.sbReady
  ? supabase.createClient(window.LIA_CONFIG.supabaseUrl, window.LIA_CONFIG.supabaseAnonKey)
  : null;

window._sb = _sb;

/* Pantalla de login */
function AuthScreen({ onAuth }) {
  const [tab, setTab]               = React.useState('login');
  const [email, setEmail]           = React.useState('');
  const [pwd, setPwd]               = React.useState('');
  const [name, setName]             = React.useState('');
  const [empresa, setEmpresa]       = React.useState('');
  const [tipoPersona, setTipo]      = React.useState('juridica');
  const [repLegal, setRepLegal]     = React.useState('');
  const [cedula, setCedula]         = React.useState('');
  const [err, setErr]               = React.useState('');
  const [ok, setOk]                 = React.useState('');
  const [loading, setLoading]       = React.useState(false);
  const [showPwd, setShowPwd]       = React.useState(false);

  async function iniciarSesion(e) {
    e.preventDefault();
    setErr(''); setOk('');
    if (!_sb) { setErr('Error de configuración. Contactá soporte.'); return; }
    setLoading(true);
    try {
      const { data, error } = await _sb.auth.signInWithPassword({ email, password: pwd });
      if (error) { setErr(error.message === 'Invalid login credentials' ? 'Correo o contraseña incorrectos.' : error.message); return; }
      if (data.user) onAuth(data.user);
    } catch(e) { setErr('Error: ' + e.message); }
    finally { setLoading(false); }
  }

  async function registrarse(e) {
    e.preventDefault();
    setErr(''); setOk('');
    if (!_sb) { setErr('Error de configuración. Contactá soporte.'); return; }
    const esFisica = tipoPersona === 'fisica';
    const nombreFinal = esFisica ? name : repLegal;
    const empresaFinal = esFisica ? empresa : name;
    if (!nombreFinal || !email || !pwd) { setErr('Completá todos los campos obligatorios.'); return; }
    if (!esFisica && !empresaFinal) { setErr('Ingresá la razón social de la empresa.'); return; }
    if (pwd.length < 6) { setErr('La contraseña debe tener al menos 6 caracteres.'); return; }
    setLoading(true);
    try {
      const { data, error } = await _sb.auth.signUp({
        email, password: pwd,
        options: { data: {
          full_name:      nombreFinal,
          company_name:   empresaFinal,
          tipo_persona:   tipoPersona,
          cedula_juridica: tipoPersona === 'juridica' ? cedula : '',
        }}
      });
      if (error) { setErr(error.message); return; }
      if (data.session) { onAuth(data.user); }
      else { setOk('Cuenta creada. Revisá tu correo para confirmar antes de entrar.'); }
    } catch(e) { setErr('Error: ' + e.message); }
    finally { setLoading(false); }
  }

  const inp = {
    style: {
      width: '100%', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(96,165,250,0.25)',
      borderRadius: 10, padding: '11px 14px', color: 'var(--text)', fontSize: 14,
      fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box'
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'var(--bg-deep)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9999, padding: 20
    }}>
      {/* Fondo con halo */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(900px 600px at 50% 30%, rgba(37,99,235,0.18), transparent 60%)'
      }} />

      <div className="fade-up" style={{
        position: 'relative', width: '100%', maxWidth: 440,
        background: 'var(--surface)', border: '1px solid rgba(96,165,250,0.2)',
        borderRadius: 20, padding: 32
      }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <div style={{
            width: 52, height: 52, borderRadius: 14, margin: '0 auto 14px',
            background: 'linear-gradient(150deg, #f5f8ff, #cdd9ef)',
            display: 'grid', placeItems: 'center',
            boxShadow: '0 4px 14px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.7)'
          }}>
            <span style={{ fontFamily: 'Syne', fontWeight: 800, fontSize: 22, color: '#2563eb', letterSpacing: '-0.04em' }}>
              <span style={{ color: '#64748b' }}>L</span>IA
            </span>
          </div>
          <div style={{ fontFamily: 'Syne', fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>LIA Solutions</div>
          <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 4 }}>Licitaciones Inteligentes Automatizadas</div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', background: 'rgba(96,165,250,0.06)', borderRadius: 10, padding: 3, marginBottom: 22 }}>
          {['login','registro'].map(t => (
            <button key={t} onClick={() => { setTab(t); setErr(''); setOk(''); }}
              style={{
                flex: 1, padding: '8px 0', borderRadius: 8, border: 'none', cursor: 'pointer',
                fontFamily: 'Syne', fontWeight: 700, fontSize: 13,
                background: tab === t ? 'linear-gradient(135deg, #2563eb, #1d4ed8)' : 'transparent',
                color: tab === t ? '#fff' : 'var(--silver)', transition: 'all .15s'
              }}>
              {t === 'login' ? 'Iniciar sesión' : 'Registrarse'}
            </button>
          ))}
        </div>

        <form onSubmit={tab === 'login' ? iniciarSesion : registrarse}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {tab === 'registro' && (
              <>
                {/* Selector tipo de persona */}
                <div style={{ display: 'flex', background: 'rgba(96,165,250,0.06)', borderRadius: 10, padding: 3, gap: 4 }}>
                  {[['fisica','Persona Física'],['juridica','Persona Jurídica']].map(([v,lbl]) => (
                    <button key={v} type="button" onClick={() => { setTipo(v); setErr(''); }}
                      style={{ flex: 1, padding: '7px 0', borderRadius: 7, border: 'none', cursor: 'pointer',
                        fontFamily: 'Syne', fontWeight: 700, fontSize: 12,
                        background: tipoPersona === v ? 'linear-gradient(135deg,#2563eb,#1d4ed8)' : 'transparent',
                        color: tipoPersona === v ? '#fff' : 'var(--silver)', transition: 'all .15s' }}>
                      {lbl}
                    </button>
                  ))}
                </div>

                {tipoPersona === 'juridica' ? (
                  <>
                    <div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Razón social <span style={{color:'#f87171'}}>*</span></div>
                      <input {...inp} value={name} onChange={e => setName(e.target.value)} placeholder="Nombre de la empresa o sociedad" />
                    </div>
                    <div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Cédula jurídica <span style={{color:'var(--muted)'}}>· opcional</span></div>
                      <input {...inp} value={cedula} onChange={e => setCedula(e.target.value)} placeholder="Ej: 3-101-123456" />
                    </div>
                    <div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Representante legal <span style={{color:'#f87171'}}>*</span></div>
                      <input {...inp} value={repLegal} onChange={e => setRepLegal(e.target.value)} placeholder="Nombre del representante" />
                    </div>
                  </>
                ) : (
                  <>
                    <div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Nombre completo <span style={{color:'#f87171'}}>*</span></div>
                      <input {...inp} value={name} onChange={e => setName(e.target.value)} placeholder="Tu nombre completo" />
                    </div>
                    <div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Empresa <span style={{color:'var(--muted)'}}>· opcional</span></div>
                      <input {...inp} value={empresa} onChange={e => setEmpresa(e.target.value)} placeholder="Empresa donde trabajás" />
                    </div>
                  </>
                )}
              </>
            )}
            <div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Correo electrónico</div>
              <input {...inp} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="correo@empresa.com" />
            </div>
            <div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginBottom: 6 }}>Contraseña</div>
              <div style={{ position: 'relative' }}>
                <input {...inp} type={showPwd ? 'text' : 'password'} value={pwd}
                  onChange={e => setPwd(e.target.value)} placeholder="Mínimo 6 caracteres"
                  style={{ ...inp.style, paddingRight: 44 }} />
                <button type="button" onClick={() => setShowPwd(v => !v)}
                  style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', fontSize: '1rem' }}>
                  {showPwd ? '🙈' : '👁'}
                </button>
              </div>
            </div>
          </div>

          {err && <div style={{ marginTop: 12, color: '#f87171', fontSize: 13, padding: '8px 12px', background: 'rgba(248,113,113,0.08)', borderRadius: 8, border: '1px solid rgba(248,113,113,0.2)' }}>{err}</div>}
          {ok  && <div style={{ marginTop: 12, color: '#22c55e', fontSize: 13, padding: '8px 12px', background: 'rgba(34,197,94,0.08)', borderRadius: 8, border: '1px solid rgba(34,197,94,0.2)' }}>{ok}</div>}

          <button type="submit" disabled={loading} style={{
            width: '100%', marginTop: 18, padding: '12px 0',
            background: 'linear-gradient(135deg, #2563eb, #1d4ed8)',
            border: 'none', borderRadius: 11, color: '#fff',
            fontFamily: 'Syne', fontWeight: 700, fontSize: 14,
            cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1,
            boxShadow: '0 8px 24px -8px rgba(37,99,235,0.5)'
          }}>
            {loading ? 'Procesando...' : (tab === 'login' ? 'Entrar a LIA' : 'Crear cuenta')}
          </button>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { _sb, AuthScreen });
