// ── InovaPED — Central de Promoções + Agente de IA ──────────────────────
// Reps mandam promoções diárias (foto/PDF/planilha/texto). A IA cruza com o
// custo REAL do ERP e diz se vale a pena. Usa window.ERP + window.IC.REPS.
const TopbarP = window.BuyerParts1.Topbar;

const PROMO_REPS = (window.IC && window.IC.REPS) ? window.IC.REPS : [];
const attachMeta = {
  foto:     { icon: 'box',     label: 'Foto da tabela', tint: '#4EA8DE' },
  pdf:      { icon: 'receipt', label: 'PDF',            tint: '#FF1330' },
  planilha: { icon: 'table',   label: 'Planilha',       tint: '#00935A' },
  texto:    { icon: 'send',    label: 'Texto',          tint: '#A8730A' },
};

// monta promoções do dia a partir de produtos REAIS do ERP
function buildPromos() {
  const ERP = window.ERP; if (!ERP || !ERP.p.length) return [];
  // pega produtos variados com custo conhecido
  const pool = ERP.p.filter(p => p[PIDX.cu] > 3 && p[PIDX.h].length).slice(0, 600);
  const pick = [];
  const step = Math.max(1, Math.floor(pool.length / 40));
  for (let i = 0; i < pool.length && pick.length < 22; i += step) pick.push(pool[i]);
  const reps = PROMO_REPS.length ? PROMO_REPS : [{ id:'r1', name:'Rep', lab:'—', color:'#FF1330', tax:'sem' }];
  const attachTypes = ['foto','pdf','planilha','texto','foto','planilha'];
  const chans = ['whatsapp','whatsapp','inova','whatsapp','inova'];
  const times = ['08:12','08:40','09:05','09:31','10:02','10:18','11:00','11:27','12:10','13:05','13:44','14:20','15:02','15:39','16:11','16:48','17:20','17:55','18:10','18:33','18:50','19:05'];
  // variação determinística do preço ofertado vs custo real
  const factors = [-0.18,-0.12,-0.09,-0.06,-0.04,-0.02,0.01,0.03,0.06,-0.15,-0.08,0.04,-0.11,-0.05,0.02,-0.07,-0.21,0.05,-0.03,-0.10,-0.06,0.08];
  return pick.map((p, i) => {
    const realCost = p[PIDX.cu];
    const offered = Math.round(realCost * (1 + factors[i % factors.length]) * 100) / 100;
    const rep = reps[i % reps.length];
    const qty = [50,100,30,200,80,120,60,150][i % 8];
    const validM = ['08/2026','11/2026','06/2026','03/2027','12/2026','09/2026'][i % 6];
    return {
      id: 'promo' + i, p, rep, offered, realCost,
      delta: ((offered - realCost) / realCost) * 100,
      channel: chans[i % chans.length], attach: attachTypes[i % attachTypes.length],
      time: times[i % times.length], qty, valid: validM, est: p[PIDX.est],
    };
  });
}

// verdade da IA
function aiVerdict(promo) {
  const d = promo.delta;
  const inStock = promo.est > 0;
  if (d <= -8) return { tone: 'green', score: 9 + Math.min(1, (-d-8)/10), label: 'Comprar já', note: `Preço ${Math.abs(d).toFixed(1)}% abaixo do seu último custo real. Oportunidade forte.` };
  if (d <= -3) return { tone: 'green', score: 7.5, label: 'Vale a pena', note: `${Math.abs(d).toFixed(1)}% abaixo do custo. ${inStock ? 'Você tem estoque — repor no preço bom.' : 'Produto sem estoque, bom momento.'}` };
  if (d < 3)  return { tone: 'yellow', score: 5.5, label: 'Neutro', note: 'Praticamente no mesmo custo. Negociar prazo ou bonificação.' };
  return { tone: 'red', score: 3, label: 'Acima do custo', note: `${d.toFixed(1)}% acima do seu último custo. Recusar ou contraproposta.` };
}

