// ─────────────────────────────────────────────────────────────
// cockpit.jsx — Visão Geral do Patrimônio
//   • Modo Mensal (A): saldo inicial, entradas, saídas, alocação,
//     extrato do mês e lançamentos por categoria.
//   • Modo Anual (B): totais do ano, saldo atual, gastos acumulados
//     (barras mês a mês), alocação mês a mês por categoria e
//     a visão acumulada das categorias do ano.
// O dropdown de período escolhe entre meses e anos.
// ─────────────────────────────────────────────────────────────
const { LedgerIcon, LedgerButton, LedgerPageHeader, LedgerKpi, LedgerAlert, LedgerSegmented, LedgerChip, LedgerCategoryCard, LedgerSpendingChart, LedgerAllocationBlock, LedgerStackedCategoryChart, LedgerTreemap } = window;

function LedgerCockpitScreen({ state, settings, onNavigate, currentYM, setCurrentYM }) {
  const S = window.LedgerStore;
  const { isMobile, isNarrow } = window.useViewport();
  const stack = isNarrow;

  const ymKeys = React.useMemo(() => {
    const set = new Set();
    state.transactions.forEach(t => set.add(S.ymKey(t.date)));
    Object.keys(state.monthlyBalances).forEach(k => set.add(k));
    // Meses que só têm previsões (ainda sem lançamento real) também precisam
    // aparecer, senão não dá pra navegar até eles para ver o que está previsto.
    (state.forecasts || []).forEach(f => { if (f.status === 'pending' && f.dueDate) set.add(S.ymKey(f.dueDate)); });
    set.add(S.ymKey(new Date()));
    return Array.from(set).sort().reverse();
  }, [state]);
  const years = React.useMemo(() => S.yearsAvailable(state), [state]);

  const period = currentYM || ymKeys[0] || S.ymKey(new Date());
  const isYear = /^Y/.test(period);
  const activeYear = isYear ? period.slice(1) : null;

  const periodSelect = (
    <select
      value={period}
      onChange={e => setCurrentYM(e.target.value)}
      style={{
        fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600,
        padding: '8px 12px', borderRadius: 'var(--r-3)',
        border: '1px solid var(--border)', background: 'var(--bg-elevated)',
        color: 'var(--fg)', outline: 'none', cursor: 'pointer',
      }}
    >
      <optgroup label="Anual">
        {years.map(y => <option key={'Y' + y} value={'Y' + y}>Ano {y}</option>)}
      </optgroup>
      <optgroup label="Mensal">
        {ymKeys.map(k => <option key={k} value={k}>{S.ymLabel(k)}</option>)}
      </optgroup>
    </select>
  );

  const header = (
    <LedgerPageHeader
      eyebrow="O Painel"
      title={isYear ? `Visão do Ano · ${activeYear}` : 'Visão Geral do Patrimônio'}
      actions={
        <>
          {periodSelect}
          <LedgerButton variant="secondary" icon="download" onClick={() => window.LedgerReport.downloadCockpit(state, period)}>Relatório</LedgerButton>
          <LedgerButton variant="primary" icon="plus" onClick={() => onNavigate('add')}>Nova Transação</LedgerButton>
        </>
      }
    />
  );

  if (isYear) {
    return <AnnualCockpit state={state} settings={settings} onNavigate={onNavigate} year={activeYear} header={header} stack={stack} isMobile={isMobile} setCurrentYM={setCurrentYM} />;
  }
  return <MonthlyCockpit state={state} settings={settings} onNavigate={onNavigate} ymk={period} header={header} stack={stack} isMobile={isMobile} setCurrentYM={setCurrentYM} />;
}

