// ── InovaPED — Cockpit de Preços (estilo mercado / trading) ─────────────
// Usa window.ERPMARKET: séries de custo reais (produtos com estoque>0).
const TopbarM = window.BuyerParts1.Topbar;

const catColor = (c) => ({ med:'#FF1330', sup:'#FF6B57', gen:'#FF9E80', derm:'#C77DFF', hig:'#4EA8DE', baby:'#FF4D6D', out:'#7A7A82' }[c] || T.mute);
const catName = (c) => ({ med:'Medicamentos', sup:'Suplementos', gen:'Genéricos', derm:'Dermocosméticos', hig:'Higiene', baby:'Mamãe & Bebê', out:'Outros' }[c] || c);
const mfmt = (n) => (n==null||isNaN(n)) ? '—' : n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// seta + cor — SUBIU custo = ruim (vermelho), CAIU = bom (verde)
function Trend({ pct, big }) {
  if (pct == null) return <span style={{ color: T.mute2 }}>—</span>;
  const up = pct > 0.05, down = pct < -0.05;
  const c = up ? T.redBright : down ? T.green : T.mute;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, color: c, fontWeight: 800, fontSize: big ? 15 : 12.5, fontVariantNumeric: 'tabular-nums' }}>
      {up ? '▲' : down ? '▼' : '■'} {Math.abs(pct).toFixed(1)}%
    </span>
  );
}

// gráfico tipo "ticker" — área + linha, eixo, marcadores
function MarketChart({ series, height = 260 }) {
  if (!series || series.length < 2) return null;
  const w = 900, padL = 52, padR = 16, padT = 18, padB = 28;
  const vals = series.map(s => s[1]);
  const min = Math.min(...vals), max = Math.max(...vals), rng = (max - min) || 1;
  const lo = min - rng * 0.12, hi = max + rng * 0.12, R = hi - lo;
  const X = i => padL + (i / (series.length - 1)) * (w - padL - padR);
  const Y = v => (height - padB) - ((v - lo) / R) * (height - padT - padB);
  const pts = series.map((s, i) => [X(i), Y(s[1])]);
  const line = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = line + ` L ${X(series.length-1).toFixed(1)} ${height-padB} L ${X(0).toFixed(1)} ${height-padB} Z`;
  const rising = series[series.length-1][1] >= series[0][1];
  const col = rising ? T.redBright : T.green; // custo subindo = vermelho
  const grid = 4;
  return (
    <svg viewBox={`0 0 ${w} ${height}`} style={{ width: '100%', height, display: 'block' }} preserveAspectRatio="none">
      <defs><linearGradient id="mkg" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={col} stopOpacity="0.28" /><stop offset="100%" stopColor={col} stopOpacity="0" /></linearGradient></defs>
      {Array.from({length: grid+1}).map((_, g) => { const v = lo + (R * g / grid); const y = Y(v); return (
        <g key={g}><line x1={padL} x2={w-padR} y1={y} y2={y} stroke={T.border} strokeWidth="1" /><text x={padL-8} y={y+3} fill={T.mute2} fontSize="11" textAnchor="end" fontFamily="var(--mono)">{mfmt(v)}</text></g>
      ); })}
      <path d={area} fill="url(#mkg)" />
      <path d={line} fill="none" stroke={col} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill={T.surface} stroke={col} strokeWidth="2" vectorEffect="non-scaling-stroke" />)}
      {series.map((s, i) => <text key={i} x={X(i)} y={height-9} fill={T.mute2} fontSize="11" textAnchor="middle" fontFamily="var(--mono)">{s[0].slice(3)}</text>)}
    </svg>
  );
}