function PromoIA() {
  const promos = useMemo(() => buildPromos(), []);
  const [filter, setFilter] = useState('all'); // all | green | red
  const [sel, setSel] = useState(null);
  const withV = promos.map(p => ({ ...p, v: aiVerdict(p) }));
  const list = withV.filter(p => filter === 'all' || (filter === 'green' && p.v.tone === 'green') || (filter === 'red' && p.v.tone === 'red'));

  const greenN = withV.filter(p => p.v.tone === 'green').length;
  const econ = withV.filter(p => p.v.tone === 'green').reduce((a, p) => a + (p.realCost - p.offered) * p.qty, 0);

  return (
    <div>
      <TopbarP title="Promoções & Agente IA" sub="Os reps enviam promoções do dia · a IA cruza com seu custo real e recomenda"
        action={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: T.mute2 }}><Icon name="shield" size={13} color={T.mute2} /> Só comprador</span>} />

      {/* AGENTE IA — resumo */}
      <Glass style={{ marginBottom: 16, background: 'linear-gradient(135deg, rgba(255,19,48,0.10), rgba(255,19,48,0.02))' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ width: 54, height: 54, borderRadius: 15, background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center', boxShadow: '0 8px 24px rgba(255,19,48,0.4)', flexShrink: 0 }}><Icon name="sparkle" size={28} color="#fff" /></div>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display:'flex', alignItems:'center', gap: 8, marginBottom: 3 }}><span style={{ fontWeight: 800, fontSize: 16, fontFamily: 'var(--display)' }}>Agente IA InovaPED</span><span className="ruptdot" style={{ width: 7, height: 7, borderRadius: 99, background: T.green }} /><span style={{ fontSize: 11.5, color: T.green, fontWeight: 700 }}>ativo</span></div>
            <div style={{ fontSize: 13.5, color: T.text, lineHeight: 1.5 }}>Analisei <b>{promos.length} promoções</b> recebidas hoje (foto, PDF, planilha e texto). Encontrei <b style={{ color: T.green }}>{greenN} oportunidades</b> abaixo do seu custo real, com economia potencial de <b style={{ color: T.green }}>R$ {fmtBRL(econ)}</b>. Recomendo priorizar as marcadas como <b style={{ color: T.green }}>"Comprar já"</b>.</div>
          </div>
          <button style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 18px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, flexShrink: 0 }}><Icon name="plus" size={17} color="#fff" strokeWidth={2.4} /> Cotar oportunidades</button>
        </div>
      </Glass>

      {/* KPIs + filtro */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}>
        <Glass pad={16}><div style={{ fontSize: 12, color: T.mute }}>Promoções hoje</div><div style={{ fontSize: 23, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{promos.length}</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ display:'flex',alignItems:'center',gap:6, fontSize: 12, color: T.mute }}><span style={{color:T.green}}>▼</span> Valem a pena</div><div style={{ fontSize: 23, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>{greenN}</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ fontSize: 12, color: T.mute }}>Economia potencial</div><div style={{ fontSize: 23, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>R$ {(econ/1000).toLocaleString('pt-BR',{maximumFractionDigits:1})}k</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ fontSize: 12, color: T.mute }}>Canais</div><div style={{ fontSize: 23, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4, display:'flex',alignItems:'center',gap:8 }}><Icon name="whatsapp" size={20} color="#25D366" /><Icon name="bolt" size={18} color={T.redBright} /></div></Glass>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
        {[['all','Todas'],['green','▼ Oportunidades'],['red','▲ Acima do custo']].map(([id,l]) => { const on = filter === id; const tc = id==='green'?T.green:id==='red'?T.redBright:T.text; return (
          <button key={id} onClick={() => setFilter(id)} style={{ padding: '8px 15px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, border: `1px solid ${on ? T.borderHi : T.border}`, color: on ? tc : T.mute, background: on ? T.panelHi : 'transparent' }}>{l}</button>
        ); })}
      </div>

      {/* feed de promoções */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 14 }}>
        {list.map(promo => <PromoCard key={promo.id} promo={promo} onOpen={() => setSel(promo)} />)}
      </div>

      {sel && <PromoDetail promo={sel} onClose={() => setSel(null)} />}
    </div>
  );
}

