// ─────────────────────────────────────────────────────────────
// report.jsx — gera relatórios em HTML (imprimível / salvável em PDF)
// para o Painel (mensal ou anual) e para as Metas de Investimento.
// Cada relatório abre uma nova janela já pronta para imprimir.
// ─────────────────────────────────────────────────────────────

const REPORT_CSS = `
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'Manrope', -apple-system, system-ui, sans-serif; color: #0F172A; background: #fff; padding: 48px; line-height: 1.5; }
  .r-head { display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 2px solid #0F172A; padding-bottom: 20px; margin-bottom: 28px; }
  .r-brand { display: flex; align-items: center; gap: 12px; }
  .r-logo { width: 40px; height: 40px; border-radius: 10px; background: #0F172A; color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; }
  .r-brand h1 { font-size: 20px; letter-spacing: -0.4px; }
  .r-brand .sub { font-size: 10px; letter-spacing: 2px; color: #64748B; text-transform: uppercase; margin-top: 2px; }
  .r-meta { text-align: right; font-size: 12px; color: #64748B; }
  .r-title { font-size: 28px; font-weight: 800; letter-spacing: -0.6px; margin-bottom: 4px; }
  .r-sub { font-size: 13px; color: #64748B; margin-bottom: 28px; }
  .kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 32px; }
  .kpi { border: 1px solid #E2E8F0; border-radius: 12px; padding: 16px; }
  .kpi .lbl { font-size: 10px; letter-spacing: 1px; color: #64748B; text-transform: uppercase; margin-bottom: 8px; }
  .kpi .val { font-size: 20px; font-weight: 800; letter-spacing: -0.4px; }
  .kpi.pos .val { color: #009668; } .kpi.neg .val { color: #B00369; }
  h2 { font-size: 16px; margin: 28px 0 12px; }
  table { width: 100%; border-collapse: collapse; margin-bottom: 12px; }
  th { text-align: left; font-size: 10px; letter-spacing: 1px; color: #64748B; text-transform: uppercase; padding: 8px 10px; border-bottom: 1px solid #E2E8F0; }
  td { font-size: 13px; padding: 9px 10px; border-bottom: 1px solid #F1F5F9; }
  td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
  .pos { color: #009668; } .neg { color: #B00369; }
  .bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
  .bar-row .nm { width: 200px; font-size: 13px; }
  .bar-track { flex: 1; height: 10px; background: #F1F5F9; border-radius: 5px; overflow: hidden; }
  .bar-fill { height: 100%; border-radius: 5px; }
  .bar-row .amt { width: 130px; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
  .foot { margin-top: 40px; padding-top: 16px; border-top: 1px solid #E2E8F0; font-size: 11px; color: #94A3B8; font-style: italic; text-align: center; }
  .print-bar { position: fixed; top: 16px; right: 16px; display: flex; gap: 8px; }
  .print-bar button { font-family: inherit; font-weight: 700; font-size: 13px; padding: 10px 18px; border: none; border-radius: 8px; cursor: pointer; }
  .print-bar .primary { background: #B00369; color: #fff; }
  .print-bar .ghost { background: #F1F5F9; color: #0F172A; }
  @media print { .print-bar { display: none; } body { padding: 24px; } }
`;

const CAT_COLORS = {
  basic: '#334155', education: '#3B6FF1', wishes: '#B00369', investments: '#009668',
};

function reportShell(title, sub, bodyHtml) {
  return `<!doctype html><html lang="pt-BR"><head><meta charset="utf-8" />
<title>${title}</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;600;700;800&display=swap" rel="stylesheet" />
<style>${REPORT_CSS}</style></head><body>
<div class="print-bar"><button class="primary" onclick="window.print()">Imprimir / Salvar PDF</button><button class="ghost" onclick="window.close()">Fechar</button></div>
${bodyHtml}
<div class="foot">The Ledger · Relatório gerado em ${new Date().toLocaleString('pt-BR')} · Dados deste dispositivo</div>
</body></html>`;
}

function reportHeader(titleLine) {
  return `<div class="r-head">
    <div class="r-brand"><div class="r-logo">L</div><div><h1>The Ledger</h1><div class="sub">Curadoria Precisa</div></div></div>
    <div class="r-meta">${titleLine}</div>
  </div>`;
}