function Cockpit() {
  const M = window.ERPMARKET || [];
  const [sel, setSel] = useState(M[0]);
  const [cat, setCat] = useState('all');
  const [tab, setTab] = useState('todos'); // todos | alta | baixa
  const [q, setQ] = useState('');

  const norm = (s) => (s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'');
  const list = useMemo(() => {
    let l = M.filter(m => (cat === 'all' || m.cat === cat) && (!q || norm(m.n + ' ' + m.fab).includes(norm(q))));
    if (tab === 'alta') l = l.filter(m => m.dl > 0.05).sort((a,b) => b.dl - a.dl);
    else if (tab === 'baixa') l = l.filter(m => m.dl < -0.05).sort((a,b) => a.dl - b.dl);
    return l;
  }, [cat, tab, q]);

  // "índice" do mercado: média das variações mensais
  const idxMonth = M.length ? M.reduce((a,m) => a + m.dl, 0) / M.length : 0;
  const subindo = M.filter(m => m.dl > 0.05).length, caindo = M.filter(m => m.dl < -0.05).length;

  return (
    <div>
      <TopbarM title="Cockpit de Preços" sub="Mercado de custos ao vivo · variação real do que você compra · só itens com estoque"
        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>} />

      {/* índice de mercado */}
      <div style={{ display: 'flex', gap: 14, marginBottom: 16, flexWrap: 'wrap' }}>
        <Glass pad={18} style={{ flex: 1.4, minWidth: 240 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div><div style={{ fontSize: 12, color: T.mute }}>Índice de Custo Inova</div><div style={{ fontSize: 28, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{(100 + idxMonth).toFixed(2)}</div></div>
            <div style={{ textAlign: 'right' }}><Trend pct={idxMonth} big /><div style={{ fontSize: 11, color: T.mute2, marginTop: 3 }}>média mês · {M.length} ativos</div></div>
          </div>
        </Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 160 }}><div style={{ display:'flex',alignItems:'center',gap:6, fontSize: 12, color: T.mute }}><span style={{color:T.redBright}}>▲</span> Subindo</div><div style={{ fontSize: 26, fontWeight: 800, color: T.redBright, fontFamily: 'var(--display)', marginTop: 4 }}>{subindo}</div><div style={{ fontSize: 11, color: T.mute2 }}>custos em alta</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 160 }}><div style={{ display:'flex',alignItems:'center',gap:6, fontSize: 12, color: T.mute }}><span style={{color:T.green}}>▼</span> Caindo</div><div style={{ fontSize: 26, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>{caindo}</div><div style={{ fontSize: 11, color: T.mute2 }}>oportunidade de compra</div></Glass>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 16, alignItems: 'start' }}>
        {/* gráfico principal */}
        <Glass>
          {sel && <>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 12 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 99, background: catColor(sel.cat) }} />
                  <span style={{ fontSize: 11.5, color: T.mute, fontWeight: 600 }}>{catName(sel.cat)}</span>
                  {sel.cv && <Pill tone="mute" style={{ fontSize: 10 }}>curva {sel.cv}</Pill>}
                  <Pill tone="green" style={{ fontSize: 10 }}>estoque {sel.est}</Pill>
                </div>
                <div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)', letterSpacing: -0.3, lineHeight: 1.15 }}>{sel.n}</div>
                <div style={{ fontSize: 12, color: T.mute2, marginTop: 3 }}>{sel.fab} · cód {sel.c}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', fontVariantNumeric: 'tabular-nums' }}>R$ {mfmt(sel.cu)}</div>
                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 3 }}><span style={{ fontSize: 11, color: T.mute2 }}>mês</span><Trend pct={sel.dl} /></div>
                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}><span style={{ fontSize: 11, color: T.mute2 }}>período</span><Trend pct={sel.dt} /></div>
              </div>
            </div>
            <MarketChart series={sel.s} />
            <div style={{ display: 'flex', gap: 10, marginTop: 14, flexWrap: 'wrap' }}>
              <MiniStat label="Custo atual" value={'R$ ' + mfmt(sel.cu)} />
              <MiniStat label="Preço venda" value={'R$ ' + mfmt(sel.pv)} />
              <MiniStat label="Markup" value={(sel.mk||0).toFixed(0) + '%'} color={sel.mk >= 40 ? T.green : T.text} />
              <MiniStat label="Mín. período" value={'R$ ' + mfmt(Math.min(...sel.s.map(s=>s[1])))} color={T.green} />
              <MiniStat label="Máx. período" value={'R$ ' + mfmt(Math.max(...sel.s.map(s=>s[1])))} color={T.redBright} />
            </div>
          </>}
        </Glass>

        {/* watchlist */}
        <Glass pad={0} style={{ overflow: 'hidden' }}>
          <div style={{ padding: 12, borderBottom: `1px solid ${T.border}` }}>
            <div style={{ position: 'relative', marginBottom: 10 }}>
              <Icon name="search" size={15} color={T.mute} style={{ position: 'absolute', left: 11, top: 10 }} />
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar ativo…" style={{ width: '100%', boxSizing: 'border-box', padding: '9px 12px 9px 34px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13, outline: 'none' }} />
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {[['todos','Todos'],['alta','▲ Altas'],['baixa','▼ Baixas']].map(([id,l]) => { const on = tab === id; const tc = id==='alta'?T.redBright:id==='baixa'?T.green:T.text; return (
                <button key={id} onClick={() => setTab(id)} style={{ flex: 1, padding: '7px', borderRadius: 9, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, border: `1px solid ${on ? T.borderHi : T.border}`, color: on ? tc : T.mute, background: on ? T.panelHi : 'transparent' }}>{l}</button>
              ); })}
            </div>
          </div>
          <div style={{ maxHeight: 520, overflow: 'auto' }}>
            {list.map(m => { const on = sel && sel.c === m.c; const up = m.dl > 0.05, down = m.dl < -0.05; const c = up ? T.redBright : down ? T.green : T.mute;
              return (
                <button key={m.c} onClick={() => setSel(m)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px', border: 'none', borderBottom: `1px solid ${T.border}`, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', background: on ? T.redBg : 'transparent', boxShadow: on ? `inset 2px 0 0 ${T.red}` : 'none' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: T.text }}>{m.n}</div>
                    <div style={{ fontSize: 10.5, color: T.mute2 }}>{m.fab.slice(0, 22)}</div>
                  </div>
                  <div style={{ width: 54, height: 22, flexShrink: 0 }}><SparkLine data={m.s.map(s=>s[1])} w={54} h={22} color={c} /></div>
                  <div style={{ textAlign: 'right', flexShrink: 0, width: 72 }}>
                    <div style={{ fontWeight: 700, fontSize: 12.5, fontVariantNumeric: 'tabular-nums' }}>R$ {mfmt(m.cu)}</div>
                    <div style={{ fontSize: 11, fontWeight: 800, color: c, fontVariantNumeric: 'tabular-nums' }}>{up?'▲':down?'▼':'■'} {Math.abs(m.dl).toFixed(1)}%</div>
                  </div>
                </button>
              );
            })}
            {list.length === 0 && <div style={{ padding: 30, textAlign: 'center', color: T.mute2, fontSize: 13 }}>Nenhum ativo nesse filtro</div>}
          </div>
        </Glass>
      </div>

      {/* tabela de movimentações */}
      <div style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap' }}>
          <Chip on={cat === 'all'} onClick={() => setCat('all')}>Todas categorias</Chip>
          {['med','sup','gen','derm','hig','baby'].map(c => <Chip key={c} on={cat === c} onClick={() => setCat(c)}>{catName(c)}</Chip>)}
        </div>
        <Glass pad={0} style={{ overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead><tr style={{ background: T.panel }}>
              <th style={thE('left', 280)}>Ativo</th><th style={thE('left', 130)}>Categoria</th><th style={thE('right', 80)}>Estoque</th><th style={thE('right', 110)}>Custo atual</th><th style={thE('right', 90)}>Var. mês</th><th style={thE('right', 90)}>Var. período</th><th style={thE('center', 90)}>Tendência</th>
            </tr></thead>
            <tbody>
              {list.slice(0, 40).map(m => { const up = m.dl > 0.05, down = m.dl < -0.05; const c = up ? T.redBright : down ? T.green : T.mute;
                return (
                  <tr key={m.c} onClick={() => setSel(m)} className="erp-row" style={{ borderTop: `1px solid ${T.border}`, cursor: 'pointer' }}>
                    <td style={tdE('left')}><div style={{ fontWeight: 600 }}>{m.n}</div><div style={{ fontSize: 11, color: T.mute2 }}>{m.fab}</div></td>
                    <td style={tdE('left')}><Pill tone="mute"><span style={{ width: 7, height: 7, borderRadius: 99, background: catColor(m.cat) }} />{catName(m.cat)}</Pill></td>
                    <td style={{ ...tdE('right'), fontVariantNumeric: 'tabular-nums', color: T.mute }}>{m.est}</td>
                    <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {mfmt(m.cu)}</td>
                    <td style={tdE('right')}><Trend pct={m.dl} /></td>
                    <td style={tdE('right')}><Trend pct={m.dt} /></td>
                    <td style={tdE('center')}><div style={{ width: 70, height: 24, margin: '0 auto' }}><SparkLine data={m.s.map(s=>s[1])} w={70} h={24} color={c} /></div></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Glass>
      </div>
    </div>
  );
}
function MiniStat({ label, value, color }) {
  return <div style={{ flex: 1, minWidth: 100, padding: '10px 12px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}` }}><div style={{ fontSize: 10.5, color: T.mute2 }}>{label}</div><div style={{ fontSize: 15, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 2, color: color || T.text, fontVariantNumeric: 'tabular-nums' }}>{value}</div></div>;
}

window.BuyerCockpit = { Cockpit };
