export async function initInsights(state, { fmtBRL }){
  const ul = document.getElementById('insightsList');
  if (!ul) return;
  ul.innerHTML = '<li class="muted">Analisando…</li>';
  try {
    const metrics = await loadFinanceMetrics(state.filters);
    const alerts = [];
    if ((metrics?.payables?.overdue_count||0) > 0) {
      alerts.push(`Há ${metrics.payables.overdue_count} despesas vencidas — atenção imediata`);
    }
    const pendPay = Number(metrics?.payables?.total_pending||0);
    const pendRec = Number(metrics?.receivables?.total_pending||0);
    if (pendPay > pendRec * 1.2) {
      alerts.push(`Pendente a pagar (${fmtBRL(pendPay)}) supera a receber (${fmtBRL(pendRec)})`);
    }
    if ((metrics?.payables?.due_today_count||0) >= 5) {
      alerts.push(`Muitos vencimentos hoje (${metrics.payables.due_today_count}) — priorize pagamentos`);
    }
    if ((metrics?.receivables?.next_7d_count||0) >= 10) {
      alerts.push(`Receitas concentradas nos próximos 7 dias (${metrics.receivables.next_7d_count})`);
    }

    ul.innerHTML = alerts.length ? alerts.map(a=>`<li>${a}</li>`).join('') : '<li class="muted">Sem anomalias detectadas</li>';
  } catch(e) {
    console.error('Insights error:', e);
    ul.innerHTML = '<li class="muted">Falha ao carregar insights</li>';
  }
}

async function loadFinanceMetrics(filters){
  const params = new URLSearchParams();
  if (filters?.start) params.set('start', filters.start);
  if (filters?.end) params.set('end', filters.end);
  const resp = await apiRequest('/api/finance/metrics?'+params.toString(), { headers: { 'Accept': 'application/json' } });
  const json = await resp.json();
  return json || {};
}