function PromoCard({ promo, onOpen }) {
  const v = promo.v;
  const tone = v.tone === 'green' ? T.green : v.tone === 'red' ? T.redBright : T.yellow;
  const toneBg = v.tone === 'green' ? T.greenBg : v.tone === 'red' ? T.redBg : T.yellowBg;
  const am = attachMeta[promo.attach];
  const ch = promo.channel === 'whatsapp' ? { n:'WhatsApp', c:'#25D366', i:'whatsapp' } : { n:'InovaPED', c:T.redBright, i:'bolt' };
  return (
    <Glass hover pad={0} onClick={onOpen} style={{ overflow: 'hidden', cursor: 'pointer' }}>
      <div style={{ padding: '13px 15px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${T.border}` }}>
        <div style={{ width: 34, height: 34, borderRadius: 99, background: promo.rep.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, color: '#fff', fontSize: 14, flexShrink: 0 }}>{promo.rep.name[0]}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{promo.rep.name}</div>
          <div style={{ fontSize: 11, color: T.mute2, display:'flex', alignItems:'center', gap: 5 }}><Icon name={ch.i} size={11} color={ch.c} />{ch.n} · {promo.time}</div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 99, fontSize: 10.5, fontWeight: 700, color: am.tint, background: am.tint + '1A', border: `1px solid ${am.tint}44` }}><Icon name={am.icon} size={11} color={am.tint} />{am.label}</span>
      </div>
      <div style={{ padding: 15 }}>
        <div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.25, marginBottom: 2 }}>{promo.p[PIDX.n]}</div>
        <div style={{ fontSize: 11.5, color: T.mute2 }}>{promo.p[PIDX.fab]} · {promo.rep.tax === 'com' ? 'c/ imposto' : 's/ imposto'} · val. {promo.valid}</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginTop: 12 }}>
          <div><div style={{ fontSize: 10.5, color: T.mute2 }}>Ofertado</div><div style={{ fontSize: 20, fontWeight: 800, fontFamily: 'var(--display)', fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(promo.offered)}</div></div>
          <div><div style={{ fontSize: 10.5, color: T.mute2 }}>Seu custo</div><div style={{ fontSize: 13, color: T.mute, fontVariantNumeric: 'tabular-nums', paddingBottom: 3 }}>R$ {fmtBRL(promo.realCost)}</div></div>
          <div style={{ marginLeft: 'auto', paddingBottom: 2 }}><span style={{ display:'inline-flex', alignItems:'center', gap:3, fontWeight: 800, fontSize: 14, color: promo.delta <= 0 ? T.green : T.redBright, fontVariantNumeric:'tabular-nums' }}>{promo.delta <= 0 ? '▼' : '▲'} {Math.abs(promo.delta).toFixed(1)}%</span></div>
        </div>
        {/* veredito IA */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 13, padding: '10px 12px', borderRadius: 11, background: toneBg, border: `1px solid ${tone}44` }}>
          <Icon name="sparkle" size={15} color={tone} />
          <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 800, fontSize: 12.5, color: tone }}>{v.label}</div><div style={{ fontSize: 11, color: T.mute, lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v.note}</div></div>
          <div style={{ textAlign: 'center', flexShrink: 0 }}><div style={{ fontSize: 16, fontWeight: 800, color: tone, fontFamily: 'var(--display)' }}>{v.score.toFixed(1)}</div><div style={{ fontSize: 8.5, color: T.mute2 }}>IA</div></div>
        </div>
      </div>
    </Glass>
  );
}

