export async function initKpis(state, utils){
  const { fmtBRL } = utils;
  const elFat = document.querySelector('#kpiFatTotal div:nth-child(2)');
  const elFatDelta = document.getElementById('kpiFatTotalDelta');
  const elOpen = document.querySelector('#kpiPedidosAbertos div:nth-child(2)');
  const elOpenDelta = document.getElementById('kpiPedidosAbertosDelta');
  const elTicket = document.querySelector('#kpiTicketMedio div:nth-child(2)');
  const elTicketDelta = document.getElementById('kpiTicketMedioDelta');
  const elConv = document.querySelector('#kpiConversao div:nth-child(2)');
  const elConvDelta = document.getElementById('kpiConversaoDelta');

  // Carregar dados de PDV e Pedidos/Orçamentos
  const [pdvRes, pedRes, orcRes] = await Promise.all([
    window.apiRequest('/api/pdv/vendas', { method: 'GET' }),
    window.apiRequest('/api/vendas/pedidos', { method: 'GET' }),
    window.apiRequest('/api/vendas/orcamentos', { method: 'GET' }),
  ]);
  const pdvData = pdvRes.ok ? (await pdvRes.json()).data || [] : [];
  const pedData = pedRes.ok ? (await pedRes.json()).data || [] : [];
  const orcData = orcRes.ok ? (await orcRes.json()).data || [] : [];

  // Filtro por período simples no cliente
  const { start, end } = state.filters || {};
  function inRange(dt){
    if (!dt) return true;
    const d = new Date(dt);
    if (start && d < new Date(start)) return false;
    if (end) { const e = new Date(end); e.setHours(23,59,59,999); if (d > e) return false; }
    return true;
  }

  const pdvFiltered = pdvData.filter(r => inRange(r.created_at));
  const pedFiltered = pedData.filter(r => inRange(r.created_at));
  const orcFiltered = orcData.filter(r => inRange(r.created_at));

  const fatPDV = pdvFiltered.reduce((a,b)=>a+Number(b.valor_total||0),0);
  const fatPedidos = pedFiltered.reduce((a,b)=>a+Number(b.valor_total||0),0);
  const fatTotal = fatPDV + fatPedidos;

  const pedidosAbertos = pedFiltered.filter(p => String(p.status||'').toLowerCase() !== 'faturado' && String(p.status||'').toLowerCase() !== 'cancelado').length;

  const totalItens = pedFiltered.length + pdvFiltered.length;
  const ticketMedio = totalItens > 0 ? (fatTotal / totalItens) : 0;

  const conv = (orcFiltered.length > 0) ? (pedFiltered.length / orcFiltered.length) * 100 : 0;

  // Exibir
  if (elFat) { elFat.textContent = fmtBRL(fatTotal); elFat.classList.add('income'); }
  if (elOpen) elOpen.textContent = String(pedidosAbertos);
  if (elTicket) { elTicket.textContent = fmtBRL(ticketMedio); elTicket.classList.add('income'); }
  if (elConv) elConv.textContent = String((conv).toFixed(1)).replace('.', ',') + '%';

  // Deltas fictícios (placeholder) — podem ser substituídos por endpoint histórico
  if (elFatDelta) elFatDelta.textContent = '↑ vs. ontem';
  if (elOpenDelta) elOpenDelta.textContent = '—';
  if (elTicketDelta) elTicketDelta.textContent = '↑ 3.1%';
  if (elConvDelta) elConvDelta.textContent = '↓ 1.2%';

  // Report para alertas
  if (window.__dashboardReportSnapshot) {
    window.__dashboardReportSnapshot({ fatTotal, pedidosAbertos, ticketMedio, conv });
  }
}