// ── InovaPED — Comprador: Representantes ────────────────────────────────
const Topbar4 = window.BuyerParts1.Topbar;
const ICd = window.IC;
const cat4 = window.BuyerParts1.catById;

// stats mock a partir das ofertas
function repStats(rid) {
  const keys = Object.keys(ICd.OFFERS).filter(k => k.endsWith(':' + rid) && ICd.OFFERS[k] != null);
  let wins = 0, totVar = 0, n = 0;
  keys.forEach(k => {
    const pid = k.split(':')[0]; const p = ICd.PRODUCTS.find(x => x.id === pid); if (!p) return;
    const price = ICd.OFFERS[k]; totVar += ((price - p.lastCost) / p.lastCost) * 100; n++;
    if (price < p.lastCost) wins++;
  });
  return { offers: keys.length, wins, avgVar: n ? totVar / n : 0, respRate: keys.length ? Math.min(100, 60 + keys.length * 5) : 0 };
}

function Reps() {
  const [search, setSearch] = useState('');
  const [catF, setCatF] = useState('all');
  const [taxF, setTaxF] = useState('all');
  const [sortBy, setSortBy] = useState('rating');
  const [invite, setInvite] = useState(false);

  let list = ICd.REPS.filter(r =>
    (!search || r.name.toLowerCase().includes(search.toLowerCase()) || r.contact.toLowerCase().includes(search.toLowerCase())) &&
    (catF === 'all' || r.cats.includes(catF)) && (taxF === 'all' || r.tax === taxF)
  );
  list = [...list].sort((a, b) => sortBy === 'rating' ? b.rating - a.rating : sortBy === 'offers' ? repStats(b.id).offers - repStats(a.id).offers : a.name.localeCompare(b.name));

  return (
    <div>
      <Topbar4 title="Representantes" sub="Fornecedores cadastrados na Rede Inova"
        action={<button onClick={() => setInvite(true)} style={{ display:'flex',alignItems:'center',gap:8, padding: '11px 18px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 6px 20px rgba(255,19,48,0.45)' }}><Icon name="plus" size={18} color="#fff" strokeWidth={2.4} /> Convidar representante</button>} />

      {/* toolbar */}
      <Glass pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 260px', minWidth: 200 }}>
            <Icon name="search" size={16} color={T.mute} style={{ position: 'absolute', left: 12, top: 11 }} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar representante ou contato..."
              style={{ width: '100%', boxSizing: 'border-box', padding: '9px 12px 9px 38px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, outline: 'none' }} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="receipt" size={14} color={T.mute2} /><RSeg value={taxF} onChange={setTaxF} opts={[['all','Todos'],['com','c/ imp.'],['sem','s/ imp.']]} /></div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ fontSize: 12, color: T.mute2 }}>Ordenar</span><RSeg value={sortBy} onChange={setSortBy} opts={[['rating','Avaliação'],['offers','Ofertas'],['name','Nome']]} /></div>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 12 }}>
          <RChip on={catF === 'all'} onClick={() => setCatF('all')}>Todas categorias</RChip>
          {ICd.CATEGORIES.map(c => <RChip key={c.id} on={catF === c.id} onClick={() => setCatF(c.id)}>{c.name}</RChip>)}
        </div>
      </Glass>

      {/* grid de cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 14 }}>
        {list.map(r => { const st = repStats(r.id); const score = Math.min(10, r.rating/5*4 + st.respRate/100*3.5 + (st.offers ? st.wins/st.offers : 0)*2.5); const badges = (ICd.BADGES[r.id] || []); return (
          <Glass key={r.id} hover pad={18}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 13 }}>
              <div style={{ width: 48, height: 48, borderRadius: 13, background: r.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, fontSize: 19, color: '#fff', flexShrink: 0 }}>{r.name[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 15.5 }}>{r.name}</div>
                <div style={{ fontSize: 12.5, color: T.mute, marginTop: 2, display:'flex',alignItems:'center',gap:6 }}>{r.contact} · <span style={{ display:'inline-flex',alignItems:'center',gap:3 }}><Icon name="star" size={12} color="#FFC83D" /> {r.rating}</span></div>
              </div>
              <Pill tone={r.tax === 'com' ? 'mute' : 'white'} style={{ alignSelf: 'flex-start' }}>{r.tax === 'com' ? 'c/ imp.' : 's/ imp.'}</Pill>
              <div style={{ textAlign: 'center', flexShrink: 0 }}>
                <div style={{ width: 46, height: 46, borderRadius: 13, background: score >= 8 ? T.greenBg : score >= 6 ? T.yellowBg : T.redBg, border: `1.5px solid ${score >= 8 ? 'rgba(0,230,140,0.4)' : score >= 6 ? 'rgba(255,200,61,0.4)' : 'rgba(255,19,48,0.35)'}`, display:'flex',alignItems:'center',justifyContent:'center', flexDirection: 'column' }}>
                  <span style={{ fontWeight: 800, fontSize: 17, fontFamily: 'var(--display)', color: score >= 8 ? T.green : score >= 6 ? T.yellow : T.redBright, lineHeight: 1 }}>{score.toFixed(1)}</span>
                </div>
                <div style={{ fontSize: 9.5, color: T.mute2, marginTop: 3, textTransform: 'uppercase', letterSpacing: 0.5 }}>Score</div>
              </div>
            </div>

            {badges.length > 0 && <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 12 }}>
              {badges.map(b => { const bi = ICd.BADGE_INFO[b]; return <span key={b} style={{ display:'inline-flex',alignItems:'center',gap:5, padding: '4px 9px', borderRadius: 8, fontSize: 11, fontWeight: 700, background: T.panel, color: bi.color, border: `1px solid ${bi.color}40` }}><Icon name={bi.icon} size={12} color={bi.color} />{bi.label}</span>; })}
            </div>}

            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 14 }}>
              {r.cats.map(cid => { const c = cat4(cid); return <span key={cid} style={{ display:'inline-flex',alignItems:'center',gap:5, padding: '4px 10px', borderRadius: 99, fontSize: 11.5, fontWeight: 600, background: T.redBg, color: T.redBright, border: '1px solid rgba(255,19,48,0.25)' }}><Icon name={c.icon} size={12} color={T.redBright} />{c.name}</span>; })}
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${T.border}` }}>
              <St label="Ofertas" value={st.offers} />
              <St label="Melhor preço" value={st.wins} color={T.green} />
              <St label="Var. média" value={`${st.avgVar.toFixed(1)}%`} color={st.avgVar <= 0 ? T.green : T.redBright} />
            </div>
            <div style={{ marginTop: 12 }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize: 11.5, color: T.mute2, marginBottom: 5 }}><span>Taxa de resposta</span><span style={{ color: T.text, fontWeight: 700 }}>{st.respRate}%</span></div>
              <div style={{ height: 6, borderRadius: 99, background: T.panelHi, overflow: 'hidden' }}><div style={{ width: st.respRate + '%', height: '100%', background: `linear-gradient(90deg, ${T.redBright}, ${T.redDeep})` }} /></div>
            </div>
          </Glass>
        ); })}
      </div>
      {!list.length && <div style={{ textAlign: 'center', color: T.mute2, padding: 50 }}>Nenhum representante encontrado.</div>}

      {invite && <InviteModal onClose={() => setInvite(false)} />}
    </div>
  );
}

function St({ label, value, color }) {
  return <div style={{ flex: 1 }}><div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--display)', color: color || T.text }}>{value}</div><div style={{ fontSize: 11, color: T.mute2 }}>{label}</div></div>;
}
function RSeg({ value, onChange, opts }) {
  return <div style={{ display: 'flex', gap: 2, padding: 3, borderRadius: 10, background: T.panel, border: `1px solid ${T.border}` }}>
    {opts.map(([v, l]) => { const on = value === v; return <button key={v} onClick={() => onChange(v)} style={{ padding: '6px 11px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, color: on ? '#fff' : T.mute, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'transparent' }}>{l}</button>; })}
  </div>;
}
function RChip({ children, on, onClick }) {
  return <button onClick={onClick} style={{ padding: '8px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent', whiteSpace:'nowrap' }}>{children}</button>;
}

function InviteModal({ onClose }) {
  const [copied, setCopied] = useState(false);
  const link = 'https://inovaped.com.br/convite/8F3K-92AX';
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 30 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 460, borderRadius: 22, background: T.surface, border: `1px solid ${T.borderHi}`, padding: 28 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div><div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)' }}>Convidar representante</div><div style={{ fontSize: 13, color: T.mute, marginTop: 4 }}>Envie o link e ele se cadastra escolhendo as categorias.</div></div>
          <button onClick={onClose} style={{ background: T.panel, border: `1px solid ${T.border}`, borderRadius: 9, width: 34, height: 34, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={17} color={T.mute} /></button>
        </div>
        <div style={{ marginTop: 20, fontSize: 12, fontWeight: 600, color: T.mute, marginBottom: 8 }}>LINK DE CONVITE</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1, padding: '12px 14px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}`, fontSize: 13.5, color: T.text, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display:'flex',alignItems:'center' }}>{link}</div>
          <button onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }} style={{ padding: '0 18px', borderRadius: 11, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13.5, color: '#fff', background: copied ? T.green : `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',gap:6 }}>{copied ? <><Icon name="check" size={16} color="#fff" strokeWidth={3}/> Copiado</> : 'Copiar'}</button>
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <button style={{ flex: 1, display:'flex',alignItems:'center',justifyContent:'center',gap:8, padding: '12px', borderRadius: 11, border: '1px solid rgba(0,230,140,0.4)', background: 'rgba(0,230,140,0.12)', color: T.green, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13.5 }}><Icon name="whatsapp" size={17} color={T.green} /> Enviar no WhatsApp</button>
          <button style={{ flex: 1, display:'flex',alignItems:'center',justifyContent:'center',gap:8, padding: '12px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13.5 }}><Icon name="send" size={16} color={T.mute} /> Por e-mail</button>
        </div>
      </div>
    </div>
  );
}

window.BuyerParts4 = { Reps };
