// KPIs financeiros rápidos para o dashboard
export async function initFinanceKpis(state, { fmtBRL }){
  const elTotalPay = document.querySelector('#kpiFinApagarTotal > div:nth-child(2)');
  const elTodayPay = document.querySelector('#kpiFinApagarHoje > div:nth-child(2)');
  const elNext7Pay = document.querySelector('#kpiFinApagarProx7 > div:nth-child(2)');
  const elTotalRec = document.querySelector('#kpiFinAreceberTotal > div:nth-child(2)');
  const elTodayRec = document.querySelector('#kpiFinAreceberHoje > div:nth-child(2)');
  const elNext7Rec = document.querySelector('#kpiFinAreceberProx7 > div:nth-child(2)');
  const elPay5Total = document.getElementById('kpiFinApagarProxTotal5');
  const elRec5Total = document.getElementById('kpiFinAreceberProxTotal5');
  const btnPayDetail = document.getElementById('btnPayNextDetail');
  const btnRecDetail = document.getElementById('btnRecNextDetail');

  try {
    const qs = new URLSearchParams();
    if (state?.filters?.start) qs.set('start', state.filters.start);
    if (state?.filters?.end) qs.set('end', state.filters.end);
    const res = await apiRequest(`/api/finance/metrics?${qs.toString()}`, { headers: { 'Accept': 'application/json' } });
    if (!res.ok) throw new Error('Falha ao carregar métricas');
    const json = await res.json();
    const pay = json.payables || {};
    const rec = json.receivables || {};
    if (elTotalPay) elTotalPay.textContent = fmtBRL(pay.total_pending || 0);
    if (elTodayPay) elTodayPay.textContent = String(pay.due_today_count || 0);
    if (elNext7Pay) elNext7Pay.textContent = String(pay.next_7d_count || 0);
    if (elTotalRec) elTotalRec.textContent = fmtBRL(rec.total_pending || 0);
    if (elTodayRec) elTodayRec.textContent = String(rec.due_today_count || 0);
    if (elNext7Rec) elNext7Rec.textContent = String(rec.next_7d_count || 0);
    if (elPay5Total) {
      const details = Array.isArray(pay.next_dates_detail) ? pay.next_dates_detail : [];
      const sum = details.slice(0,5).reduce((acc, d)=> acc + (Number(d.total||0)), 0);
      elPay5Total.textContent = fmtBRL(sum || 0);
    }
    if (elRec5Total) {
      const rdetails = Array.isArray(rec.next_dates_detail) ? rec.next_dates_detail : [];
      const rsum = rdetails.slice(0,5).reduce((acc, d)=> acc + (Number(d.total||0)), 0);
      elRec5Total.textContent = fmtBRL(rsum || 0);
    }
    // Deltas comparando com período anterior
    const filters = state?.filters || {};
    if (filters.start && filters.end) {
      const prev = previousRange(filters.start, filters.end);
      const qsp = new URLSearchParams(); qsp.set('start', prev.start); qsp.set('end', prev.end);
      const resPrev = await apiRequest(`/api/finance/metrics?${qsp.toString()}`, { headers: { 'Accept': 'application/json' } });
      if (resPrev.ok) {
        const jsonPrev = await resPrev.json();
        const payPrev = jsonPrev.payables || {}; const recPrev = jsonPrev.receivables || {};
        setDelta('kpiFinApagarTotalDelta', (pay.total_pending||0) - (payPrev.total_pending||0), true, fmtBRL);
        setDelta('kpiFinApagarHojeDelta', (pay.due_today_count||0) - (payPrev.due_today_count||0));
        setDelta('kpiFinApagarProx7Delta', (pay.next_7d_count||0) - (payPrev.next_7d_count||0));
        setDelta('kpiFinAreceberTotalDelta', (rec.total_pending||0) - (recPrev.total_pending||0), true, fmtBRL);
        setDelta('kpiFinAreceberHojeDelta', (rec.due_today_count||0) - (recPrev.due_today_count||0));
        setDelta('kpiFinAreceberProx7Delta', (rec.next_7d_count||0) - (recPrev.next_7d_count||0));
      }
    }
    // Report para alertas, se útil no futuro
    if (typeof window.__dashboardReportSnapshot === 'function') {
      window.__dashboardReportSnapshot({
        finance: {
          payables_total_pending: pay.total_pending || 0,
          receivables_total_pending: rec.total_pending || 0,
          payables_due_today_count: pay.due_today_count || 0,
          payables_next_7d_count: pay.next_7d_count || 0
        }
      });
    }

    // Modal de detalhes para próximos 5 dias (pendentes)
    const openModal = async (kind) => {
      const modal = document.getElementById('finModal');
      const body = document.getElementById('finModalBody');
      const title = document.getElementById('finModalTitle');
      if (!modal || !body || !title) return;
      title.textContent = kind === 'pay' ? 'Despesas pendentes — próximos 5 dias' : 'Receitas pendentes — próximos 5 dias';
      body.innerHTML = '<div class="muted">Carregando…</div>';
      // Range de hoje até +5 dias
      const today = new Date();
      const end = new Date(); end.setDate(end.getDate()+5);
      const fmt = (d)=> `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
      const qs = new URLSearchParams({ start: fmt(today), end: fmt(end), per_page: '200' });
      try {
        const url = kind === 'pay' ? `/api/finance/payables?${qs.toString()}` : `/api/finance/receivables?${qs.toString()}`;
        const res = await apiRequest(url, { headers: { 'Accept':'application/json' } });
        const json = res.ok ? (await res.json()) : { data: [] };
        const items = json.data || json.items || [];
        const filtered = items.filter(it => String(it.status||'').toLowerCase() === 'pendente');
        const total = filtered.reduce((acc, it)=> acc + (it.amount_cents ? it.amount_cents/100 : (it.amount||0)), 0);
        const rows = filtered.map(it => {
          const dateIso = kind === 'pay' ? it.due_at : (it.receive_at || it.due_at);
          const date = fmtDateBR(dateIso);
          const desc = kind === 'pay' ? (it.description || it.supplier_name || '-') : (it.customer_name || it.origin || it.description || '-');
          const val = fmtBRL(it.amount_cents ? it.amount_cents/100 : (it.amount||0));
          return `<tr><td>${date}</td><td>${escapeHtml(desc)}</td><td style="text-align:right;">${val}</td></tr>`;
        }).join('');
        body.innerHTML = `
          <div style="margin-bottom:0.5rem;"><strong>Total:</strong> ${fmtBRL(total)}</div>
          <div class="table-responsive"><table class="table"><thead><tr><th>Data</th><th>Descrição</th><th style="text-align:right;">Valor</th></tr></thead><tbody>${rows || '<tr><td colspan="3" class="muted">Sem pendências</td></tr>'}</tbody></table></div>
        `;
      } catch(e) {
        body.innerHTML = `<div class="muted">Erro ao carregar: ${escapeHtml(e.message||String(e))}</div>`;
      }
      modal.style.display = 'flex';
    };

    btnPayDetail?.addEventListener('click', ()=>openModal('pay'));
    btnRecDetail?.addEventListener('click', ()=>openModal('rec'));
  } catch (e) {
    if (elTotalPay) elTotalPay.textContent = '—';
    if (elTodayPay) elTodayPay.textContent = '—';
    if (elNext7Pay) elNext7Pay.textContent = '—';
    if (elTotalRec) elTotalRec.textContent = '—';
    if (elTodayRec) elTodayRec.textContent = '—';
    if (elNext7Rec) elNext7Rec.textContent = '—';
    if (elPay5Total) elPay5Total.textContent = '—';
    if (elRec5Total) elRec5Total.textContent = '—';
    ['kpiFinApagarTotalDelta','kpiFinApagarHojeDelta','kpiFinApagarProx7Delta','kpiFinAreceberTotalDelta','kpiFinAreceberHojeDelta','kpiFinAreceberProx7Delta'].forEach(id=>{
      const el = document.getElementById(id); if (el) el.textContent = '—';
    });
    console.error('Finance KPIs error:', e);
  }
}

function escapeHtml(s){
  try { return String(s||'').replace(/[&<>"]|'/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c])); }
  catch(_){ return String(s||''); }
}

function fmtDateBR(iso){
  try {
    const d = new Date(iso);
    return `${String(d.getDate()).padStart(2,'0')}-${String(d.getMonth()+1).padStart(2,'0')}-${d.getFullYear()}`;
  } catch(e){ return iso; }
}

function renderMiniBars(container, details, type, fmtBRL){
  if (!container) return;
  const arr = Array.isArray(details) ? details : [];
  if (!arr.length) {
    container.innerHTML = '';
    try {
      const emptyLabel = type === 'expense' ? 'Próximos vencimentos – sem dados' : 'Próximos recebimentos – sem dados';
      container.setAttribute('aria-label', emptyLabel);
    } catch(_){}
    return;
  }
  const values = arr.map(d=> Number(d.total||d.count||1));
  const max = Math.max(...values, 1);
  const color = type === 'expense' ? 'var(--color-expense-red)' : 'var(--color-revenue-blue)';
  container.innerHTML = arr.map((d, i)=>{
    const h = Math.round((values[i]/max) * 100);
    const label = `${fmtDateBR(d.date)}${d.count?` • ${d.count}`:''}${d.total?` • ${typeof fmtBRL==='function'?fmtBRL(d.total):d.total}`:''}`;
    return `<div style="width:20%; min-width:24px; display:inline-block; text-align:center;">
              <div style="background:${color}; height:${h}%; border-radius:4px;"></div>
              <div class="muted" style="font-size:11px; margin-top:2px;">${label}</div>
            </div>`;
  }).join('');

  // Descrição acessível resumida para leitores de tela
  try {
    const prefix = type === 'expense' ? 'Próximos vencimentos' : 'Próximos recebimentos';
    const summary = arr.map(d => {
      const date = fmtDateBR(d.date);
      const count = d.count ? `${d.count} títulos` : '';
      const total = d.total ? `${typeof fmtBRL==='function'?fmtBRL(d.total):d.total}` : '';
      const parts = [date, count, total].filter(Boolean);
      return parts.join(', ');
    }).join('; ');
    container.setAttribute('aria-label', `${prefix} – ${summary}`);
  } catch(_){}
}

function previousRange(startIso, endIso){
  try {
    const s = new Date(startIso); const e = new Date(endIso);
    const msPerDay = 24*60*60*1000;
    const len = Math.max(1, Math.ceil((e - s) / msPerDay) + 1);
    const prevEnd = new Date(s.getTime() - msPerDay);
    const prevStart = new Date(prevEnd.getTime() - (len-1)*msPerDay);
    const fmt = (d)=> `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
    return { start: fmt(prevStart), end: fmt(prevEnd) };
  } catch(_){ return { start: startIso, end: endIso }; }
}

function setDelta(elId, diff, isMoney=false, fmtBRL){
  const el = document.getElementById(elId);
  if (!el) return;
  const sign = diff > 0 ? '+' : (diff < 0 ? '−' : '');
  el.classList.remove('delta-pos','delta-neg','delta-zero');
  if (diff > 0) el.classList.add('delta-pos'); else if (diff < 0) el.classList.add('delta-neg'); else el.classList.add('delta-zero');
  if (isMoney && typeof fmtBRL === 'function') {
    el.textContent = sign ? `${sign}${fmtBRL(Math.abs(diff))}` : '—';
  } else {
    el.textContent = sign ? `${sign}${Math.abs(diff)}` : '—';
  }
}