// ═══════════════════════════════════════════════════════════════════
// Tela de login — admin (Maria) vs visualizador (vendedor)
// ═══════════════════════════════════════════════════════════════════

function LoginScreen({ onLogin, vendedores }) {
  const { isMobile } = useMobile();
  const [tab, setTab] = useState('admin');

  // Admin
  const [email, setEmail] = useState('');
  const [senha, setSenha] = useState('');
  const [showPwd, setShowPwd] = useState(false);

  // Visualizador
  const [vendedorId, setVendedorId] = useState('');
  const [senhaVis, setSenhaVis] = useState('');
  const [showPwdVis, setShowPwdVis] = useState(false);

  const [erro, setErro] = useState('');

  const visualizadores = vendedores.filter(v => v.papel !== 'Diretora' && v.ativo);
  const vendedorSel = visualizadores.find(v => v.id === vendedorId);

  const trocarTab = (t) => { setTab(t); setErro(''); setSenha(''); setSenhaVis(''); setVendedorId(''); };

  const [carregando, setCarregando] = useState(false);

  // Retorna: 'ok' = autenticou, 'wrong' = senha errada, 'fallback' = usar senha local
  const signInFirebase = async (emailFb, senhFb) => {
    if (!window.FIREBASE_AUTH) return 'fallback';
    try {
      await window.FIREBASE_AUTH.signInWithEmailAndPassword(emailFb, senhFb);
      return 'ok';
    } catch (e) {
      if (e.code === 'auth/wrong-password' || e.code === 'auth/invalid-credential') return 'wrong';
      // user-not-found, operation-not-allowed, rede → cai no fallback local
      return 'fallback';
    }
  };

  const tentarAdmin = async () => {
    setErro('');
    if (!email || !senha) { setErro('Preencha e-mail e senha.'); return; }
    const diretor = vendedores.find(v =>
      v.email?.toLowerCase() === email.trim().toLowerCase() &&
      (v.papel === 'Diretora' || v.papel === 'Diretor')
    );
    if (!diretor) { setErro('E-mail não encontrado ou sem acesso de administrador.'); return; }
    setCarregando(true);
    const res = await signInFirebase(email.trim().toLowerCase(), senha);
    setCarregando(false);
    if (res === 'wrong') { setErro('Senha incorreta.'); return; }
    if (res === 'fallback' && senha !== (diretor.senha || 'escalab2026')) { setErro('Senha incorreta.'); return; }
    onLogin(diretor.id);
  };

  const tentarVendedor = async () => {
    setErro('');
    if (!vendedorId) { setErro('Selecione seu nome.'); return; }
    if (!senhaVis) { setErro('Digite sua senha.'); return; }
    setCarregando(true);
    const res = await signInFirebase(vendedorSel.email, senhaVis);
    setCarregando(false);
    if (res === 'wrong') { setErro('Senha incorreta.'); return; }
    if (res === 'fallback' && senhaVis !== (vendedorSel.senha || 'escalab123')) { setErro('Senha incorreta.'); return; }
    onLogin(vendedorId);
  };

  const handleKeyAdmin = (e) => { if (e.key === 'Enter') tentarAdmin(); };
  const handleKeyVis   = (e) => { if (e.key === 'Enter') tentarVendedor(); };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr', background: 'var(--escalab-paper)' }}>
      {/* Painel esquerdo — branding */}
      <div style={{ background: 'linear-gradient(160deg, #00382E 0%, #005E4D 60%, #00967B 100%)', color: '#fff', padding: isMobile ? '32px 28px' : '52px 56px', display: isMobile ? 'none' : 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -120, right: -120, width: 380, height: 380, borderRadius: '50%', background: 'radial-gradient(circle, rgba(94,233,196,.25), transparent 70%)' }} />
        <div style={{ position: 'absolute', bottom: -160, left: -100, width: 420, height: 420, borderRadius: '50%', background: 'radial-gradient(circle, rgba(94,233,196,.15), transparent 70%)' }} />

        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ color: 'var(--escalab-brand-accent)' }}><Dot /></div>
          <div>
            <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.01em' }}>Escalab</div>
            <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)' }}>Comissionamento</div>
          </div>
        </div>

        <div style={{ position: 'relative', maxWidth: 480 }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--escalab-brand-accent)', marginBottom: 18 }}>
            01 · 1T/2026 · em curso
          </div>
          <h1 style={{ color: '#fff', fontSize: 48, margin: 0, letterSpacing: '-.025em', lineHeight: 1.05 }}>
            Benefício para valorizar o impacto do seu trabalho
          </h1>
          <p style={{ color: 'rgba(255,255,255,.78)', marginTop: 18, fontSize: 15, lineHeight: 1.5 }}>
            Modelo <strong style={{ color: 'var(--escalab-brand-accent)' }}>O.T.E. — On Target Earning</strong>: remuneração disponível para vendedores de cada etapa da jornada de vendas
          </p>
        </div>

        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', gap: 28 }}>
            <div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1 }}>
                {vendedores.filter(v => v.ativo).length}
              </div>
              <div style={{ fontSize: 11.5, fontWeight: 500, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)', marginTop: 6 }}>Comissionados</div>
            </div>
            <div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1 }}>R$ 3,5 mi</div>
              <div style={{ fontSize: 11.5, fontWeight: 500, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)', marginTop: 6 }}>Meta projetos</div>
            </div>
            <div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1 }}>R$ 1,8 mi</div>
              <div style={{ fontSize: 11.5, fontWeight: 500, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)', marginTop: 6 }}>Meta editais</div>
            </div>
          </div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,.5)' }}>
            © 2026 Escalab · Comissionamento O.T.E.
          </div>
        </div>
      </div>

      {/* Painel direito — formulário */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: isMobile ? '36px 24px' : '52px 56px', background: isMobile ? 'linear-gradient(160deg, #00382E 0%, #005E4D 60%, #00967B 100%)' : 'transparent' }}>
        <div style={{ width: '100%', maxWidth: 420 }}>
          {isMobile && (
            <div style={{ marginBottom: 28, textAlign: 'center' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--escalab-brand-accent)', marginBottom: 8 }}><Dot /></div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#fff', letterSpacing: '-.01em' }}>Escalab</div>
              <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)' }}>Comissionamento O.T.E.</div>
            </div>
          )}
          <Eyebrow idx="↳" style={{ color: isMobile ? 'rgba(255,255,255,.6)' : undefined }}>Acesso ao sistema</Eyebrow>
          <h2 style={{ fontSize: 28, margin: 0, letterSpacing: '-.02em', lineHeight: 1.1, color: isMobile ? '#fff' : 'var(--escalab-ink)' }}>
            Bem-vindo de volta.
          </h2>
          <p style={{ color: isMobile ? 'rgba(255,255,255,.75)' : 'var(--escalab-slate)', fontSize: 14, marginTop: 10, marginBottom: 24 }}>
            Escolha o tipo de acesso para continuar.
          </p>

          {/* Tab toggle */}
          <div style={{ display: 'flex', background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: 4, marginBottom: 22 }}>
            {[
              { id: 'admin', label: 'Administrador', icon: 'lock' },
              { id: 'visualizador', label: 'Visualizador', icon: 'user' },
            ].map(t => (
              <button key={t.id} onClick={() => trocarTab(t.id)}
                style={{ flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '10px 14px', border: 0, borderRadius: 7, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  background: tab === t.id ? '#fff' : 'transparent',
                  color: tab === t.id ? 'var(--escalab-brand-deep)' : 'var(--escalab-slate)',
                  boxShadow: tab === t.id ? 'var(--shadow-sm)' : 'none',
                  transition: 'all .15s' }}>
                <Icon name={t.icon} size={14} />
                {t.label}
              </button>
            ))}
          </div>

          {tab === 'admin' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field label="E-mail">
                <Input value={email} onChange={setEmail} type="email" placeholder="maria@escalab.com.br" />
              </Field>
              <Field label="Senha">
                <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff', overflow: 'hidden' }}>
                  <input value={senha} onChange={e => setSenha(e.target.value)} onKeyDown={handleKeyAdmin}
                    type={showPwd ? 'text' : 'password'} placeholder="••••••••"
                    style={{ border: 0, outline: 0, flex: 1, padding: '10px 12px', fontSize: 14, fontFamily: 'inherit', background: 'transparent' }} />
                  <button type="button" onClick={() => setShowPwd(!showPwd)} style={{ border: 0, background: 'transparent', cursor: 'pointer', padding: '0 12px', color: 'var(--escalab-slate)', display: 'flex' }}>
                    <Icon name="eye" size={15} />
                  </button>
                </div>
              </Field>
              {erro && <Banner tone="warn" icon="warn">{erro}</Banner>}
              <Button variant="primary" size="lg" iconRight="send" onClick={tentarAdmin} disabled={carregando} style={{ justifyContent: 'center', width: '100%', marginTop: 4 }}>
                {carregando ? 'Verificando…' : 'Entrar como administrador'}
              </Button>
              <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', textAlign: 'center', padding: 10, background: 'var(--escalab-paper)', borderRadius: 8 }}>
                Acesso restrito à diretoria · Fale com a Maria em caso de dúvida.
              </div>
            </div>
          )}

          {tab === 'visualizador' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field label="Quem é você?">
                <Select value={vendedorId} onChange={v => { setVendedorId(v); setErro(''); setSenhaVis(''); }}
                  placeholder="Selecione seu nome…"
                  options={visualizadores.map(v => ({ value: v.id, label: v.nome + ' — ' + v.papel }))} />
              </Field>

              {vendedorSel && (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: 'var(--escalab-brand-tint)', border: '1px solid var(--escalab-brand-soft)', borderRadius: 10 }}>
                    <Avatar v={vendedorSel} size={40} />
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{vendedorSel.nome}</div>
                      <div style={{ fontSize: 12, color: 'var(--escalab-brand-deep)' }}>{vendedorSel.papel} · {vendedorSel.setor}</div>
                    </div>
                  </div>

                  <Field label="Senha">
                    <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff', overflow: 'hidden' }}>
                      <input value={senhaVis} onChange={e => setSenhaVis(e.target.value)} onKeyDown={handleKeyVis}
                        type={showPwdVis ? 'text' : 'password'} placeholder="••••••••"
                        style={{ border: 0, outline: 0, flex: 1, padding: '10px 12px', fontSize: 14, fontFamily: 'inherit', background: 'transparent' }} />
                      <button type="button" onClick={() => setShowPwdVis(!showPwdVis)} style={{ border: 0, background: 'transparent', cursor: 'pointer', padding: '0 12px', color: 'var(--escalab-slate)', display: 'flex' }}>
                        <Icon name="eye" size={15} />
                      </button>
                    </div>
                  </Field>
                </>
              )}

              {erro && <Banner tone="warn" icon="warn">{erro}</Banner>}

              <Button variant="primary" size="lg" iconRight="send" onClick={tentarVendedor}
                disabled={!vendedorId || carregando} style={{ justifyContent: 'center', width: '100%' }}>
                {carregando ? 'Verificando…' : 'Acessar meu extrato'}
              </Button>

              <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', textAlign: 'center', padding: 10, background: 'var(--escalab-paper)', borderRadius: 8 }}>
                Use sua senha pessoal · Pode alterar a qualquer momento no seu extrato.
              </div>
            </div>
          )}

          <div style={{ marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--escalab-line)', fontSize: 12, color: 'var(--escalab-mute)', textAlign: 'center' }}>
            Problemas para entrar? Fale com a Maria · comunicalab@escalab.com.br
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });
