// ── Inova Cotação — DASHBOARD 100x (movimento + cor + dados reais do ERP) ──
// Sobrescreve BuyerParts1.Dashboard. Usa window.ERPSTATS (agregados reais),
// window.ERP (catálogo) e window.IC (cotações/ofertas). Nomes prefixados "dx".
const dxIC = window.IC;
const dxS  = window.ERPSTATS || { total:0, lines:0, totalQtd:0, months:[], sups:[], cats:[], buckets:{}, avgTicket:0 };

const DX_CATC = { med:'#FF3B54', sup:'#FF6B57', gen:'#FFA56B', derm:'#C77DFF', hig:'#4EA8DE', baby:'#FF4D6D', out:'#8A8A92' };
const DX_CATN = { med:'Medicamentos', sup:'Suplementos', gen:'Genéricos', derm:'Dermocosméticos', hig:'Higiene', baby:'Mamãe & Bebê', out:'Outros' };
const DX_MONN = { '01':'Jan','02':'Fev','03':'Mar','04':'Abr','05':'Mai','06':'Jun','07':'Jul','08':'Ago','09':'Set','10':'Out','11':'Nov','12':'Dez' };

function dxA(hex, a) {
  const h = (hex || '#888').replace('#','');
  const f = h.length === 3 ? h.split('').map(c => c + c).join('') : h;
  const n = parseInt(f, 16);
  return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`;
}
const dxBRL  = (n) => 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const dxM    = (n) => 'R$ ' + (n/1e6).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + 'M';
const dxK    = (n) => 'R$ ' + (n/1e3).toLocaleString('pt-BR', { maximumFractionDigits: 0 }) + 'k';
const dxNum  = (n) => n.toLocaleString('pt-BR');

// ── live clock (movimento) ──────────────────────────────────────────────
function DxClock() {
  const [t, setT] = React.useState(new Date());
  React.useEffect(() => { const id = setInterval(() => setT(new Date()), 1000); return () => clearInterval(id); }, []);
  const p = (x) => String(x).padStart(2, '0');
  return (
    <span style={{ fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums', letterSpacing: 0.5 }}>
      {p(t.getHours())}:{p(t.getMinutes())}:{p(t.getSeconds())}
    </span>
  );
}

// ── ponto "ao vivo" pulsante ────────────────────────────────────────────
function DxLiveDot({ color }) {
  const c = color || T.green;
  return (
    <span style={{ position: 'relative', width: 8, height: 8, display: 'inline-block' }}>
      <span style={{ position: 'absolute', inset: 0, borderRadius: 99, background: c }} />
      <span style={{ position: 'absolute', inset: 0, borderRadius: 99, background: c, animation: 'dxPing 1.8s ease-out infinite' }} />
    </span>
  );
}

window.DxBits = { dxIC, dxS, DX_CATC, DX_CATN, DX_MONN, dxA, dxBRL, dxM, dxK, dxNum, DxClock, DxLiveDot };

// ── KPI card rico (cor + spark + delta) ─────────────────────────────────
function DxStat({ label, value, prefix='', suffix='', decimals=0, delta, icon, color, spark, foot }) {
  const c = color || T.red;
  return (
    <Glass pad={18} hover style={{ position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: `linear-gradient(90deg, ${c}, ${dxA(c,0)})` }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ fontSize: 12.5, color: T.mute, fontWeight: 600 }}>{label}</div>
        <div style={{ width: 32, height: 32, borderRadius: 9, background: dxA(c, 0.15), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={16} color={c} />
        </div>
      </div>
      <div style={{ fontSize: 27, fontWeight: 800, marginTop: 11, fontFamily: 'var(--display)', letterSpacing: -0.5 }}>
        <CountUp value={value} prefix={prefix} suffix={suffix} decimals={decimals} />
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 7, gap: 8, minHeight: 22 }}>
        <div style={{ fontSize: 11.5, color: T.mute2, display: 'flex', alignItems: 'center', gap: 6 }}>
          {delta != null && <Delta pct={delta} size={11} />}{foot}
        </div>
        {spark && <SparkLine data={spark} color={c} w={72} h={22} />}
      </div>
    </Glass>
  );
}

// ── Área animada de compras mensais (dados reais) ───────────────────────
function DxArea({ months, accent }) {
  const ac = accent || T.red;
  const data = months.map(m => ({ lbl: DX_MONN[m.ym.slice(5)] || m.ym, t: m.t, c: m.c }));
  const W = 640, H = 230, padX = 16, padT = 26, padB = 34;
  const max = Math.max(...data.map(d => d.t), 1) * 1.12;
  const xs = i => padX + (data.length === 1 ? (W - padX*2)/2 : (i/(data.length-1))*(W - padX*2));
  const ys = v => H - padB - (v/max)*(H - padB - padT);
  const pts = data.map((d,i) => [xs(i), ys(d.t)]);
  const line = pts.map((p,i) => (i?'L':'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = line + ` L ${xs(data.length-1).toFixed(1)} ${H-padB} L ${xs(0).toFixed(1)} ${H-padB} Z`;
  const gid = 'dxarea';
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block', overflow: 'visible' }}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={dxA(ac, 0.42)} />
          <stop offset="100%" stopColor={dxA(ac, 0)} />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g,i) => (
        <line key={i} x1={padX} x2={W-padX} y1={padT + g*(H-padB-padT)} y2={padT + g*(H-padB-padT)} stroke={T.border} strokeWidth="1" strokeDasharray="3 5" />
      ))}
      <path d={area} fill={`url(#${gid})`} style={{ opacity: 0, animation: 'icfade .8s ease .3s forwards' }} />
      <path d={line} fill="none" stroke={ac} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
        style={{ strokeDasharray: 1400, strokeDashoffset: 1400, animation: 'dxDraw 1.1s cubic-bezier(.4,.8,.3,1) forwards' }} />
      {pts.map((p,i) => (
        <g key={i}>
          <circle cx={p[0]} cy={p[1]} r="4.5" fill={T.bg} stroke={ac} strokeWidth="2.5" style={{ opacity: 0, animation: `icScaleIn .4s ease ${0.6 + i*0.08}s forwards` }} />
          <text x={p[0]} y={p[1] - 13} textAnchor="middle" fill={T.text} fontSize="12.5" fontWeight="700" fontFamily="var(--mono)" style={{ opacity: 0, animation: `icfade .4s ease ${0.7 + i*0.08}s forwards` }}>{(data[i].t/1e6).toFixed(2)}M</text>
          <text x={p[0]} y={H-12} textAnchor="middle" fill={T.mute} fontSize="12" fontWeight="600">{data[i].lbl}</text>
        </g>
      ))}
    </svg>
  );
}

