// ── Inova Cotação — Módulo Comprador (desktop) ──────────────────────────
// T, Icon, Glass, Pill, Delta, BarChart, LineChart já são globais (shared.jsx)
const IC = window.IC;

function catById(id){ return IC.CATEGORIES.find(c => c.id === id); }
function repById(id){ return IC.REPS.find(r => r.id === id); }

// ── Sidebar ─────────────────────────────────────────────────────────────
function Sidebar({ view, setView }) {
  const items = [
    { id: 'dash',   label: 'Dashboard',  icon: 'chart' },
    { id: 'quotes', label: 'Cotações',   icon: 'list' },
    { id: 'grid',   label: 'Grade Comparativa', icon: 'table' },
    { id: 'auction',label: 'Leilão Reverso',    icon: 'bolt' },
    { id: 'mural',  label: 'Mural de Ofertas',  icon: 'tag' },
    { id: 'promo',  label: 'Promoções & IA',    icon: 'sparkle' },
    { id: 'reps',   label: 'Representantes',     icon: 'user' },
    { id: 'chat',   label: 'Mensagens',  icon: 'send' },
    { id: 'orders', label: 'Pedidos',    icon: 'receipt' },
    { id: 'retorno',label: 'Retorno da Cotação', icon: 'refresh' },
    { id: 'xml',    label: 'Conferência XML',   icon: 'shield' },
    { id: 'base',   label: 'Base de Produtos',  icon: 'box' },
    { id: 'simil',  label: 'Similaridade', icon: 'shield' },
    { id: 'distrib',label: 'Distribuidoras', icon: 'box' },
    { id: 'compras',label: 'Compras & Performance', icon: 'chart' },
    { id: 'repos',  label: 'Reposição Inteligente', icon: 'bolt' },
    { id: 'cockpit',label: 'Cockpit de Preços',  icon: 'chart' },
    { id: 'settings',label: 'Configurações',    icon: 'filter' },
  ];
  return (
    <div style={{ width: 248, flexShrink: 0, padding: '24px 18px', display: 'flex', flexDirection: 'column', gap: 18, borderRight: `1px solid ${T.border}`, background: T.panel, height: '100%', boxSizing: 'border-box' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '0 6px' }}>
        <img src="assets/logo.png" alt="InovaPED" style={{ width: 190, maxWidth: '100%', objectFit: 'contain' }} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 3, overflowY: 'auto', flex: 1, minHeight: 0, margin: '0 -6px', padding: '0 6px' }}>
        {items.map(it => {
          const on = view === it.id;
          return (
            <button key={it.id} onClick={() => setView(it.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '11px 13px', borderRadius: 12,
              border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
              background: on ? 'linear-gradient(90deg, rgba(255,19,48,0.18), rgba(255,19,48,0.04))' : 'transparent',
              color: on ? T.text : T.mute, fontWeight: on ? 700 : 500, fontSize: 14,
              boxShadow: on ? `inset 2px 0 0 ${T.red}` : 'none', transition: 'background .15s, color .15s',
            }}
            onMouseEnter={e => { if(!on) e.currentTarget.style.background = T.panel; }}
            onMouseLeave={e => { if(!on) e.currentTarget.style.background = 'transparent'; }}>
              <Icon name={it.icon} size={19} color={on ? T.red : T.mute} />
              {it.label}
            </button>
          );
        })}
      </div>

      <div style={{ flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ padding: 14, borderRadius: 14, background: T.panel, border: `1px solid ${T.border}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: T.mute, marginBottom: 6 }}>
            <Icon name="box" size={15} color={T.mute} /> Base ERP HOS
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, fontFamily: 'var(--display)' }}>{(window.ERP ? window.ERP.p.length : 24830).toLocaleString('pt-BR')}</div>
          <div style={{ fontSize: 11, color: T.green, display:'flex', alignItems:'center', gap:4 }}><Icon name="check" size={13} color={T.green}/> Sincronizado há 2h</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 8px' }}>
          <div style={{ width: 34, height: 34, borderRadius: 999, background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center', fontWeight:800, fontSize:14, color: '#fff' }}>F</div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>Felipe Costa</div>
            <div style={{ fontSize: 11, color: T.mute }}>Comprador</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Topbar ──────────────────────────────────────────────────────────────
function Topbar({ title, sub, action }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 26, flexWrap: 'wrap' }}>
      <div style={{ minWidth: 0 }}>
        <h1 style={{ margin: 0, fontSize: 'clamp(22px, 2.4vw, 30px)', lineHeight: 1.12, fontWeight: 800, letterSpacing: -0.6, fontFamily: 'var(--display)', textWrap: 'balance' }}>{title}</h1>
        {sub && <div style={{ color: T.mute, fontSize: 14, marginTop: 6 }}>{sub}</div>}
      </div>
      {action}
    </div>
  );
}

// ── KPI ─────────────────────────────────────────────────────────────────
function Kpi({ label, num, prefix = '', suffix = '', decimals = 0, value, delta, icon, accent }) {
  return (
    <Glass pad={18} style={{ flex: '1 1 150px' }}>
      <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: 30, height: 30, borderRadius: 9, background: accent ? T.redBg : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center' }}>
          <Icon name={icon} size={16} color={accent ? T.redBright : T.mute} />
        </div>
      </div>
      <div style={{ fontSize: 27, fontWeight: 800, marginTop: 10, fontFamily: 'var(--display)', letterSpacing: -0.5 }}>
        {num != null ? <CountUp value={num} prefix={prefix} suffix={suffix} decimals={decimals} /> : value}
      </div>
      {delta != null && <div style={{ marginTop: 4 }}><Delta pct={delta} /> <span style={{ color: T.mute2, fontSize: 12 }}>vs. semana ant.</span></div>}
    </Glass>
  );
}

// ── DASHBOARD ───────────────────────────────────────────────────────────
function Dashboard() {
  const pieColors = ['#FF3B54', '#FF1330', '#C00016', '#8A8A92', '#5C5C63'];
  const donutData = IC.VOLUME_BY_CAT.map((d, i) => ({ label: d.cat, value: d.value, color: pieColors[i % pieColors.length] }));
  const repRanking = [
    { label: 'NutriMax Supplements', value: 38200, display: 'R$ 38,2k' },
    { label: 'Pharma Distribuidora', value: 22400, display: 'R$ 22,4k' },
    { label: 'BioVida Atacado',      value: 14100, display: 'R$ 14,1k' },
    { label: 'Galaxy Medic',         value: 7600,  display: 'R$ 7,6k' },
    { label: 'DermaCenter',          value: 2100,  display: 'R$ 2,1k' },
  ].map(d => ({ ...d, color: `linear-gradient(90deg, ${T.green}, #0AA968)` }));
  const respWeek = [
    { cat: 'Seg', value: 12 }, { cat: 'Ter', value: 19 }, { cat: 'Qua', value: 8 },
    { cat: 'Qui', value: 24 }, { cat: 'Sex', value: 17 }, { cat: 'Sáb', value: 5 },
  ];
  return (
    <div>
      <Topbar title="Dashboard de Performance" sub="Visão geral de compras • Semana 22 / 2026"
        action={<Pill tone="green"><span style={{ width: 7, height: 7, borderRadius: 99, background: T.green }} /> Ao vivo</Pill>} />
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(168px, 1fr))' }}>
        <Kpi label="Volume em cotação" num={1.26} prefix="R$ " suffix="M" decimals={2} delta={-4.2} icon="chart" accent />
        <Kpi label="Economia gerada" num={84.3} prefix="R$ " suffix="k" decimals={1} delta={-8.4} icon="trophy" />
        <Kpi label="Cotações abertas" num={2} icon="clock" />
        <Kpi label="Reps ativos" num={5} icon="user" />
      </div>

      <Glass style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
          <Icon name="bolt" size={17} color={T.redBright} /><div style={{ fontWeight: 700, fontSize: 15 }}>Radar de Oportunidade & Sazonalidade</div><span style={{ fontSize: 12, color: T.mute }}>· alertas inteligentes</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {IC.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' ? 'rgba(255,19,48,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={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}><span style={{ fontWeight: 700, fontSize: 13.5 }}>{s.title}</span></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>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16, marginBottom: 16 }}>
        <Glass>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Volume de compras por categoria</div>
            <Pill tone="mute">Últimos 30 dias</Pill>
          </div>
          <BarChart data={IC.VOLUME_BY_CAT} />
        </Glass>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 16 }}>Participação por categoria</div>
          <Donut data={donutData} />
        </Glass>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16, marginBottom: 16 }}>
        <Glass>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Índice de custo médio</div>
            <Delta pct={-8.4} />
          </div>
          <LineChart data={IC.COST_TREND} />
          <div style={{ fontSize: 12, color: T.mute, marginTop: 4 }}>Base 100 = Semana 15. Queda reflete economia nas cotações.</div>
        </Glass>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 16 }}>Economia gerada por representante</div>
          <HBars data={repRanking} />
        </Glass>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 8 }}>Respostas de reps na semana</div>
          <BarChart data={respWeek} height={170} />
        </Glass>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14 }}>Oportunidades recentes <span style={{ color: T.green, fontWeight: 600 }}>(abaixo do último custo)</span></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[['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]].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: 'rgba(0,230,140,0.05)', border:`1px solid rgba(0,230,140,0.18)` }}>
                  <div style={{ flex: 1, fontWeight: 600, fontSize: 13.5 }}>{r[0]}</div>
                  <div style={{ color: T.mute, fontSize: 12.5, width: 96 }}>{r[1]}</div>
                  <div style={{ color: T.mute2, fontSize: 12.5, fontVariantNumeric:'tabular-nums' }}>R$ {IC.fmt(r[2])}</div>
                  <Icon name="chevron" size={13} color={T.mute2} />
                  <div style={{ fontWeight: 800, fontSize: 13.5, fontVariantNumeric:'tabular-nums', width: 72, textAlign:'right', color: T.green }}>R$ {IC.fmt(r[3])}</div>
                  <div style={{ width: 64, textAlign:'right' }}><Delta pct={pct} size={11} /></div>
                </div>
              );
            })}
          </div>
        </Glass>
      </div>
    </div>
  );
}

window.BuyerParts1 = { Sidebar, Topbar, Kpi, Dashboard, catById, repById };
