/* global React, Icon, Badge, Button, brl, Card, KpiMini, PageHead, FooterPager,
   calcPeriod, calcPreviousPeriod, CompareKPI, RelFilterBar, RelExportMenu, relFmtDate,
   ChartCanvas, EvolutionChart, FunnelChart, RankingBar, FilterDropdown, DistClassBadge,
   IBGE_TO_UF_REL, CurvaABCChart, AgingChart, FrequenciaHistograma */

// ═══════════════════════════════════════════════════════════════════════════════
// VENDAS COMPLETAS (Fase 2)
// ═══════════════════════════════════════════════════════════════════════════════

function RelVendasSection({ filters, setFilters, onNav }) {
  const [pedidos, setPedidos]     = React.useState(null);
  const [allPedidos, setAllPedidos] = React.useState(null); // all statuses for funnel
  const [prevData, setPrevData]   = React.useState(null);
  const [filterOpts, setFilterOpts] = React.useState({ canais: [], vendedores: [], formas: [] });
  const [busca, setBusca]         = React.useState('');

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);
  const { start: prevStart, end: prevEnd } = calcPreviousPeriod(start, end);

  const s0 = start.toISOString();
  const s1 = new Date(end.getTime() + 86400000).toISOString();
  const ps0 = prevStart.toISOString();
  const ps1 = new Date(prevEnd.getTime() + 86400000).toISOString();

  // Fetch data
  React.useEffect(() => {
    if (!window.tmSupabase) { setPedidos([]); setAllPedidos([]); setPrevData([]); return; }
    setPedidos(null); setAllPedidos(null); setPrevData(null);
    Promise.all([
      window.tmSupabase.from('pedidos')
        .select('id, numero, cliente_nome, canal, vendedor, total, status, data_venda, created_at, forma_pagamento, unidade_negocio')
        .eq('status', 'Atendido')
        .gte('created_at', s0).lte('created_at', s1)
        .order('created_at', { ascending: false }),
      window.tmSupabase.from('pedidos')
        .select('id, total')
        .eq('status', 'Atendido')
        .gte('created_at', ps0).lte('created_at', ps1),
      // All statuses for funnel
      window.tmSupabase.from('pedidos')
        .select('id, status, total')
        .gte('created_at', s0).lte('created_at', s1),
    ]).then(([curr, prev, allSt]) => {
      setPedidos(curr.data || []);
      setPrevData(prev.data || []);
      setAllPedidos(allSt.data || []);
      // Extract filter options
      const data = curr.data || [];
      setFilterOpts({
        canais: [...new Set(data.map(p => p.canal).filter(Boolean))].sort(),
        vendedores: [...new Set(data.map(p => p.vendedor).filter(Boolean))].sort(),
        formas: [...new Set(data.map(p => p.forma_pagamento).filter(Boolean))].sort(),
      });
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  // Apply local filters
  const filtered = (pedidos || []).filter(p => {
    const q = busca.toLowerCase();
    const matchBusca = !q || (p.numero||'').toLowerCase().includes(q) || (p.cliente_nome||'').toLowerCase().includes(q) || (p.vendedor||'').toLowerCase().includes(q);
    const matchCanal = !filters.canal || p.canal === filters.canal;
    const matchVend  = !filters.vendedor || p.vendedor === filters.vendedor;
    const matchForma = !filters.formaPgto || p.forma_pagamento === filters.formaPgto;
    return matchBusca && matchCanal && matchVend && matchForma;
  });

  const totalFat = filtered.reduce((a, p) => a + (parseFloat(p.total) || 0), 0);
  const nPed     = filtered.length;
  const ticket   = nPed > 0 ? totalFat / nPed : 0;
  const prevFat  = (prevData || []).reduce((a, p) => a + (parseFloat(p.total) || 0), 0);
  const prevN    = (prevData || []).length;
  const prevTicket = prevN > 0 ? prevFat / prevN : 0;

  // Breakdown por canal
  const porCanal = {};
  filtered.forEach(p => {
    const c = p.canal || 'Sem canal';
    if (!porCanal[c]) porCanal[c] = { fat: 0, qtd: 0 };
    porCanal[c].fat += parseFloat(p.total) || 0;
    porCanal[c].qtd += 1;
  });
  const canalRows = Object.entries(porCanal).sort((a,b) => b[1].fat - a[1].fat);

  // Ranking vendedores
  const byVend = {};
  filtered.forEach(p => {
    const v = p.vendedor || 'Sem vendedor';
    if (!byVend[v]) byVend[v] = { nome: v, fat: 0, pedidos: 0 };
    byVend[v].fat += parseFloat(p.total) || 0;
    byVend[v].pedidos++;
  });
  const vendRanking = Object.values(byVend).sort((a,b) => b.fat - a.fat).map(v => ({
    ...v, ticket: v.pedidos > 0 ? v.fat / v.pedidos : 0,
  }));

  // Funil operacional
  const pedidosPorStatus = {};
  (allPedidos || []).forEach(p => {
    const st = p.status || 'Outro';
    pedidosPorStatus[st] = (pedidosPorStatus[st] || 0) + 1;
  });

  const exportarCSV = () => {
    const linhas = [
      ['N Pedido','Cliente','Canal','Vendedor','Data Venda','Forma Pgto','Total'],
      ...filtered.map(p => [
        p.numero, p.cliente_nome, p.canal, p.vendedor,
        relFmtDate(p.data_venda || p.created_at), p.forma_pagamento,
        `R$ ${brl(parseFloat(p.total)||0)}`,
      ])
    ];
    const csv = linhas.map(r => r.join(';')).join('\n');
    const blob = new Blob(['﻿'+csv], { type:'text/csv;charset=utf-8;' });
    const url  = URL.createObjectURL(blob);
    const a    = Object.assign(document.createElement('a'), { href:url, download:`vendas-${new Date().toISOString().slice(0,10)}.csv` });
    document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
  };

  const loading = pedidos === null;

  return (
    <div>
      {/* Filtros avancados */}
      {!loading && (
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
          {filterOpts.canais.length > 0 && (
            <FilterDropdown label="Canal" value={filters.canal} options={filterOpts.canais}
              onChange={v => setFilters(f => ({ ...f, canal: v }))} />
          )}
          {filterOpts.vendedores.length > 0 && (
            <FilterDropdown label="Vendedor" value={filters.vendedor} options={filterOpts.vendedores}
              onChange={v => setFilters(f => ({ ...f, vendedor: v }))} />
          )}
          {filterOpts.formas.length > 0 && (
            <FilterDropdown label="Forma Pgto" value={filters.formaPgto} options={filterOpts.formas}
              onChange={v => setFilters(f => ({ ...f, formaPgto: v }))} />
          )}
        </div>
      )}

      {/* KPIs comparativos */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Faturamento" current={totalFat} previous={prevFat} format="currency" loading={loading} />
        <CompareKPI label="Pedidos" current={nPed} previous={prevN} format="number" loading={loading} />
        <CompareKPI label="Ticket medio" current={ticket} previous={prevTicket} format="currency" loading={loading} />
        <CompareKPI label="Canais ativos" current={canalRows.length} previous={null} format="number" loading={loading} sub="no periodo" />
      </div>

      {/* Grafico de evolucao + Funil */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 16, marginBottom: 16 }}>
        <Card title="Evolucao de vendas">
          <div style={{ padding: '8px 16px 16px' }}>
            <EvolutionChart pedidos={filtered} start={start} end={end} />
          </div>
        </Card>
        <Card title="Funil operacional">
          <div style={{ padding: '12px 16px 16px' }}>
            <FunnelChart pedidosPorStatus={pedidosPorStatus} />
          </div>
        </Card>
      </div>

      {/* Ranking vendedores + Breakdown canal */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <Card title="Ranking de vendedores">
          {vendRanking.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados</div>
          ) : (
            <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr><th>#</th><th>Vendedor</th><th style={{textAlign:'right'}}>Faturamento</th><th style={{textAlign:'center'}}>Pedidos</th><th style={{textAlign:'right'}}>Ticket</th></tr>
                </thead>
                <tbody>
                  {vendRanking.slice(0, 10).map((v, i) => (
                    <tr key={v.nome}>
                      <td style={{ fontWeight:600, color: i < 3 ? 'var(--tm-brand-champagne)' : 'var(--tm-fg-4)', width: 30 }}>{i+1}</td>
                      <td style={{ fontWeight:500 }}>{v.nome}</td>
                      <td style={{ textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:600 }}>R$ {brl(v.fat)}</td>
                      <td style={{ textAlign:'center', color:'var(--tm-fg-3)' }}>{v.pedidos}</td>
                      <td style={{ textAlign:'right', fontVariantNumeric:'tabular-nums', fontSize:12, color:'var(--tm-fg-3)' }}>R$ {brl(v.ticket)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card>

        <Card title="Faturamento por canal">
          {canalRows.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados</div>
          ) : (
            <div style={{ padding: '4px 16px 12px' }}>
              {canalRows.map(([canal, d]) => {
                const pct = totalFat > 0 ? (d.fat / totalFat) * 100 : 0;
                return (
                  <div key={canal} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderBottom:'1px solid var(--tm-line-1)' }}>
                    <div style={{ minWidth:110, fontSize:12.5, color:'var(--tm-fg-1)' }}>{canal}</div>
                    <div style={{ flex:1, background:'var(--tm-bg-2)', borderRadius:4, height:8, overflow:'hidden' }}>
                      <div style={{ width:`${pct.toFixed(1)}%`, background:'var(--tm-brand-champagne)', height:'100%', borderRadius:4 }} />
                    </div>
                    <div style={{ minWidth:80, textAlign:'right', fontSize:12.5, fontVariantNumeric:'tabular-nums', color:'var(--tm-fg-1)' }}>R$ {brl(d.fat)}</div>
                    <div style={{ minWidth:38, textAlign:'right', fontSize:11, color:'var(--tm-fg-4)' }}>{pct.toFixed(0)}%</div>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      </div>

      {/* Tabela de pedidos */}
      <Card title="Pedidos faturados"
            action={
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input className="input" placeholder="Buscar pedido, cliente..." value={busca}
                  onChange={e => setBusca(e.target.value)}
                  style={{ fontSize:12, padding:'4px 10px', width:200 }} />
                <RelExportMenu onCSV={exportarCSV} disabled={loading} />
              </div>
            }>
        {loading ? (
          <div style={{ padding:'40px 0', textAlign:'center', color:'var(--tm-fg-3)', fontSize:13 }}>Carregando...</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding:'40px 0', textAlign:'center', color:'var(--tm-fg-3)' }}>
            <Icon name="package" size={32} style={{ opacity:0.3, marginBottom:10 }} />
            <div style={{ fontSize:13 }}>Nenhum pedido faturado no periodo</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
            <table className="data-table" style={{ width:'100%' }}>
              <thead>
                <tr>
                  <th>N Pedido</th><th>Cliente</th><th>Canal</th><th>Vendedor</th>
                  <th>Data</th><th>Forma Pgto</th><th style={{ textAlign:'right' }}>Total</th>
                </tr>
              </thead>
              <tbody>
                {filtered.slice(0, 50).map(p => (
                  <tr key={p.id}>
                    <td style={{ fontFamily:'monospace', fontSize:12 }}>{p.numero || '—'}</td>
                    <td>{p.cliente_nome || '—'}</td>
                    <td>{p.canal || '—'}</td>
                    <td>{p.vendedor || '—'}</td>
                    <td style={{ fontSize:12, color:'var(--tm-fg-3)', whiteSpace:'nowrap' }}>{relFmtDate(p.data_venda || p.created_at)}</td>
                    <td style={{ fontSize:12 }}>{p.forma_pagamento || '—'}</td>
                    <td style={{ textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:600, whiteSpace:'nowrap' }}>R$ {brl(parseFloat(p.total)||0)}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr>
                  <td colSpan={6} style={{ textAlign:'right', fontSize:12, color:'var(--tm-fg-3)', paddingTop:8 }}>
                    Total ({nPed} pedidos{filtered.length > 50 ? `, mostrando 50` : ''})
                  </td>
                  <td style={{ textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:700, paddingTop:8, whiteSpace:'nowrap' }}>R$ {brl(totalFat)}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// DISTRIBUIDORES HUB (Fase 2)
// ═══════════════════════════════════════════════════════════════════════════════

function RelDistribuidoresSection({ filters, setFilters, onNav }) {
  const [dados, setDados]     = React.useState(null);
  const [prevFat, setPrevFat] = React.useState(null);
  const [busca, setBusca]     = React.useState('');
  const [rankTab, setRankTab] = React.useState('volume');
  const [topCurva, setTopCurva] = React.useState(null); // dados para curva de crescimento

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);
  const { start: prevStart, end: prevEnd } = calcPreviousPeriod(start, end);

  React.useEffect(() => {
    if (!window.tmSupabase) { setDados({ dist: [], inativos: [] }); setPrevFat(0); return; }
    setDados(null);
    const s0 = start.toISOString();
    const s1 = new Date(end.getTime() + 86400000).toISOString();
    const ps0 = prevStart.toISOString();
    const ps1 = new Date(prevEnd.getTime() + 86400000).toISOString();

    Promise.all([
      window.tmSupabase.from('distribuidores').select('id,nome,cidade,uf,geral_uf,geral_cidade,status,total_faturado,total_saloes,cliente_desde,celular,email,responsavel,territorio').order('nome'),
      window.tmSupabase.from('pedidos').select('id,cliente_nome,total,status,created_at').eq('status','Atendido').gte('created_at', s0).lte('created_at', s1),
      window.tmSupabase.from('pedidos').select('id,cliente_nome,total').eq('status','Atendido').gte('created_at', ps0).lte('created_at', ps1),
      // All pedidos for recompra / inactivity
      window.tmSupabase.from('pedidos').select('cliente_nome,total,created_at,status').eq('status','Atendido').order('created_at', { ascending: true }),
    ]).then(([dRes, pRes, prevRes, allPedRes]) => {
      const dist = dRes.data || [];
      const peds = pRes.data || [];
      const prevPeds = prevRes.data || [];
      const allPeds = allPedRes.data || [];

      // Faturamento no periodo
      const fatMap = {};
      peds.forEach(p => {
        const k = p.cliente_nome;
        if (!fatMap[k]) fatMap[k] = { total: 0, qtd: 0 };
        fatMap[k].total += parseFloat(p.total) || 0;
        fatMap[k].qtd += 1;
      });

      // Frequencia e ciclo de recompra (all time)
      const byClient = {};
      allPeds.forEach(p => {
        const n = p.cliente_nome;
        if (!byClient[n]) byClient[n] = [];
        byClient[n].push(new Date(p.created_at));
      });
      const now = Date.now();

      const merged = dist.map(d => {
        const datas = byClient[d.nome] || [];
        let cicloMedio = null;
        if (datas.length >= 2) {
          datas.sort((a,b) => a - b);
          const intervalos = [];
          for (let i = 1; i < datas.length; i++) intervalos.push((datas[i] - datas[i-1]) / 86400000);
          cicloMedio = Math.round(intervalos.reduce((a,b) => a + b, 0) / intervalos.length);
        }
        const ultimaCompra = datas.length > 0 ? datas[datas.length - 1] : null;
        const diasInativo = ultimaCompra ? Math.floor((now - ultimaCompra.getTime()) / 86400000) : 999;

        return {
          ...d,
          fatReal: fatMap[d.nome]?.total || 0,
          pedReal: fatMap[d.nome]?.qtd || 0,
          totalCompras: datas.length,
          cicloMedio,
          diasInativo,
          ultimaCompra,
          ticket: fatMap[d.nome]?.qtd > 0 ? fatMap[d.nome].total / fatMap[d.nome].qtd : 0,
        };
      });

      // Inativos: sem pedido no periodo e > 45 dias desde ultimo
      const inativos = merged.filter(d => d.fatReal === 0 && d.diasInativo > 45 && d.totalCompras > 0)
        .sort((a,b) => b.diasInativo - a.diasInativo);

      setDados({ dist: merged.sort((a,b) => b.fatReal - a.fatReal), inativos });
      setPrevFat(prevPeds.reduce((a,p) => a + (parseFloat(p.total)||0), 0));

      // Curva de crescimento: top 5 dist por faturamento, evolucao mensal
      const top5 = merged.filter(d => d.fatReal > 0).slice(0, 5).map(d => d.nome);
      if (top5.length > 0) {
        const curvaData = {};
        top5.forEach(nome => { curvaData[nome] = {}; });
        allPeds.forEach(p => {
          if (!top5.includes(p.cliente_nome)) return;
          const dt = new Date(p.created_at);
          const key = dt.toISOString().slice(0, 7);
          if (!curvaData[p.cliente_nome][key]) curvaData[p.cliente_nome][key] = 0;
          curvaData[p.cliente_nome][key] += parseFloat(p.total) || 0;
        });
        // Last 6 months
        const months = [];
        for (let i = 5; i >= 0; i--) {
          const d = new Date(); d.setMonth(d.getMonth() - i);
          months.push(d.toISOString().slice(0, 7));
        }
        const colors = ['#C9A36B', '#6BA3D6', '#5BB17A', '#D4A04A', '#D9655E'];
        setTopCurva({
          labels: months.map(m => { const [y,mo] = m.split('-'); return new Date(y, mo-1).toLocaleDateString('pt-BR',{month:'short'}); }),
          datasets: top5.map((nome, i) => ({
            label: nome.length > 20 ? nome.slice(0,18) + '...' : nome,
            data: months.map(m => curvaData[nome][m] || 0),
            borderColor: colors[i], backgroundColor: 'transparent',
            borderWidth: 2, tension: 0.3, pointRadius: 3, pointBackgroundColor: colors[i],
          })),
        });
      }
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  const filtered = (dados?.dist || []).filter(d => {
    const q = busca.toLowerCase();
    const duf = d.uf || d.geral_uf || '';
    const matchBusca = !q || d.nome.toLowerCase().includes(q) || (d.cidade || d.geral_cidade || '').toLowerCase().includes(q) || duf.toLowerCase().includes(q);
    const matchEstado = !filters.estado || duf === filters.estado;
    return matchBusca && matchEstado;
  });
  const totalFat = filtered.reduce((a,d) => a + d.fatReal, 0);
  const ativos = filtered.filter(d => d.fatReal > 0).length;
  const ticketDist = ativos > 0 ? totalFat / ativos : 0;
  const loading = !dados;

  // Estados disponiveis para filtro
  const ufs = dados ? [...new Set(dados.dist.map(d => d.uf || d.geral_uf).filter(Boolean))].sort() : [];

  // Ranking multi-criterio
  const getRankedData = () => {
    const withData = filtered.filter(d => d.fatReal > 0 || d.totalCompras > 0);
    switch (rankTab) {
      case 'volume': return withData.sort((a,b) => b.fatReal - a.fatReal).map(d => ({ nome: d.nome, valor: d.fatReal }));
      case 'frequencia': return withData.sort((a,b) => b.pedReal - a.pedReal).map(d => ({ nome: d.nome, valor: d.pedReal }));
      case 'ticket': return withData.filter(d => d.ticket > 0).sort((a,b) => b.ticket - a.ticket).map(d => ({ nome: d.nome, valor: d.ticket }));
      case 'recorrencia': return withData.filter(d => d.totalCompras >= 2).sort((a,b) => b.totalCompras - a.totalCompras).map(d => ({ nome: d.nome, valor: d.totalCompras }));
      case 'regiao': {
        const byUf = {};
        withData.forEach(d => {
          const uf = d.uf || 'N/A';
          if (!byUf[uf]) byUf[uf] = { nome: uf, valor: 0 };
          byUf[uf].valor += d.fatReal;
        });
        return Object.values(byUf).sort((a,b) => b.valor - a.valor);
      }
      default: return [];
    }
  };
  const rankedData = loading ? [] : getRankedData();
  const rankFmt = (v) => {
    if (rankTab === 'volume' || rankTab === 'ticket' || rankTab === 'regiao') return `R$ ${brl(v)}`;
    if (rankTab === 'frequencia') return `${v} ped.`;
    if (rankTab === 'recorrencia') return `${v} compras`;
    return v;
  };

  // Mapa
  const mapRef = React.useRef(null);
  const leafletRef = React.useRef(null);
  const geoLayerRef = React.useRef(null);
  const geoCache = React.useRef(null);
  const [mapStatus, setMapStatus] = React.useState('loading');

  // Build ufFat from filtered data — inclui todos os distribuidores cadastrados
  const ufFat = React.useMemo(() => {
    const map = {};
    (dados?.dist || []).forEach(d => {
      const uf = d.uf || d.geral_uf;
      // Registra a UF principal do distribuidor
      const ufs = [uf];
      // Se o distribuidor tem território definido, inclui essas UFs também
      if (d.territorio && Array.isArray(d.territorio) && d.territorio.length > 0) {
        d.territorio.forEach(t => { if (t && !ufs.includes(t)) ufs.push(t); });
      }
      ufs.filter(Boolean).forEach(u => {
        if (!map[u]) map[u] = { fat: 0, pedidos: 0, topDist: '', distCount: 0 };
        map[u].fat += d.fatReal || 0;
        map[u].pedidos += d.pedReal || 0;
        map[u].distCount += 1;
        if (!map[u].topDist || (d.fatReal || 0) > 0) map[u].topDist = d.nome;
      });
    });
    return map;
  }, [dados]);

  // Map creation (once)
  React.useEffect(() => {
    if (!mapRef.current || !window.L || leafletRef.current) return;
    leafletRef.current = window.L.map(mapRef.current, {
      center: [-14.5, -51.5], zoom: 4,
      zoomControl: true, attributionControl: false,
      scrollWheelZoom: true, dragging: true,
      minZoom: 3, maxZoom: 7,
    });
    return () => { if (leafletRef.current) { leafletRef.current.remove(); leafletRef.current = null; } };
  }, []);

  // Map data update
  const startKey = Math.floor(start.getTime() / 60000);
  const endKey = Math.floor(end.getTime() / 60000);
  React.useEffect(() => {
    const map = leafletRef.current;
    if (!map || !dados) return;
    const L = window.L;
    if (geoLayerRef.current) { map.removeLayer(geoLayerRef.current); geoLayerRef.current = null; }
    setMapStatus('loading');

    const maxFat = Math.max(...Object.values(ufFat).map(u => u.fat), 1);
    const getColor = (fat, hasDistributor) => {
      if (!hasDistributor) return 'rgba(148,163,184,0.12)';
      if (!fat || fat === 0) return 'rgba(201,163,107,0.25)'; // dourado leve = tem distribuidor mas sem vendas no periodo
      const intensity = Math.min(fat / maxFat, 1);
      const r = Math.round(148 + (201 - 148) * intensity);
      const g = 163;
      const b = Math.round(184 + (107 - 184) * intensity);
      return `rgba(${r},${g},${b},${0.3 + intensity * 0.6})`;
    };

    const buildLayer = (geo) => {
      const layer = L.geoJSON(geo, {
        style: (f) => {
          const uf = IBGE_TO_UF_REL[parseInt(f.properties?.codarea ?? f.id ?? 0)];
          const info = ufFat[uf];
          return { fillColor: getColor(info?.fat || 0, !!info), fillOpacity: 1, weight: 1, color: 'rgba(255,255,255,0.3)' };
        },
        onEachFeature: (f, layer) => {
          const uf = IBGE_TO_UF_REL[parseInt(f.properties?.codarea ?? f.id ?? 0)] || '?';
          const info = ufFat[uf];
          let html;
          if (info && info.fat > 0) {
            html = `<b>${uf}</b><br>${info.distCount} distribuidor${info.distCount !== 1 ? 'es' : ''}<br>R$ ${brl(info.fat)}<br>${info.pedidos} pedido${info.pedidos !== 1 ? 's' : ''}<br><small>${info.topDist}</small>`;
          } else if (info) {
            html = `<b>${uf}</b><br>${info.distCount} distribuidor${info.distCount !== 1 ? 'es' : ''}<br><span style="color:#C9A36B">Cadastrado · sem vendas no periodo</span><br><small>${info.topDist}</small>`;
          } else {
            html = `<b>${uf}</b><br><span style="color:#94a3b8">Sem distribuidores</span>`;
          }
          layer.bindTooltip(html, { sticky: true });
          layer.on({
            mouseover: (e) => { e.target.setStyle({ fillOpacity: 1, weight: 2.5, color: '#C9A36B' }); e.target.bringToFront(); },
            mouseout: (e) => { e.target.setStyle({ weight: 1, color: 'rgba(255,255,255,0.3)', fillOpacity: 1 }); },
          });
        },
      });
      layer.addTo(map);
      geoLayerRef.current = layer;
      setMapStatus('ready');
    };

    if (geoCache.current) {
      buildLayer(geoCache.current);
    } else {
      fetch('https://servicodados.ibge.gov.br/api/v3/malhas/paises/BR?intrarregiao=UF&formato=application/vnd.geo+json')
        .then(r => r.json())
        .then(geo => { geoCache.current = geo; buildLayer(geo); })
        .catch(() => setMapStatus('error'));
    }
  }, [startKey, endKey, dados]);

  return (
    <div>
      {/* Filtro estado */}
      {ufs.length > 0 && (
        <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
          <FilterDropdown label="Estado (UF)" value={filters.estado} options={ufs}
            onChange={v => setFilters(f => ({ ...f, estado: v }))} />
        </div>
      )}

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Total distribuidores" current={dados ? dados.dist.length : null} previous={null} format="number" loading={loading} sub="cadastrados" />
        <CompareKPI label="Ativos no periodo" current={ativos} previous={null} format="number" loading={loading} sub="com pedidos" />
        <CompareKPI label="Faturamento" current={totalFat} previous={prevFat} format="currency" loading={loading} />
        <CompareKPI label="Ticket medio" current={ticketDist} previous={null} format="currency" loading={loading} sub="por dist. ativo" />
      </div>

      {/* Curva de crescimento + Mapa */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <Card title="Curva de crescimento — Top 5">
          <div style={{ padding: '8px 16px 16px' }}>
            {topCurva ? (
              <ChartCanvas type="line" data={topCurva} options={{
                scales: {
                  x: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: 'rgba(255,255,255,0.45)', font: { size: 10 } } },
                  y: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: 'rgba(255,255,255,0.45)', font: { size: 10 }, callback: v => v >= 1000 ? `${(v/1000).toFixed(0)}k` : v }, beginAtZero: true },
                },
                plugins: {
                  legend: { display: true, position: 'bottom', labels: { color: 'rgba(255,255,255,0.5)', font: { size: 10 }, boxWidth: 12, padding: 8 } },
                  tooltip: { backgroundColor: 'rgba(11,11,13,0.92)', callbacks: { label: ctx => `${ctx.dataset.label}: R$ ${brl(ctx.parsed.y)}` } },
                },
              }} height={220} />
            ) : (
              <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>
                {loading ? 'Carregando...' : 'Sem dados suficientes'}
              </div>
            )}
          </div>
        </Card>

        <Card title="Mapa de distribuidores">
          <div style={{ position: 'relative', height: 220, borderRadius: 8, overflow: 'hidden', background: 'var(--tm-bg-2)' }}>
            <div ref={mapRef} style={{ width: '100%', height: '100%' }} />
            {mapStatus === 'loading' && (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--tm-bg-2)' }}>
                <Icon name="loader" size={20} style={{ opacity: 0.4 }} />
              </div>
            )}
            {mapStatus === 'error' && (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--tm-fg-3)' }}>
                <span style={{ fontSize: 12 }}>Mapa indisponivel</span>
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Ranking multi-criterio + Inativos */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <Card title="Ranking inteligente">
          <div style={{ padding: '8px 16px 16px' }}>
            <div style={{ display: 'flex', gap: 4, marginBottom: 12, flexWrap: 'wrap' }}>
              {[
                { id: 'volume', label: 'Volume' },
                { id: 'frequencia', label: 'Frequencia' },
                { id: 'ticket', label: 'Ticket' },
                { id: 'recorrencia', label: 'Recorrencia' },
                { id: 'regiao', label: 'Regiao' },
              ].map(t => (
                <span key={t.id} className={`chip${rankTab === t.id ? ' active' : ''}`}
                  style={{ cursor: 'pointer', fontSize: 11 }} onClick={() => setRankTab(t.id)}>
                  {t.label}
                </span>
              ))}
            </div>
            <RankingBar items={rankedData} valueKey="valor" labelKey="nome" formatFn={rankFmt} maxItems={10} />
          </div>
        </Card>

        <Card title={`Distribuidores inativos (${dados?.inativos?.length || 0})`}>
          {!dados ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : dados.inativos.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)' }}>
              <Icon name="check-circle" size={24} style={{ opacity: 0.3, marginBottom: 8 }} />
              <div style={{ fontSize: 13 }}>Todos os distribuidores ativos!</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', padding: '4px 16px 12px' }}>
              {dados.inativos.slice(0, 8).map((d, i) => (
                <div key={d.nome} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0',
                  borderBottom: i < Math.min(dados.inativos.length, 8) - 1 ? '1px solid var(--tm-line-1)' : 'none',
                  cursor: 'pointer',
                }} onClick={() => onNav('crm/distribuidores')}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: d.diasInativo > 90 ? 'var(--tm-danger)' : '#D4A04A', flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, color: 'var(--tm-fg-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.nome}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--tm-fg-4)' }}>
                      {d.diasInativo}d inativo
                      {d.cicloMedio ? ` · ciclo ${d.cicloMedio}d` : ''}
                      {d.ultimaCompra ? ` · ultima: ${relFmtDate(d.ultimaCompra.toISOString())}` : ''}
                    </div>
                  </div>
                  <Icon name="chevron-right" size={14} style={{ color: 'var(--tm-fg-4)', flexShrink: 0 }} />
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      {/* Tabela principal com classificacao */}
      <Card title="Todos os distribuidores"
        action={<input className="input" placeholder="Buscar distribuidor..." value={busca} onChange={e => setBusca(e.target.value)} style={{ fontSize:12, padding:'4px 10px', width:200 }} />}>
        {loading ? (
          <div style={{ padding:'40px 0', textAlign:'center', color:'var(--tm-fg-3)', fontSize:13 }}>Carregando...</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding:'40px 0', textAlign:'center', color:'var(--tm-fg-3)' }}>
            <Icon name="building-2" size={32} style={{ opacity:0.3, marginBottom:10 }} />
            <div style={{ fontSize:13 }}>Nenhum distribuidor encontrado</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
            <table className="data-table" style={{ width:'100%' }}>
              <thead>
                <tr>
                  <th style={{ width: 28 }}>#</th><th>Distribuidor</th><th>Classe</th><th>Cidade</th>
                  <th style={{textAlign:'center'}}>Pedidos</th><th style={{textAlign:'right'}}>Faturamento</th>
                  <th style={{textAlign:'center'}}>Ciclo</th>
                </tr>
              </thead>
              <tbody>
                {filtered.slice(0, 30).map((d, i) => (
                  <tr key={d.id}>
                    <td style={{ fontWeight:600, color: i < 3 ? 'var(--tm-brand-champagne)' : 'var(--tm-fg-4)' }}>{i+1}</td>
                    <td style={{ fontWeight:500 }}>{d.nome}</td>
                    <td><DistClassBadge fat={d.fatReal} pedidos={d.pedReal} /></td>
                    <td style={{ fontSize:12, color:'var(--tm-fg-3)' }}>{d.cidade ? `${d.cidade}${d.uf ? ` · ${d.uf}` : ''}` : d.uf || '—'}</td>
                    <td style={{ textAlign:'center' }}>{d.pedReal || '—'}</td>
                    <td style={{ textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight: d.fatReal > 0 ? 600 : 400, color: d.fatReal > 0 ? 'var(--tm-fg-1)' : 'var(--tm-fg-4)', whiteSpace:'nowrap' }}>
                      {d.fatReal > 0 ? `R$ ${brl(d.fatReal)}` : '—'}
                    </td>
                    <td style={{ textAlign:'center', fontSize:12, color:'var(--tm-fg-3)' }}>
                      {d.cicloMedio ? `${d.cicloMedio}d` : '—'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// CLIENTES & RECORRÊNCIA (Fase 3)
// ═══════════════════════════════════════════════════════════════════════════════

function RelClientesSection({ filters, onNav }) {
  const [dados, setDados] = React.useState(null);
  const [prevData, setPrevData] = React.useState(null);
  const [busca, setBusca] = React.useState('');
  const [viewTab, setViewTab] = React.useState('geral');

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);
  const { start: prevStart, end: prevEnd } = calcPreviousPeriod(start, end);

  React.useEffect(() => {
    if (!window.tmSupabase) { setDados({ clientes: [], freqFaixas: [], risco: [], ltvRanking: [] }); setPrevData({}); return; }
    setDados(null);
    const s0 = start.toISOString();
    const s1 = new Date(end.getTime() + 86400000).toISOString();
    const ps0 = prevStart.toISOString();
    const ps1 = new Date(prevEnd.getTime() + 86400000).toISOString();

    Promise.all([
      window.tmSupabase.from('clientes').select('id,nome,cidade,uf,celular,email,cliente_desde').order('nome'),
      window.tmSupabase.from('distribuidores').select('id,nome,cidade,uf,celular,email,cliente_desde').order('nome'),
      window.tmSupabase.from('saloes').select('id,nome,cidade,uf,celular,email,cliente_desde').order('nome'),
      window.tmSupabase.from('pedidos').select('cliente_nome,total,status,created_at').eq('status','Atendido').gte('created_at', s0).lte('created_at', s1),
      window.tmSupabase.from('pedidos').select('cliente_nome,total,status,created_at').eq('status','Atendido').gte('created_at', ps0).lte('created_at', ps1),
      window.tmSupabase.from('pedidos').select('cliente_nome,total,created_at').eq('status','Atendido').order('created_at', { ascending: true }),
      window.tmSupabase.from('pedido_itens').select('pedido_id,descricao,sku,quantidade,preco_lista'),
      window.tmSupabase.from('pedidos').select('id,cliente_nome').eq('status','Atendido'),
    ]).then(([cRes, dRes, sRes, pRes, prevRes, allPedRes, itensRes, pedIdRes]) => {
      const peds = pRes.data || [];
      const prevPeds = prevRes.data || [];
      const allPeds = allPedRes.data || [];
      const itens = itensRes.data || [];
      const pedIds = pedIdRes.data || [];

      const fatMap = {};
      peds.forEach(p => {
        const k = p.cliente_nome;
        if (!fatMap[k]) fatMap[k] = { total: 0, qtd: 0, ultima: null };
        fatMap[k].total += parseFloat(p.total) || 0;
        fatMap[k].qtd += 1;
        if (!fatMap[k].ultima || p.created_at > fatMap[k].ultima) fatMap[k].ultima = p.created_at;
      });

      // All-time data by client
      const byClient = {};
      allPeds.forEach(p => {
        const n = p.cliente_nome;
        if (!byClient[n]) byClient[n] = { datas: [], totalLtv: 0 };
        byClient[n].datas.push(new Date(p.created_at));
        byClient[n].totalLtv += parseFloat(p.total) || 0;
      });

      const now = Date.now();
      const merge = (list, tipo) => list.map(c => {
        const hist = byClient[c.nome] || { datas: [], totalLtv: 0 };
        const datas = hist.datas.sort((a, b) => a - b);
        let cicloMedio = null;
        if (datas.length >= 2) {
          const intervalos = [];
          for (let i = 1; i < datas.length; i++) intervalos.push((datas[i] - datas[i-1]) / 86400000);
          cicloMedio = Math.round(intervalos.reduce((a, b) => a + b, 0) / intervalos.length);
        }
        const ultimaCompra = datas.length > 0 ? datas[datas.length - 1] : null;
        const diasInativo = ultimaCompra ? Math.floor((now - ultimaCompra.getTime()) / 86400000) : 999;
        const emRisco = cicloMedio && diasInativo > cicloMedio * 1.5;

        return {
          ...c, tipo,
          fat: fatMap[c.nome]?.total || 0,
          pedQtd: fatMap[c.nome]?.qtd || 0,
          ultimaCompra: fatMap[c.nome]?.ultima,
          totalCompras: datas.length,
          ltv: hist.totalLtv,
          cicloMedio,
          diasInativo,
          emRisco,
          proximaCompra: cicloMedio && ultimaCompra ? new Date(ultimaCompra.getTime() + cicloMedio * 86400000) : null,
        };
      });

      const all = [
        ...merge(cRes.data || [], 'Cliente'),
        ...merge(dRes.data || [], 'Distribuidor'),
        ...merge(sRes.data || [], 'Salao'),
      ].sort((a, b) => b.fat - a.fat);

      // Frequencia histogram
      const freqBuckets = { '1 compra': 0, '2-3 compras': 0, '4-6 compras': 0, '7-12 compras': 0, '13+ compras': 0 };
      all.forEach(c => {
        const n = c.totalCompras;
        if (n === 0) return;
        if (n === 1) freqBuckets['1 compra']++;
        else if (n <= 3) freqBuckets['2-3 compras']++;
        else if (n <= 6) freqBuckets['4-6 compras']++;
        else if (n <= 12) freqBuckets['7-12 compras']++;
        else freqBuckets['13+ compras']++;
      });
      const freqFaixas = Object.entries(freqBuckets).map(([label, count]) => ({ label, count }));

      // Risco de perda
      const risco = all.filter(c => c.emRisco && c.totalCompras >= 2).sort((a, b) => b.ltv - a.ltv);

      // LTV ranking
      const ltvRanking = all.filter(c => c.ltv > 0).sort((a, b) => b.ltv - a.ltv).slice(0, 20);

      // Produtos favoritos por cliente (top 5 clients)
      const pedIdMap = {};
      pedIds.forEach(p => { pedIdMap[p.id] = p.cliente_nome; });
      const prodByClient = {};
      itens.forEach(it => {
        const cli = pedIdMap[it.pedido_id];
        if (!cli) return;
        if (!prodByClient[cli]) prodByClient[cli] = {};
        const k = it.descricao || it.sku;
        if (!prodByClient[cli][k]) prodByClient[cli][k] = 0;
        prodByClient[cli][k] += it.quantidade || 0;
      });

      const topClients = all.filter(c => c.ltv > 0).slice(0, 5);
      const prodFavoritos = topClients.map(c => {
        const prods = prodByClient[c.nome] || {};
        const top3 = Object.entries(prods).sort((a, b) => b[1] - a[1]).slice(0, 3);
        return { nome: c.nome, produtos: top3 };
      });

      setDados({ clientes: all, freqFaixas, risco, ltvRanking, prodFavoritos });
      setPrevData({ fat: prevPeds.reduce((a, p) => a + (parseFloat(p.total) || 0), 0), n: prevPeds.length });
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  const d = dados || {};
  const filtered = (d.clientes || []).filter(c => {
    const q = busca.toLowerCase();
    return !q || c.nome.toLowerCase().includes(q) || (c.cidade || '').toLowerCase().includes(q) || c.tipo.toLowerCase().includes(q);
  });
  const comCompra = filtered.filter(c => c.fat > 0);
  const totalFat = comCompra.reduce((a, c) => a + c.fat, 0);
  const recorrentes = filtered.filter(c => c.totalCompras >= 2).length;
  const loading = dados === null;

  return (
    <div>
      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Total contatos" current={filtered.length} previous={null} format="number" loading={loading} sub="clientes + dist + saloes" />
        <CompareKPI label="Com compras" current={comCompra.length} previous={prevData ? prevData.n : null} format="number" loading={loading} />
        <CompareKPI label="Recorrentes" current={recorrentes} previous={null} format="number" loading={loading} sub="2+ compras" />
        <CompareKPI label="Em risco" current={(d.risco || []).length} previous={null} format="number" loading={loading} sub="> ciclo x 1.5" />
      </div>

      {/* View tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
        {[
          { id: 'geral', label: 'Visao Geral' },
          { id: 'recorrencia', label: 'Recorrencia' },
          { id: 'risco', label: 'Risco de Perda' },
          { id: 'ltv', label: 'LTV Ranking' },
        ].map(t => (
          <span key={t.id} className={`chip${viewTab === t.id ? ' active' : ''}`}
            style={{ cursor: 'pointer', fontSize: 11 }} onClick={() => setViewTab(t.id)}>
            {t.label}
          </span>
        ))}
      </div>

      {viewTab === 'geral' && (
        <>
          {/* Frequencia histograma + Produtos favoritos */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
            <Card title="Frequencia de compra">
              <div style={{ padding: '8px 16px 16px' }}>
                <FrequenciaHistograma faixas={d.freqFaixas} height={200} />
              </div>
            </Card>
            <Card title="Produtos favoritos — Top 5 clientes">
              {loading ? (
                <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
              ) : (d.prodFavoritos || []).length === 0 ? (
                <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados</div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0, padding: '8px 16px 12px' }}>
                  {d.prodFavoritos.map((cli, idx) => (
                    <div key={cli.nome} style={{ padding: '12px 0', borderBottom: idx < d.prodFavoritos.length - 1 ? '1px solid var(--tm-line-1)' : 'none' }}>
                      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--tm-fg-1)', marginBottom: 8 }}>{cli.nome}</div>
                      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                        {cli.produtos.map(([prod, qty]) => (
                          <span key={prod} style={{ fontSize: 10.5, padding: '3px 10px', borderRadius: 4, background: 'var(--tm-bg-2)', color: 'var(--tm-fg-3)' }}>
                            {prod.length > 25 ? prod.slice(0, 23) + '..' : prod} ({qty}x)
                          </span>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>

          {/* Main table */}
          <Card title="Lista de contatos"
            action={<input className="input" placeholder="Buscar nome, cidade..." value={busca} onChange={e => setBusca(e.target.value)} style={{ fontSize: 12, padding: '4px 10px', width: 200 }} />}>
            {loading ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
            ) : filtered.length === 0 ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)' }}>
                <Icon name="users-2" size={32} style={{ opacity: 0.3, marginBottom: 10 }} />
                <div style={{ fontSize: 13 }}>Nenhum contato encontrado</div>
              </div>
            ) : (
              <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead><tr><th style={{ width: 28 }}>#</th><th>Nome</th><th>Tipo</th><th>Cidade</th><th style={{ textAlign: 'center' }}>Pedidos</th><th>Ultima</th><th style={{ textAlign: 'right' }}>Faturamento</th></tr></thead>
                  <tbody>
                    {filtered.slice(0, 50).map((c, i) => (
                      <tr key={`${c.tipo}-${c.id}`}>
                        <td style={{ color: 'var(--tm-fg-3)' }}>{i + 1}</td>
                        <td style={{ fontWeight: 500 }}>{c.nome}</td>
                        <td><Badge tone={c.tipo === 'Distribuidor' ? 'warning' : c.tipo === 'Salao' ? 'info' : 'default'}>{c.tipo}</Badge></td>
                        <td style={{ fontSize: 12, color: 'var(--tm-fg-3)' }}>{c.cidade || '—'}</td>
                        <td style={{ textAlign: 'center' }}>{c.totalCompras || '—'}</td>
                        <td style={{ fontSize: 12, color: 'var(--tm-fg-3)', whiteSpace: 'nowrap' }}>{relFmtDate(c.ultimaCompra)}</td>
                        <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: c.fat > 0 ? 600 : 400, color: c.fat > 0 ? 'var(--tm-fg-1)' : 'var(--tm-fg-4)', whiteSpace: 'nowrap' }}>
                          {c.fat > 0 ? `R$ ${brl(c.fat)}` : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card>
        </>
      )}

      {viewTab === 'recorrencia' && (
        <Card title="Previsao de recompra">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (() => {
            const comCiclo = filtered.filter(c => c.cicloMedio && c.proximaCompra).sort((a, b) => a.proximaCompra - b.proximaCompra);
            if (comCiclo.length === 0) return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Nenhum cliente com ciclo calculavel (necessario 2+ compras)</div>;
            const hoje = new Date();
            return (
              <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead><tr><th>Cliente</th><th>Tipo</th><th style={{ textAlign: 'center' }}>Ciclo medio</th><th style={{ textAlign: 'center' }}>Total compras</th><th>Ultima compra</th><th>Proxima prevista</th><th>Status</th></tr></thead>
                <tbody>
                  {comCiclo.slice(0, 40).map(c => {
                    const atrasado = c.proximaCompra < hoje;
                    const diasPara = Math.ceil((c.proximaCompra - hoje) / 86400000);
                    return (
                      <tr key={`${c.tipo}-${c.id}`}>
                        <td style={{ fontWeight: 500 }}>{c.nome}</td>
                        <td><Badge tone={c.tipo === 'Distribuidor' ? 'warning' : c.tipo === 'Salao' ? 'info' : 'default'}>{c.tipo}</Badge></td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{c.cicloMedio}d</td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{c.totalCompras}</td>
                        <td style={{ fontSize: 12, color: 'var(--tm-fg-3)' }}>{relFmtDate(c.ultimaCompra)}</td>
                        <td style={{ fontSize: 12, color: atrasado ? 'var(--tm-danger)' : 'var(--tm-fg-2)' }}>{c.proximaCompra.toLocaleDateString('pt-BR')}</td>
                        <td>
                          {atrasado ? (
                            <Badge tone="danger">{Math.abs(diasPara)}d atrasado</Badge>
                          ) : diasPara <= 7 ? (
                            <Badge tone="warning">em {diasPara}d</Badge>
                          ) : (
                            <span style={{ fontSize: 11, color: 'var(--tm-fg-4)' }}>em {diasPara}d</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              </div>
            );
          })()}
        </Card>
      )}

      {viewTab === 'risco' && (
        <Card title="Clientes em risco de perda">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (d.risco || []).length === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)' }}>
              <Icon name="check-circle" size={28} style={{ opacity: 0.3, marginBottom: 8 }} />
              <div style={{ fontSize: 13 }}>Nenhum cliente em risco!</div>
            </div>
          ) : (
            <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead><tr><th>Cliente</th><th>Tipo</th><th style={{ textAlign: 'center' }}>Ciclo</th><th style={{ textAlign: 'center' }}>Dias inativo</th><th style={{ textAlign: 'right' }}>LTV</th><th>Atraso</th></tr></thead>
                <tbody>
                  {d.risco.slice(0, 30).map(c => {
                    const atraso = c.diasInativo - c.cicloMedio;
                    return (
                      <tr key={`${c.tipo}-${c.id}`}>
                        <td style={{ fontWeight: 500 }}>{c.nome}</td>
                        <td><Badge tone={c.tipo === 'Distribuidor' ? 'warning' : c.tipo === 'Salao' ? 'info' : 'default'}>{c.tipo}</Badge></td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{c.cicloMedio}d</td>
                        <td style={{ textAlign: 'center', fontSize: 12, color: 'var(--tm-danger)' }}>{c.diasInativo}d</td>
                        <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600, whiteSpace: 'nowrap' }}>R$ {brl(c.ltv)}</td>
                        <td><Badge tone="danger">+{atraso}d</Badge></td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </Card>
      )}

      {viewTab === 'ltv' && (
        <Card title="LTV Ranking — Top 20">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (
            <div style={{ padding: '8px 16px 16px' }}>
              <RankingBar
                items={(d.ltvRanking || []).map(c => ({ nome: c.nome, valor: c.ltv }))}
                valueKey="valor" labelKey="nome"
                formatFn={v => `R$ ${brl(v)}`}
                maxItems={20}
              />
            </div>
          )}
        </Card>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// FINANCEIRO AVANÇADO (Fase 3)
// ═══════════════════════════════════════════════════════════════════════════════

function RelFinanceiroSection({ filters, onNav }) {
  const [dados, setDados] = React.useState(null);
  const [prevFat, setPrevFat] = React.useState(null);
  const [taxRate, setTaxRate] = React.useState(15);

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);
  const { start: prevStart, end: prevEnd } = calcPreviousPeriod(start, end);

  React.useEffect(() => {
    if (!window.tmSupabase) { setDados({}); setPrevFat(0); return; }
    setDados(null);
    const s0 = start.toISOString();
    const s1 = new Date(end.getTime() + 86400000).toISOString();
    const ps0 = prevStart.toISOString();
    const ps1 = new Date(prevEnd.getTime() + 86400000).toISOString();

    Promise.all([
      window.tmSupabase.from('pedidos').select('id,total,status,created_at,cliente_nome').eq('status','Atendido').gte('created_at', s0).lte('created_at', s1),
      window.tmSupabase.from('contas_receber').select('valor,valor_recebido,status,vencimento,forma_pagamento,cliente_nome,referencia,parcela'),
      window.tmSupabase.from('contas_pagar').select('valor,status,vencimento,categoria,fornecedor'),
      window.tmSupabase.from('pedidos').select('total').eq('status','Atendido').gte('created_at', ps0).lte('created_at', ps1),
      window.tmSupabase.from('pedido_itens').select('pedido_id,quantidade,preco_lista,preco_custo'),
      window.tmSupabase.from('pedidos').select('id,total,created_at,cliente_nome').eq('status','Atendido').order('created_at', { ascending: false }).limit(200),
    ]).then(([pRes, crRes, cpRes, prevRes, itensRes, recentRes]) => {
      const pedidos = pRes.data || [];
      const cr = crRes.data || [];
      const cp = cpRes.data || [];
      const itens = itensRes.data || [];
      const recentPeds = recentRes.data || [];

      const faturamento = pedidos.reduce((a, p) => a + (parseFloat(p.total) || 0), 0);
      const recebido = cr.filter(r => r.status === 'Recebido').reduce((a, r) => a + (parseFloat(r.valor_recebido) || parseFloat(r.valor) || 0), 0);
      const aReceber = cr.filter(r => r.status !== 'Recebido').reduce((a, r) => a + ((parseFloat(r.valor) || 0) - (parseFloat(r.valor_recebido) || 0)), 0);
      const vencidos = cr.filter(r => r.status !== 'Recebido' && r.vencimento && new Date(r.vencimento) < new Date());
      const totalVencido = vencidos.reduce((a, r) => a + ((parseFloat(r.valor) || 0) - (parseFloat(r.valor_recebido) || 0)), 0);
      const pago = cp.filter(r => r.status === 'Pago').reduce((a, r) => a + (parseFloat(r.valor) || 0), 0);
      const aPagar = cp.filter(r => r.status !== 'Pago').reduce((a, r) => a + (parseFloat(r.valor) || 0), 0);

      // CMV from pedido_itens
      const pedIdsInPeriod = new Set(pedidos.map(p => p.id));
      let cmv = 0;
      itens.forEach(it => {
        if (!pedIdsInPeriod.has(it.pedido_id)) return;
        const custo = parseFloat(it.preco_custo) || 0;
        const qty = it.quantidade || 0;
        cmv += custo * qty;
      });

      // Aging de inadimplencia
      const hoje = new Date();
      const aging = [
        { label: '0-30 dias', valor: 0 },
        { label: '31-60 dias', valor: 0 },
        { label: '61-90 dias', valor: 0 },
        { label: '90+ dias', valor: 0 },
      ];
      vencidos.forEach(r => {
        const venc = new Date(r.vencimento);
        const dias = Math.floor((hoje - venc) / 86400000);
        const saldo = (parseFloat(r.valor) || 0) - (parseFloat(r.valor_recebido) || 0);
        if (dias <= 30) aging[0].valor += saldo;
        else if (dias <= 60) aging[1].valor += saldo;
        else if (dias <= 90) aging[2].valor += saldo;
        else aging[3].valor += saldo;
      });

      // Projecao 30 dias (media diaria * 30)
      const diasPeriodo = Math.max(1, Math.ceil((end - start) / 86400000));
      const mediaDiaria = faturamento / diasPeriodo;
      const projecao30 = mediaDiaria * 30;

      // Margem por venda (recent 50)
      const margemPorVenda = [];
      const pedIdSet = new Set(pedidos.map(p => p.id));
      const custoByPedido = {};
      itens.forEach(it => {
        if (!custoByPedido[it.pedido_id]) custoByPedido[it.pedido_id] = 0;
        custoByPedido[it.pedido_id] += (parseFloat(it.preco_custo) || 0) * (it.quantidade || 0);
      });
      pedidos.slice(0, 50).forEach(p => {
        const total = parseFloat(p.total) || 0;
        const custo = custoByPedido[p.id] || 0;
        const margem = total > 0 && custo > 0 ? ((total - custo) / total) * 100 : null;
        margemPorVenda.push({ id: p.id, cliente: p.cliente_nome, total, custo, margem, data: p.created_at });
      });

      // Fluxo de caixa visual (daily in period)
      const fluxoDiario = {};
      pedidos.forEach(p => {
        const day = new Date(p.created_at).toISOString().slice(0, 10);
        if (!fluxoDiario[day]) fluxoDiario[day] = { entrada: 0, saida: 0 };
        fluxoDiario[day].entrada += parseFloat(p.total) || 0;
      });
      cp.filter(c => c.status === 'Pago' && c.vencimento).forEach(c => {
        const day = new Date(c.vencimento).toISOString().slice(0, 10);
        if (!fluxoDiario[day]) fluxoDiario[day] = { entrada: 0, saida: 0 };
        fluxoDiario[day].saida += parseFloat(c.valor) || 0;
      });
      const fluxoSorted = Object.entries(fluxoDiario).sort((a, b) => a[0].localeCompare(b[0])).slice(-30);

      const saldoLiquido = recebido - pago;
      setDados({
        faturamento, recebido, aReceber, totalVencido, vencidosQtd: vencidos.length,
        pago, aPagar, saldoLiquido, cr, cp, nPed: pedidos.length,
        cmv, aging, projecao30, margemPorVenda, fluxoSorted,
      });
      setPrevFat((prevRes.data || []).reduce((a, p) => a + (parseFloat(p.total) || 0), 0));
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  const d = dados || {};
  const loading = dados === null;

  // DRE Real
  const impostos = (d.faturamento || 0) * (taxRate / 100);
  const lucroBruto = (d.faturamento || 0) - (d.cmv || 0);
  const lucroLiquido = lucroBruto - impostos - (d.pago || 0);
  const margemBruta = d.faturamento > 0 ? (lucroBruto / d.faturamento) * 100 : 0;
  const margemLiquida = d.faturamento > 0 ? (lucroLiquido / d.faturamento) * 100 : 0;

  const dreRows = [
    { label: 'Receita Bruta', valor: d.faturamento, tone: '' },
    { label: `(-) Impostos (${taxRate}%)`, valor: impostos, tone: 'down' },
    { label: '(-) CMV (Custo Mercadoria)', valor: d.cmv, tone: 'down' },
    { label: `(=) Lucro Bruto (${margemBruta.toFixed(1)}%)`, valor: lucroBruto, tone: lucroBruto >= 0 ? 'up' : 'down', bold: true },
    { label: '(-) Despesas Operacionais', valor: d.pago, tone: 'down' },
    { label: `(=) Lucro Liquido (${margemLiquida.toFixed(1)}%)`, valor: lucroLiquido, tone: lucroLiquido >= 0 ? 'up' : 'down', bold: true },
  ];

  // Fluxo de caixa chart data
  const fluxoChartData = React.useMemo(() => {
    if (!d.fluxoSorted || d.fluxoSorted.length === 0) return null;
    const labels = d.fluxoSorted.map(([day]) => {
      const dt = new Date(day + 'T12:00:00');
      return dt.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
    });
    return {
      labels,
      datasets: [
        { label: 'Entradas', data: d.fluxoSorted.map(([, v]) => v.entrada), backgroundColor: 'rgba(91,177,122,0.7)', borderRadius: 3 },
        { label: 'Saidas', data: d.fluxoSorted.map(([, v]) => -v.saida), backgroundColor: 'rgba(217,101,94,0.7)', borderRadius: 3 },
      ],
    };
  }, [d.fluxoSorted]);

  const formaMap = {};
  (d.cr || []).forEach(r => {
    const f = r.forma_pagamento || 'Outros';
    if (!formaMap[f]) formaMap[f] = { val: 0, qtd: 0 };
    formaMap[f].val += parseFloat(r.valor) || 0;
    formaMap[f].qtd += 1;
  });
  const formaRows = Object.entries(formaMap).sort((a, b) => b[1].val - a[1].val);
  const totalForma = formaRows.reduce((a, [, v]) => a + v.val, 0);

  return (
    <div>
      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Faturamento" current={d.faturamento || 0} previous={prevFat} format="currency" loading={loading} />
        <CompareKPI label="Lucro Liquido" current={lucroLiquido} previous={null} format="currency" loading={loading} sub={`margem ${margemLiquida.toFixed(1)}%`} />
        <CompareKPI label="Inadimplencia" current={d.totalVencido || 0} previous={null} format="currency" loading={loading} sub={d.vencidosQtd > 0 ? `${d.vencidosQtd} titulos` : 'em dia'} />
        <CompareKPI label="Projecao 30d" current={d.projecao30 || 0} previous={null} format="currency" loading={loading} sub="com base no ritmo atual" />
      </div>

      {/* DRE + Aging */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <Card title="DRE — Demonstrativo de Resultado"
          action={
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 10.5, color: 'var(--tm-fg-4)' }}>Impostos:</span>
              <input type="number" value={taxRate} onChange={e => setTaxRate(Math.max(0, Math.min(100, Number(e.target.value))))}
                style={{ width: 48, height: 24, fontSize: 11, textAlign: 'center', borderRadius: 4, border: '1px solid var(--tm-line-2)', background: 'var(--tm-bg-2)', color: 'var(--tm-fg-1)', fontFamily: 'inherit' }} />
              <span style={{ fontSize: 10.5, color: 'var(--tm-fg-4)' }}>%</span>
            </div>
          }>
          <div style={{ padding: '4px 0' }}>
            {loading ? (
              <div style={{ padding: '30px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
            ) : dreRows.map((row, i) => (
              <div key={i} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '12px 16px', borderBottom: i < dreRows.length - 1 ? '1px solid var(--tm-line-1)' : 'none',
                background: row.bold ? 'color-mix(in srgb, var(--tm-brand-champagne) 5%, transparent)' : 'transparent',
              }}>
                <span style={{ fontSize: 13, fontWeight: row.bold ? 700 : 400, color: 'var(--tm-fg-2)' }}>{row.label}</span>
                <span style={{
                  fontSize: 14, fontWeight: row.bold ? 700 : 600, fontVariantNumeric: 'tabular-nums',
                  color: row.tone === 'up' ? 'var(--tm-success)' : row.tone === 'down' ? 'var(--tm-danger)' : row.tone === 'warn' ? '#D4A04A' : 'var(--tm-fg-1)',
                }}>
                  R$ {brl(row.valor || 0)}
                </span>
              </div>
            ))}
          </div>
        </Card>

        <Card title="Aging de inadimplencia">
          <div style={{ padding: '8px 16px 16px' }}>
            <AgingChart faixas={d.aging} height={200} />
            {!loading && d.aging && (
              <div style={{ display: 'flex', justifyContent: 'space-around', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--tm-line-1)' }}>
                {d.aging.map(f => (
                  <div key={f.label} style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 11, color: 'var(--tm-fg-4)' }}>{f.label}</div>
                    <div style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: 'tabular-nums', color: f.valor > 0 ? 'var(--tm-danger)' : 'var(--tm-fg-3)' }}>
                      R$ {brl(f.valor)}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Fluxo de caixa + Recebiveis forma pgto */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <Card title="Fluxo de caixa — ultimos 30 dias">
          <div style={{ padding: '8px 16px 16px' }}>
            {!fluxoChartData ? (
              <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>{loading ? 'Carregando...' : 'Sem dados'}</div>
            ) : (
              <ChartCanvas type="bar" data={fluxoChartData} options={{
                scales: {
                  x: { stacked: true, grid: { display: false }, ticks: { color: 'rgba(255,255,255,0.45)', font: { size: 9 }, maxTicksLimit: 10 } },
                  y: { stacked: true, grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: 'rgba(255,255,255,0.45)', font: { size: 10 }, callback: v => v >= 1000 ? `${(v/1000).toFixed(0)}k` : v < -1000 ? `${(v/1000).toFixed(0)}k` : v } },
                },
                plugins: {
                  legend: { display: true, position: 'bottom', labels: { color: 'rgba(255,255,255,0.5)', font: { size: 10 }, boxWidth: 10 } },
                  tooltip: { backgroundColor: 'rgba(11,11,13,0.92)', callbacks: { label: ctx => `${ctx.dataset.label}: R$ ${brl(Math.abs(ctx.parsed.y))}` } },
                },
              }} height={220} />
            )}
          </div>
        </Card>

        <Card title="Recebiveis por forma de pagamento">
          {formaRows.length === 0 ? (
            <div style={{ padding: '30px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>{dados ? 'Sem dados' : 'Carregando...'}</div>
          ) : (
            <div style={{ padding: '4px 0' }}>
              {formaRows.map(([forma, v]) => {
                const pct = totalForma > 0 ? (v.val / totalForma) * 100 : 0;
                return (
                  <div key={forma} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px', borderBottom: '1px solid var(--tm-line-1)' }}>
                    <div style={{ minWidth: 100, fontSize: 13, color: 'var(--tm-fg-1)' }}>{forma}</div>
                    <div style={{ flex: 1, background: 'var(--tm-bg-2)', borderRadius: 4, height: 8, overflow: 'hidden' }}>
                      <div style={{ width: `${pct}%`, background: 'var(--tm-brand-champagne)', height: '100%', borderRadius: 4 }} />
                    </div>
                    <div style={{ minWidth: 90, textAlign: 'right', fontSize: 13, fontVariantNumeric: 'tabular-nums' }}>R$ {brl(v.val)}</div>
                    <div style={{ minWidth: 40, textAlign: 'right', fontSize: 11, color: 'var(--tm-fg-4)' }}>{v.qtd}x</div>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      </div>

      {/* Margem por venda */}
      <Card title="Margem real por venda — ultimos 50 pedidos">
        {loading ? (
          <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
        ) : (d.margemPorVenda || []).filter(m => m.margem !== null).length === 0 ? (
          <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)' }}>
            <Icon name="calculator" size={28} style={{ opacity: 0.3, marginBottom: 8 }} />
            <div style={{ fontSize: 13 }}>Sem dados de custo. Preencha preco_custo nos itens.</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
            <table className="data-table" style={{ width: '100%' }}>
              <thead><tr><th>Cliente</th><th>Data</th><th style={{ textAlign: 'right' }}>Venda</th><th style={{ textAlign: 'right' }}>Custo</th><th style={{ textAlign: 'right' }}>Margem</th></tr></thead>
              <tbody>
                {(d.margemPorVenda || []).filter(m => m.margem !== null).slice(0, 30).map(m => (
                  <tr key={m.id}>
                    <td style={{ fontWeight: 500, fontSize: 12 }}>{m.cliente || '—'}</td>
                    <td style={{ fontSize: 12, color: 'var(--tm-fg-3)', whiteSpace: 'nowrap' }}>{relFmtDate(m.data)}</td>
                    <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, whiteSpace: 'nowrap' }}>R$ {brl(m.total)}</td>
                    <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, color: 'var(--tm-fg-3)', whiteSpace: 'nowrap' }}>R$ {brl(m.custo)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 600, fontSize: 12, color: m.margem >= 30 ? 'var(--tm-success)' : m.margem >= 15 ? '#D4A04A' : 'var(--tm-danger)' }}>
                      {m.margem.toFixed(1)}%
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// INSIGHTS (mantido da Fase 1)
// ═══════════════════════════════════════════════════════════════════════════════

function RelInsightsSection({ filters, onNav }) {
  const [insights, setInsights] = React.useState(null);

  React.useEffect(() => {
    if (!window.tmSupabase) { setInsights([]); return; }
    setInsights(null);
    Promise.all([
      window.tmSupabase.from('pedidos').select('total,status,created_at,cliente_nome').eq('status','Atendido'),
      window.tmSupabase.from('pedido_itens').select('sku,descricao,quantidade,preco_lista'),
      window.tmSupabase.from('produtos').select('nome,sku,estoque,preco_venda,preco_custo,linha,status_estoque'),
      window.tmSupabase.from('contas_receber').select('valor,valor_recebido,status,vencimento'),
      window.tmSupabase.from('distribuidores').select('nome,status,total_faturado'),
    ]).then(([pRes, iRes, prRes, crRes, dRes]) => {
      const peds = pRes.data || [];
      const itens = iRes.data || [];
      const prods = prRes.data || [];
      const cr = crRes.data || [];
      const dist = dRes.data || [];
      const tips = [];

      const fat = peds.reduce((a,p) => a + (parseFloat(p.total)||0), 0);
      if (fat > 0) tips.push({ icon: 'trending-up', tone: 'success', title: 'Faturamento ativo', desc: `R$ ${brl(fat)} em pedidos faturados com ${peds.length} pedido(s).` });

      const semEstoque = prods.filter(p => (p.estoque||0) <= 0);
      const estBaixo = prods.filter(p => (p.estoque||0) > 0 && (p.estoque||0) <= 5);
      if (semEstoque.length > 0) tips.push({ icon: 'alert-triangle', tone: 'danger', title: `${semEstoque.length} produto(s) sem estoque`, desc: `Itens zerados: ${semEstoque.slice(0,3).map(p=>p.nome).join(', ')}${semEstoque.length > 3 ? '...' : ''}.` });
      if (estBaixo.length > 0) tips.push({ icon: 'package', tone: 'warning', title: `${estBaixo.length} produto(s) com estoque baixo`, desc: `Menos de 5 unidades. Planeje reposicao.` });

      const hoje = new Date();
      const vencidas = cr.filter(r => r.status !== 'Recebido' && r.vencimento && new Date(r.vencimento) < hoje);
      const proxVenc = cr.filter(r => r.status !== 'Recebido' && r.vencimento && new Date(r.vencimento) >= hoje && new Date(r.vencimento) <= new Date(hoje.getTime() + 7*86400000));
      if (vencidas.length > 0) tips.push({ icon: 'alert-circle', tone: 'danger', title: `${vencidas.length} titulo(s) vencido(s)`, desc: `Total vencido: R$ ${brl(vencidas.reduce((a,r) => a + (parseFloat(r.valor)||0), 0))}.` });
      if (proxVenc.length > 0) tips.push({ icon: 'clock', tone: 'warning', title: `${proxVenc.length} titulo(s) vencendo em 7 dias`, desc: `Fique atento aos recebimentos proximos.` });

      const skuMap = {};
      itens.forEach(it => { if (!skuMap[it.sku]) skuMap[it.sku] = { desc: it.descricao, qty: 0 }; skuMap[it.sku].qty += it.quantidade || 0; });
      const topSku = Object.entries(skuMap).sort((a,b) => b[1].qty - a[1].qty);
      if (topSku.length > 0) tips.push({ icon: 'star', tone: 'success', title: `SKU mais vendido: ${topSku[0][0]}`, desc: `${topSku[0][1].desc} com ${topSku[0][1].qty} unidades vendidas.` });

      const distInativos = dist.filter(d => !peds.some(p => p.cliente_nome === d.nome));
      if (distInativos.length > 0) tips.push({ icon: 'user-x', tone: 'warning', title: `${distInativos.length} distribuidor(es) sem pedidos`, desc: `${distInativos.map(d=>d.nome).slice(0,3).join(', ')} sem pedidos faturados.` });

      const semCusto = prods.filter(p => !(parseFloat(p.preco_custo) > 0) && parseFloat(p.preco_venda) > 0);
      if (semCusto.length > 5) tips.push({ icon: 'calculator', tone: 'info', title: `${semCusto.length} produtos sem custo`, desc: `Preencha o custo para calcular margem.` });

      const linhasVendidas = new Set();
      itens.forEach(it => { const prod = prods.find(p => p.sku === it.sku); if (prod?.linha) linhasVendidas.add(prod.linha); });
      const linhasTotal = new Set(prods.map(p => p.linha).filter(Boolean));
      if (linhasTotal.size > 0 && linhasVendidas.size < linhasTotal.size / 2) {
        tips.push({ icon: 'layers', tone: 'info', title: `Apenas ${linhasVendidas.size} de ${linhasTotal.size} linhas vendidas`, desc: `Diversifique o faturamento.` });
      }

      if (tips.length === 0) tips.push({ icon: 'sparkles', tone: 'info', title: 'Sem insights no momento', desc: 'Continue inserindo dados para gerar analises.' });
      setInsights(tips);
    });
  }, [filters.periodId]);

  return (
    <div>
      {!insights ? (
        <div style={{ padding:'60px 0', textAlign:'center', color:'var(--tm-fg-3)', fontSize:13 }}>Analisando dados...</div>
      ) : (
        <div style={{ display:'flex', flexDirection:'column', gap:12, marginTop:8 }}>
          {insights.map((tip, i) => (
            <Card key={i}>
              <div style={{ display:'flex', gap:14, padding:'16px 20px', alignItems:'flex-start' }}>
                <div style={{ width:36, height:36, borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                  background: tip.tone === 'success' ? 'rgba(91,177,122,0.12)' : tip.tone === 'danger' ? 'rgba(217,101,94,0.12)' : tip.tone === 'warning' ? 'rgba(212,160,74,0.12)' : 'rgba(255,255,255,0.06)' }}>
                  <Icon name={tip.icon} size={18} style={{ color: tip.tone === 'success' ? 'var(--tm-success)' : tip.tone === 'danger' ? 'var(--tm-danger)' : tip.tone === 'warning' ? '#D4A04A' : 'var(--tm-fg-3)' }} />
                </div>
                <div>
                  <div style={{ fontSize:14, fontWeight:600, color:'var(--tm-fg-1)', marginBottom:4 }}>{tip.title}</div>
                  <div style={{ fontSize:12.5, color:'var(--tm-fg-3)', lineHeight:1.5 }}>{tip.desc}</div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// PRODUTOS & ESTOQUE (Fase 3)
// ═══════════════════════════════════════════════════════════════════════════════

function RelProdutosSection({ filters, onNav }) {
  const [dados, setDados] = React.useState(null);
  const [viewTab, setViewTab] = React.useState('vendidos');
  const [toggleUnit, setToggleUnit] = React.useState('faturamento');

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);

  React.useEffect(() => {
    if (!window.tmSupabase) { setDados({}); return; }
    setDados(null);
    const s0 = start.toISOString();
    const s1 = new Date(end.getTime() + 86400000).toISOString();

    Promise.all([
      window.tmSupabase.from('produtos').select('id,nome,sku,estoque,preco_venda,preco_custo,linha,status_estoque,marca'),
      window.tmSupabase.from('pedido_itens').select('pedido_id,sku,descricao,quantidade,preco_lista,preco_custo'),
      window.tmSupabase.from('pedidos').select('id,created_at,status').eq('status', 'Atendido').gte('created_at', s0).lte('created_at', s1),
      window.tmSupabase.from('pedidos').select('id,created_at,status').eq('status', 'Atendido'),
    ]).then(([prRes, itRes, pedRes, allPedRes]) => {
      const produtos = prRes.data || [];
      const itens = itRes.data || [];
      const pedidos = pedRes.data || [];
      const allPeds = allPedRes.data || [];

      const pedIdsInPeriod = new Set(pedidos.map(p => p.id));
      const allPedIds = new Set(allPeds.map(p => p.id));

      // Aggregate itens in period
      const skuAgg = {};
      itens.forEach(it => {
        if (!pedIdsInPeriod.has(it.pedido_id)) return;
        const k = it.sku || it.descricao;
        if (!skuAgg[k]) skuAgg[k] = { sku: it.sku, descricao: it.descricao, qtd: 0, fat: 0, custo: 0 };
        skuAgg[k].qtd += it.quantidade || 0;
        skuAgg[k].fat += (it.quantidade || 0) * (parseFloat(it.preco_lista) || 0);
        skuAgg[k].custo += (it.quantidade || 0) * (parseFloat(it.preco_custo) || 0);
      });

      // All-time itens for giro
      const skuAggAll = {};
      itens.forEach(it => {
        if (!allPedIds.has(it.pedido_id)) return;
        const k = it.sku || it.descricao;
        if (!skuAggAll[k]) skuAggAll[k] = { qtd: 0 };
        skuAggAll[k].qtd += it.quantidade || 0;
      });

      // Merge products with sales data
      const merged = produtos.map(p => {
        const agg = skuAgg[p.sku] || { qtd: 0, fat: 0, custo: 0 };
        const aggAll = skuAggAll[p.sku] || { qtd: 0 };
        const margem = agg.fat > 0 && agg.custo > 0 ? ((agg.fat - agg.custo) / agg.fat) * 100 : null;
        const estoque = p.estoque || 0;
        // Giro = vendas periodo / estoque medio (simplified: vendas / estoque atual)
        const giro = estoque > 0 ? agg.qtd / estoque : 0;
        // Dias de estoque = estoque / media diaria de vendas
        const diasPeriodo = Math.max(1, Math.ceil((end - start) / 86400000));
        const mediaDiaria = agg.qtd / diasPeriodo;
        const diasEstoque = mediaDiaria > 0 ? Math.round(estoque / mediaDiaria) : 999;

        return {
          ...p, qtdVendida: agg.qtd, fatVendido: agg.fat, custoVendido: agg.custo,
          margem, giro: giro.toFixed(2), diasEstoque, mediaDiaria,
          totalVendasAll: aggAll.qtd,
        };
      });

      // Mais vendidos (top 20)
      const maisVendidos = [...merged].filter(p => p.qtdVendida > 0 || p.fatVendido > 0).sort((a, b) => b.fatVendido - a.fatVendido).slice(0, 20);

      // Produtos parados 90+ dias (sem venda no periodo e ultimo pedido > 90 dias)
      const parados = merged.filter(p => p.qtdVendida === 0 && p.estoque > 0).sort((a, b) => (b.estoque * (parseFloat(b.preco_custo) || 0)) - (a.estoque * (parseFloat(a.preco_custo) || 0)));

      // Estoque critico (dias de estoque < 15 e esta vendendo)
      const criticos = merged.filter(p => p.diasEstoque < 15 && p.mediaDiaria > 0 && p.estoque > 0).sort((a, b) => a.diasEstoque - b.diasEstoque);

      // Sem estoque (estoque <= 0 e teve vendas)
      const semEstoque = merged.filter(p => p.estoque <= 0 && p.totalVendasAll > 0);

      // Performance por linha
      const byLinha = {};
      merged.forEach(p => {
        const linha = p.linha || 'Sem linha';
        if (!byLinha[linha]) byLinha[linha] = { linha, fat: 0, qtd: 0, custo: 0, produtos: 0 };
        byLinha[linha].fat += p.fatVendido;
        byLinha[linha].qtd += p.qtdVendida;
        byLinha[linha].custo += p.custoVendido;
        byLinha[linha].produtos++;
      });
      const linhas = Object.values(byLinha).filter(l => l.fat > 0).sort((a, b) => b.fat - a.fat);

      // Curva ABC data
      const abcData = [...merged].filter(p => p.fatVendido > 0).sort((a, b) => b.fatVendido - a.fatVendido).map(p => ({
        nome: p.nome || p.sku, valor: p.fatVendido,
      }));

      setDados({ maisVendidos, parados, criticos, semEstoque, linhas, abcData, merged });
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  const d = dados || {};
  const loading = dados === null;

  const totalFat = (d.maisVendidos || []).reduce((a, p) => a + p.fatVendido, 0);
  const totalQtd = (d.maisVendidos || []).reduce((a, p) => a + p.qtdVendida, 0);

  return (
    <div>
      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Produtos vendidos" current={(d.abcData || []).length} previous={null} format="number" loading={loading} sub="SKUs distintos" />
        <CompareKPI label="Faturamento produtos" current={totalFat} previous={null} format="currency" loading={loading} />
        <CompareKPI label="Estoque critico" current={(d.criticos || []).length} previous={null} format="number" loading={loading} sub="< 15 dias" />
        <CompareKPI label="Parados" current={(d.parados || []).length} previous={null} format="number" loading={loading} sub="sem vendas no periodo" />
      </div>

      {/* View tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
        {[
          { id: 'vendidos', label: 'Mais Vendidos' },
          { id: 'abc', label: 'Curva ABC' },
          { id: 'estoque', label: 'Estoque' },
          { id: 'linhas', label: 'Por Linha' },
        ].map(t => (
          <span key={t.id} className={`chip${viewTab === t.id ? ' active' : ''}`}
            style={{ cursor: 'pointer', fontSize: 11 }} onClick={() => setViewTab(t.id)}>
            {t.label}
          </span>
        ))}
      </div>

      {viewTab === 'vendidos' && (
        <>
          <Card title="Top 20 produtos"
            action={
              <div style={{ display: 'flex', gap: 4 }}>
                {['faturamento', 'unidades'].map(t => (
                  <span key={t} className={`chip${toggleUnit === t ? ' active' : ''}`}
                    style={{ cursor: 'pointer', fontSize: 10.5 }} onClick={() => setToggleUnit(t)}>
                    {t === 'faturamento' ? 'R$ Faturamento' : 'Unidades'}
                  </span>
                ))}
              </div>
            }>
            {loading ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
            ) : (d.maisVendidos || []).length === 0 ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem vendas no periodo</div>
            ) : (
              <div style={{ padding: '8px 16px 16px' }}>
                <RankingBar
                  items={(d.maisVendidos || []).map(p => ({
                    nome: (p.nome || p.sku || '—').length > 30 ? (p.nome || p.sku).slice(0, 28) + '..' : (p.nome || p.sku || '—'),
                    valor: toggleUnit === 'faturamento' ? p.fatVendido : p.qtdVendida,
                  }))}
                  valueKey="valor" labelKey="nome"
                  formatFn={v => toggleUnit === 'faturamento' ? `R$ ${brl(v)}` : `${v} un.`}
                  maxItems={20}
                />
              </div>
            )}
          </Card>

          {/* Margem por produto */}
          {!loading && (d.maisVendidos || []).some(p => p.margem !== null) && (
            <Card title="Margem por produto — Top vendidos" style={{ marginTop: 16 }}>
              <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead><tr><th>Produto</th><th>Linha</th><th style={{ textAlign: 'right' }}>Faturamento</th><th style={{ textAlign: 'right' }}>Custo</th><th style={{ textAlign: 'right' }}>Margem</th></tr></thead>
                  <tbody>
                    {(d.maisVendidos || []).filter(p => p.margem !== null).map(p => (
                      <tr key={p.id}>
                        <td style={{ fontWeight: 500, fontSize: 12 }}>{p.nome || p.sku}</td>
                        <td style={{ fontSize: 12, color: 'var(--tm-fg-3)' }}>{p.linha || '—'}</td>
                        <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, whiteSpace: 'nowrap' }}>R$ {brl(p.fatVendido)}</td>
                        <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, color: 'var(--tm-fg-3)', whiteSpace: 'nowrap' }}>R$ {brl(p.custoVendido)}</td>
                        <td style={{ textAlign: 'right', fontWeight: 600, fontSize: 12, color: p.margem >= 30 ? 'var(--tm-success)' : p.margem >= 15 ? '#D4A04A' : 'var(--tm-danger)' }}>
                          {p.margem.toFixed(1)}%
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          )}
        </>
      )}

      {viewTab === 'abc' && (
        <Card title="Curva ABC — Concentracao de faturamento">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (d.abcData || []).length === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados suficientes</div>
          ) : (
            <div style={{ padding: '8px 16px 16px' }}>
              <CurvaABCChart items={(d.abcData || []).slice(0, 30)} labelKey="nome" valueKey="valor" height={280} />
              <div style={{ display: 'flex', gap: 16, justifyContent: 'center', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--tm-line-1)' }}>
                {(() => {
                  const total = (d.abcData || []).reduce((a, it) => a + it.valor, 0);
                  let cum = 0;
                  let countA = 0, countB = 0, countC = 0;
                  (d.abcData || []).forEach(it => {
                    cum += it.valor;
                    const pct = (cum / total) * 100;
                    if (pct <= 80) countA++;
                    else if (pct <= 95) countB++;
                    else countC++;
                  });
                  return [
                    { label: 'Classe A (80%)', count: countA, color: '#C9A36B' },
                    { label: 'Classe B (15%)', count: countB, color: '#6BA3D6' },
                    { label: 'Classe C (5%)', count: countC, color: '#94a3b8' },
                  ].map(cls => (
                    <div key={cls.label} style={{ textAlign: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 2 }}>
                        <div style={{ width: 8, height: 8, borderRadius: 2, background: cls.color }} />
                        <span style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>{cls.label}</span>
                      </div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--tm-fg-1)' }}>{cls.count} SKUs</div>
                    </div>
                  ));
                })()}
              </div>
            </div>
          )}
        </Card>
      )}

      {viewTab === 'estoque' && (
        <>
          {/* Estoque critico */}
          <Card title={`Estoque critico — < 15 dias (${(d.criticos || []).length})`}>
            {loading ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
            ) : (d.criticos || []).length === 0 ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)' }}>
                <Icon name="check-circle" size={28} style={{ opacity: 0.3, marginBottom: 8 }} />
                <div style={{ fontSize: 13 }}>Nenhum produto em nivel critico</div>
              </div>
            ) : (
              <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead><tr><th>Produto</th><th>SKU</th><th style={{ textAlign: 'center' }}>Estoque</th><th style={{ textAlign: 'center' }}>Media dia</th><th style={{ textAlign: 'center' }}>Dias restantes</th><th>Previsao ruptura</th></tr></thead>
                  <tbody>
                    {(d.criticos || []).slice(0, 20).map(p => {
                      const rupturaDate = new Date(Date.now() + p.diasEstoque * 86400000);
                      return (
                        <tr key={p.id}>
                          <td style={{ fontWeight: 500, fontSize: 12 }}>{p.nome || '—'}</td>
                          <td style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--tm-fg-3)' }}>{p.sku || '—'}</td>
                          <td style={{ textAlign: 'center', fontSize: 12 }}>{p.estoque}</td>
                          <td style={{ textAlign: 'center', fontSize: 12, color: 'var(--tm-fg-3)' }}>{p.mediaDiaria.toFixed(1)}</td>
                          <td style={{ textAlign: 'center', fontSize: 12, fontWeight: 600, color: p.diasEstoque <= 7 ? 'var(--tm-danger)' : '#D4A04A' }}>{p.diasEstoque}d</td>
                          <td style={{ fontSize: 11, color: p.diasEstoque <= 7 ? 'var(--tm-danger)' : 'var(--tm-fg-3)', whiteSpace: 'nowrap' }}>{rupturaDate.toLocaleDateString('pt-BR')}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </Card>

          {/* Sem estoque + Parados */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
            <Card title={`Sem estoque (${(d.semEstoque || []).length})`}>
              {(d.semEstoque || []).length === 0 ? (
                <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Todos com estoque</div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', maxHeight: 250, overflowY: 'auto', padding: '4px 16px 12px' }}>
                  {(d.semEstoque || []).slice(0, 15).map(p => (
                    <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0', borderBottom: '1px solid var(--tm-line-1)' }}>
                      <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--tm-danger)', flexShrink: 0 }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12, color: 'var(--tm-fg-1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.nome || p.sku}</div>
                        <div style={{ fontSize: 10.5, color: 'var(--tm-fg-4)' }}>{p.totalVendasAll} vendas historico</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>

            <Card title={`Parados — sem venda (${(d.parados || []).length})`}>
              {(d.parados || []).length === 0 ? (
                <div style={{ padding: 24, textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Todos vendendo</div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', maxHeight: 250, overflowY: 'auto', padding: '4px 16px 12px' }}>
                  {(d.parados || []).slice(0, 15).map(p => (
                    <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0', borderBottom: '1px solid var(--tm-line-1)' }}>
                      <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#D4A04A', flexShrink: 0 }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12, color: 'var(--tm-fg-1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.nome || p.sku}</div>
                        <div style={{ fontSize: 10.5, color: 'var(--tm-fg-4)' }}>
                          Estoque: {p.estoque} · Capital parado: R$ {brl((p.estoque || 0) * (parseFloat(p.preco_custo) || 0))}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>

          {/* Giro de estoque */}
          {!loading && (
            <Card title="Giro de estoque — Top 20" style={{ marginTop: 16 }}>
              <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead><tr><th>Produto</th><th>Linha</th><th style={{ textAlign: 'center' }}>Estoque</th><th style={{ textAlign: 'center' }}>Vendas periodo</th><th style={{ textAlign: 'center' }}>Giro</th><th style={{ textAlign: 'center' }}>Dias cobertura</th></tr></thead>
                  <tbody>
                    {(d.merged || []).filter(p => p.estoque > 0 && p.qtdVendida > 0).sort((a, b) => parseFloat(b.giro) - parseFloat(a.giro)).slice(0, 20).map(p => (
                      <tr key={p.id}>
                        <td style={{ fontWeight: 500, fontSize: 12 }}>{p.nome || p.sku}</td>
                        <td style={{ fontSize: 12, color: 'var(--tm-fg-3)' }}>{p.linha || '—'}</td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{p.estoque}</td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{p.qtdVendida}</td>
                        <td style={{ textAlign: 'center', fontSize: 12, fontWeight: 600, color: parseFloat(p.giro) >= 1 ? 'var(--tm-success)' : parseFloat(p.giro) >= 0.5 ? '#D4A04A' : 'var(--tm-fg-3)' }}>{p.giro}x</td>
                        <td style={{ textAlign: 'center', fontSize: 12, color: p.diasEstoque <= 15 ? 'var(--tm-danger)' : 'var(--tm-fg-3)' }}>{p.diasEstoque === 999 ? '—' : `${p.diasEstoque}d`}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          )}
        </>
      )}

      {viewTab === 'linhas' && (
        <Card title="Performance por linha">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (d.linhas || []).length === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados de linha</div>
          ) : (
            <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead><tr><th>Linha</th><th style={{ textAlign: 'center' }}>Produtos</th><th style={{ textAlign: 'center' }}>Unidades</th><th style={{ textAlign: 'right' }}>Faturamento</th><th style={{ textAlign: 'right' }}>Margem</th><th style={{ textAlign: 'right' }}>% do total</th></tr></thead>
                <tbody>
                  {(d.linhas || []).map(l => {
                    const margem = l.fat > 0 && l.custo > 0 ? ((l.fat - l.custo) / l.fat * 100) : null;
                    const pctTotal = totalFat > 0 ? (l.fat / totalFat * 100) : 0;
                    return (
                      <tr key={l.linha}>
                        <td style={{ fontWeight: 500 }}>{l.linha}</td>
                        <td style={{ textAlign: 'center', fontSize: 12, color: 'var(--tm-fg-3)' }}>{l.produtos}</td>
                        <td style={{ textAlign: 'center', fontSize: 12 }}>{l.qtd}</td>
                        <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600, whiteSpace: 'nowrap' }}>R$ {brl(l.fat)}</td>
                        <td style={{ textAlign: 'right', fontSize: 12, color: margem !== null ? (margem >= 30 ? 'var(--tm-success)' : margem >= 15 ? '#D4A04A' : 'var(--tm-danger)') : 'var(--tm-fg-4)' }}>
                          {margem !== null ? `${margem.toFixed(1)}%` : '—'}
                        </td>
                        <td style={{ textAlign: 'right', fontSize: 12, color: 'var(--tm-fg-3)' }}>{pctTotal.toFixed(1)}%</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </Card>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// CURVA ABC — Análise completa multi-métrica
// ═══════════════════════════════════════════════════════════════════════════════

function RelCurvaABCSection({ filters, setFilters, onNav }) {
  const [rawData, setRawData]   = React.useState(null);
  const [metrica, setMetrica]   = React.useState('faturamento');
  const [nivel, setNivel]       = React.useState('produto');
  const [busca, setBusca]       = React.useState('');
  const [page, setPage]         = React.useState(1);
  const [filtroClasse, setFiltroClasse]   = React.useState('Todas');
  const [filtroEstoque, setFiltroEstoque] = React.useState('Todos');
  const [detalhe, setDetalhe]   = React.useState(null);
  const PER_PAGE = 20;

  const { start, end } = calcPeriod(filters.periodId, filters.customStart, filters.customEnd);
  const { start: prevStart, end: prevEnd } = calcPreviousPeriod(start, end);

  const s0 = start.toISOString();
  const s1 = new Date(end.getTime() + 86400000).toISOString();
  const ps0 = prevStart.toISOString();
  const ps1 = new Date(prevEnd.getTime() + 86400000).toISOString();

  // ─── Data Fetching ───────────────────────────────────────────────────────
  React.useEffect(() => {
    if (!window.tmSupabase) { setRawData({ produtos: [], variacoes: [], itens: [], pedidos: [], pedidosPrev: [] }); return; }
    setRawData(null);
    Promise.all([
      window.tmSupabase.from('produtos').select('id,nome,sku,marca,linha,categoria,estoque,preco_venda,preco_custo,tem_variacoes'),
      window.tmSupabase.from('produto_variacoes').select('id,produto_id,nome,sku,estoque,preco_venda,custo'),
      window.tmSupabase.from('pedido_itens').select('pedido_id,produto_id,variacao_id,sku,descricao,quantidade,preco_lista,desconto_pct'),
      window.tmSupabase.from('pedidos').select('id,created_at,status,canal,vendedor').eq('status', 'Atendido').gte('created_at', s0).lte('created_at', s1),
      window.tmSupabase.from('pedidos').select('id,created_at,status,canal,vendedor').eq('status', 'Atendido').gte('created_at', ps0).lte('created_at', ps1),
    ]).then(([prRes, vrRes, itRes, pedRes, prevPedRes]) => {
      setRawData({
        produtos: prRes.data || [],
        variacoes: vrRes.data || [],
        itens: itRes.data || [],
        pedidos: pedRes.data || [],
        pedidosPrev: prevPedRes.data || [],
      });
    });
  }, [filters.periodId, filters.customStart, filters.customEnd]);

  // ─── Processamento ABC (useMemo) ────────────────────────────────────────
  const computed = React.useMemo(() => {
    if (!rawData) return null;
    const { produtos, variacoes, itens, pedidos, pedidosPrev } = rawData;

    // Filtrar pedidos por canal/vendedor
    const filterPeds = (peds) => {
      let f = peds;
      if (filters.canal) f = f.filter(p => p.canal === filters.canal);
      if (filters.vendedor) f = f.filter(p => p.vendedor === filters.vendedor);
      return f;
    };

    const filteredPeds = filterPeds(pedidos);
    const filteredPrevPeds = filterPeds(pedidosPrev);
    const pedIds = new Set(filteredPeds.map(p => p.id));
    const prevPedIds = new Set(filteredPrevPeds.map(p => p.id));

    // Mapa de produtos para merge
    const prodMap = {};
    produtos.forEach(p => { prodMap[p.id] = p; });

    // Mapa de variações
    const varMap = {};
    variacoes.forEach(v => { varMap[v.id] = v; });

    // Variações agrupadas por produto
    const varsByProd = {};
    variacoes.forEach(v => {
      if (!varsByProd[v.produto_id]) varsByProd[v.produto_id] = [];
      varsByProd[v.produto_id].push(v);
    });

    const diasPeriodo = Math.max(1, Math.ceil((end - start) / 86400000));

    // ─── Agregar por nível ──────────────────────────────────────────────
    function agregar(itensArr, pedIdSet) {
      const agg = {};
      itensArr.forEach(it => {
        if (!pedIdSet.has(it.pedido_id)) return;
        let key, nome, sku, prodId;

        if (nivel === 'produto') {
          prodId = it.produto_id;
          if (!prodId) {
            // Tentar resolver por SKU
            const found = produtos.find(p => p.sku === it.sku);
            prodId = found ? found.id : it.sku || it.descricao;
          }
          key = prodId;
          const prod = prodMap[prodId];
          nome = prod ? prod.nome : (it.descricao || it.sku || '—');
          sku = prod ? prod.sku : it.sku;
        } else {
          // nível variação/SKU
          key = it.sku || `${it.produto_id}_${it.variacao_id}` || it.descricao;
          const vari = it.variacao_id ? varMap[it.variacao_id] : null;
          const prod = prodMap[it.produto_id];
          if (vari && prod) {
            nome = `${prod.nome} — ${vari.nome}`;
          } else if (prod) {
            nome = prod.nome;
          } else {
            nome = it.descricao || it.sku || '—';
          }
          sku = it.sku || (vari ? vari.sku : '');
          prodId = it.produto_id;
        }

        if (!agg[key]) agg[key] = { key, nome, sku, prodId, qtd: 0, fat: 0, custo: 0 };
        const qty = it.quantidade || 0;
        agg[key].qtd += qty;
        agg[key].fat += qty * (parseFloat(it.preco_lista) || 0);
        // Resolver custo do produto ou variação
        const vari = it.variacao_id ? varMap[it.variacao_id] : null;
        const prodRef = prodMap[it.produto_id];
        const unitCost = vari ? (parseFloat(vari.custo) || 0) : (prodRef ? (parseFloat(prodRef.preco_custo) || 0) : 0);
        agg[key].custo += qty * unitCost;
      });
      return agg;
    }

    const aggCur = agregar(itens, pedIds);
    const aggPrev = agregar(itens, prevPedIds);

    // Enriquecer itens
    let items = Object.values(aggCur).map(row => {
      const prod = prodMap[row.prodId];
      let estoque = 0;
      if (nivel === 'produto' && prod) {
        if (prod.tem_variacoes && varsByProd[prod.id]) {
          estoque = varsByProd[prod.id].reduce((s, v) => s + (v.estoque || 0), 0);
        } else {
          estoque = prod.estoque || 0;
        }
      } else if (nivel === 'variacao') {
        // Tentar achar a variação pelo SKU
        const vari = variacoes.find(v => v.sku === row.sku);
        if (vari) {
          estoque = vari.estoque || 0;
        } else if (prod) {
          estoque = prod.estoque || 0;
        }
      }

      const lucro = row.fat - row.custo;
      const margemPct = row.fat > 0 ? (lucro / row.fat) * 100 : 0;
      const mediaDiaria = row.qtd / diasPeriodo;
      const diasEstoque = mediaDiaria > 0 ? Math.round(estoque / mediaDiaria) : 999;
      const giro = estoque > 0 ? row.qtd / estoque : 0;

      return {
        key: row.key,
        nome: row.nome,
        sku: row.sku,
        marca: prod ? (prod.marca || '') : '',
        linha: prod ? (prod.linha || '') : '',
        categoria: prod ? (prod.categoria || '') : '',
        qtd: row.qtd,
        fat: row.fat,
        custo: row.custo,
        lucro,
        margemPct,
        estoque,
        mediaDiaria,
        diasEstoque,
        giro,
      };
    });

    // Filtros marca/linha/categoria + busca
    if (filters.marca) items = items.filter(i => i.marca === filters.marca);
    if (filters.linha) items = items.filter(i => i.linha === filters.linha);
    if (filters.categoria) items = items.filter(i => i.categoria === filters.categoria);

    // Definir valor da métrica
    const getMetricVal = (item) => {
      switch (metrica) {
        case 'faturamento': return item.fat;
        case 'quantidade':  return item.qtd;
        case 'lucro':       return item.lucro;
        case 'margem':      return item.margemPct;
        case 'giro':        return item.giro;
        default:            return item.fat;
      }
    };

    // Ordenar
    items.sort((a, b) => getMetricVal(b) - getMetricVal(a));

    // Aplicar busca depois de ordenar
    let filteredItems = items;
    if (busca.trim()) {
      const q = busca.toLowerCase();
      filteredItems = items.filter(i =>
        (i.nome || '').toLowerCase().includes(q) ||
        (i.sku || '').toLowerCase().includes(q) ||
        (i.marca || '').toLowerCase().includes(q) ||
        (i.linha || '').toLowerCase().includes(q)
      );
    }

    // Classificar ABC (sobre items sem busca, para manter classe estável)
    const totalMetric = items.reduce((s, i) => s + Math.max(0, getMetricVal(i)), 0);
    let cum = 0;
    const classMap = {};
    items.forEach(it => {
      const val = Math.max(0, getMetricVal(it));
      cum += val;
      const pct = totalMetric > 0 ? (cum / totalMetric) * 100 : 100;
      const classe = pct <= 80 ? 'A' : pct <= 95 ? 'B' : 'C';
      it.partPct = totalMetric > 0 ? (val / totalMetric) * 100 : 0;
      it.acumPct = totalMetric > 0 ? pct : 0;
      it.classe = classe;
      classMap[it.key] = classe;
    });

    // Classificar período anterior
    const prevItems = Object.values(aggPrev);
    const prevMetricVal = (row) => {
      const lucro = row.fat - row.custo;
      const margemPct = row.fat > 0 ? (lucro / row.fat) * 100 : 0;
      const prod = prodMap[row.prodId];
      let estoque = 0;
      if (nivel === 'produto' && prod) {
        estoque = prod.tem_variacoes && varsByProd[prod.id]
          ? varsByProd[prod.id].reduce((s, v) => s + (v.estoque || 0), 0)
          : (prod.estoque || 0);
      }
      const giro = estoque > 0 ? row.qtd / estoque : 0;
      switch (metrica) {
        case 'faturamento': return row.fat;
        case 'quantidade':  return row.qtd;
        case 'lucro':       return lucro;
        case 'margem':      return margemPct;
        case 'giro':        return giro;
        default:            return row.fat;
      }
    };
    prevItems.sort((a, b) => prevMetricVal(b) - prevMetricVal(a));
    const prevTotal = prevItems.reduce((s, i) => s + Math.max(0, prevMetricVal(i)), 0);
    let prevCum = 0;
    const prevClassMap = {};
    prevItems.forEach(it => {
      prevCum += Math.max(0, prevMetricVal(it));
      const pct = prevTotal > 0 ? (prevCum / prevTotal) * 100 : 100;
      prevClassMap[it.key] = pct <= 80 ? 'A' : pct <= 95 ? 'B' : 'C';
    });

    // Detectar mudanças de classe
    const classMudancas = [];
    items.forEach(it => {
      const prev = prevClassMap[it.key];
      if (prev && prev !== it.classe) {
        classMudancas.push({
          nome: it.nome,
          sku: it.sku,
          anterior: prev,
          atual: it.classe,
          fat: it.fat,
          varFat: (() => {
            const prevRow = aggPrev[it.key];
            if (!prevRow) return null;
            return prevRow.fat > 0 ? ((it.fat - prevRow.fat) / prevRow.fat) * 100 : null;
          })(),
        });
      }
    });

    // Contagens
    const countA = items.filter(i => i.classe === 'A').length;
    const countB = items.filter(i => i.classe === 'B').length;
    const countC = items.filter(i => i.classe === 'C').length;
    const fatA = items.filter(i => i.classe === 'A').reduce((s, i) => s + i.fat, 0);
    const fatB = items.filter(i => i.classe === 'B').reduce((s, i) => s + i.fat, 0);
    const fatC = items.filter(i => i.classe === 'C').reduce((s, i) => s + i.fat, 0);
    const totalFat = items.reduce((s, i) => s + i.fat, 0);
    const totalQtd = items.reduce((s, i) => s + i.qtd, 0);

    // Sugestão por produto
    const getSugestao = (item) => {
      if (item.classe === 'A' && item.diasEstoque < 15 && item.diasEstoque !== 999) {
        return { text: 'Repor estoque urgente', tone: 'danger', icon: 'alert-triangle' };
      }
      if (item.classe === 'A' && item.margemPct < 15 && item.fat > 0) {
        return { text: 'Negociar custo / reajustar preco', tone: 'warning', icon: 'alert-circle' };
      }
      if (item.classe === 'A') {
        return { text: 'Priorizar estoque e negociacao', tone: 'success', icon: 'check-circle' };
      }
      if (item.classe === 'B' && item.margemPct > 30) {
        return { text: 'Potencial Classe A — investir', tone: 'info', icon: 'trending-up' };
      }
      if (item.classe === 'C' && item.diasEstoque > 90) {
        return { text: 'Criar promocao para girar', tone: 'warning', icon: 'tag' };
      }
      if (item.classe === 'C' && item.qtd === 0) {
        return { text: 'Avaliar descontinuacao', tone: 'danger', icon: 'x-circle' };
      }
      return null;
    };

    // Insights automaticos com nomes de produtos
    const insights = [];
    if (items.length > 0) {
      const pctCatalogoA = ((countA / items.length) * 100).toFixed(0);
      const pctFatA = totalFat > 0 ? ((fatA / totalFat) * 100).toFixed(0) : 0;
      const leader = items[0];
      const leaderPct = totalFat > 0 ? ((leader.fat / totalFat) * 100).toFixed(1) : '0';
      insights.push({
        icon: 'bar-chart-3', color: '#C9A36B',
        text: `Classe A = ${pctFatA}% do faturamento com apenas ${pctCatalogoA}% do catalogo (${countA} de ${items.length} SKUs)`,
        detail: `Lider: ${leader.nome} (${leaderPct}% do total)`,
      });

      const riscoRupturaA = items.filter(i => i.classe === 'A' && i.diasEstoque < 15 && i.diasEstoque !== 999);
      if (riscoRupturaA.length > 0) {
        const topRisco = riscoRupturaA.sort((a, b) => a.diasEstoque - b.diasEstoque)[0];
        insights.push({
          icon: 'alert-triangle', color: 'var(--tm-danger)',
          text: `${riscoRupturaA.length} produto(s) Classe A com menos de 15 dias de estoque — risco de ruptura`,
          detail: `Mais critico: ${topRisco.nome} (${topRisco.diasEstoque}d)`,
        });
      }

      const oportB = items.filter(i => i.classe === 'B' && i.margemPct > 30);
      if (oportB.length > 0) {
        const topOp = oportB.sort((a, b) => b.margemPct - a.margemPct)[0];
        insights.push({
          icon: 'trending-up', color: 'var(--tm-success)',
          text: `${oportB.length} produto(s) Classe B com margem acima de 30% — potencial para subir para A`,
          detail: `Destaque: ${topOp.nome} (${topOp.margemPct.toFixed(1)}% margem)`,
        });
      }

      const capitalParadoC = items.filter(i => i.classe === 'C' && i.diasEstoque > 90);
      const valorParado = capitalParadoC.reduce((s, i) => s + (i.estoque * (i.custo > 0 && i.qtd > 0 ? (i.custo / i.qtd) : 0)), 0);
      if (capitalParadoC.length > 0) {
        insights.push({
          icon: 'package', color: '#D4A04A',
          text: `${capitalParadoC.length} produto(s) Classe C com estoque para mais de 90 dias${valorParado > 0 ? ` — R$ ${brl(valorParado)} em capital parado` : ''}`,
        });
      }

      const margemBaixaA = items.filter(i => i.classe === 'A' && i.margemPct < 15 && i.fat > 0);
      if (margemBaixaA.length > 0) {
        const worst = margemBaixaA.sort((a, b) => a.margemPct - b.margemPct)[0];
        insights.push({
          icon: 'alert-circle', color: 'var(--tm-danger)',
          text: `${margemBaixaA.length} produto(s) Classe A com margem abaixo de 15% — atencao na precificacao`,
          detail: `Pior margem: ${worst.nome} (${worst.margemPct.toFixed(1)}%)`,
        });
      }
    }

    // Acoes recomendadas
    const acoes = [];
    const reporEstoque = items.filter(i => i.classe === 'A' && i.diasEstoque < 15 && i.diasEstoque !== 999);
    if (reporEstoque.length > 0) {
      acoes.push({ tipo: 'repor', label: 'Repor estoque', color: 'var(--tm-danger)', icon: 'alert-triangle', items: reporEstoque.slice(0, 3).map(i => i.nome) });
    }
    const criarCampanha = items.filter(i => i.classe === 'B' && i.margemPct > 30);
    if (criarCampanha.length > 0) {
      acoes.push({ tipo: 'campanha', label: 'Criar campanha', color: '#D4A04A', icon: 'trending-up', items: criarCampanha.slice(0, 3).map(i => i.nome) });
    }
    const promoverGiro = items.filter(i => i.classe === 'C' && i.diasEstoque > 90 && i.qtd > 0);
    if (promoverGiro.length > 0) {
      acoes.push({ tipo: 'giro', label: 'Promover giro', color: '#e67e22', icon: 'tag', items: promoverGiro.slice(0, 3).map(i => i.nome) });
    }
    const descontinuar = items.filter(i => i.classe === 'C' && i.qtd === 0);
    if (descontinuar.length > 0) {
      acoes.push({ tipo: 'descontinuar', label: 'Avaliar descontinuacao', color: 'var(--tm-fg-4)', icon: 'x-circle', items: descontinuar.slice(0, 3).map(i => i.nome) });
    }
    const revisarPreco = items.filter(i => i.classe === 'A' && i.margemPct < 15 && i.fat > 0);
    if (revisarPreco.length > 0) {
      acoes.push({ tipo: 'preco', label: 'Revisar precificacao', color: '#6BA3D6', icon: 'alert-circle', items: revisarPreco.slice(0, 3).map(i => i.nome) });
    }

    // Leitura rapida highlights
    const highlights = [];
    if (items.length > 0) {
      // Produto lider
      const leader = items[0];
      const leaderPct = totalFat > 0 ? ((leader.fat / totalFat) * 100).toFixed(1) : '0';
      highlights.push({ icon: 'award', title: 'Produto lider', line1: leader.nome, line2: `${leaderPct}% do faturamento — R$ ${brl(leader.fat)}`, bg: '#C9A36B18', border: '#C9A36B44' });

      // Risco de ruptura
      const rupturaA = items.filter(i => i.classe === 'A' && i.diasEstoque < 15 && i.diasEstoque !== 999);
      if (rupturaA.length > 0) {
        const top = rupturaA.sort((a, b) => a.diasEstoque - b.diasEstoque)[0];
        highlights.push({ icon: 'alert-triangle', title: 'Risco de ruptura', line1: `${rupturaA.length} produto(s) Classe A com estoque critico`, line2: `${top.nome} — ${top.diasEstoque} dias restantes`, bg: 'rgba(217,101,94,0.08)', border: 'rgba(217,101,94,0.25)' });
      }

      // Oportunidade
      const oport = items.filter(i => i.classe === 'B' && i.margemPct > 30);
      if (oport.length > 0) {
        const topOp = oport.sort((a, b) => b.margemPct - a.margemPct)[0];
        highlights.push({ icon: 'trending-up', title: 'Oportunidade', line1: `${oport.length} Classe B com margem alta`, line2: `${topOp.nome} — ${topOp.margemPct.toFixed(1)}% margem`, bg: 'rgba(91,177,122,0.08)', border: 'rgba(91,177,122,0.25)' });
      }

      // Capital parado
      const capParado = items.filter(i => i.classe === 'C' && i.diasEstoque > 90);
      const valParado = capParado.reduce((s, i) => s + (i.estoque * (i.custo > 0 && i.qtd > 0 ? (i.custo / i.qtd) : 0)), 0);
      if (capParado.length > 0) {
        highlights.push({ icon: 'package', title: 'Capital parado', line1: `${capParado.length} produto(s) Classe C com +90 dias estoque`, line2: valParado > 0 ? `R$ ${brl(valParado)} em estoque parado` : 'Valor nao calculavel', bg: 'rgba(212,160,74,0.08)', border: 'rgba(212,160,74,0.25)' });
      }

      // Margem destaque
      const margemA = items.filter(i => i.classe === 'A' && i.margemPct > 0);
      if (margemA.length > 0) {
        const best = margemA.sort((a, b) => b.margemPct - a.margemPct)[0];
        highlights.push({ icon: 'star', title: 'Margem destaque', line1: best.nome, line2: `${best.margemPct.toFixed(1)}% de margem — Classe A`, bg: '#C9A36B18', border: '#C9A36B44' });
      }
    }

    // Dados para gráfico Pareto (top 30)
    const paretoData = items.slice(0, 30).map(i => ({
      nome: (i.nome || '').length > 20 ? i.nome.slice(0, 18) + '..' : i.nome,
      valor: getMetricVal(i),
    }));

    // Dados para doughnut
    const doughnutData = {
      labels: ['Classe A', 'Classe B', 'Classe C'],
      values: [fatA, fatB, fatC],
      colors: ['#C9A36B', '#6BA3D6', '#94a3b8'],
    };

    return {
      items, filteredItems, paretoData, doughnutData,
      countA, countB, countC, fatA, fatB, fatC,
      totalFat, totalQtd, totalItems: items.length,
      insights, classMudancas, getSugestao, getMetricVal,
      acoes, highlights,
    };
  }, [rawData, metrica, nivel, busca, filters.canal, filters.vendedor, filters.marca, filters.linha, filters.categoria]);

  // Reset page on filter change
  React.useEffect(() => { setPage(1); }, [metrica, nivel, busca, filters, filtroClasse, filtroEstoque]);

  const loading = rawData === null;
  const c = computed || {};

  // Apply classe and estoque filters on top of search-filtered items
  const displayItems = React.useMemo(() => {
    let list = c.filteredItems || [];
    if (filtroClasse !== 'Todas') list = list.filter(i => i.classe === filtroClasse);
    if (filtroEstoque === 'Com estoque') list = list.filter(i => i.estoque > 0);
    if (filtroEstoque === 'Sem estoque') list = list.filter(i => i.estoque === 0);
    if (filtroEstoque === 'Critico') list = list.filter(i => i.diasEstoque < 15 && i.diasEstoque !== 999);
    return list;
  }, [c.filteredItems, filtroClasse, filtroEstoque]);

  const totalPages = Math.max(1, Math.ceil(displayItems.length / PER_PAGE));
  const pagedItems = displayItems.slice((page - 1) * PER_PAGE, page * PER_PAGE);

  const metricLabel = { faturamento: 'Faturamento', quantidade: 'Quantidade', lucro: 'Lucro', margem: 'Margem %', giro: 'Giro' };
  const metricFormat = (val) => {
    if (metrica === 'margem') return val.toFixed(1) + '%';
    if (metrica === 'giro') return val.toFixed(2) + 'x';
    if (metrica === 'quantidade') return Math.round(val).toLocaleString('pt-BR');
    return 'R$ ' + brl(val);
  };

  // ─── Export CSV ──────────────────────────────────────────────────────────
  const exportCSV = () => {
    if (!c.items || c.items.length === 0) return;
    const sep = ';';
    const headers = ['#', 'Produto', 'SKU', 'Marca', 'Linha', 'Categoria', 'Qtd', 'Faturamento', 'Custo', 'Lucro', 'Margem%', 'Part%', 'Acum%', 'Classe', 'Estoque', 'Dias Cobertura', 'Sugestao'];
    const rows = c.items.map((it, i) => {
      const sug = c.getSugestao(it);
      return [
        i + 1, it.nome, it.sku, it.marca, it.linha, it.categoria, it.qtd,
        it.fat.toFixed(2).replace('.', ','), it.custo.toFixed(2).replace('.', ','),
        it.lucro.toFixed(2).replace('.', ','), it.margemPct.toFixed(1).replace('.', ','),
        it.partPct.toFixed(2).replace('.', ','), it.acumPct.toFixed(2).replace('.', ','),
        it.classe, it.estoque, it.diasEstoque === 999 ? '—' : it.diasEstoque,
        sug ? sug.text : '',
      ].join(sep);
    });
    const csv = '﻿' + headers.join(sep) + '\n' + rows.join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = Object.assign(document.createElement('a'), { href: url, download: 'curva-abc-' + new Date().toISOString().slice(0, 10) + '.csv' });
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 3000);
  };

  // ─── Classe badge helper (enhanced) ─────────────────────────────────────
  const classeBadge = (cls, small) => {
    const colors = { A: '#C9A36B', B: '#6BA3D6', C: '#94a3b8' };
    const color = colors[cls] || '#94a3b8';
    if (small) {
      return (
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          padding: '3px 10px', borderRadius: 12,
          background: color + '22', color: color,
          fontSize: 11, fontWeight: 600, lineHeight: 1,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: color }} />
          {'Classe ' + cls}
        </span>
      );
    }
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 26, height: 26, borderRadius: 6,
        background: color, color: '#fff',
        fontSize: 12, fontWeight: 700, lineHeight: 1,
      }}>{cls}</span>
    );
  };

  // Seta de mudança de classe
  const classeArrow = (prev, atual) => {
    const isUp = (prev === 'C' && (atual === 'B' || atual === 'A')) || (prev === 'B' && atual === 'A');
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12 }}>
        {classeBadge(prev, true)}
        <Icon name={isUp ? 'arrow-up' : 'arrow-down'} size={12}
          style={{ color: isUp ? 'var(--tm-success)' : 'var(--tm-danger)' }} />
        {classeBadge(atual, true)}
      </span>
    );
  };

  // Doughnut chart data for Chart.js
  const doughnutChartData = React.useMemo(() => {
    if (!c.doughnutData) return null;
    return {
      data: {
        labels: c.doughnutData.labels,
        datasets: [{
          data: c.doughnutData.values,
          backgroundColor: c.doughnutData.colors,
          borderWidth: 0,
          hoverOffset: 6,
        }],
      },
      options: {
        cutout: '58%',
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: 'rgba(11,11,13,0.92)',
            callbacks: {
              label: function(ctx) { return ctx.label + ': R$ ' + brl(ctx.parsed); }
            },
          },
        },
      },
    };
  }, [c.doughnutData]);

  return (
    <div>
      {/* Metric selector + Level toggle */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 14, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: 4 }}>
          {['faturamento', 'quantidade', 'lucro', 'margem', 'giro'].map(m => (
            <span key={m} className={'chip' + (metrica === m ? ' active' : '')}
              style={{ cursor: 'pointer', fontSize: 11 }}
              onClick={() => setMetrica(m)}>
              {metricLabel[m]}
            </span>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
          {[
            { id: 'produto', label: 'Produto Pai' },
            { id: 'variacao', label: 'Variacao / SKU' },
          ].map(t => (
            <span key={t.id} className={'chip' + (nivel === t.id ? ' active' : '')}
              style={{ cursor: 'pointer', fontSize: 11 }}
              onClick={() => setNivel(t.id)}>
              {t.label}
            </span>
          ))}
        </div>
      </div>

      {/* KPI row: 3 CompareKPI + 3 rich class cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12, marginBottom: 16 }}>
        <CompareKPI label="Faturamento Total" current={c.totalFat || 0} previous={null} format="currency" loading={loading} />
        <CompareKPI label="Qtd Vendida" current={c.totalQtd || 0} previous={null} format="number" loading={loading} />
        <CompareKPI label="SKUs ativos" current={c.totalItems || 0} previous={null} format="number" loading={loading} />

        {/* Class A card */}
        {[
          { cls: 'A', count: c.countA || 0, fat: c.fatA || 0, color: '#C9A36B' },
          { cls: 'B', count: c.countB || 0, fat: c.fatB || 0, color: '#6BA3D6' },
          { cls: 'C', count: c.countC || 0, fat: c.fatC || 0, color: '#94a3b8' },
        ].map(cc => {
          const pctFat = (c.totalFat || 0) > 0 ? ((cc.fat / c.totalFat) * 100).toFixed(0) : '0';
          return (
            <div key={cc.cls} style={{
              background: 'var(--tm-bg-2)', borderRadius: 'var(--tm-radius-md)',
              boxShadow: 'inset 0 0 0 1px var(--tm-line-1)',
              padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 6,
              borderLeft: '3px solid ' + cc.color, minWidth: 0,
            }}>
              {loading ? (
                <div style={{ fontSize: 13, color: 'var(--tm-fg-4)' }}>...</div>
              ) : (
                React.createElement(React.Fragment, null,
                  React.createElement('div', { style: { fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: cc.color, fontWeight: 700 } }, 'Classe ' + cc.cls),
                  React.createElement('div', { style: { fontSize: 12, color: 'var(--tm-fg-3)', lineHeight: 1.4 } },
                    cc.count + ' SKUs  ·  ' + pctFat + '% do faturamento'
                  ),
                  React.createElement('div', { style: { fontSize: 18, fontWeight: 600, fontVariantNumeric: 'tabular-nums', color: 'var(--tm-fg-1)' } },
                    'R$ ' + brl(cc.fat)
                  )
                )
              )}
            </div>
          );
        })}
      </div>

      {/* Leitura rapida */}
      {!loading && (c.highlights || []).length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--tm-fg-2)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="zap" size={14} style={{ color: '#C9A36B' }} />
            Leitura rapida
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10 }}>
            {c.highlights.map(function(h, i) {
              return (
                <div key={i} style={{
                  background: h.bg, border: '1px solid ' + h.border,
                  borderRadius: 10, padding: '14px 16px',
                  display: 'flex', gap: 12, alignItems: 'flex-start',
                }}>
                  <Icon name={h.icon} size={18} style={{ color: h.border.replace(/[0-9a-f]{2}\)$/i, '1)').replace(/18$/, 'cc'), flexShrink: 0, marginTop: 2 }} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--tm-fg-3)', fontWeight: 600, marginBottom: 4 }}>{h.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--tm-fg-1)', fontWeight: 500, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{h.line1}</div>
                    <div style={{ fontSize: 11, color: 'var(--tm-fg-3)', marginTop: 2, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{h.line2}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Charts row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: 16, marginBottom: 16 }}>
        {/* Pareto */}
        <Card title={'Curva ABC — ' + metricLabel[metrica]}>
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (c.paretoData || []).length === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados no periodo</div>
          ) : (
            <div style={{ padding: '8px 16px 16px' }}>
              <CurvaABCChart items={c.paretoData} labelKey="nome" valueKey="valor" height={340} />
              <div style={{ display: 'flex', gap: 16, justifyContent: 'center', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--tm-line-1)' }}>
                {[
                  { label: 'Classe A (80%)', count: c.countA, color: '#C9A36B' },
                  { label: 'Classe B (15%)', count: c.countB, color: '#6BA3D6' },
                  { label: 'Classe C (5%)',  count: c.countC, color: '#94a3b8' },
                ].map(function(cls) {
                  return (
                    <div key={cls.label} style={{ textAlign: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 2 }}>
                        <div style={{ width: 8, height: 8, borderRadius: 2, background: cls.color }} />
                        <span style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>{cls.label}</span>
                      </div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--tm-fg-1)' }}>{cls.count} SKUs</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </Card>

        {/* Doughnut with enhanced legend */}
        <Card title="Distribuicao por classe">
          {loading ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
          ) : (c.totalFat || 0) === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Sem dados</div>
          ) : doughnutChartData ? (
            <div style={{ padding: '8px 16px 16px' }}>
              <ChartCanvas type="doughnut" data={doughnutChartData.data} options={doughnutChartData.options} height={220} />
              {/* Enhanced legend with progress bars */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '12px 0 0' }}>
                {[
                  { label: 'Classe A', fat: c.fatA, count: c.countA, color: '#C9A36B' },
                  { label: 'Classe B', fat: c.fatB, count: c.countB, color: '#6BA3D6' },
                  { label: 'Classe C', fat: c.fatC, count: c.countC, color: '#94a3b8' },
                ].map(function(cls) {
                  var pct = (c.totalFat || 0) > 0 ? ((cls.fat / c.totalFat) * 100) : 0;
                  return (
                    <div key={cls.label}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, marginBottom: 4 }}>
                        <div style={{ width: 8, height: 8, borderRadius: 2, background: cls.color, flexShrink: 0 }} />
                        <span style={{ color: 'var(--tm-fg-3)', flex: 1 }}>{cls.label} ({cls.count})</span>
                        <span style={{ fontSize: 11, color: 'var(--tm-fg-3)', fontVariantNumeric: 'tabular-nums' }}>{pct.toFixed(0)}%</span>
                        <span style={{ fontWeight: 600, fontVariantNumeric: 'tabular-nums', minWidth: 90, textAlign: 'right' }}>R$ {brl(cls.fat)}</span>
                      </div>
                      <div style={{ height: 4, borderRadius: 2, background: 'var(--tm-bg-3)', overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: pct + '%', borderRadius: 2, background: cls.color, transition: 'width 0.4s ease' }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ) : null}
        </Card>
      </div>

      {/* Insights automaticos */}
      {!loading && (c.insights || []).length > 0 && (
        <Card title="Insights automaticos" style={{ marginBottom: 16 }}>
          <div style={{ padding: '8px 16px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {c.insights.map(function(ins, i) {
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', borderRadius: 8, background: 'var(--tm-bg-3)' }}>
                  <Icon name={ins.icon} size={16} style={{ color: ins.color, flexShrink: 0, marginTop: 1 }} />
                  <div style={{ flex: 1 }}>
                    <span style={{ fontSize: 12.5, color: 'var(--tm-fg-1)', lineHeight: 1.5 }}>{ins.text}</span>
                    {ins.detail && (
                      <div style={{ fontSize: 11, color: 'var(--tm-fg-3)', marginTop: 2 }}>{ins.detail}</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      )}

      {/* Acoes recomendadas */}
      {!loading && (c.acoes || []).length > 0 && (
        <Card title="Acoes recomendadas" style={{ marginBottom: 16 }}>
          <div style={{ padding: '8px 16px 16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 10 }}>
            {c.acoes.map(function(acao, i) {
              return (
                <div key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 10,
                  padding: '12px 14px', borderRadius: 8,
                  background: 'var(--tm-bg-3)', border: '1px solid var(--tm-line-1)',
                }}>
                  <Icon name={acao.icon} size={15} style={{ color: acao.color, flexShrink: 0, marginTop: 1 }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: acao.color, marginBottom: 4 }}>{acao.label}</div>
                    {acao.items.map(function(nome, j) {
                      return (
                        <div key={j} style={{ fontSize: 11.5, color: 'var(--tm-fg-2)', lineHeight: 1.6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {'· ' + nome}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      )}

      {/* Mudancas de classe */}
      {!loading && (c.classMudancas || []).length > 0 && (
        <Card title="Mudancas de classe vs periodo anterior" style={{ marginBottom: 16 }}>
          <div style={{ overflowX: 'auto', padding: '4px 16px 16px' }}>
            <table className="data-table" style={{ width: '100%' }}>
              <thead>
                <tr>
                  <th>Produto</th>
                  <th>SKU</th>
                  <th style={{ textAlign: 'center' }}>Mudanca</th>
                  <th style={{ textAlign: 'right' }}>Faturamento atual</th>
                  <th style={{ textAlign: 'right' }}>Var. %</th>
                </tr>
              </thead>
              <tbody>
                {c.classMudancas.slice(0, 15).map(function(m, i) {
                  return (
                    <tr key={i}>
                      <td style={{ fontWeight: 500, fontSize: 12 }}>{m.nome}</td>
                      <td style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--tm-fg-3)' }}>{m.sku || '—'}</td>
                      <td style={{ textAlign: 'center' }}>{classeArrow(m.anterior, m.atual)}</td>
                      <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, whiteSpace: 'nowrap' }}>R$ {brl(m.fat)}</td>
                      <td style={{ textAlign: 'right', fontSize: 12, fontWeight: 600,
                        color: m.varFat !== null ? (m.varFat >= 0 ? 'var(--tm-success)' : 'var(--tm-danger)') : 'var(--tm-fg-4)' }}>
                        {m.varFat !== null ? ('' + (m.varFat >= 0 ? '+' : '') + m.varFat.toFixed(1) + '%') : '—'}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* Tabela detalhada */}
      <Card title="Analise detalhada"
        action={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ position: 'relative' }}>
              <Icon name="search" size={13} style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', color: 'var(--tm-fg-4)' }} />
              <input
                value={busca} onChange={function(e) { setBusca(e.target.value); }}
                placeholder="Buscar produto, SKU, marca..."
                style={{
                  background: 'var(--tm-bg-3)', border: '1px solid var(--tm-line-1)', borderRadius: 6,
                  padding: '6px 10px 6px 28px', fontSize: 12, color: 'var(--tm-fg-1)',
                  width: 200, outline: 'none', fontFamily: 'inherit',
                }}
              />
            </div>
            <button onClick={exportCSV} style={{
              display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px',
              background: 'var(--tm-bg-3)', border: '1px solid var(--tm-line-1)',
              borderRadius: 6, cursor: 'pointer', color: 'var(--tm-fg-2)',
              fontSize: 11, fontFamily: 'inherit',
            }}>
              <Icon name="download" size={12} />
              Exportar CSV
            </button>
          </div>
        }>

        {/* Filter chips */}
        {!loading && (
          <div style={{ padding: '12px 16px 0', display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 11, color: 'var(--tm-fg-3)', fontWeight: 500 }}>Classe:</span>
              {['Todas', 'A', 'B', 'C'].map(function(v) {
                var isActive = filtroClasse === v;
                var chipColor = v === 'A' ? '#C9A36B' : v === 'B' ? '#6BA3D6' : v === 'C' ? '#94a3b8' : null;
                return (
                  <span key={v}
                    onClick={function() { setFiltroClasse(v); }}
                    style={{
                      cursor: 'pointer', fontSize: 11, padding: '3px 10px', borderRadius: 10,
                      fontWeight: isActive ? 600 : 400,
                      background: isActive ? (chipColor ? chipColor + '22' : 'var(--tm-bg-3)') : 'transparent',
                      color: isActive ? (chipColor || 'var(--tm-fg-1)') : 'var(--tm-fg-3)',
                      border: '1px solid ' + (isActive ? (chipColor ? chipColor + '44' : 'var(--tm-line-2)') : 'var(--tm-line-1)'),
                      transition: 'all 0.15s ease',
                    }}>
                    {v === 'Todas' ? 'Todas' : 'Classe ' + v}
                  </span>
                );
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 11, color: 'var(--tm-fg-3)', fontWeight: 500 }}>Estoque:</span>
              {['Todos', 'Com estoque', 'Sem estoque', 'Critico'].map(function(v) {
                var isActive = filtroEstoque === v;
                var chipColor = v === 'Critico' ? 'var(--tm-danger)' : null;
                return (
                  <span key={v}
                    onClick={function() { setFiltroEstoque(v); }}
                    style={{
                      cursor: 'pointer', fontSize: 11, padding: '3px 10px', borderRadius: 10,
                      fontWeight: isActive ? 600 : 400,
                      background: isActive ? (chipColor ? 'rgba(217,101,94,0.1)' : 'var(--tm-bg-3)') : 'transparent',
                      color: isActive ? (chipColor || 'var(--tm-fg-1)') : 'var(--tm-fg-3)',
                      border: '1px solid ' + (isActive ? (chipColor ? 'rgba(217,101,94,0.3)' : 'var(--tm-line-2)') : 'var(--tm-line-1)'),
                      transition: 'all 0.15s ease',
                    }}>
                    {v}
                  </span>
                );
              })}
            </div>
          </div>
        )}

        {loading ? (
          <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Carregando...</div>
        ) : displayItems.length === 0 ? (
          <div style={{ padding: '50px 24px', textAlign: 'center', color: 'var(--tm-fg-3)' }}>
            <Icon name="package" size={36} style={{ opacity: 0.25, marginBottom: 12 }} />
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--tm-fg-2)', marginBottom: 8 }}>
              Nenhuma venda encontrada para gerar a Curva ABC neste periodo.
            </div>
            <div style={{ fontSize: 12, color: 'var(--tm-fg-3)', lineHeight: 1.8, maxWidth: 380, margin: '0 auto', textAlign: 'left' }}>
              <div>{'· Altere o periodo de analise'}</div>
              <div>{'· Verifique se existem pedidos com status Atendido'}</div>
              <div>{'· Selecione outra marca se estiver usando filtro'}</div>
              {(filtroClasse !== 'Todas' || filtroEstoque !== 'Todos') && (
                <div>{'· Remova os filtros de classe/estoque acima'}</div>
              )}
            </div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto', padding: '0 0 4px' }}>
            <table className="data-table" style={{ width: '100%', minWidth: 1200 }}>
              <thead>
                <tr>
                  <th style={{ width: 36, textAlign: 'center' }}>#</th>
                  <th>Produto</th>
                  <th>SKU</th>
                  <th>Marca</th>
                  <th>Linha</th>
                  <th>Categoria</th>
                  <th style={{ textAlign: 'center' }}>Qtd</th>
                  <th style={{ textAlign: 'right' }}>Faturamento</th>
                  <th style={{ textAlign: 'right' }}>Custo</th>
                  <th style={{ textAlign: 'right' }}>Lucro</th>
                  <th style={{ textAlign: 'right' }}>Margem</th>
                  <th style={{ textAlign: 'right' }}>Part%</th>
                  <th style={{ textAlign: 'right' }}>Acum%</th>
                  <th style={{ textAlign: 'center' }}>Classe</th>
                  <th style={{ textAlign: 'center' }}>Estoque</th>
                  <th style={{ textAlign: 'center' }}>Dias Cob.</th>
                  <th>Sugestao</th>
                </tr>
              </thead>
              <tbody>
                {pagedItems.map(function(it, idx) {
                  var globalIdx = (page - 1) * PER_PAGE + idx;
                  var sug = c.getSugestao(it);
                  var toneColors = { danger: 'var(--tm-danger)', warning: '#D4A04A', success: 'var(--tm-success)', info: '#6BA3D6' };
                  return (
                    <tr key={it.key}
                      style={{ cursor: 'pointer', background: idx % 2 === 1 ? 'var(--tm-bg-2)' : 'transparent' }}
                      onClick={function() { setDetalhe(it); }}
                      onMouseEnter={function(e) { e.currentTarget.style.background = 'var(--tm-bg-3)'; }}
                      onMouseLeave={function(e) { e.currentTarget.style.background = idx % 2 === 1 ? 'var(--tm-bg-2)' : 'transparent'; }}
                    >
                      <td style={{ textAlign: 'center', fontSize: 11, color: 'var(--tm-fg-4)' }}>{globalIdx + 1}</td>
                      <td title={it.nome} style={{ fontWeight: 500, fontSize: 12, maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.nome}</td>
                      <td style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--tm-fg-3)' }}>{it.sku || '—'}</td>
                      <td style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>{it.marca || '—'}</td>
                      <td style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>{it.linha || '—'}</td>
                      <td style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>{it.categoria || '—'}</td>
                      <td style={{ textAlign: 'center', fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>{it.qtd}</td>
                      <td style={{ textAlign: 'right', fontSize: 12, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', fontWeight: 500 }}>R$ {brl(it.fat)}</td>
                      <td style={{ textAlign: 'right', fontSize: 12, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', color: 'var(--tm-fg-3)' }}>R$ {brl(it.custo)}</td>
                      <td style={{ textAlign: 'right', fontSize: 12, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', color: it.lucro >= 0 ? 'var(--tm-success)' : 'var(--tm-danger)' }}>R$ {brl(it.lucro)}</td>
                      <td style={{ textAlign: 'right', fontSize: 12, fontWeight: 600,
                        color: it.margemPct >= 30 ? 'var(--tm-success)' : it.margemPct >= 15 ? '#D4A04A' : 'var(--tm-danger)' }}>
                        {it.margemPct.toFixed(1)}%
                      </td>
                      <td style={{ textAlign: 'right', fontSize: 11, color: 'var(--tm-fg-3)', fontVariantNumeric: 'tabular-nums' }}>{it.partPct.toFixed(1)}%</td>
                      <td style={{ textAlign: 'right', fontSize: 11, color: 'var(--tm-fg-3)', fontVariantNumeric: 'tabular-nums' }}>{it.acumPct.toFixed(1)}%</td>
                      <td style={{ textAlign: 'center' }}>{classeBadge(it.classe, true)}</td>
                      <td style={{ textAlign: 'center', fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>{it.estoque}</td>
                      <td style={{ textAlign: 'center', fontSize: 12 }}>
                        {it.diasEstoque === 999 ? (
                          <span style={{ color: 'var(--tm-fg-4)' }}>—</span>
                        ) : (
                          <span style={{ fontWeight: 600, color: it.diasEstoque < 15 ? 'var(--tm-danger)' : it.diasEstoque < 30 ? '#D4A04A' : 'var(--tm-fg-2)' }}>
                            {it.diasEstoque}d
                            {it.diasEstoque < 15 && it.classe === 'A' && (
                              <Icon name="alert-triangle" size={10} style={{ color: 'var(--tm-danger)', marginLeft: 3 }} />
                            )}
                          </span>
                        )}
                      </td>
                      <td style={{ fontSize: 11 }}>
                        {sug ? (
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: toneColors[sug.tone] || 'var(--tm-fg-3)' }}>
                            <Icon name={sug.icon} size={11} />
                            {sug.text}
                          </span>
                        ) : '—'}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
        {!loading && displayItems.length > PER_PAGE && (
          <FooterPager total={displayItems.length} perPage={PER_PAGE} page={page} onPage={setPage} />
        )}
      </Card>

      {/* Product Detail Modal */}
      {detalhe && (function() {
        var it = detalhe;
        var sug = c.getSugestao ? c.getSugestao(it) : null;
        var toneColors = { danger: 'var(--tm-danger)', warning: '#D4A04A', success: 'var(--tm-success)', info: '#6BA3D6' };
        var classColors = { A: '#C9A36B', B: '#6BA3D6', C: '#94a3b8' };

        return (
          <div style={{
            position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
            background: 'rgba(0,0,0,0.55)', zIndex: 9999,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 20,
          }} onClick={function(e) { if (e.target === e.currentTarget) setDetalhe(null); }}>
            <div style={{
              background: 'var(--tm-bg-1)', borderRadius: 14, width: '100%', maxWidth: 520,
              maxHeight: '85vh', overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,0.4)',
              border: '1px solid var(--tm-line-1)',
            }}>
              {/* Header */}
              <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--tm-line-1)', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--tm-fg-1)', lineHeight: 1.3, marginBottom: 6 }}>{it.nome}</div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                    {classeBadge(it.classe, true)}
                    {it.sku && <span style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--tm-fg-3)', background: 'var(--tm-bg-3)', padding: '2px 8px', borderRadius: 4 }}>{it.sku}</span>}
                  </div>
                  {(it.marca || it.linha || it.categoria) && (
                    <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 6 }}>
                      {[it.marca, it.linha, it.categoria].filter(Boolean).join(' · ')}
                    </div>
                  )}
                </div>
                <button onClick={function() { setDetalhe(null); }} style={{
                  background: 'var(--tm-bg-3)', border: '1px solid var(--tm-line-1)', borderRadius: 8,
                  width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: 'pointer', color: 'var(--tm-fg-3)', flexShrink: 0,
                }}>
                  <Icon name="x" size={16} />
                </button>
              </div>

              {/* Metrics grid */}
              <div style={{ padding: '16px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                {[
                  { label: 'Faturamento', value: 'R$ ' + brl(it.fat), color: 'var(--tm-fg-1)' },
                  { label: 'Quantidade', value: it.qtd.toLocaleString('pt-BR'), color: 'var(--tm-fg-1)' },
                  { label: 'Lucro', value: 'R$ ' + brl(it.lucro), color: it.lucro >= 0 ? 'var(--tm-success)' : 'var(--tm-danger)' },
                  { label: 'Margem', value: it.margemPct.toFixed(1) + '%', color: it.margemPct >= 30 ? 'var(--tm-success)' : it.margemPct >= 15 ? '#D4A04A' : 'var(--tm-danger)' },
                  { label: 'Estoque', value: String(it.estoque), color: 'var(--tm-fg-1)' },
                  { label: 'Cobertura', value: it.diasEstoque === 999 ? 'N/A' : it.diasEstoque + ' dias', color: it.diasEstoque < 15 && it.diasEstoque !== 999 ? 'var(--tm-danger)' : 'var(--tm-fg-1)' },
                ].map(function(m, i) {
                  return (
                    <div key={i} style={{ background: 'var(--tm-bg-2)', borderRadius: 8, padding: '12px 14px', border: '1px solid var(--tm-line-1)' }}>
                      <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--tm-fg-4)', marginBottom: 4 }}>{m.label}</div>
                      <div style={{ fontSize: 16, fontWeight: 600, fontVariantNumeric: 'tabular-nums', color: m.color }}>{m.value}</div>
                    </div>
                  );
                })}
              </div>

              {/* Participacao */}
              <div style={{ padding: '0 24px 16px' }}>
                <div style={{ background: 'var(--tm-bg-2)', borderRadius: 8, padding: '12px 14px', border: '1px solid var(--tm-line-1)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ fontSize: 11, color: 'var(--tm-fg-3)' }}>Participacao no total</span>
                    <span style={{ fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{(it.partPct || 0).toFixed(1)}%</span>
                  </div>
                  <div style={{ height: 6, borderRadius: 3, background: 'var(--tm-bg-3)', overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: Math.min(100, it.partPct || 0) + '%', borderRadius: 3, background: classColors[it.classe] || '#94a3b8' }} />
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--tm-fg-4)', marginTop: 4 }}>Acumulado: {(it.acumPct || 0).toFixed(1)}%</div>
                </div>
              </div>

              {/* Sugestao */}
              {sug && (
                <div style={{ padding: '0 24px 20px' }}>
                  <div style={{
                    display: 'flex', alignItems: 'flex-start', gap: 10,
                    padding: '12px 14px', borderRadius: 8,
                    background: (toneColors[sug.tone] || 'var(--tm-fg-3)') === 'var(--tm-danger)' ? 'rgba(217,101,94,0.08)' :
                      (toneColors[sug.tone] || 'var(--tm-fg-3)') === '#D4A04A' ? 'rgba(212,160,74,0.08)' :
                      (toneColors[sug.tone] || 'var(--tm-fg-3)') === 'var(--tm-success)' ? 'rgba(91,177,122,0.08)' :
                      'rgba(107,163,214,0.08)',
                    border: '1px solid ' + ((toneColors[sug.tone] || 'var(--tm-fg-3)') === 'var(--tm-danger)' ? 'rgba(217,101,94,0.2)' :
                      (toneColors[sug.tone] || 'var(--tm-fg-3)') === '#D4A04A' ? 'rgba(212,160,74,0.2)' :
                      (toneColors[sug.tone] || 'var(--tm-fg-3)') === 'var(--tm-success)' ? 'rgba(91,177,122,0.2)' :
                      'rgba(107,163,214,0.2)'),
                  }}>
                    <Icon name={sug.icon} size={15} style={{ color: toneColors[sug.tone] || 'var(--tm-fg-3)', flexShrink: 0, marginTop: 1 }} />
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: toneColors[sug.tone] || 'var(--tm-fg-3)', marginBottom: 2 }}>Sugestao</div>
                      <div style={{ fontSize: 12, color: 'var(--tm-fg-2)', lineHeight: 1.5 }}>{sug.text}</div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })()}
    </div>
  );
}

function RelExecutivoSection({ filters, onNav }) {
  return (
    <div style={{ padding:'60px 0', textAlign:'center', color:'var(--tm-fg-3)' }}>
      <Icon name="layout" size={40} style={{ opacity:0.3, marginBottom:12 }} />
      <div style={{ fontSize:14, fontWeight:500, marginBottom:6 }}>Resumo Executivo</div>
      <div style={{ fontSize:12.5 }}>Visao consolidada com KPIs, sparklines e alertas — em breve.</div>
    </div>
  );
}

// ─── Export ──────────────────────────────────────────────────────────────────
Object.assign(window, {
  RelVendasSection, RelDistribuidoresSection, RelClientesSection,
  RelFinanceiroSection, RelInsightsSection, RelProdutosSection, RelCurvaABCSection, RelExecutivoSection,
});