// ── Mix por categoria — barra empilhada + legenda (cor!) ────────────────
function DxCatMix({ cats, sel, onSel }) {
  const total = cats.reduce((s,c) => s + c.t, 0) || 1;
  const sorted = [...cats].sort((a,b) => b.t - a.t);
  const full = sel && sel !== 'all';
  return (
    <div>
      <div style={{ display: 'flex', width: '100%', height: 16, borderRadius: 8, overflow: 'hidden', marginBottom: 18, background: T.panel }}>
        {sorted.map((c,i) => (
          <div key={c.k} title={DX_CATN[c.k]} className="dxhbar" style={{ width: (c.t/total*100) + '%', background: DX_CATC[c.k], animationDelay: (i*0.06) + 's' }} />
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {sorted.map(c => {
          const on = sel === c.k;
          return (
            <div key={c.k} onClick={() => onSel && onSel(c.k)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 8px', margin: '0 -8px', borderRadius: 9, cursor: onSel ? 'pointer' : 'default', background: on ? dxA(DX_CATC[c.k], 0.1) : 'transparent', transition: 'background .15s' }}
              onMouseEnter={e => { if(onSel && !on) e.currentTarget.style.background = T.panel; }} onMouseLeave={e => { if(onSel && !on) e.currentTarget.style.background = 'transparent'; }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: DX_CATC[c.k], flexShrink: 0 }} />
              <span style={{ flex: 1, fontSize: 13, color: T.text, fontWeight: on ? 700 : 500 }}>{DX_CATN[c.k]}</span>
              <span style={{ fontSize: 11.5, color: T.mute2, fontFamily: 'var(--mono)', width: 56, textAlign: 'right' }}>{(c.t/total*100).toFixed(1)}%</span>
              <span style={{ fontSize: 12.5, color: T.text, fontFamily: 'var(--mono)', fontWeight: 700, width: 64, textAlign: 'right' }}>{dxK(c.t)}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Top fornecedores (barras horizontais animadas, dado real) ───────────
function DxSuppliers({ sups }) {
  const top = sups.slice(0, 6);
  const max = Math.max(...top.map(s => s.t));
  const nice = (n) => n.replace(/ (LTDA|S\/A|ME|EIRELI|S\.A\.?).*$/i, '').replace(/\.$/, '');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
      {top.map((s,i) => (
        <div key={i}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5, gap: 10 }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: T.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              <span style={{ color: T.mute2, fontFamily: 'var(--mono)', marginRight: 7 }}>{i+1}</span>{nice(s.n)}
            </span>
            <span style={{ fontSize: 12.5, fontWeight: 700, fontFamily: 'var(--mono)', color: T.text, flexShrink: 0 }}>{dxK(s.t)}</span>
          </div>
          <div style={{ height: 8, borderRadius: 6, background: T.panel, overflow: 'hidden' }}>
            <div className="dxhbar" style={{ width: (s.t/max*100) + '%', height: '100%', borderRadius: 6, animationDelay: (i*0.07) + 's',
              background: `linear-gradient(90deg, ${T.redDeep}, ${T.redBright})` }} />
          </div>
          <div style={{ fontSize: 10.5, color: T.mute2, marginTop: 3 }}>{dxNum(s.c)} entradas · {dxNum(s.p)} pedidos</div>
        </div>
      ))}
    </div>
  );
}

// ── Histograma de faixa de custo (dado real) ────────────────────────────
function DxHisto({ buckets }) {
  const order = ['<20','20-40','40-60','60-100','100+'];
  const labels = { '<20':'< R$20', '20-40':'R$20–40', '40-60':'R$40–60', '60-100':'R$60–100', '100+':'R$100+' };
  const vals = order.map(k => buckets[k] || 0);
  const max = Math.max(...vals, 1);
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, height: 168, paddingTop: 8 }}>
      {order.map((k,i) => (
        <div key={k} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', height: '100%', justifyContent: 'flex-end', gap: 8 }}>
          <div style={{ fontSize: 12, fontWeight: 700, fontFamily: 'var(--mono)', color: T.text }}>{dxNum(buckets[k] || 0)}</div>
          <div className="dxbar" style={{ width: '100%', maxWidth: 46, height: ((buckets[k]||0)/max*100) + '%', minHeight: 4, borderRadius: '7px 7px 3px 3px', animationDelay: (i*0.07) + 's',
            background: `linear-gradient(180deg, ${T.redBright}, ${dxA(T.redDeep, 0.55)})` }} />
          <div style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>{labels[k]}</div>
        </div>
      ))}
    </div>
  );
}

// ── Feed de atividade AO VIVO (movimento: novos eventos entram) ─────────
function DxFeed() {
  const mapNotif = (n) => ({
    icon: n.tipo === 'offer' ? 'tag' : n.tipo === 'deadline' ? 'clock' : n.tipo === 'order' ? 'receipt' : n.tipo === 'cotacao' ? 'list' : 'user',
    color: n.tipo === 'offer' ? T.green : n.tipo === 'deadline' ? T.yellow : n.tipo === 'order' ? T.blue : T.red,
    title: n.titulo, text: n.texto, time: 'agora',
  });
  const seed = [];
  const pool = [
    { icon:'tag',   color:T.green,  title:'NutriMax baixou preço', text:'Creatina 300g a R$ 49,90 — 8,4% abaixo do custo', time:'agora' },
    { icon:'bolt',  color:T.red,    title:'Leilão aquecendo',      text:'Whey 900g · 3 lances nos últimos 2 min', time:'agora' },
    { icon:'send',  color:T.blue,   title:'BioVida está digitando',text:'Dermocosméticos — nova tabela a caminho', time:'agora' },
    { icon:'check', color:T.green,  title:'Oferta verde',          text:'Dipirona 500mg cotada abaixo do PMC', time:'agora' },
    { icon:'clock', color:T.yellow, title:'Prazo encerrando',      text:'Genéricos · Reposição vence em 42 min', time:'agora' },
    { icon:'tag',   color:T.green,  title:'Pharma respondeu',      text:'5 itens de Suplementos atualizados', time:'agora' },
  ];
  const [items, setItems] = React.useState(seed);
  // semeia com notificações REAIS
  React.useEffect(() => {
    if (window.api) window.api.get('/notifications')
      .then(r => { const live = (r.items || []).slice(0, 7).map(mapNotif); if (live.length) setItems(live); })
      .catch(() => {});
  }, []);
  React.useEffect(() => {
    const id = setInterval(() => {
      setItems(prev => [pool[Math.floor(Math.random()*pool.length)], ...prev].slice(0, 7));
    }, 4200);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="dxfeed" style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 360, overflow: 'hidden' }}>
      {items.map((it, i) => (
        <div key={items.length - i + '-' + it.title} style={{ display: 'flex', gap: 11, alignItems: 'flex-start', padding: '10px 12px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}` }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: dxA(it.color, 0.15), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={it.icon} size={15} color={it.color} />
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{it.title}</div>
            <div style={{ fontSize: 12, color: T.mute, lineHeight: 1.35 }}>{it.text}</div>
          </div>
          <div style={{ fontSize: 10.5, color: T.mute2, whiteSpace: 'nowrap', flexShrink: 0 }}>{it.time}</div>
        </div>
      ))}
    </div>
  );
}

// ── Faixa HERO — economia em destaque com brilho ────────────────────────
function DxHero() {
  const econMonth = 84300, econYTD = 612480, taxa = 9.4;
  const minis = [
    { lbl: 'Comprado em 2026',  val: dxM(dxS.total),        sub: dxNum(dxS.lines) + ' entradas' },
    { lbl: 'Ticket médio',      val: dxBRL(dxS.avgTicket),  sub: dxNum(dxS.totalQtd) + ' unidades' },
    { lbl: 'Taxa de economia',  val: taxa.toFixed(1) + '%', sub: 'média vs. último custo' },
  ];
  return (
    <Glass pad={0} style={{ overflow: 'hidden', position: 'relative' }}>
      <div className="dxsheen" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(120% 140% at 0% 0%, ${dxA(T.green, 0.16)}, transparent 55%)`, pointerEvents: 'none' }} />
      <div style={{ position: 'relative', display: 'flex', flexWrap: 'wrap', alignItems: 'stretch' }}>
        <div style={{ flex: '1 1 320px', padding: '24px 26px', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4, borderRight: `1px solid ${T.border}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: T.mute, fontWeight: 600 }}>
            <Icon name="trophy" size={15} color={T.green} /> Economia gerada · acumulado do ano
          </div>
          <div style={{ fontSize: 'clamp(34px, 4.5vw, 52px)', fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -1.4, color: T.green, lineHeight: 1.05 }}>
            <CountUp value={econYTD} prefix="R$ " decimals={0} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: T.mute }}>
            <DxLiveDot color={T.green} /> <span><b style={{ color: T.text }}>{dxK(econMonth)}</b> só neste mês</span>
            <span style={{ color: T.mute2 }}>·</span>
            <Delta pct={-8.4} size={12} /> <span style={{ color: T.mute2 }}>vs. mês anterior</span>
          </div>
        </div>
        {minis.map((m, i) => (
          <div key={i} style={{ flex: '1 1 170px', padding: '24px 22px', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 5, borderRight: i < minis.length - 1 ? `1px solid ${T.border}` : 'none' }}>
            <div style={{ fontSize: 12, color: T.mute, fontWeight: 600 }}>{m.lbl}</div>
            <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.5 }}>{m.val}</div>
            <div style={{ fontSize: 11.5, color: T.mute2 }}>{m.sub}</div>
          </div>
        ))}
      </div>
    </Glass>
  );
}