function openReport(html) {
  const blob = new Blob([html], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  const w = window.open(url, '_blank');
  if (!w) {
    // popup blocked → download instead
    const a = document.createElement('a');
    a.href = url; a.download = 'relatorio-the-ledger.html';
    document.body.appendChild(a); a.click(); a.remove();
  }
  setTimeout(() => URL.revokeObjectURL(url), 60000);
}

// ── COCKPIT REPORT ───────────────────────────────────────────
function buildCockpitReport(state, period) {
  const S = window.LedgerStore;
  const isYear = /^Y/.test(period);
  if (isYear) {
    const year = period.slice(1);
    const { inSum, outSum, delta } = S.yearTotals(state, year);
    const endBal = S.yearEndingBalance(state, year);
    const series = S.yearMonthsSeries(state, year);
    const byCatYear = S.byCategoryYear(state, year);
    const maxMonth = Math.max(1, ...series.map(s => s.value));
    const monthsRows = series.map(s => `<tr><td>${s.label}</td><td class="num pos">${S.fmtMoney(s.inSum)}</td><td class="num neg">${S.fmtMoney(s.outSum)}</td><td class="num">${S.fmtMoney(s.inSum - s.outSum, { signed: true })}</td></tr>`).join('');
    const catBars = S.CATEGORIES.map(c => {
      const v = byCatYear[c.id] || 0; const pct = outSum > 0 ? Math.round(v / outSum * 100) : 0;
      return `<div class="bar-row"><div class="nm">${c.name}</div><div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${CAT_COLORS[c.id]}"></div></div><div class="amt">${S.fmtMoney(v)} · ${pct}%</div></div>`;
    }).join('');
    const body = reportHeader(`Relatório Anual<br/><strong style="color:#0F172A;font-size:14px">${year}</strong>`)
      + `<div class="r-title">Visão do Ano · ${year}</div><div class="r-sub">Resumo consolidado de entradas, saídas e alocação.</div>`
      + `<div class="kpis">
          <div class="kpi pos"><div class="lbl">Entradas no ano</div><div class="val">${S.fmtMoney(inSum)}</div></div>
          <div class="kpi neg"><div class="lbl">Saídas no ano</div><div class="val">${S.fmtMoney(outSum)}</div></div>
          <div class="kpi"><div class="lbl">Resultado</div><div class="val">${S.fmtMoney(delta, { signed: true })}</div></div>
          <div class="kpi"><div class="lbl">Saldo atual</div><div class="val">${S.fmtMoney(endBal)}</div></div>
        </div>`
      + `<h2>Mês a mês</h2><table><thead><tr><th>Mês</th><th class="num">Entradas</th><th class="num">Saídas</th><th class="num">Resultado</th></tr></thead><tbody>${monthsRows}</tbody></table>`
      + `<h2>Gastos por categoria (acumulado do ano)</h2>${catBars}`;
    return reportShell(`Relatório Anual ${year} · The Ledger`, '', body);
  }
  // monthly
  const ymk = period;
  const startBal = state.monthlyBalances[ymk] || 0;
  const { inSum, outSum, delta } = S.monthTotals(state, ymk);
  const endBal = startBal + delta;
  const byCat = S.byCategory(state, ymk);
  const tx = S.transactionsInMonth(state, ymk).slice().sort((a, b) => new Date(b.date) - new Date(a.date));
  const catBars = S.CATEGORIES.map(c => {
    const v = byCat[c.id] || 0; const pct = outSum > 0 ? Math.round(v / outSum * 100) : 0;
    return `<div class="bar-row"><div class="nm">${c.name}</div><div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${CAT_COLORS[c.id]}"></div></div><div class="amt">${S.fmtMoney(v)} · ${pct}%</div></div>`;
  }).join('');
  const txRows = tx.map(r => {
    const cat = S.catLookup(r.categoryId); const sub = S.subLookup(r.categoryId, r.subcategoryId);
    const isIncome = r.amount > 0;
    return `<tr><td>${S.fmtDate(r.date, { short: true })}</td><td>${r.note || (isIncome ? (r.source || 'Entrada') : (sub ? sub.name : cat ? cat.name : '—'))}</td><td>${isIncome ? 'Entrada' : (cat ? cat.name : '—')}</td><td class="num ${isIncome ? 'pos' : 'neg'}">${S.fmtMoney(r.amount, { signed: true })}</td></tr>`;
  }).join('');
  const body = reportHeader(`Relatório Mensal<br/><strong style="color:#0F172A;font-size:14px">${S.ymLabel(ymk)}</strong>`)
    + `<div class="r-title">${S.ymLabel(ymk)}</div><div class="r-sub">Extrato e alocação do mês.</div>`
    + `<div class="kpis">
        <div class="kpi"><div class="lbl">Saldo inicial</div><div class="val">${S.fmtMoney(startBal)}</div></div>
        <div class="kpi pos"><div class="lbl">Entradas</div><div class="val">${S.fmtMoney(inSum)}</div></div>
        <div class="kpi neg"><div class="lbl">Saídas</div><div class="val">${S.fmtMoney(outSum)}</div></div>
        <div class="kpi"><div class="lbl">Saldo final</div><div class="val">${S.fmtMoney(endBal)}</div></div>
      </div>`
    + `<h2>Gastos por categoria</h2>${catBars}`
    + `<h2>Extrato do mês (${tx.length})</h2><table><thead><tr><th>Data</th><th>Descrição</th><th>Categoria</th><th class="num">Valor</th></tr></thead><tbody>${txRows || '<tr><td colspan="4" style="text-align:center;color:#94A3B8;padding:24px">Nenhum lançamento.</td></tr>'}</tbody></table>`;
  return reportShell(`Relatório ${S.ymLabel(ymk)} · The Ledger`, '', body);
}

// ── GOALS REPORT ─────────────────────────────────────────────
function buildGoalsReport(state) {
  const S = window.LedgerStore;
  const totalSaved = state.goals.reduce((s, g) => s + (g.saved || 0), 0);
  const totalTarget = state.goals.reduce((s, g) => s + (g.target || 0), 0);
  const totalYield = state.goals.reduce((s, g) => s + S.goalYield(g), 0);
  const overallPct = totalTarget > 0 ? Math.round(totalSaved / totalTarget * 100) : 0;
  const typeAlloc = S.investmentTypeAllocation(state);
  const unalloc = state.goals.reduce((s, g) => s + S.goalUnallocated(g), 0);
  const allocItems = typeAlloc.slice();
  if (unalloc > 0) allocItems.push({ type: 'Não alocado', value: unalloc, color: '#94A3B8' });
  const allocTotal = allocItems.reduce((s, it) => s + it.value, 0) || 1;
  const allocBars = allocItems.map(it => {
    const pct = Math.round(it.value / allocTotal * 100);
    return `<div class="bar-row"><div class="nm">${it.type}</div><div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${it.color}"></div></div><div class="amt">${S.fmtMoney(it.value)} · ${pct}%</div></div>`;
  }).join('');
  const goalSections = state.goals.map(g => {
    const pct = Math.min(100, Math.round((g.saved || 0) / Math.max(1, g.target) * 100));
    const holdings = g.holdings || [];
    const hRows = holdings.map(h => {
      const hy = S.holdingYield(h);
      return `<tr><td>${h.name}</td><td>${h.type}</td><td class="num">${S.fmtMoney(h.invested || 0)}</td><td class="num">${S.fmtMoney(h.currentValue || 0)}</td><td class="num ${hy >= 0 ? 'pos' : 'neg'}">${hy === 0 ? '—' : S.fmtMoney(hy, { signed: true })}</td></tr>`;
    }).join('');
    return `<h2>${g.name} — ${pct}% de ${S.fmtMoney(g.target)}</h2>
      <table><thead><tr><th>Investimento</th><th>Tipo</th><th class="num">Aportado</th><th class="num">Valor atual</th><th class="num">Rendimento</th></tr></thead>
      <tbody>${hRows || '<tr><td colspan="5" style="text-align:center;color:#94A3B8;padding:16px">Sem investimentos detalhados (saldo: ' + S.fmtMoney(g.saved || 0) + ')</td></tr>'}</tbody></table>`;
  }).join('');
  const body = reportHeader(`Relatório de Investimentos<br/><strong style="color:#0F172A;font-size:14px">${new Date().toLocaleDateString('pt-BR')}</strong>`)
    + `<div class="r-title">Metas de Investimento</div><div class="r-sub">Posição consolidada das metas e seus investimentos.</div>`
    + `<div class="kpis">
        <div class="kpi pos"><div class="lbl">Total investido</div><div class="val">${S.fmtMoney(totalSaved)}</div></div>
        <div class="kpi ${totalYield >= 0 ? 'pos' : 'neg'}"><div class="lbl">Rendimento total</div><div class="val">${S.fmtMoney(totalYield, { signed: true })}</div></div>
        <div class="kpi"><div class="lbl">Meta total</div><div class="val">${S.fmtMoney(totalTarget)}</div></div>
        <div class="kpi"><div class="lbl">Progresso geral</div><div class="val">${overallPct}%</div></div>
      </div>`
    + `<h2>Alocação por tipo de investimento</h2>${allocBars}`
    + goalSections;
  return reportShell('Relatório de Investimentos · The Ledger', '', body);
}

window.LedgerReport = {
  downloadCockpit: (state, period) => openReport(buildCockpitReport(state, period)),
  downloadGoals: (state) => openReport(buildGoalsReport(state)),
};