function PromoDetail({ promo, onClose }) {
  const v = promo.v || aiVerdict(promo);
  const tone = v.tone === 'green' ? T.green : v.tone === 'red' ? T.redBright : T.yellow;
  const hist = promo.p[PIDX.h] || [];
  const sup = (i) => (window.ERP.s[i] || ['—',''])[0];
  const series = [...hist].reverse().map(h => h[1]).filter(x => x > 0);
  const am = attachMeta[promo.attach];
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.62)', backdropFilter: 'blur(7px)', zIndex: 200, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(620px, 96vw)', height: '100%', overflow: 'auto', background: `linear-gradient(180deg, ${T.surface}, ${T.bg})`, borderLeft: `1px solid ${T.borderHi}`, boxShadow: '-30px 0 80px rgba(0,0,0,0.6)', animation: 'icRight .3s cubic-bezier(.2,.8,.2,1) both' }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 5, padding: '18px 22px', background: T.surface, borderBottom: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <div style={{ width: 38, height: 38, borderRadius: 99, background: promo.rep.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, color: '#fff' }}>{promo.rep.name[0]}</div>
            <div><div style={{ fontWeight: 700, fontSize: 14.5 }}>{promo.rep.name}</div><div style={{ fontSize: 11.5, color: T.mute }}>{promo.rep.lab} · {promo.time}</div></div>
          </div>
          <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={18} color={T.mute} /></button>
        </div>
        <div style={{ padding: 22 }}>
          {/* anexo simulado */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 16 }}>
            <div style={{ width: 46, height: 46, borderRadius: 11, background: am.tint + '22', display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={am.icon} size={22} color={am.tint} /></div>
            <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 13.5 }}>{am.label} recebido{promo.attach === 'foto' ? 'a' : ''}</div><div style={{ fontSize: 11.5, color: T.mute }}>A IA leu o documento e extraiu o produto e o preço automaticamente.</div></div>
            <Pill tone="green"><Icon name="check" size={11} color={T.green} strokeWidth={3} /> lido pela IA</Pill>
          </div>

          <div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--display)', lineHeight: 1.2 }}>{promo.p[PIDX.n]}</div>
          <div style={{ fontSize: 12.5, color: T.mute, marginTop: 4 }}>{promo.p[PIDX.fab]} · EAN {promo.p[PIDX.ean]} · cód {promo.p[PIDX.c]}</div>

          {/* veredito IA grande */}
          <div style={{ display: 'flex', gap: 14, alignItems: 'center', padding: 16, borderRadius: 15, background: (v.tone==='green'?T.greenBg:v.tone==='red'?T.redBg:T.yellowBg), border: `1px solid ${tone}55`, margin: '16px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: tone + '22', display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><span style={{ fontSize: 20, fontWeight: 800, color: tone, fontFamily: 'var(--display)', lineHeight: 1 }}>{v.score.toFixed(1)}</span><span style={{ fontSize: 8.5, color: T.mute2 }}>nota IA</span></div>
            <div style={{ flex: 1 }}><div style={{ display:'flex', alignItems:'center', gap: 7 }}><Icon name="sparkle" size={16} color={tone} /><span style={{ fontWeight: 800, fontSize: 15, color: tone }}>{v.label}</span></div><div style={{ fontSize: 13, color: T.text, marginTop: 4, lineHeight: 1.45 }}>{v.note}</div></div>
          </div>

          {/* comparativo preço */}
          <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
            <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}` }}><div style={{ fontSize: 11, color: T.mute2 }}>Preço ofertado</div><div style={{ fontSize: 20, fontWeight: 800, fontFamily: 'var(--display)' }}>R$ {fmtBRL(promo.offered)}</div><div style={{ fontSize: 10.5, color: T.mute2 }}>{promo.rep.tax === 'com' ? 'c/ imposto' : 's/ imposto'} · {promo.qty}un</div></div>
            <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}` }}><div style={{ fontSize: 11, color: T.mute2 }}>Seu último custo</div><div style={{ fontSize: 20, fontWeight: 800, fontFamily: 'var(--display)', color: T.mute }}>R$ {fmtBRL(promo.realCost)}</div><div style={{ fontSize: 10.5, color: T.mute2 }}>ERP HOS</div></div>
            <div style={{ flex: 1, padding: 14, borderRadius: 13, background: (promo.delta<=0?T.greenBg:T.redBg), border: `1px solid ${(promo.delta<=0?T.green:T.redBright)}44` }}><div style={{ fontSize: 11, color: T.mute2 }}>Diferença</div><div style={{ fontSize: 20, fontWeight: 800, fontFamily: 'var(--display)', color: promo.delta<=0?T.green:T.redBright }}>{promo.delta<=0?'▼':'▲'} {Math.abs(promo.delta).toFixed(1)}%</div><div style={{ fontSize: 10.5, color: T.mute2 }}>economia R$ {fmtBRL(Math.max(0,(promo.realCost-promo.offered)*promo.qty))}</div></div>
          </div>

          {series.length > 1 && <div style={{ marginBottom: 16 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, marginBottom: 8 }}>Seu histórico de custo</div>
            <Glass pad={14}><div style={{ height: 70 }}><SparkLine data={series} w={520} h={70} color={series[series.length-1] >= series[0] ? T.redBright : T.green} /></div>
              <div style={{ fontSize: 11, color: T.mute2, marginTop: 6 }}>Última compra de {sup(hist[0][3])} a R$ {fmtBRL(hist[0][1])}</div>
            </Glass>
          </div>}

          <div style={{ display: 'flex', gap: 10 }}>
            <button style={{ flex: 1, padding: '13px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="plus" size={17} color="#fff" strokeWidth={2.4} /> Adicionar à cotação</button>
            <button style={{ padding: '13px 16px', borderRadius: 12, border: `1px solid ${T.border}`, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 14, color: T.text, background: T.panel }}>Responder</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.BuyerPromo = { PromoIA };