// ── título de seção reutilizável ────────────────────────────────────────
function DxCardHead({ icon, color, title, note, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
        {icon && <Icon name={icon} size={17} color={color || T.redBright} />}
        <div style={{ fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
        {note && <span style={{ fontSize: 12, color: T.mute, whiteSpace: 'nowrap' }}>· {note}</span>}
      </div>
      {right}
    </div>
  );
}

// ── controle segmentado (período) ───────────────────────────────────────
function DxSeg({ options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', padding: 3, borderRadius: 11, background: T.panel, border: `1px solid ${T.border}`, gap: 2 }}>
      {options.map(o => {
        const on = o.id === value;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{
            padding: '7px 13px', borderRadius: 8, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 12.5, fontWeight: on ? 700 : 600, whiteSpace: 'nowrap',
            background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'transparent',
            color: on ? '#fff' : T.mute, boxShadow: on ? '0 2px 8px rgba(255,19,48,0.35)' : 'none', transition: 'all .15s',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

// ── chip de categoria (cor) ─────────────────────────────────────────────
function DxChip({ label, color, on, onClick }) {
  const c = color || T.red;
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit',
      fontSize: 12.5, fontWeight: on ? 700 : 600, whiteSpace: 'nowrap', transition: 'all .15s',
      background: on ? dxA(c, 0.16) : T.panel, color: on ? c : T.mute,
      border: `1px solid ${on ? dxA(c, 0.5) : T.border}`,
    }}>
      <span style={{ width: 8, height: 8, borderRadius: 3, background: c, opacity: on ? 1 : 0.55 }} />{label}
    </button>
  );
}

// ── busca rápida no catálogo real (24k produtos) ────────────────────────
function DxSearch() {
  const ERP = window.ERP || { p: [], s: [] };
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const results = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    if (s.length < 2) return [];
    const out = [];
    for (let i = 0; i < ERP.p.length && out.length < 7; i++) {
      const p = ERP.p[i];
      if ((p[2] && p[2].toLowerCase().includes(s)) || (p[0] && String(p[0]).includes(s)) || (p[1] && String(p[1]).includes(s))) out.push(p);
    }
    return out;
  }, [q]);
  return (
    <div style={{ position: 'relative', flex: '1 1 280px', minWidth: 220 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '0 13px', height: 40, borderRadius: 11, background: T.panel, border: `1px solid ${open && results.length ? dxA(T.red, 0.5) : T.border}`, transition: 'border .15s' }}>
        <Icon name="search" size={16} color={T.mute} />
        <input value={q} onChange={e => { setQ(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 150)}
          placeholder="Buscar produto, código ou EAN nos 24.830 itens…" style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: T.text, fontSize: 13.5, fontFamily: 'inherit' }} />
        {q && <button onClick={() => setQ('')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: T.mute2, display: 'flex' }}><Icon name="x" size={15} color={T.mute2} /></button>}
      </div>
      {open && results.length > 0 && (
        <div style={{ position: 'absolute', top: 46, left: 0, right: 0, zIndex: 40, background: T.surface, border: `1px solid ${T.borderHi}`, borderRadius: 13, boxShadow: '0 18px 50px rgba(0,0,0,0.55)', overflow: 'hidden', animation: 'icScaleIn .16s ease both' }}>
          {results.map((p, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 13px', borderBottom: i < results.length-1 ? `1px solid ${T.border}` : 'none', cursor: 'pointer' }}
              onMouseEnter={e => e.currentTarget.style.background = T.panel} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ width: 8, height: 8, borderRadius: 3, background: DX_CATC[p[14]] || T.mute, flexShrink: 0 }} />
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: T.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p[2]}</div>
                <div style={{ fontSize: 11, color: T.mute2, fontFamily: 'var(--mono)' }}>#{p[0]} · {p[6] || '—'}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, fontFamily: 'var(--mono)', color: T.text }}>R$ {dxIC.fmt(p[7])}</div>
                <div style={{ fontSize: 10.5, color: T.mute2 }}>custo</div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── DASHBOARD montado ───────────────────────────────────────────────────
function DxDashboard() {
  const { Topbar } = window.BuyerParts1;
  const [period, setPeriod] = React.useState('2026');
  const [cat, setCat] = React.useState('all');
  const [live, setLive] = React.useState(null); // contadores vivos do ciclo
  React.useEffect(() => { if (window.api) window.api.get('/dashboard').then(setLive).catch(() => {}); }, []);

  const PERIODS = [
    { id: '30d',  label: '30 dias', n: 1 },
    { id: '90d',  label: '90 dias', n: 3 },
    { id: '2026', label: '2026',    n: 99 },
    { id: 'tudo', label: 'Tudo',    n: 99 },
  ];
  const pn = (PERIODS.find(p => p.id === period) || {}).n || 99;
  const months = dxS.months.slice(-pn);
  const periodTotal = months.reduce((s, m) => s + m.t, 0);
  const periodLines = months.reduce((s, m) => s + m.c, 0);

  // escopo por categoria
  const allCats = [...dxS.cats].sort((a, b) => b.t - a.t);
  const scopeCat = cat === 'all' ? null : dxS.cats.find(c => c.k === cat);
  const accent = scopeCat ? DX_CATC[cat] : T.red;
  const scopeTotal = scopeCat ? scopeCat.t : dxS.total;
  const scopeLines = scopeCat ? scopeCat.c : dxS.lines;
  const shownCats = scopeCat ? allCats.filter(c => c.k === cat) : allCats;

  const sparkMonths = dxS.months.map(m => m.t);
  const sparkCounts = dxS.months.map(m => m.c);
  const totalProd = (window.ERP && window.ERP.p) ? window.ERP.p.length : (dxIC.TOTAL_PRODUCTS || 24830);
  const lastM = dxS.months.length ? dxS.months[dxS.months.length-1].t : 1.58e6;

  const opp = [
    ['Whey Protein Concentrado 900g','NutriMax',89.90,81.90],
    ['BCAA 2:1:1 120 cápsulas','NutriMax',38.20,35.80],
    ['Creatina Monohidratada 300g','NutriMax',54.50,49.90],
    ['Dipirona 500mg c/20','Profarma',8.40,7.10],
  ];

  return (
    <div>
      <Topbar title="Dashboard de Performance" sub="Central de compras · Rede Inova · Semana 22 / 2026"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Pill tone="mute"><Icon name="clock" size={13} color={T.mute} /> <DxClock /></Pill>
            <Pill tone="green"><DxLiveDot color={T.green} /> Ao vivo</Pill>
          </div>
        } />

      {/* BARRA DE CONTROLE — busca + período + categoria + export */}
      <Glass pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 12 }}>
          <DxSearch />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="calendar" size={15} color={T.mute2} />
            <DxSeg options={PERIODS} value={period} onChange={setPeriod} />
          </div>
          <button style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '0 15px', height: 40, borderRadius: 11, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 4px 14px rgba(255,19,48,0.3)' }}>
            <Icon name="arrowDown" size={15} color="#fff" /> Exportar
          </button>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 13 }}>
          <DxChip label="Todas categorias" color={T.text} on={cat === 'all'} onClick={() => setCat('all')} />
          {allCats.map(c => (
            <DxChip key={c.k} label={DX_CATN[c.k]} color={DX_CATC[c.k]} on={cat === c.k} onClick={() => setCat(cat === c.k ? 'all' : c.k)} />
          ))}
        </div>
      </Glass>

      {/* HERO */}
      <div style={{ marginBottom: 16 }}><DxHero /></div>

      {/* KPIs */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(178px, 1fr))' }}>
        <DxStat label={scopeCat ? 'Comprado · ' + DX_CATN[cat] : 'Comprado no período'} value={periodTotal/1e6 * (scopeCat ? (scopeTotal/dxS.total) : 1)} prefix="R$ " suffix="M" decimals={2} delta={4.4} icon="receipt" color={accent} spark={sparkMonths} foot={(PERIODS.find(p=>p.id===period)||{}).label} />
        <DxStat label="Linhas de entrada" value={scopeCat ? scopeLines : periodLines} icon="list" color={T.blue} spark={sparkCounts} foot={scopeCat ? DX_CATN[cat] : 'no período'} />
        <DxStat label="Itens comprados" value={dxS.totalQtd} icon="box" color={T.yellow} spark={sparkCounts} foot="unidades no ano" />
        <DxStat label="Ticket médio" value={dxS.avgTicket} prefix="R$ " decimals={2} delta={2.1} icon="tag" color="#C77DFF" foot="por linha de nota" />
        <DxStat label="Catálogo ativo" value={totalProd} icon="box" color={T.green} foot="sincronizado há 2h" />
        <DxStat label="Cotações abertas" value={live ? live.cotacoes.abertas : 0} icon="list" color={T.yellow} foot={live ? `${live.ofertas.total} ofertas recebidas` : '—'} />
        <DxStat label="Reps ativos" value={live ? live.repsAtivos : 0} icon="user" color={T.redBright} foot={live ? `${live.ofertas.verdes} ofertas verdes` : '—'} />
        <DxStat label="Economia capturada" value={live ? live.pedidos.economia : 0} prefix="R$ " decimals={2} icon="tag" color={T.green} foot={live ? `${live.pedidos.total} pedidos fechados` : '—'} />
      </div>

      {/* Radar de Oportunidade */}
      <Glass style={{ marginBottom: 16 }}>
        <DxCardHead icon="bolt" title="Radar de Oportunidade & Sazonalidade" note="alertas inteligentes" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 12 }}>
          {dxIC.SEASON.map((s, i) => (
            <div key={i} className={s.tag === 'Ruptura' ? 'ruptglow' : ''} style={{ padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${s.tag === 'Ruptura' ? dxA(T.red, 0.4) : T.border}`, display: 'flex', gap: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: T.redBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={s.icon} size={19} color={T.redBright} /></div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 13.5, marginBottom: 3 }}>{s.title}</div>
                <div style={{ fontSize: 12, color: T.mute, lineHeight: 1.4 }}>{s.text}</div>
                <Pill tone={s.tag === 'Ruptura' ? 'red' : s.tag === 'Radar' ? 'green' : 'yellow'} style={{ marginTop: 8 }}>{s.tag}</Pill>
              </div>
            </div>
          ))}
        </div>
      </Glass>

      {/* Evolução mensal + Mix categoria */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.7fr) minmax(0, 1fr)', gap: 16, marginBottom: 16 }} className="dxresp2">
        <Glass>
          <DxCardHead icon="chart" color={accent} title="Evolução de compras" note={(scopeCat ? DX_CATN[cat] + ' · ' : '') + 'valor de entrada'}
            right={<Pill tone="mute">{dxM(periodTotal)} no período</Pill>} />
          <DxArea months={months} accent={accent} />
        </Glass>
        <Glass>
          <DxCardHead title="Mix por categoria" note={dxNum(scopeLines) + ' entradas'} />
          <DxCatMix cats={shownCats} sel={cat} onSel={(k) => setCat(cat === k ? 'all' : k)} />
        </Glass>
      </div>

      {/* Fornecedores + Histograma */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16, marginBottom: 16 }}>
        <Glass>
          <DxCardHead icon="user" title="Principais fornecedores" note="por volume comprado" />
          <DxSuppliers sups={dxS.sups} />
        </Glass>
        <Glass>
          <DxCardHead icon="box" title="Distribuição por faixa de custo" note={dxNum(totalProd) + ' itens'} />
          <DxHisto buckets={dxS.buckets} />
        </Glass>
      </div>

      {/* Feed ao vivo + Oportunidades */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        <Glass>
          <DxCardHead icon="bolt" color={T.green} title="Atividade ao vivo"
            right={<Pill tone="green"><DxLiveDot color={T.green} /> tempo real</Pill>} />
          <DxFeed />
        </Glass>
        <Glass>
          <DxCardHead icon="trophy" color={T.green} title="Oportunidades" note="abaixo do último custo" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {opp.map((r,i) => {
              const pct = ((r[3]-r[2])/r[2])*100;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderRadius: 12, background: dxA(T.green, 0.05), border: `1px solid ${dxA(T.green, 0.18)}` }}>
                  <div style={{ flex: 1, fontWeight: 600, fontSize: 13.5, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r[0]}</div>
                  <div style={{ color: T.mute, fontSize: 12.5, width: 78, flexShrink: 0 }}>{r[1]}</div>
                  <div style={{ color: T.mute2, fontSize: 12.5, fontFamily: 'var(--mono)', flexShrink: 0 }}>R$ {dxIC.fmt(r[2])}</div>
                  <Icon name="chevron" size={13} color={T.mute2} />
                  <div style={{ fontWeight: 800, fontSize: 13.5, fontFamily: 'var(--mono)', width: 70, textAlign: 'right', color: T.green, flexShrink: 0 }}>R$ {dxIC.fmt(r[3])}</div>
                  <div style={{ width: 60, textAlign: 'right', flexShrink: 0 }}><Delta pct={pct} size={11} /></div>
                </div>
              );
            })}
          </div>
        </Glass>
      </div>
    </div>
  );
}

// sobrescreve o Dashboard original
if (window.BuyerParts1) window.BuyerParts1.Dashboard = DxDashboard;
