/* ============================================================================
   FSC tabs A — Visão Geral, Fluxo de Caixa, Categorias
   ============================================================================ */
const FSC = window.FSC, FCH = window.FSCCharts, UI = window.FSCUI, IcoA = window.FSCIcon;
const { fmt } = FSC;
const { Card, Kpi, Money, Pill, SectionTitle, Segmented } = UI;
const { LineChart, BarsChart, Donut, HBars, Heatmap, Legend, PALETTE } = FCH;

/* ---------------------- VISÃO GERAL ---------------------- */
function OverviewTab({ data, months, prevMonths, trendMonths, drillTo }) {
  const k = FSC.kpis(data, months, prevMonths);
  const ser = FSC.monthlySeries(data, trendMonths);
  const comp = FSC.byCategory(FSC.inMonths(data, months), 'despesa');
  const top = comp.slice(0, 7).map((c, i) => ({ label: c.category, value: c.value, color: PALETTE[i % PALETTE.length] }));
  const rest = comp.slice(7).reduce((s, c) => s + c.value, 0);
  if (rest > 0) top.push({ label: 'Outras', value: rest, color: 'var(--cat-6)' });
  const bigs = comp.slice(0, 6).map((c, i) => ({ label: c.category, value: c.value, color: PALETTE[i % PALETTE.length] }));

  return (
    <div className="stack">
      <div className="grid-kpi">
        <Kpi label="Receita" value={fmt.brl0(k.receita)} delta={k.d && k.d.receita} deltaMode="higher-good" accent="var(--green-600)" />
        <Kpi label="Despesa" value={fmt.brl0(k.despesa)} delta={k.d && k.d.despesa} deltaMode="lower-good" accent="var(--clay-600)" />
        <Kpi label="Saldo" value={fmt.brl0(k.saldo)} delta={k.d && k.d.saldo} deltaMode="higher-good" accent="var(--ink-900)" />
        <Kpi label="Taxa de poupança" value={fmt.pct(k.taxaPoupanca, 1)} delta={k.d && k.d.taxaPoupanca} deltaMode="higher-good" deltaUnit="pp" accent="var(--cat-5)" />
        <Kpi label="Despesa vs orçamento" value={fmt.pct(k.despVsOrc, 0)} sub={`teto ${fmt.brl0(k.budgetTotal)}`} accent="var(--ochre-600)" />
        <Kpi label="Câmbio médio EUR/BRL" value={fmt.rate(k.fxAvg)} sub={`${k.recorrentesCount} recorrentes`} accent="var(--cat-7)" />
      </div>

      <div className="grid-2">
        <Card title="Receita × Despesa" subtitle="Evolução mensal no período (ou últimos 12 meses)">
          <LineChart
            series={[
              { name: 'Receita', color: 'var(--green-600)', values: ser.map((s) => s.receita) },
              { name: 'Despesa', color: 'var(--clay-600)', values: ser.map((s) => s.despesa) },
            ]}
            labels={trendMonths.map(fmt.monthShort)} height={250} area yFormat={fmt.compact} />
        </Card>
        <Card title="Composição da despesa" subtitle="Por categoria no período">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
            <Donut data={top} size={188} thickness={24} centerTop="Despesa" centerBottom={fmt.brlCompact(k.despesa)} onSlice={(d) => d.label !== 'Outras' && drillTo({ category: d.label })} />
            <Legend items={top.map((t) => ({ label: t.label, color: t.color, value: fmt.brlCompact(t.value) }))} columns={2} />
          </div>
        </Card>
      </div>

      <Card title="Maiores despesas" subtitle="Clique para auditar as transações da categoria">
        <HBars data={bigs} valueFormat={fmt.brl0} onRow={(d) => drillTo({ category: d.label })} />
      </Card>
    </div>
  );
}

