// ── InovaPED — Página de Login ──────────────────────────────────────────
// card de cotação ao vivo que cicla produtos REAIS do ERP
function LiveCotacao() {
  const items = React.useMemo(() => {
    const ERP = window.ERP;
    if (!ERP || !ERP.p.length) return [{ n: 'Whey Protein 900g', fab: 'NutriMax', cu: 89.9, off: 81.9 }];
    const pool = ERP.p.filter(p => p[7] > 8 && p[15] && p[15].length).slice(0, 400);
    const picks = [];
    for (let i = 0; i < pool.length && picks.length < 6; i += Math.floor(pool.length / 6) || 1) {
      const p = pool[i]; const f = [-0.12,-0.08,-0.15,-0.06,-0.1,-0.09][picks.length % 6];
      picks.push({ n: p[2], fab: p[6], cu: p[7], off: Math.round(p[7] * (1 + f) * 100) / 100 });
    }
    return picks;
  }, []);
  const [idx, setIdx] = useState(0);
  useEffect(() => { const t = setInterval(() => setIdx(i => (i + 1) % items.length), 2600); return () => clearInterval(t); }, [items.length]);
  const it = items[idx];
  const pct = ((it.off - it.cu) / it.cu) * 100;
  return (
    <div style={{ position: 'absolute', right: 40, top: '44%', width: 264, padding: 16, borderRadius: 18, background: 'rgba(18,18,22,0.78)', border: '1px solid rgba(255,255,255,0.14)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', boxShadow: '0 24px 60px rgba(0,0,0,0.55)', animation: 'icFloat 6s ease-in-out infinite', zIndex: 3 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 12 }}>
        <span style={{ width: 7, height: 7, borderRadius: 99, background: '#00E68C', animation: 'icpulse 1.1s infinite', boxShadow: '0 0 10px #00E68C' }} />
        <span style={{ fontSize: 10.5, fontWeight: 800, color: '#00E68C', letterSpacing: 1 }}>COTAÇÃO AO VIVO</span>
        <span style={{ marginLeft: 'auto', fontSize: 9.5, color: '#5C5C63', fontWeight: 700 }}>ERP HOS</span>
      </div>
      <div key={idx} style={{ animation: 'icfade .4s ease both' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: '#F7F7F8', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.n}</div>
        <div style={{ fontSize: 11, color: '#8A8A92', marginBottom: 10 }}>{it.fab}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 11.5, color: '#8A8A92', fontWeight: 600 }}>oferta do rep</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, color: pct <= 0 ? '#00E68C' : '#FF3B54', fontWeight: 800, fontSize: 15 }}>{pct <= 0 ? '▼' : '▲'} {Math.abs(pct).toFixed(1)}%</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 4, marginTop: 12 }}>
        {items.map((_, i) => <div key={i} style={{ flex: 1, height: 3, borderRadius: 99, background: i === idx ? '#FF3B54' : 'rgba(255,255,255,0.14)', transition: 'background .3s' }} />)}
      </div>
    </div>
  );
}