// ════════════════════════════════════════════════════════════
// A) MONTHLY
// ════════════════════════════════════════════════════════════
function MonthlyCockpit({ state, settings, onNavigate, ymk, header, stack, isMobile, setCurrentYM }) {
  const S = window.LedgerStore;
  const startingBalance = S.getStartingBalance(state, ymk);
  const { inSum, outSum, aportesSum, delta } = S.monthTotals(state, ymk);
  const endingBalance = startingBalance + delta;

  const byCat = S.byCategory(state, ymk);
  const catColors = settings.categoryColors;
  const allocItems = S.CATEGORIES.map(c => ({
    label: c.name, pct: byCat[c.id] || 0, color: catColors[c.id] || 'var(--slate-400)',
  })).filter(x => x.pct > 0);

  const monthTx = React.useMemo(
    () => S.transactionsInMonth(state, ymk).slice().sort((a, b) => new Date(b.date) - new Date(a.date)),
    [state, ymk]
  );

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1280, margin: '0 auto' }} data-screen-label="Cockpit">
      {header}

      {delta < 0 && (
        <LedgerAlert tone="negative" title="Alerta de Saldo Mensal"
          body={`Seus gastos superaram a renda em ${S.fmtMoney(Math.abs(delta))} este mês. Revise a categoria com maior gasto.`}
          icon="trending-down" />
      )}
      {delta >= 0 && inSum > 0 && (
        <LedgerAlert tone="positive" title="No Caminho"
          body={`Você está ${S.fmtMoney(delta)} à frente dos gastos este mês. Considere aportar o excedente em uma meta.`}
          icon="trending-up"
          action={<LedgerButton variant="secondary" size="sm" onClick={() => onNavigate('goals')}>Ir para Metas</LedgerButton>} />
      )}

      {/* Linha 1 — saldos: inicial e final na mesma cor, resultado em destaque (azul) */}
      <div className="ledger-kpi-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label="Saldo Inicial" value={S.fmtMoney(startingBalance)}
          footer={<span style={{ cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }} onClick={() => onNavigate('balance')}>Editar saldo manual</span>} />
        <LedgerKpi label="Saldo Final" value={S.fmtMoney(endingBalance)} footer={`Δ ${S.fmtMoney(delta, { signed: true })} este mês`} />
        <LedgerKpi label="Resultado do Mês" value={S.fmtMoney(delta, { signed: true })} variant="inverse" footer={delta >= 0 ? 'Superávit' : 'Déficit'} />
      </div>

      {/* Linha 2 — fluxo do mês: entradas, aportes (azul) e saídas */}
      <div className="ledger-kpi-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label="Total de Entradas" value={S.fmtMoney(inSum)} variant="positive" footer={<LedgerChip tone="income">ENTRADA</LedgerChip>} />
        {aportesSum > 0 && (
          <LedgerKpi label="Aportes" value={S.fmtMoney(aportesSum)} variant="info" footer={<LedgerChip tone="growth">INVESTIDO</LedgerChip>} />
        )}
        <LedgerKpi label="Total de Saídas" value={S.fmtMoney(outSum)} variant="negative" footer={<LedgerChip tone="accent">{(outSum + aportesSum) > inSum ? 'ACIMA DO ORÇAMENTO' : 'DESPESAS'}</LedgerChip>} />
      </div>

      {/* Previsões do mês — visual discreto para diferenciar de valores realizados */}
      {(() => {
        const fcIn = S.forecastedInflow(state, ymk);
        const fcOut = S.forecastedOutflow(state, ymk);
        const fcAportes = S.forecastedTransfers(state, ymk);
        if (fcIn === 0 && fcOut === 0 && fcAportes === 0) return null;
        const projectedOut = outSum + fcOut + aportesSum + fcAportes;
        // Parte do saldo já realizado (que já desconta aportes reais do mês) e
        // aplica só o que falta prever: entradas, saídas e aportes pendentes.
        const projectedEnd = endingBalance + fcIn - fcOut - fcAportes;

        const item = (label, value, color) => (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', whiteSpace: 'nowrap' }}>{label}</span>
            <span className="num" style={{ fontSize: 16, fontWeight: 700, color: color || 'var(--fg-2)', whiteSpace: 'nowrap' }}>{value}</span>
          </div>
        );

        return (
          <div style={{
            border: '1px dashed var(--border)',
            borderRadius: 'var(--r-4)',
            background: 'transparent',
            padding: '16px 20px',
            display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            alignItems: isMobile ? 'stretch' : 'center',
            gap: isMobile ? 14 : 24,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexShrink: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <LedgerIcon name="calendar-clock" size={15} color="var(--fg-3)" />
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, letterSpacing: '0.8px', textTransform: 'uppercase', color: 'var(--fg-3)' }}>
                  Previsão do mês
                </span>
              </div>
              {isMobile && (
                <button onClick={() => onNavigate('forecasts')} style={{
                  all: 'unset', cursor: 'pointer',
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg-2)',
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                }}>
                  Ver previsões <LedgerIcon name="arrow-right" size={13} color="currentColor" />
                </button>
              )}
            </div>
            <div style={{
              display: isMobile ? 'grid' : 'flex',
              gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : undefined,
              gap: isMobile ? 16 : 28,
              flexWrap: 'wrap', flex: 1,
            }}>
              {item('A receber', S.fmtMoney(fcIn), fcIn > 0 ? 'var(--fg-positive)' : 'var(--fg-2)')}
              {item('A pagar', S.fmtMoney(fcOut), fcOut > 0 ? 'var(--brand-magenta)' : 'var(--fg-2)')}
              {fcAportes > 0 && item('Aportes previstos', S.fmtMoney(fcAportes), 'var(--info-500)')}
              {item('Saída total projetada', S.fmtMoney(projectedOut))}
              {item('Saldo final projetado', S.fmtMoney(projectedEnd))}
            </div>
            {!isMobile && (
              <button onClick={() => onNavigate('forecasts')} style={{
                all: 'unset', cursor: 'pointer', flexShrink: 0,
                fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg-2)',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}
              onMouseEnter={e => e.currentTarget.style.color = 'var(--fg)'}
              onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-2)'}>
                Ver previsões <LedgerIcon name="arrow-right" size={13} color="currentColor" />
              </button>
            )}
          </div>
        );
      })()}

      {/* Allocation + month extract */}
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'stretch' }}>
        <LedgerAllocationBlock
          items={allocItems.length ? allocItems : [{ label: 'Nenhum gasto ainda', pct: 1, color: 'var(--slate-200)' }]}
          total={S.fmtMoney(outSum).replace('R$ ', 'R$\u00a0')}
          totalLabel="TOTAL SAÍDA"
        />
        <MonthExtract tx={monthTx} ymk={ymk} onNavigate={onNavigate} />
      </div>

      {/* Category cards */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>POR CATEGORIA</div>
            <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, lineHeight: '32px', color: 'var(--fg-strong)' }}>Lançamentos por Categoria</h2>
          </div>
          <button onClick={() => onNavigate('transactions')} style={{
            all: 'unset', cursor: 'pointer', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--fg)',
            textDecoration: 'underline', textUnderlineOffset: 3,
          }}>Abrir Lançamentos →</button>
        </div>
        <div className="ledger-kpi-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
          {S.CATEGORIES.map(c => {
            const lastMonthKey = (() => { const d = new Date(ymk + '-01'); d.setMonth(d.getMonth() - 1); return S.ymKey(d); })();
            const lastTotal = S.byCategory(state, lastMonthKey)[c.id] || 0;
            const thisTotal = byCat[c.id] || 0;
            let delta2 = null;
            if (lastTotal > 0) {
              const pct = ((thisTotal - lastTotal) / lastTotal) * 100;
              delta2 = {
                label: pct === 0 ? 'Estável' : (pct > 0 ? `↑ ${S.fmtPct(pct)}` : `↓ ${S.fmtPct(pct)}`),
                tone: pct === 0 ? 'neutral' : (pct < 0 ? 'positive' : 'negative'),
              };
            }
            return <LedgerCategoryCard key={c.id} category={c} value={thisTotal} delta={delta2} onClick={() => onNavigate('transactions', { filterCategory: c.id, month: ymk })} />;
          })}
        </div>
      </div>

      {/* Treemap por categoria/subcategoria — visão mais detalhada dos gastos */}
      {(() => {
        const tree = S.bySubcategoryTree(state, ymk);
        if (tree.length === 0) return null;
        const flatItems = [];
        tree.forEach(c => {
          const color = catColors[c.id] || 'var(--slate-400)';
          c.subs.forEach(s => {
            flatItems.push({
              label: `${c.name} · ${s.name}`,
              value: s.value,
              color,
            });
          });
        });
        return (
          <LedgerTreemap
            items={flatItems}
            eyebrow="DETALHADO"
            title="Lançamentos por Categoria e Subcategoria"
            totalLabel="TOTAL DE SAÍDAS"
          />
        );
      })()}

      {/* Forecasts below category breakdown */}
      <UpcomingForecastsBlock state={state} ymk={ymk} endingBalance={endingBalance} onNavigate={onNavigate} stack={stack} />
    </div>
  );
}

// Compact extract of a month's income + expenses
function MonthExtract({ tx, ymk, onNavigate }) {
  const S = window.LedgerStore;
  return (
    <div style={{ flex: '1 1 460px', minWidth: 0, background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-4)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 24px 14px' }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>EXTRATO DO MÊS</div>
          <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '26px', color: 'var(--fg-strong)' }}>Entradas e Saídas</h3>
        </div>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)' }}>{tx.length} {tx.length === 1 ? 'lançamento' : 'lançamentos'}</span>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', maxHeight: 340 }}>
        {tx.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 13 }}>
            Nenhum lançamento neste mês.
          </div>
        )}
        {tx.map((r, idx) => {
          const cat = S.catLookup(r.categoryId);
          const sub = S.subLookup(r.categoryId, r.subcategoryId);
          const isIncome = r.amount > 0;
          return (
            <div key={r.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 24px',
              borderTop: idx === 0 ? '1px solid var(--border)' : '1px solid var(--border)',
            }}>
              <div style={{
                width: 34, height: 34, borderRadius: 'var(--r-2)', flexShrink: 0,
                background: isIncome ? 'var(--positive-50)' : 'var(--bg-muted)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <LedgerIcon name={isIncome ? 'arrow-down-left' : (cat ? cat.icon : 'circle-dollar-sign')} size={15} color={isIncome ? 'var(--positive-700)' : 'var(--fg)'} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {r.note || (isIncome ? r.source : sub && sub.name) || (cat && cat.name) || 'Sem título'}
                </div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 1 }}>
                  {S.fmtDate(r.date, { short: true })} · {isIncome ? (r.source || 'Entrada') : (cat ? cat.name : '—')}
                </div>
              </div>
              <div className="num" style={{ fontSize: 14, fontWeight: 700, whiteSpace: 'nowrap', color: isIncome ? 'var(--fg-positive)' : 'var(--fg-strong)' }}>
                {S.fmtMoney(r.amount, { signed: true })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════
// B) ANNUAL / GLOBAL
// ════════════════════════════════════════════════════════════
function AnnualCockpit({ state, settings, onNavigate, year, header, stack, isMobile, setCurrentYM }) {
  const S = window.LedgerStore;
  const { inSum, outSum, aportesSum, delta } = S.yearTotals(state, year);
  const endBal = S.yearEndingBalance(state, year);
  const series = React.useMemo(() => S.yearMonthsSeries(state, year), [state, year]);
  const perMonth = React.useMemo(() => S.byCategoryPerMonth(state, year), [state, year]);
  const byCatYear = S.byCategoryYear(state, year);
  const catColors = settings.categoryColors;
  const isCurrentYear = String(new Date().getFullYear()) === String(year);

  const allocItems = S.CATEGORIES.map(c => ({
    label: c.name, pct: byCatYear[c.id] || 0, color: catColors[c.id] || 'var(--slate-400)',
  })).filter(x => x.pct > 0);

  // active month for the bar chart highlight = busiest month
  const peakIdx = series.reduce((best, d, i, arr) => d.value > arr[best].value ? i : best, 0);

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1280, margin: '0 auto' }} data-screen-label="Cockpit Anual">
      {header}

      {/* Linha 1 — saldo do ano e resultado em destaque (azul) */}
      <div className="ledger-kpi-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label={isCurrentYear ? 'Saldo Atual' : 'Saldo no fim do ano'} value={S.fmtMoney(endBal)} footer="Saldo projetado" />
        <LedgerKpi label="Resultado do ano" value={S.fmtMoney(delta, { signed: true })} variant="inverse" footer={delta >= 0 ? 'Superávit' : 'Déficit'} />
      </div>

      {/* Linha 2 — fluxo do ano: entradas, aportes (azul) e saídas */}
      <div className="ledger-kpi-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label={`Entradas em ${year}`} value={S.fmtMoney(inSum)} variant="positive" footer="Acumulado do ano" />
        {aportesSum > 0 && (
          <LedgerKpi label={`Aportes em ${year}`} value={S.fmtMoney(aportesSum)} variant="info" footer="Investido no ano" />
        )}
        <LedgerKpi label={`Saídas em ${year}`} value={S.fmtMoney(outSum)} variant="negative" footer="Acumulado do ano" />
      </div>


      {/* Accumulated spending — bars month by month */}
      <LedgerSpendingChart
        data={series}
        activeIndex={peakIdx}
        style="bars"
        onSelect={(i) => setCurrentYM(series[i].ymk)}
      />

      {/* Allocation month by month within categories */}
      <LedgerStackedCategoryChart
        data={perMonth}
        categories={S.CATEGORIES}
        colors={catColors}
        activeYmk={null}
        onSelect={(ymk) => setCurrentYM(ymk)}
      />

      {/* Accumulated categories for the whole year */}
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'stretch' }}>
        <LedgerAllocationBlock
          items={allocItems.length ? allocItems : [{ label: 'Nenhum gasto no ano', pct: 1, color: 'var(--slate-200)' }]}
          total={S.fmtMoney(outSum).replace('R$ ', 'R$\u00a0')}
          totalLabel="SAÍDAS NO ANO"
        />
        <div style={{ flex: '1 1 460px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>ACUMULADO DO ANO</div>
            <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--fg-strong)' }}>Categorias em {year}</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 1fr', gap: 14 }}>
            {S.CATEGORIES.map(c => (
              <LedgerCategoryCard key={c.id} category={c} value={byCatYear[c.id] || 0} onClick={() => onNavigate('transactions', { filterCategory: c.id })} />
            ))}
          </div>
        </div>
      </div>

      {/* Treemap por categoria/subcategoria — acumulado do ano inteiro */}
      {(() => {
        const tree = S.bySubcategoryTreeYear(state, year);
        if (tree.length === 0) return null;
        const flatItems = [];
        tree.forEach(c => {
          const color = catColors[c.id] || 'var(--slate-400)';
          c.subs.forEach(s => {
            flatItems.push({
              label: `${c.name} · ${s.name}`,
              value: s.value,
              color,
            });
          });
        });
        return (
          <LedgerTreemap
            items={flatItems}
            eyebrow="DETALHADO"
            title={`Lançamentos por Categoria e Subcategoria em ${year}`}
            totalLabel="TOTAL DE SAÍDAS NO ANO"
          />
        );
      })()}
    </div>
  );
}

// ── UPCOMING FORECASTS (shared, monthly view) ────────────────
function UpcomingForecastsBlock({ state, ymk, endingBalance, onNavigate, stack }) {
  const S = window.LedgerStore;
  const upcoming = S.upcomingForecasts(state, 45).slice(0, 6);
  const monthOut = S.forecastedOutflow(state, ymk);
  const monthIn = S.forecastedInflow(state, ymk);
  const monthAportes = S.forecastedTransfers(state, ymk);
  const projectedEnd = endingBalance - monthOut + monthIn - monthAportes;
  if (upcoming.length === 0) return null;
  return (
    <div style={{ background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)', border: '1px solid var(--border)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 24px', borderBottom: '1px solid var(--border)', background: 'var(--bg-muted)', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>EM ABERTO</div>
          <div style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--fg-strong)' }}>Previsões — entradas e saídas</div>
        </div>
        <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ textAlign: 'right' }}>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>ENTRADA PREVISTA</div>
            <div className="num" style={{ fontSize: 16, lineHeight: '22px', color: 'var(--fg-positive)' }}>{S.fmtMoney(monthIn)}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>SAÍDA PREVISTA</div>
            <div className="num" style={{ fontSize: 16, lineHeight: '22px', color: 'var(--brand-magenta)' }}>{S.fmtMoney(monthOut)}</div>
          </div>
          {monthAportes > 0 && (
            <div style={{ textAlign: 'right' }}>
              <div className="meta" style={{ color: 'var(--fg-3)' }}>APORTE PREVISTO</div>
              <div className="num" style={{ fontSize: 16, lineHeight: '22px', color: 'var(--info-500)' }}>{S.fmtMoney(monthAportes)}</div>
            </div>
          )}
          <div style={{ textAlign: 'right' }}>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>SALDO PROJETADO</div>
            <div className="num" style={{ fontSize: 16, lineHeight: '22px', color: projectedEnd < 0 ? 'var(--brand-magenta)' : 'var(--fg-strong)' }}>{S.fmtMoney(projectedEnd)}</div>
          </div>
          <LedgerButton variant="secondary" size="sm" iconRight="arrow-right" onClick={() => onNavigate('forecasts')}>Ver todas</LedgerButton>
        </div>
      </div>
      {upcoming.map((f, idx) => {
        const kind = f.kind || 'expense';
        const isIncome = kind === 'income';
        const isTransfer = kind === 'transfer';
        const cat = !isIncome && !isTransfer && S.catLookup(f.categoryId);
        const sub = !isIncome && !isTransfer && cat && S.subLookup(f.categoryId, f.subcategoryId, state);
        const displayName = (f.name && f.name !== 'Lançamento' && f.name !== 'Despesa fixa')
          ? f.name
          : (sub ? sub.name : cat ? cat.name : (isIncome ? (f.source || 'Entrada') : 'Previsão'));
        const d = new Date(f.dueDate);
        const days = Math.ceil((d - new Date()) / (1000 * 60 * 60 * 24));
        const overdue = days < 0;
        const soon = days >= 0 && days <= 7;
        const itemColor = isIncome ? 'var(--fg-positive)' : isTransfer ? 'var(--info-500)' : 'var(--fg-strong)';
        const iconBg = isIncome ? 'var(--positive-50)' : isTransfer ? 'var(--info-100)' : overdue ? 'var(--brand-magenta-100)' : soon ? 'var(--warning-100)' : 'var(--bg-muted)';
        const iconColor = isIncome ? 'var(--positive-700)' : isTransfer ? 'var(--info-500)' : (overdue ? 'var(--brand-magenta-700)' : 'var(--fg-strong)');
        const iconName = isIncome ? 'arrow-down-left' : isTransfer ? 'trending-up' : (cat ? cat.icon : 'calendar');
        // Aportes não são "saída" — não entram com sinal negativo
        const displayAmount = isIncome || isTransfer ? Math.abs(f.amount) : -Math.abs(f.amount);
        if (stack) {
          return (
            <div key={f.id} style={{ padding: '12px 16px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)', display: 'flex', gap: 10, alignItems: 'center' }}>
              <div style={{ width: 36, height: 36, borderRadius: 'var(--r-3)', background: iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <LedgerIcon name={iconName} size={16} color={iconColor} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: overdue ? 'var(--brand-magenta)' : 'var(--fg-3)', marginTop: 2 }}>{S.fmtDate(f.dueDate, { short: true })} · {overdue ? 'Atrasado' : `${days}d`}</div>
              </div>
              <div className="num" style={{ fontSize: 14, fontWeight: 700, color: itemColor, whiteSpace: 'nowrap' }}>{S.fmtMoney(displayAmount, { signed: true })}</div>
            </div>
          );
        }
        return (
          <div key={f.id} style={{ display: 'grid', gridTemplateColumns: '90px minmax(0,1fr) 140px 130px', padding: '14px 24px', alignItems: 'center', gap: 12, borderTop: idx === 0 ? 'none' : '1px solid var(--border)' }}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <div className="mono" style={{ fontSize: 12, color: overdue ? 'var(--brand-magenta)' : 'var(--fg)', fontWeight: 700 }}>{S.fmtDate(f.dueDate, { short: true })}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '0.5px', color: 'var(--fg-3)', textTransform: 'uppercase' }}>{overdue ? 'Atrasado' : `Em ${days}d`}</div>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', minWidth: 0 }}>
              <div style={{ width: 32, height: 32, borderRadius: 'var(--r-2)', background: iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <LedgerIcon name={iconName} size={14} color={iconColor} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{displayName}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 1 }}>
                  {isIncome ? (f.source || 'Entrada') : isTransfer ? 'Aporte' : (cat ? cat.name : '—')}{f.fixed ? ' · Fixo' : ''}
                </div>
              </div>
            </div>
            <div>{isIncome ? <LedgerChip tone="income">ENTRADA</LedgerChip> : isTransfer ? <LedgerChip tone="growth">APORTE</LedgerChip> : cat && <LedgerChip tone={cat.chipTone}>{cat.name}</LedgerChip>}</div>
            <div className="num" style={{ textAlign: 'right', fontSize: 15, color: itemColor }}>{S.fmtMoney(displayAmount, { signed: true })}</div>
          </div>
        );
      })}
    </div>
  );
}

window.LedgerCockpitScreen = LedgerCockpitScreen;