/* ---------------------- FLUXO DE CAIXA ---------------------- */
function CashFlowTab({ data, months, trendMonths }) {
  const win = months.length >= 2 ? months : trendMonths;
  const ser = FSC.monthlySeries(data, win);
  const labels = win.map(fmt.monthShort);
  const accSaldo = FSC.accumulate(ser, 'saldo');
  const taxa = ser.map((s) => (s.receita > 0 ? (s.saldo / s.receita) * 100 : 0));
  const desp = ser.map((s) => s.despesa);
  const mm3 = FSC.movingAvg(desp, 3);

  return (
    <div className="stack">
      <Card title="Receita × Despesa por mês" subtitle="Barras agrupadas">
        <BarsChart labels={labels} series={[
          { name: 'Receita', color: 'var(--green-600)', values: ser.map((s) => s.receita) },
          { name: 'Despesa', color: 'var(--clay-600)', values: desp },
        ]} height={260} yFormat={fmt.compact} />
      </Card>
      <div className="grid-2e">
        <Card title="Saldo acumulado" subtitle="Soma corrente do saldo mensal">
          <LineChart series={[{ name: 'Saldo acumulado', color: 'var(--ink-900)', values: accSaldo }]} labels={labels} height={230} area yFormat={fmt.compact} />
        </Card>
        <Card title="Taxa de poupança no tempo" subtitle="Saldo ÷ receita, mês a mês">
          <LineChart series={[{ name: 'Taxa de poupança', color: 'var(--cat-5)', values: taxa }]} labels={labels} height={230} yFormat={(v) => fmt.pct(v, 0)} />
        </Card>
      </div>
      <Card title="Despesa mensal & média móvel (3m)" subtitle="Tendência suavizada do gasto">
        <LineChart series={[
          { name: 'Despesa', color: 'var(--clay-600)', values: desp },
          { name: 'Média móvel 3m', color: 'var(--ink-700)', values: mm3 },
        ]} labels={labels} height={250} yFormat={fmt.compact} />
      </Card>
    </div>
  );
}

/* ---------------------- CATEGORIAS ---------------------- */
function CategoriesTab({ data, months, trendMonths, drillTo }) {
  const txs = FSC.inMonths(data, months);
  const comp = FSC.byCategory(txs, 'despesa');
  const nMonths = months.length || 1;
  const top = comp.slice(0, 8).map((c, i) => ({ label: c.category, value: c.value, color: PALETTE[i % PALETTE.length] }));
  const rest = comp.slice(8).reduce((s, c) => s + c.value, 0);
  const donut = top.slice();
  if (rest > 0) donut.push({ label: 'Outras', value: rest, color: 'var(--cat-6)' });

  // gasto vs orçamento
  const budgetRows = comp.map((c) => {
    const ceiling = (data.budget[c.category] || 0) * nMonths;
    return { category: c.category, spent: c.value, ceiling, pct: ceiling > 0 ? (c.value / ceiling) * 100 : null };
  }).filter((r) => r.ceiling > 0).sort((a, b) => b.pct - a.pct).slice(0, 9);

  // heatmap
  const hm = FSC.heatmap(data, trendMonths, 10);

  return (
    <div className="stack">
      <div className="grid-2">
        <Card title="Gasto vs orçamento" subtitle={`Tetos do período (${nMonths} ${nMonths > 1 ? 'meses' : 'mês'})`}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
            {budgetRows.map((r, i) => {
              const over = r.pct > 100;
              return (
                <div key={i} onClick={() => drillTo({ category: r.category })} style={{ cursor: 'pointer' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 4 }}>
                    <span style={{ color: 'var(--text-secondary)', fontWeight: 500 }}>{r.category}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: over ? 'var(--negative)' : 'var(--text-primary)' }}>
                      {fmt.brl0(r.spent)} <span style={{ color: 'var(--text-faint)', fontWeight: 500 }}>/ {fmt.brl0(r.ceiling)}</span>
                    </span>
                  </div>
                  <div style={{ position: 'relative', height: 8, background: 'var(--sand-50)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ width: `${Math.min(100, r.pct)}%`, height: '100%', background: over ? 'var(--clay-600)' : (r.pct > 85 ? 'var(--ochre-600)' : 'var(--green-600)'), borderRadius: 999 }} />
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
        <Card title="Composição" subtitle="Distribuição da despesa">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
            <Donut data={donut} size={188} thickness={24} centerTop="Categorias" centerBottom={String(comp.length)} onSlice={(d) => d.label !== 'Outras' && drillTo({ category: d.label })} />
            <Legend items={donut.map((t) => ({ label: t.label, color: t.color, value: fmt.brlCompact(t.value) }))} columns={2} />
          </div>
        </Card>
      </div>
      <Card title="Mapa de calor · mês × categoria" subtitle="Intensidade da despesa nos últimos meses — passe o mouse para ver valores">
        <Heatmap rows={hm.cats} cols={hm.months} matrix={hm.matrix} valueFormat={fmt.brl0} colFormat={fmt.monthShort} />
      </Card>
    </div>
  );
}

window.FSCTabsA = { OverviewTab, CashFlowTab, CategoriesTab };