// faixa rolante de preços reais
function PriceTicker() {
  const items = React.useMemo(() => {
    const ERP = window.ERP; if (!ERP || !ERP.p.length) return [];
    const pool = ERP.p.filter(p => p[7] > 5 && p[3] > 0).slice(0, 600);
    const out = [];
    for (let i = 0; i < pool.length && out.length < 16; i += Math.floor(pool.length / 16) || 1) {
      const p = pool[i]; out.push({ n: p[2].slice(0, 26), cu: p[7], mk: p[8] });
    }
    return out;
  }, []);
  if (!items.length) return null;
  const row = [...items, ...items];
  return (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 38, overflow: 'hidden', borderTop: '1px solid rgba(255,255,255,0.08)', background: 'rgba(0,0,0,0.4)', zIndex: 4, display: 'flex', alignItems: 'center' }}>
      <div style={{ display: 'flex', gap: 28, whiteSpace: 'nowrap', animation: 'icMarquee 38s linear infinite', paddingLeft: 28 }}>
        {row.map((it, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 11.5, color: '#A0A0A8' }}>
            <span style={{ width: 5, height: 5, borderRadius: 99, background: '#FF3B54' }} />
            <span style={{ color: '#D8D8DC', fontWeight: 600 }}>{it.n}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function Login({ onLogin }) {
  const [role, setRole] = useState('buyer');
  const [email, setEmail] = useState(role === 'buyer' ? 'felipe@redeinova.com.br' : 'rodrigo@nutrimax.com.br');
  const [pass, setPass] = useState('');
  const [remember, setRemember] = useState(true);
  const [show, setShow] = useState(false);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const [showSignup, setShowSignup] = useState(false);

  const pickRole = (r) => { setRole(r); setEmail(r === 'buyer' ? 'felipe@redeinova.com.br' : 'rodrigo@nutrimax.com.br'); };
  const submit = async () => {
    if (loading) return;
    setErr(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, senha: pass }) });
      const data = await r.json();
      if (!r.ok) { setErr(data.error || 'Falha no login'); setLoading(false); return; }
      const store = remember ? window.localStorage : window.sessionStorage;
      store.setItem('inovaped.token', data.token);
      store.setItem('inovaped.user', JSON.stringify(data.user));
      window.__inovaped_token = data.token;
      window.__inovaped_user = data.user;
      if (window.ICLive) { try { await window.ICLive.loadAll(); } catch (e) {} } // popula IC com dados vivos
      onLogin(data.modulo); // 'buyer' ou 'rep' decidido pelo papel real do usuário
    } catch (e) {
      setErr('Servidor indisponível. Tente novamente.'); setLoading(false);
    }
  };
  const onKey = (e) => { if (e.key === 'Enter') submit(); };

  const features = role === 'buyer'
    ? [['chart','Dashboard de performance em tempo real'],['table','Grade comparativa com economia automática'],['box','24.830 produtos reais sincronizados do ERP HOS']]
    : [['tag','Cote por preço, faixa de quantidade e combos'],['receipt','Declare com / sem imposto num toque'],['bell','Receba avisos de cotação dentro do sistema']];

  return (
    <div style={{ height: '100%', display: 'flex', background: '#060607', color: '#F7F7F8', overflow: 'hidden' }}>
      {/* HERO marca */}
      <div style={{ flex: '1.1 1 0', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '54px 56px' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(80% 60% at 15% 10%, rgba(255,19,48,0.30), transparent 55%), radial-gradient(70% 70% at 90% 90%, rgba(192,0,22,0.26), transparent 60%), #08080A' }} />
        <div style={{ position: 'absolute', inset: 0, opacity: 0.5, background: 'repeating-linear-gradient(115deg, transparent 0 38px, rgba(255,255,255,0.018) 38px 39px)' }} />
        {/* glow blobs */}
        <div style={{ position: 'absolute', width: 460, height: 460, borderRadius: '50%', left: -120, top: 120, background: 'radial-gradient(circle, rgba(255,19,48,0.32), transparent 70%)', filter: 'blur(44px)', animation: 'icFloat 7s ease-in-out infinite, icGlow 4.5s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', width: 320, height: 320, borderRadius: '50%', right: -60, top: -40, background: 'radial-gradient(circle, rgba(192,0,22,0.36), transparent 70%)', filter: 'blur(52px)', animation: 'icFloat 9s ease-in-out infinite reverse, icGlow 6s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', width: 240, height: 240, borderRadius: '50%', right: 120, bottom: 60, background: 'radial-gradient(circle, rgba(255,59,84,0.26), transparent 70%)', filter: 'blur(48px)', animation: 'icFloat 11s ease-in-out infinite, icGlow 5s ease-in-out infinite' }} />
        {/* card cotação ao vivo — produtos reais rotativos */}
        <LiveCotacao />

        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 13 }}>
          <img src="assets/logo.png" alt="InovaPED" style={{ width: '78%', maxWidth: 430, objectFit: 'contain', filter: 'drop-shadow(0 8px 30px rgba(255,19,48,0.4))', animation: 'icFloat 9s ease-in-out infinite' }} />
        </div>

        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: T.redBright, letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 16, animation: 'icUp .5s cubic-bezier(.2,.8,.2,1) both', animationDelay: '.05s' }}>Cotação inteligente</div>
          <h1 style={{ margin: 0, fontSize: 52, lineHeight: 1.02, fontWeight: 700, letterSpacing: -1.5, fontFamily: 'var(--display)', animation: 'icUp .6s cubic-bezier(.2,.8,.2,1) both', animationDelay: '.12s' }}>O melhor preço<br/>dos seus reps,<br/><span style={{ color: T.red }}>num só lugar.</span></h1>
          <p style={{ color: '#8A8A92', fontSize: 16, lineHeight: 1.55, maxWidth: 440, marginTop: 20, animation: 'icUp .6s cubic-bezier(.2,.8,.2,1) both', animationDelay: '.2s' }}>Dispare cotações por categoria, compare ofertas com economia calculada na hora e feche o pedido nos melhores preços da rede.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 30 }}>
            {features.map(([ic, txt], i) => (
              <div key={txt} style={{ display: 'flex', alignItems: 'center', gap: 12, animation: 'icUp .5s cubic-bezier(.2,.8,.2,1) both', animationDelay: (0.3 + i * 0.09) + 's' }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,19,48,0.14)', border: '1px solid rgba(255,19,48,0.3)', display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={ic} size={17} color={T.redBright} /></div>
                <span style={{ fontSize: 14.5, color: '#D8D8DC' }}>{txt}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ position: 'relative', display: 'flex', gap: 34 }}>
          {[['24.830','produtos reais'],['90+','fornecedores'],['5','representantes']].map(([v, l], i) => (
            <div key={l} style={{ animation: 'icUp .6s cubic-bezier(.2,.8,.2,1) both', animationDelay: (0.55 + i * 0.1) + 's' }}><div style={{ fontWeight: 800, fontSize: 24, fontFamily: 'var(--display)' }}>{v}</div><div style={{ fontSize: 12, color: '#8A8A92' }}>{l}</div></div>
          ))}
        </div>
        <PriceTicker />
      </div>

      {/* FORM */}
      <div style={{ flex: '0.9 1 0', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40, borderLeft: `1px solid ${'rgba(255,255,255,0.10)'}`, background: 'rgba(0,0,0,0.3)' }}>
        <div style={{ width: '100%', maxWidth: 380, animation: 'icRight .55s cubic-bezier(.2,.8,.2,1) both', animationDelay: '.15s' }}>
          <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.5 }}>Entrar</div>
          <div style={{ color: '#8A8A92', fontSize: 14, marginTop: 6 }}>Inova Drogaria · Muriaé/MG</div>

          {/* perfil */}
          <div style={{ marginTop: 24, fontSize: 12, fontWeight: 600, color: '#8A8A92', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Entrar como</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[['buyer','Comprador','chart'],['rep','Representante','user']].map(([r, label, ic]) => {
              const on = role === r;
              return <button key={r} onClick={() => pickRole(r)} style={{ flex: 1, display:'flex',flexDirection:'column',alignItems:'center',gap:6, padding: '14px', borderRadius: 13, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, border: `1.5px solid ${on ? T.red : 'rgba(255,255,255,0.10)'}`, color: on ? '#fff' : '#F7F7F8', background: on ? 'rgba(255,19,48,0.15)' : 'rgba(255,255,255,0.045)' }}>
                <Icon name={ic} size={20} color={on ? T.redBright : '#8A8A92'} /> {label}
              </button>;
            })}
          </div>

          {/* email */}
          <div style={{ marginTop: 18 }}>
            <label style={loLbl}>E-mail</label>
            <div style={{ position: 'relative' }}>
              <Icon name="user" size={16} color={'#5C5C63'} style={{ position: 'absolute', left: 13, top: 14 }} />
              <input value={email} onChange={e => setEmail(e.target.value)} style={{ ...loIn, paddingLeft: 40 }} />
            </div>
          </div>
          {/* senha */}
          <div style={{ marginTop: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <label style={loLbl}>Senha</label>
              <a href="#" onClick={e => e.preventDefault()} style={{ fontSize: 12, color: T.redBright, textDecoration: 'none', fontWeight: 600 }}>Esqueci a senha</a>
            </div>
            <div style={{ position: 'relative' }}>
              <Icon name="shield" size={16} color={'#5C5C63'} style={{ position: 'absolute', left: 13, top: 14 }} />
              <input type={show ? 'text' : 'password'} value={pass} onChange={e => setPass(e.target.value)} onKeyDown={onKey} placeholder="sua senha" style={{ ...loIn, paddingLeft: 40, paddingRight: 44 }} />
              <button onClick={() => setShow(v => !v)} style={{ position: 'absolute', right: 8, top: 8, width: 30, height: 30, borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: '#8A8A92', fontSize: 11, fontWeight: 700 }}>{show ? 'Ocultar' : 'Ver'}</button>
            </div>
          </div>

          <label style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 16, cursor: 'pointer', fontSize: 13, color: '#8A8A92' }}>
            <span onClick={() => setRemember(v => !v)} style={{ width: 19, height: 19, borderRadius: 6, border: `1.5px solid ${remember ? T.red : 'rgba(255,255,255,0.18)'}`, background: remember ? T.red : 'transparent', display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}>{remember && <Icon name="check" size={12} color="#fff" strokeWidth={3} />}</span>
            Manter conectado
          </label>

          <button onClick={submit} disabled={loading} style={{ width: '100%', marginTop: 22, padding: '15px', borderRadius: 13, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 15.5, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 4px 14px rgba(255,19,48,0.3)', display:'flex',alignItems:'center',justifyContent:'center',gap:9 }}>
            {loading ? <Spinner /> : <>Entrar <Icon name="chevron" size={18} color="#fff" strokeWidth={2.4} /></>}
          </button>

          <div style={{ marginTop: 18, paddingTop: 18, borderTop: `1px solid ${'rgba(255,255,255,0.10)'}`, textAlign: 'center', fontSize: 13, color: '#8A8A92' }}>
            É <b style={{color:T.text}}>representante</b> e ainda não tem conta? <a href="#" onClick={e => { e.preventDefault(); setShowSignup(true); }} style={{ color: T.redBright, textDecoration: 'none', fontWeight: 700 }}>Cadastre-se</a>
          </div>
          <div style={{ marginTop: 18, fontSize: 11, color: '#5C5C63', textAlign: 'center' }}>InovaPED · Rede Inova Drogarias · Muriaé/MG</div>
          <div style={{ marginTop: 8, fontSize: 11, color: '#46464D', textAlign: 'center' }}>Desenvolvido por Nicolas Silva dos Santos</div>
        </div>
      </div>
      {showSignup && <RepSignupModal onClose={() => setShowSignup(false)} />}
    </div>
  );
}

// ── Cadastro de REPRESENTANTE (auto-cadastro → pendente de aprovação) ─────────
function RepSignupModal({ onClose }) {
  const [f, setF] = useState({ nome: '', email: '', senha: '', empresa: '', telefone: '' });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);
  const enviar = async () => {
    if (busy) return; setErr('');
    if (!f.nome || !f.email || !f.senha) { setErr('Preencha nome, e-mail e senha'); return; }
    setBusy(true);
    try {
      const r = await fetch('/api/auth/signup-rep', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(f) });
      const data = await r.json();
      if (!r.ok) { setErr(data.error || 'Falha no cadastro'); setBusy(false); return; }
      setDone(true);
    } catch (e) { setErr('Servidor indisponível'); }
    setBusy(false);
  };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '12px 13px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none', marginBottom: 10 };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.66)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 300, padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 440, maxWidth: '100%', borderRadius: 20, background: T.surface, border: `1px solid ${T.borderHi}`, boxShadow: '0 30px 90px rgba(0,0,0,0.7)', padding: 26 }}>
        {done ? (
          <div style={{ textAlign: 'center' }}>
            <div style={{ width: 60, height: 60, borderRadius: 999, background: T.greenBg, border: `1px solid rgba(0,230,140,0.4)`, display:'flex',alignItems:'center',justifyContent:'center', margin: '0 auto 16px' }}><Icon name="check" size={30} color={T.green} strokeWidth={2.4} /></div>
            <div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)' }}>Cadastro enviado!</div>
            <div style={{ color: T.mute, fontSize: 14, marginTop: 8, lineHeight: 1.5 }}>Sua conta de representante está <b style={{color:T.text}}>aguardando aprovação</b> da Rede Inova. Você poderá entrar assim que for liberado.</div>
            <button onClick={onClose} style={{ marginTop: 20, padding: '12px 28px', borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}>Entendi</button>
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
              <div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)' }}>Cadastro de Representante</div>
              <button onClick={onClose} style={{ background: T.panel, border: `1px solid ${T.border}`, borderRadius: 9, width: 32, height: 32, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={16} color={T.mute} /></button>
            </div>
            <div style={{ color: T.mute, fontSize: 13, marginBottom: 18 }}>Passa por aprovação da Rede Inova antes de liberar o acesso.</div>
            <input value={f.nome} onChange={e => setF({ ...f, nome: e.target.value })} placeholder="Seu nome *" style={inp} />
            <input value={f.empresa} onChange={e => setF({ ...f, empresa: e.target.value })} placeholder="Empresa / distribuidora" style={inp} />
            <input value={f.email} onChange={e => setF({ ...f, email: e.target.value })} placeholder="E-mail *" style={inp} />
            <input value={f.telefone} onChange={e => setF({ ...f, telefone: e.target.value })} placeholder="Telefone / WhatsApp" style={inp} />
            <input type="password" value={f.senha} onChange={e => setF({ ...f, senha: e.target.value })} placeholder="Senha *" style={inp} />
            {err && <div style={{ color: T.redBright, fontSize: 12.5, fontWeight: 600, marginBottom: 8 }}>{err}</div>}
            <button onClick={enviar} disabled={busy} style={{ width: '100%', marginTop: 6, padding: '14px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 15, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, opacity: busy ? 0.6 : 1 }}>{busy ? 'Enviando…' : 'Criar conta de representante'}</button>
          </>
        )}
      </div>
    </div>
  );
}
const loLbl = { display: 'block', fontSize: 12, fontWeight: 600, color: '#8A8A92', marginBottom: 7 };
const loIn = { width: '100%', boxSizing: 'border-box', padding: '13px 14px', borderRadius: 11, border: `1px solid ${'rgba(255,255,255,0.10)'}`, background: 'rgba(0,0,0,0.35)', color: '#F7F7F8', fontFamily: 'inherit', fontSize: 14, outline: 'none' };
function Spinner() {
  return <span style={{ width: 18, height: 18, borderRadius: 99, border: '2.5px solid rgba(255,255,255,0.35)', borderTopColor: '#fff', display: 'inline-block', animation: 'icspin 0.7s linear infinite' }} />;
}

window.Login = Login;
