/* JRN — Autenticação: Login + Recuperação de senha */

function AuthShell({ children }) {
  return (
    <div className="auth-shell" style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,1fr)', position: 'relative' }}>
      {/* Painel de marca */}
      <div className="auth-brand" style={{ position: 'relative', background: 'linear-gradient(160deg,#15233f 0%,#0d1730 100%)', color: '#fff', padding: '56px 60px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', overflow: 'hidden' }}>
        <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: .06 }} preserveAspectRatio="none">
          <defs><pattern id="grid" width="46" height="46" patternUnits="userSpaceOnUse"><path d="M46 0H0V46" fill="none" stroke="#fff" strokeWidth="1" /></pattern></defs>
          <rect width="100%" height="100%" fill="url(#grid)" />
        </svg>
        <div style={{ position: 'relative' }}>
          <img src="assets/logos/jrn.png" alt="JRN" style={{ width: 96, filter: 'brightness(0) invert(1)' }} />
        </div>
        <div style={{ position: 'relative' }}>
          <div className="kicker" style={{ color: '#8ea0c4', marginBottom: 18 }}>Portal de Indicadores</div>
          <h1 style={{ color: '#fff', fontSize: 38, lineHeight: 1.12, fontWeight: 600, maxWidth: 460 }}>
            Inteligência de gestão para todo o grupo, em um só lugar.
          </h1>
          <p style={{ color: '#aab7d2', fontSize: 15, lineHeight: 1.6, maxWidth: 420, marginTop: 18 }}>
            Acompanhe os indicadores das empresas do Grupo JRN com a governança e a segurança de acesso que cada área exige.
          </p>
        </div>
        <div style={{ position: 'relative', display: 'flex', gap: 18, alignItems: 'center', opacity: .85 }}>
          {COMPANIES.filter(c => c.id !== 'jrn').slice(0, 6).map(c => (
            <img key={c.id} src={c.logo} alt={c.nome} title={c.nome}
              style={{ height: 26, filter: 'brightness(0) invert(1)', opacity: .55 }} />
          ))}
        </div>
      </div>
      {/* Painel de formulário */}
      <div className="auth-form-wrap" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px', background: '#fff' }}>
        <div style={{ width: '100%', maxWidth: 380 }}>{children}</div>
      </div>

      {/* Desenvolvido por Nexalyze */}
      <div style={{
        position: 'fixed', bottom: 22, right: 26, zIndex: 10,
        display: 'flex', alignItems: 'center', gap: 7,
         pointerEvents: 'none', userSelect: 'none',
      }}>
        <span style={{ fontSize: 10.5, fontFamily: 'var(--font-ui)', color: '#888', letterSpacing: '.04em', textTransform: 'uppercase' }}>
          Desenvolvido por
        </span>
        <img
          src="assets/logos/nexalyze.png"
          alt="Nexalyze"
          style={{ height: 18, opacity: .85, }}
        />
      </div>
    </div>
  );
}

function LoginScreen({ onLogin }) {
  const [view, setView] = useState('login'); // login | forgot | sent
  const [email, setEmail] = useState('');
  const [pwd, setPwd] = useState('');
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [recEmail, setRecEmail] = useState('');
  const [recLoading, setRecLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      await apiLogin(email, pwd);
      await onLogin();          // onLogin chama apiMe() no App e atualiza a sessão
    } catch (err) {
      setError(err.message || 'Credenciais inválidas');
      setLoading(false);
    }
  };

  const submitForgot = async (e) => {
    e.preventDefault();
    setRecLoading(true);
    try {
      await apiForgotPassword(recEmail);
    } catch (_) {
      // Resposta é sempre genérica (anti-enumeração) — tratamos como sucesso
    }
    setRecLoading(false);
    setView('sent');
  };

  if (view === 'forgot' || view === 'sent') {
    return (
      <AuthShell>
        <button onClick={() => setView('login')} className="btn btn-ghost btn-sm" style={{ border: 'none', padding: '6px 0', marginBottom: 22, color: 'var(--muted)' }}>
          <Icons.arrowLeft size={16} /> Voltar ao login
        </button>
        {view === 'forgot' ? (
          <React.Fragment>
            <h1 style={{ fontSize: 25 }}>Recuperar acesso</h1>
            <p style={{ color: 'var(--muted)', fontSize: 14, margin: '10px 0 28px', lineHeight: 1.55 }}>
              Informe o e-mail corporativo cadastrado. Enviaremos um link seguro para redefinição de senha.
            </p>
            <form onSubmit={submitForgot} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <Field label="E-mail corporativo">
                <div style={{ position: 'relative' }}>
                  <Icons.mail size={17} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }} />
                  <input className="input" style={{ paddingLeft: 38 }} type="email" required placeholder="nome@empresa.com.br"
                    value={recEmail} onChange={e => setRecEmail(e.target.value)} />
                </div>
              </Field>
              <Btn icon="mail" type="submit" disabled={recLoading}>
                {recLoading ? <Icons.refresh className="spin" size={16} /> : null}
                {recLoading ? 'Enviando…' : 'Enviar link de redefinição'}
              </Btn>
            </form>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--ok-soft)', color: 'var(--ok)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}><Icons.mail size={24} /></div>
            <h1 style={{ fontSize: 25 }}>Verifique seu e-mail</h1>
            <p style={{ color: 'var(--muted)', fontSize: 14, margin: '10px 0 28px', lineHeight: 1.55 }}>
              Se houver uma conta associada a <strong style={{ color: 'var(--ink-2)' }}>{recEmail || 'esse endereço'}</strong>, você receberá um link de redefinição em instantes.
            </p>
            <Btn variant="soft" onClick={() => setView('login')}>Voltar ao login</Btn>
          </React.Fragment>
        )}
      </AuthShell>
    );
  }

  return (
    <AuthShell>
      <div className="kicker" style={{ marginBottom: 14 }}>Bem-vindo de volta</div>
      <h1 style={{ fontSize: 27 }}>Acessar o portal</h1>
      <p style={{ color: 'var(--muted)', fontSize: 14, margin: '9px 0 28px' }}>Entre com suas credenciais corporativas.</p>
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 17 }}>
        <Field label="E-mail corporativo">
          <div style={{ position: 'relative' }}>
            <Icons.mail size={17} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }} />
            <input className="input" style={{ paddingLeft: 38 }} type="email" required
              value={email} onChange={e => setEmail(e.target.value)} />
          </div>
        </Field>
        <Field label="Senha">
          <div style={{ position: 'relative' }}>
            <Icons.lock size={17} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }} />
            <input className="input" style={{ paddingLeft: 38, paddingRight: 40 }}
              type={showPwd ? 'text' : 'password'} required
              value={pwd} onChange={e => setPwd(e.target.value)} />
            <button type="button" onClick={() => setShowPwd(s => !s)}
              style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', padding: 2 }}>
              {showPwd ? <Icons.eyeOff size={18} /> : <Icons.eye size={18} />}
            </button>
          </div>
        </Field>
        {error && (
          <div style={{ fontSize: 13, color: 'var(--danger)', background: 'var(--danger-soft)', padding: '10px 13px', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icons.x size={15} />{error}
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginTop: -2 }}>
          <button type="button" onClick={() => setView('forgot')}
            style={{ background: 'none', border: 'none', color: 'var(--navy-700)', fontWeight: 600, fontSize: 13, cursor: 'pointer' }}>
            Esqueci a senha
          </button>
        </div>
        <Btn type="submit" disabled={loading} icon={loading ? null : 'logout'}>
          {loading ? <Icons.refresh className="spin" size={16} /> : null}
          {loading ? 'Entrando…' : 'Entrar no portal'}
        </Btn>
      </form>
      <div style={{ marginTop: 26, paddingTop: 20, borderTop: '1px solid var(--line-2)', fontSize: 12.5, color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icons.shield size={15} /> Ambiente protegido · acesso monitorado e auditado
      </div>
    </AuthShell>
  );
}

Object.assign(window, { LoginScreen });
