// ─────────────────────────────────────────────────────────────
// store.jsx — Data layer com localStorage (cache) + Firestore (nuvem)
// Cada usuário tem seus próprios dados isolados no Firestore.
// ─────────────────────────────────────────────────────────────

const LS_KEY = 'ledger.state.v1';

// ── FIRESTORE SYNC ───────────────────────────────────────────
// Salva os dados do usuário no Firestore (em background, sem bloquear a UI)
async function saveToFirestore(userId, state) {
  if (!userId || !window.firebaseDB) {
    console.warn('[Ledger] saveToFirestore abortado — userId:', userId, 'firebaseDB:', !!window.firebaseDB);
    return;
  }
  try {
    const toSave = {
      transactions:    state.transactions    || [],
      monthlyBalances: state.monthlyBalances || {},
      forecasts:       state.forecasts       || [],
      goals:           state.goals           || [],
      settings:        state.settings        || {},
      customSubs:      state.customSubs      || {},
      updatedAt:       new Date().toISOString(),
    };
    // Remove todos os campos undefined recursivamente (Firestore não aceita undefined)
    const clean = (obj) => JSON.parse(JSON.stringify(obj, (k, v) => v === undefined ? null : v));
    const cleanData = clean(toSave);
    console.log('[Ledger] Salvando no Firestore para uid:', userId, '— transações:', cleanData.transactions.length);
    await window.firebaseDB
      .collection('usuarios')
      .doc(userId)
      .set(cleanData, { merge: true });
    console.log('[Ledger] ✅ Salvo no Firestore com sucesso!');
  } catch (err) {
    console.error('[Ledger] ❌ Firestore save FALHOU:', err.code, err.message);
  }
}

// Carrega os dados do usuário do Firestore
async function loadFromFirestore(userId) {
  if (!userId || !window.firebaseDB) return null;
  try {
    const doc = await window.firebaseDB
      .collection('usuarios')
      .doc(userId)
      .get();
    if (doc.exists) return doc.data();
    return null;
  } catch (err) {
    console.warn('[Ledger] Firestore load failed:', err.message);
    return null;
  }
}

// Constrói um estado a partir dos dados da nuvem, preservando user e session atuais.
// Usado tanto no login quanto ao recarregar a página (re-sincronização).
function mergeCloudData(cloudData, userObj, sessionObj) {
  const base = defaultState();
  base.user = userObj;
  base.session = sessionObj || { startedAt: new Date().toISOString() };
  if (cloudData) {
    base.transactions    = cloudData.transactions    || [];
    base.monthlyBalances = cloudData.monthlyBalances || {};
    base.forecasts       = cloudData.forecasts       || [];
    base.goals           = cloudData.goals           || [];
    base.customSubs      = cloudData.customSubs      || {};
    base.settings        = { ...base.settings, ...(cloudData.settings || {}) };
  }
  return base;
}

// ── CATEGORY TAXONOMY ────────────────────────────────────────
const CATEGORIES = [
  {
    id: 'basic',
    name: 'Necessidades Básicas',
    icon: 'home',
    chip: 'BÁSICO',
    chipTone: 'core',
    subs: [
      { id: 'food-restaurants',   name: 'Restaurantes',      group: 'Food', fixed: false },
      { id: 'food-natural',       name: 'Hortifruti',   group: 'Food', fixed: false },
      { id: 'food-supermarket',   name: 'Supermercado',      group: 'Food', fixed: false },
      { id: 'bills-phone',        name: 'Celular',            group: 'Bills', fixed: true  },
      { id: 'bills-health',       name: 'Plano de Saúde', group: 'Bills', fixed: true  },
      { id: 'bills-credit',       name: 'Cartão de Crédito',      group: 'Bills', fixed: false },
      { id: 'bills-condominio',   name: 'Condomínio',       group: 'Bills', fixed: true  },
      { id: 'bills-cleaning',     name: 'Diarista',    group: 'Bills', fixed: true  },
      { id: 'bills-shopping',     name: 'Compras',         group: 'Bills', fixed: false },
      { id: 'bills-car-gas',      name: 'Carro · Gasolina',        group: 'Car',   fixed: false },
      { id: 'bills-car-fix',      name: 'Carro · Reparos',    group: 'Car',   fixed: false },
      { id: 'bills-car-insurance',name: 'Carro · Seguro',  group: 'Car',   fixed: true  },
      { id: 'bills-life-ins',     name: 'Seguro de Vida',   group: 'Bills', fixed: true  },
      { id: 'bills-other',        name: 'Outras Contas',      group: 'Bills', fixed: false },
    ],
  },
  {
    id: 'education',
    name: 'Educação',
    icon: 'book-open',
    chip: 'CRESCIMENTO',
    chipTone: 'growth',
    subs: [
      { id: 'edu-college', name: 'Faculdade',  fixed: true  },
      { id: 'edu-books',   name: 'Livros',    fixed: false },
      { id: 'edu-courses', name: 'Cursos',  fixed: false },
      { id: 'edu-events',  name: 'Eventos',   fixed: false },
      { id: 'edu-other',   name: 'Outros',   fixed: false },
    ],
  },
  {
    id: 'wishes',
    name: 'Meus Desejos',
    icon: 'sparkles',
    chip: 'DESEJO',
    chipTone: 'warning',
    subs: [
      { id: 'wish-shows',  name: 'Shows',   fixed: false },
      { id: 'wish-trips',  name: 'Viagens',   fixed: false },
      { id: 'wish-things', name: 'Coisas',  fixed: false },
      { id: 'wish-spa',    name: 'Spa',     fixed: false },
      { id: 'wish-other',  name: 'Outros',  fixed: false },
    ],
  },
  {
    id: 'investments',
    name: 'Investimentos',
    icon: 'trending-up',
    chip: 'INVESTIR',
    chipTone: 'alpha',
    subs: [
      { id: 'inv-goals',      name: 'Metas',          fixed: false },
      { id: 'inv-retirement', name: 'Aposentadoria', fixed: true  },
      { id: 'inv-other',      name: 'Outros',         fixed: false },
    ],
  },
];

const INCOME_SOURCES = [
  'Salário', 'Freelance', 'Dividendos', 'Aluguel', 'Bônus', 'Presente', 'Vencimento de Investimento', 'Outros',
];

const PAYMENT_METHODS = [
  { id: 'credit',  name: 'Cartão de Crédito' },
  { id: 'debit',   name: 'Débito' },
  { id: 'cash',    name: 'Dinheiro' },
  { id: 'pix',     name: 'PIX / Transferência' },
];

// Investment instrument types that can live inside a goal.
const INVESTMENT_TYPES = [
  'Fundo', 'Tesouro Direto', 'CDB', 'LCI', 'LCA',
  'Ações', 'FII', 'ETF', 'Cripto', 'Poupança', 'Previdência', 'Outro',
];
const INVESTMENT_TYPE_ICON = {
  'Fundo': 'layers', 'Tesouro Direto': 'landmark', 'CDB': 'banknote',
  'LCI': 'home', 'LCA': 'wheat', 'Ações': 'trending-up', 'FII': 'building-2',
  'ETF': 'chart-candlestick', 'Cripto': 'bitcoin', 'Poupança': 'piggy-bank',
  'Previdência': 'umbrella', 'Outro': 'circle-dollar-sign',
};

// ── FORMATTERS ───────────────────────────────────────────────
function fmtMoney(n, opts = {}) {
  const sign = n < 0 ? '−' : (opts.signed && n > 0 ? '+' : '');
  const abs = Math.abs(n).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return `${sign}R$ ${abs}`;
}
function fmtMoneyShort(n) {
  const abs = Math.abs(n);
  if (abs >= 1e6)  return (n / 1e6).toFixed(1).replace('.', ',') + 'M';
  if (abs >= 1e3)  return (n / 1e3).toFixed(1).replace('.', ',') + 'k';
  return Math.round(n).toString();
}
function fmtPct(n) {
  const sign = n > 0 ? '+' : (n < 0 ? '−' : '');
  return `${sign}${Math.abs(Math.round(n))}%`;
}
function fmtDate(iso, opts = {}) {
  const d = new Date(iso);
  const months = ['JAN','FEV','MAR','ABR','MAI','JUN','JUL','AGO','SET','OUT','NOV','DEZ'];
  if (opts.short) return `${months[d.getMonth()]} ${String(d.getDate()).padStart(2, '0')}`;
  return d.toLocaleDateString('pt-BR', { year: 'numeric', month: 'long', day: 'numeric' });
}
function ymKey(d) {
  d = d instanceof Date ? d : new Date(d);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
function ymLabel(key) {
  const [y, m] = key.split('-').map(Number);
  const names = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
  return `${names[m - 1]} ${y}`;
}

// ── PASSWORD HASHING (Web Crypto) ────────────────────────────
async function hashPassword(password, salt) {
  const enc = new TextEncoder();
  const data = enc.encode(password + ':' + salt);
  const buf = await crypto.subtle.digest('SHA-256', data);
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
}
function randomSalt() {
  const a = new Uint8Array(16);
  crypto.getRandomValues(a);
  return Array.from(a).map(b => b.toString(16).padStart(2, '0')).join('');
}

// ── STATE ────────────────────────────────────────────────────
function defaultState() {
  return {
    user: null,                          // { email, passwordHash, salt, createdAt }
    session: null,                       // { startedAt }
    monthlyBalances: {},                 // { "2026-06": 42850.00 }
    transactions: [],                    // see schema below
    forecasts: [],                       // { id, name, amount, dueDate, categoryId, subcategoryId, recurrence, fixed, note, status, realizedTxId }
    goals: [],                           // { id, name, target, saved, by, icon, history: [] }
    customSubs: {},                      // { categoryId: [{ id, name }] } — subcategorias criadas pelo usuário
    settings: {
      theme: 'light',                    // 'light' | 'dark'
      chartStyle: 'bars',                // 'bars' | 'lines' | 'area'
      currency: 'BRL',
      categoryColors: {
        basic:       'var(--slate-700)',
        education:   'var(--info-500)',
        wishes:      'var(--brand-magenta)',
        investments: 'var(--positive-500)',
      },
    },
  };
}

// Retorna as categorias com as subcategorias customizadas do usuário mescladas
function getCategoriesWithCustom(state) {
  const custom = state.customSubs || {};
  return CATEGORIES.map(c => {
    const extra = (custom[c.id] || []).map(s => ({ ...s, custom: true }));
    return { ...c, subs: [...c.subs, ...extra] };
  });
}

function loadState() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return defaultState();
    const parsed = JSON.parse(raw);
    return { ...defaultState(), ...parsed, settings: { ...defaultState().settings, ...(parsed.settings || {}), categoryColors: { ...defaultState().settings.categoryColors, ...((parsed.settings || {}).categoryColors || {}) } } };
  } catch (e) {
    return defaultState();
  }
}
let _firestoreSaveTimer = null;
function saveState(s) {
  localStorage.setItem(LS_KEY, JSON.stringify(s));
  // Sincroniza com Firestore, mas com debounce de 1,2s para não disparar
  // a cada tecla digitada (economiza chamadas e melhora a performance)
  const userId = s.user && s.user.uid;
  if (userId) {
    if (_firestoreSaveTimer) clearTimeout(_firestoreSaveTimer);
    _firestoreSaveTimer = setTimeout(() => { saveToFirestore(userId, s); }, 1200);
  }
}
function clearAllData() {
  localStorage.removeItem(LS_KEY);
}

// ── SAMPLE SEEDER ────────────────────────────────────────────
// Builds 3 months of plausible transactions ending TODAY.
function seedSampleData(state) {
  const today = new Date();
  const tx = [];
  const months = [-2, -1, 0]; // 2 months ago, last month, current month

  let id = 1;
  const push = (daysBack, amount, type, catId, subId, source, payment, note, fixed) => {
    const d = new Date(today); d.setDate(d.getDate() - daysBack);
    tx.push({
      id: id++,
      date: d.toISOString(),
      amount,
      type,
      categoryId: catId,
      subcategoryId: subId,
      source: source || null,
      paymentMethod: payment || null,
      note: note || '',
      fixed: !!fixed,
    });
  };

  // Recurring monthly bills (fixed) — last 3 months
  months.forEach(mOff => {
    const base = mOff === 0 ? 5 : (Math.abs(mOff) * 30 + 5);
    push(base + 0,  -1800, 'expense', 'basic', 'bills-condominio',  null, 'pix',    'Condomínio mensal', true);
    push(base + 2,  -380,  'expense', 'basic', 'bills-phone',       null, 'debit',  'Plano celular', true);
    push(base + 3,  -640,  'expense', 'basic', 'bills-health',      null, 'debit',  'Plano de saúde', true);
    push(base + 4,  -420,  'expense', 'basic', 'bills-cleaning',    null, 'pix',    'Diarista', true);
    push(base + 6,  -180,  'expense', 'basic', 'bills-life-ins',    null, 'debit',  'Seguro de vida', true);
    push(base + 8,  -210,  'expense', 'basic', 'bills-car-insurance', null, 'debit', 'Seguro carro', true);
    // Variable food
    push(base + 1,  -68,   'expense', 'basic', 'food-restaurants', null, 'credit', 'Almoço', false);
    push(base + 5,  -240,  'expense', 'basic', 'food-supermarket', null, 'debit',  'Mercado', false);
    push(base + 9,  -82,   'expense', 'basic', 'food-natural',     null, 'debit',  'Hortifruti', false);
    push(base + 12, -148,  'expense', 'basic', 'food-restaurants', null, 'credit', 'Jantar fora', false);
    push(base + 14, -320,  'expense', 'basic', 'food-supermarket', null, 'debit',  'Compras semana', false);
    // Education
    push(base + 7,  -210,  'expense', 'education', 'edu-courses', null, 'credit', 'Curso online', false);
    push(base + 18, -65,   'expense', 'education', 'edu-books',   null, 'credit', 'Livros', false);
    // Wishes
    push(base + 10, -180,  'expense', 'wishes', 'wish-shows',   null, 'credit', 'Show', false);
    push(base + 16, -260,  'expense', 'wishes', 'wish-spa',     null, 'credit', 'Spa', false);
    push(base + 20, -380,  'expense', 'wishes', 'wish-things',  null, 'credit', 'Compras', false);
    // Investments
    push(base + 11, -800,  'expense', 'investments', 'inv-retirement', null, 'pix', 'Previdência', true);
    // Car gas
    push(base + 13, -190,  'expense', 'basic', 'bills-car-gas',   null, 'credit', 'Gasolina', false);
    // Income
    push(base + 25, 7240,  'income', null, null, 'Salário',   null, 'Salário', false);
    push(base + 23, 420,   'income', null, null, 'Dividendos', null, 'Dividendos', false);
  });

  // Extra current-month splurges so the alert fires
  push(2,  -624, 'expense', 'wishes', 'wish-trips',  null, 'credit', 'Viagem Lisboa', false);
  push(4,  -89,  'expense', 'basic',  'food-restaurants', null, 'credit', 'Brunch', false);
  push(1,  -52,  'expense', 'basic',  'bills-car-gas', null, 'credit', 'Posto', false);

  // Starting balances
  state.monthlyBalances = {};
  const cur = new Date(); cur.setDate(1);
  for (let i = 0; i < 3; i++) {
    const d = new Date(cur); d.setMonth(cur.getMonth() - i);
    state.monthlyBalances[ymKey(d)] = 42850 - i * 1200;
  }

  // Goals
  // Goals — some with a breakdown into specific investments (holdings)
  state.goals = [
    {
      id: 1, name: 'Cofre de Emergência', target: 18000, saved: 12400, by: 'Dez 2026', icon: 'vault',
      holdings: [
        { id: 'h-cofre-1', name: 'CDB Liquidez Diária', type: 'CDB',            invested: 7000, currentValue: 7200 },
        { id: 'h-cofre-2', name: 'Tesouro Selic 2027',   type: 'Tesouro Direto', invested: 5000, currentValue: 5200 },
      ],
    },
    {
      id: 2, name: 'Entrada — Apartamento', target: 90000, saved: 42100, by: 'Set 2027', icon: 'landmark',
      holdings: [
        { id: 'h-apto-1', name: 'LCI Banco Inter', type: 'LCI',            invested: 20000, currentValue: 20600 },
        { id: 'h-apto-2', name: 'Tesouro IPCA+ 2029', type: 'Tesouro Direto', invested: 20000, currentValue: 21500 },
      ],
    },
    {
      id: 3, name: 'Carteira de ETFs', target: 50000, saved: 28640, by: 'Aberto', icon: 'briefcase',
      holdings: [
        { id: 'h-etf-1', name: 'BOVA11',  type: 'ETF', invested: 14000, currentValue: 15200 },
        { id: 'h-etf-2', name: 'IVVB11',  type: 'ETF', invested: 12000, currentValue: 13440 },
      ],
    },
    {
      id: 4, name: 'Sabático em Lisboa', target: 9000, saved: 3200, by: 'Mai 2027', icon: 'plane',
      holdings: [],
    },
  ];

  // Forecasts — known upcoming expenses (planned, not yet realized)
  const nextDate = (day) => {
    const d = new Date(today);
    d.setDate(day);
    if (d <= today) d.setMonth(d.getMonth() + 1);
    return d.toISOString();
  };
  state.forecasts = [
    // Despesas previstas
    { id: 'f1', kind: 'expense', name: 'Mensalidade da Faculdade', amount: 2400, dueDate: nextDate(10), categoryId: 'education', subcategoryId: 'edu-college',      source: null,         recurrence: 'monthly', fixed: true,  note: 'Boleto mensal', status: 'pending', realizedTxId: null },
    { id: 'f2', kind: 'expense', name: 'Condomínio',               amount: 1800, dueDate: nextDate(5),  categoryId: 'basic',     subcategoryId: 'bills-condominio',  source: null,         recurrence: 'monthly', fixed: true,  note: '',              status: 'pending', realizedTxId: null },
    { id: 'f3', kind: 'expense', name: 'Plano de Saúde',           amount: 640,  dueDate: nextDate(8),  categoryId: 'basic',     subcategoryId: 'bills-health',      source: null,         recurrence: 'monthly', fixed: true,  note: '',              status: 'pending', realizedTxId: null },
    { id: 'f4', kind: 'expense', name: 'IPVA do Carro',            amount: 1240, dueDate: (() => { const d = new Date(today); d.setMonth(d.getMonth() + 2); d.setDate(15); return d.toISOString(); })(), categoryId: 'basic', subcategoryId: 'bills-car-insurance', source: null, recurrence: 'yearly', fixed: false, note: 'Parcela única', status: 'pending', realizedTxId: null },
    { id: 'f5', kind: 'expense', name: 'Diarista',                 amount: 420,  dueDate: nextDate(15), categoryId: 'basic',     subcategoryId: 'bills-cleaning',    source: null,         recurrence: 'monthly', fixed: true,  note: '',              status: 'pending', realizedTxId: null },
    { id: 'f6', kind: 'expense', name: 'Curso de Inglês',          amount: 380,  dueDate: nextDate(20), categoryId: 'education', subcategoryId: 'edu-courses',       source: null,         recurrence: 'monthly', fixed: false, note: 'Estimativa',    status: 'pending', realizedTxId: null },
    // Entradas previstas
    { id: 'f7', kind: 'income',  name: 'Salário',                  amount: 7240, dueDate: nextDate(28), categoryId: null,        subcategoryId: null,                source: 'Salário',   recurrence: 'monthly', fixed: true,  note: 'Pagamento mensal', status: 'pending', realizedTxId: null },
    { id: 'f8', kind: 'income',  name: 'Dividendos',               amount: 420,  dueDate: nextDate(25), categoryId: null,        subcategoryId: null,                source: 'Dividendos', recurrence: 'monthly', fixed: false, note: 'Estimativa',    status: 'pending', realizedTxId: null },
    { id: 'f9', kind: 'income',  name: 'Freelance — Projeto X',    amount: 1800, dueDate: nextDate(18), categoryId: null,        subcategoryId: null,                source: 'Freelance',  recurrence: 'once',    fixed: false, note: '50% do projeto', status: 'pending', realizedTxId: null },
  ];

  // Goal aportes across the year — tagged with goalId so the growth charts have history.
  // Generates monthly contributions for the current year up to the present month.
  const aporteId = () => 'ga-' + (id++);
  const pushAporte = (monthsBack, goalId, amount, label) => {
    const d = new Date(today); d.setMonth(d.getMonth() - monthsBack); d.setDate(12);
    if (d > today) return;
    tx.push({
      id: aporteId(), date: d.toISOString(), amount: -Math.abs(amount),
      type: 'expense', categoryId: 'investments', subcategoryId: 'inv-goals',
      source: null, paymentMethod: 'pix', note: 'Aporte: ' + label, fixed: false,
      goalId, transfer: true,
    });
  };
  // Spread contributions over the last 6 months for a believable growth curve.
  for (let m = 5; m >= 0; m--) {
    pushAporte(m, 1, 600 + (5 - m) * 40, 'Cofre de Emergência');
    pushAporte(m, 2, 1400 + (5 - m) * 120, 'Entrada — Apartamento');
    pushAporte(m, 3, 900 + (5 - m) * 60, 'Carteira de ETFs');
    if (m % 2 === 0) pushAporte(m, 4, 500, 'Sabático em Lisboa');
  }

  state.transactions = tx.sort((a, b) => new Date(b.date) - new Date(a.date));
  return state;
}

// ── DERIVED SELECTORS ────────────────────────────────────────
function transactionsInMonth(state, ymk) {
  return state.transactions.filter(t => ymKey(t.date) === ymk);
}
function monthTotals(state, ymk) {
  const tx = transactionsInMonth(state, ymk);
  let inSum = 0, outSum = 0, aportesSum = 0;
  tx.forEach(t => {
    if (t.amount > 0) { inSum += t.amount; return; }
    // Aportes (transfer) são dinheiro que saiu da conta corrente, então ainda
    // contam para o saldo final — mas são contabilizados à parte de "saídas",
    // pois não são despesa/consumo.
    if (t.transfer) aportesSum += -t.amount;
    else outSum += -t.amount;
  });
  // delta e saldo final continuam descontando tudo que saiu da conta (despesas + aportes)
  return { inSum, outSum, aportesSum, delta: inSum - outSum - aportesSum };
}
// Retorna o saldo inicial de um mês.
// Se o usuário definiu manualmente → usa esse valor.
// Caso contrário → propaga o saldo final do mês mais recente que tiver dado.
function getStartingBalance(state, ymk, depth = 0) {
  // Evita recursão infinita
  if (depth > 60) return 0;
  // Se o usuário definiu um saldo manual para esse mês, usa ele
  if (state.monthlyBalances[ymk] != null) return state.monthlyBalances[ymk];
  // Pega o mês anterior sempre — mesmo sem transações o saldo deve propagar
  const [y, m] = ymk.split('-').map(Number);
  const prevDate = new Date(y, m - 2, 1);
  const prevYmk = ymKey(prevDate);
  // Busca o mês mais antigo que tem saldo manual definido
  const hasAnyBalance = Object.keys(state.monthlyBalances || {}).length > 0;
  if (!hasAnyBalance) return 0;
  // Verifica se o mês anterior é anterior ao mês mais antigo com saldo
  const allBalanceMonths = Object.keys(state.monthlyBalances).sort();
  const oldestBalanceMonth = allBalanceMonths[0];
  if (prevYmk < oldestBalanceMonth) return 0;
  const prevStarting = getStartingBalance(state, prevYmk, depth + 1);
  const { delta } = monthTotals(state, prevYmk);
  return prevStarting + delta;
}

function byCategory(state, ymk) {
  const tx = transactionsInMonth(state, ymk).filter(t => t.amount < 0);
  const map = {};
  CATEGORIES.forEach(c => { map[c.id] = 0; });
  tx.forEach(t => { if (t.categoryId && map[t.categoryId] != null) map[t.categoryId] += -t.amount; });
  return map;
}
// Retorna a árvore categoria → subcategorias com seus totais do mês,
// para o treemap "Lançamentos por Categoria/Subcategoria" do dashboard.
// Inclui subcategorias customizadas do usuário.
// Monta a árvore categoria → subcategorias a partir de uma lista de transações
// já filtrada (despesas, com categoria). Compartilhada pelas versões mensal e anual.
// Aportes (transfer) não são gasto de consumo — não entram no treemap.
function buildSubcategoryTree(state, tx) {
  const cats = getCategoriesWithCustom(state);
  const realExpenses = tx.filter(t => !t.transfer);
  const tree = cats.map(c => {
    const subTotals = {};
    (c.subs || []).forEach(s => { subTotals[s.id] = 0; });
    let catTotal = 0;
    realExpenses.forEach(t => {
      if (t.categoryId !== c.id) return;
      const subId = t.subcategoryId || '__other__';
      subTotals[subId] = (subTotals[subId] || 0) + (-t.amount);
      catTotal += (-t.amount);
    });
    const subs = Object.keys(subTotals)
      .map(subId => {
        const subDef = (c.subs || []).find(s => s.id === subId);
        return { id: subId, name: subDef ? subDef.name : 'Outros', value: subTotals[subId] };
      })
      .filter(s => s.value > 0)
      .sort((a, b) => b.value - a.value);
    return { id: c.id, name: c.name, icon: c.icon, chipTone: c.chipTone, total: catTotal, subs };
  }).filter(c => c.total > 0).sort((a, b) => b.total - a.total);
  return tree;
}
// Árvore categoria/subcategoria de UM mês — usada no Painel mensal.
function bySubcategoryTree(state, ymk) {
  const tx = transactionsInMonth(state, ymk).filter(t => t.amount < 0 && t.categoryId);
  return buildSubcategoryTree(state, tx);
}
// Árvore categoria/subcategoria do ANO inteiro — usada no Painel anual.
function bySubcategoryTreeYear(state, year) {
  const tx = monthsInYear(year)
    .flatMap(ymk => transactionsInMonth(state, ymk))
    .filter(t => t.amount < 0 && t.categoryId);
  return buildSubcategoryTree(state, tx);
}
function monthsSeries(state, count = 7) {
  // Last `count` months ending with current month.
  const out = [];
  const cur = new Date(); cur.setDate(1);
  for (let i = count - 1; i >= 0; i--) {
    const d = new Date(cur); d.setMonth(cur.getMonth() - i);
    const k = ymKey(d);
    const { outSum } = monthTotals(state, k);
    out.push({ ymk: k, label: MONTHS_ABBR[d.getMonth()], value: outSum });
  }
  return out;
}

// ── ANNUAL / GLOBAL SELECTORS ────────────────────────────────
const MONTHS_ABBR = ['JAN','FEV','MAR','ABR','MAI','JUN','JUL','AGO','SET','OUT','NOV','DEZ'];
function yearOf(ymk) { return String(ymk).split('-')[0]; }
function monthsInYear(year) {
  return Array.from({ length: 12 }, (_, i) => `${year}-${String(i + 1).padStart(2, '0')}`);
}
function yearTotals(state, year) {
  let inSum = 0, outSum = 0, aportesSum = 0;
  monthsInYear(year).forEach(k => { const t = monthTotals(state, k); inSum += t.inSum; outSum += t.outSum; aportesSum += t.aportesSum; });
  return { inSum, outSum, aportesSum, delta: inSum - outSum - aportesSum };
}
function yearMonthsSeries(state, year) {
  return monthsInYear(year).map((k, i) => {
    const { outSum, inSum } = monthTotals(state, k);
    return { ymk: k, label: MONTHS_ABBR[i], value: outSum, outSum, inSum };
  });
}
function byCategoryYear(state, year) {
  const map = {}; CATEGORIES.forEach(c => { map[c.id] = 0; });
  monthsInYear(year).forEach(k => { const m = byCategory(state, k); CATEGORIES.forEach(c => { map[c.id] += m[c.id] || 0; }); });
  return map;
}
function byCategoryPerMonth(state, year) {
  return monthsInYear(year).map((k, i) => {
    const m = byCategory(state, k);
    let total = 0; CATEGORIES.forEach(c => { total += m[c.id] || 0; });
    return { ymk: k, label: MONTHS_ABBR[i], cats: m, total };
  });
}
function yearsAvailable(state) {
  const set = new Set();
  state.transactions.forEach(t => set.add(yearOf(ymKey(t.date))));
  Object.keys(state.monthlyBalances || {}).forEach(k => set.add(yearOf(k)));
  set.add(String(new Date().getFullYear()));
  return Array.from(set).sort().reverse();
}
function yearEndingBalance(state, year) {
  const months = monthsInYear(year);
  let last = null;
  months.forEach(k => { if (transactionsInMonth(state, k).length || state.monthlyBalances[k] != null) last = k; });
  if (!last) last = months[0];
  // Walk forward accumulating from the first month that has a manual starting balance.
  let firstWithBalance = months.find(k => state.monthlyBalances[k] != null);
  if (firstWithBalance == null) return (state.monthlyBalances[last] || 0) + monthTotals(state, last).delta;
  let bal = state.monthlyBalances[firstWithBalance] || 0;
  const startIdx = months.indexOf(firstWithBalance);
  const endIdx = months.indexOf(last);
  for (let i = startIdx; i <= endIdx; i++) {
    // a later manual balance overrides the running total
    if (i > startIdx && state.monthlyBalances[months[i]] != null) bal = state.monthlyBalances[months[i]];
    bal += monthTotals(state, months[i]).delta;
  }
  return bal;
}
function catLookup(id) { return CATEGORIES.find(c => c.id === id); }
function subLookup(catId, subId, state) {
  const c = catLookup(catId);
  if (!c) return null;
  const baseSub = c.subs.find(s => s.id === subId);
  if (baseSub) return baseSub;
  // Procura nas subcategorias customizadas
  if (state) {
    const custom = (state.customSubs || {})[catId] || [];
    return custom.find(s => s.id === subId) || null;
  }
  return null;
}

// ── GOALS / HOLDINGS ─────────────────────────────────────────
// A goal's `saved` is the authoritative total. `holdings` is an optional
// breakdown into specific instruments; the part of `saved` not covered by
// holdings is shown as "Não alocado".
function goalHoldingsCurrent(goal) {
  return (goal.holdings || []).reduce((s, h) => s + (h.currentValue || 0), 0);
}
function goalHoldingsInvested(goal) {
  return (goal.holdings || []).reduce((s, h) => s + (h.invested || 0), 0);
}
function goalUnallocated(goal) {
  return Math.max(0, (goal.saved || 0) - goalHoldingsCurrent(goal));
}
function goalYield(goal) {
  return goalHoldingsCurrent(goal) - goalHoldingsInvested(goal);
}
function holdingYield(h) {
  return (h.currentValue || 0) - (h.invested || 0);
}
function newHoldingId() {
  return 'h' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
}
// Apply an aporte (contribution) of `amount` to a goal. `holding` may be:
//   null              → goes to the goal's general (unallocated) pool
//   { id }            → adds to an existing holding (invested + currentValue)
//   { name, type }    → creates a new holding seeded with the amount
// Returns a NEW goals array.
function applyGoalAporte(goals, goalId, amount, holding) {
  const amt = Math.abs(amount);
  return (goals || []).map(g => {
    if (String(g.id) !== String(goalId)) return g;
    let holdings = (g.holdings || []).slice();
    if (holding && holding.id != null) {
      holdings = holdings.map(h => h.id === holding.id
        ? { ...h, invested: (h.invested || 0) + amt, currentValue: (h.currentValue || 0) + amt }
        : h);
    } else if (holding && holding.name) {
      holdings.push({ id: newHoldingId(), name: holding.name, type: holding.type || 'Outro', invested: amt, currentValue: amt });
    }
    return { ...g, holdings, saved: (g.saved || 0) + amt };
  });
}
// Reverte um aporte de `amount` de uma meta (ao deletar a transação do aporte).
// Subtrai do saved e, se houver holding vinculado, reduz invested/currentValue.
// Returns a NEW goals array.
function reverseGoalAporte(goals, goalId, amount, holdingId) {
  const amt = Math.abs(amount);
  return (goals || []).map(g => {
    if (String(g.id) !== String(goalId)) return g;
    let holdings = (g.holdings || []).slice();
    if (holdingId != null) {
      holdings = holdings.map(h => h.id === holdingId
        ? { ...h, invested: Math.max(0, (h.invested || 0) - amt), currentValue: Math.max(0, (h.currentValue || 0) - amt) }
        : h);
    }
    return { ...g, holdings, saved: Math.max(0, (g.saved || 0) - amt) };
  });
}
// Update a holding's current value (to reflect yield). Adjusts goal.saved by the delta.
function updateHoldingValue(goals, goalId, holdingId, newValue) {
  return (goals || []).map(g => {
    if (String(g.id) !== String(goalId)) return g;
    let delta = 0;
    const holdings = (g.holdings || []).map(h => {
      if (h.id !== holdingId) return h;
      delta = (newValue || 0) - (h.currentValue || 0);
      return { ...h, currentValue: newValue || 0 };
    });
    return { ...g, holdings, saved: (g.saved || 0) + delta };
  });
}
// Remove a holding; subtract its current value from goal.saved.
function removeHolding(goals, goalId, holdingId) {
  return (goals || []).map(g => {
    if (String(g.id) !== String(goalId)) return g;
    const h = (g.holdings || []).find(x => x.id === holdingId);
    const holdings = (g.holdings || []).filter(x => x.id !== holdingId);
    return { ...g, holdings, saved: Math.max(0, (g.saved || 0) - (h ? (h.currentValue || 0) : 0)) };
  });
}

// ── GOAL GROWTH HISTORY (derived from aporte transactions) ───
// Aportes are expense transactions tagged with goalId. We use them to
// reconstruct month-by-month contributions per goal.
const GOAL_PALETTE = ['var(--brand-magenta)', 'var(--info-500)', 'var(--positive-500)', 'var(--warning-500)', '#7C3AED', '#0891B2', '#DB2777', '#65A30D'];
const INVTYPE_PALETTE = {
  'Fundo': '#3B6FF1', 'Tesouro Direto': '#0F766E', 'CDB': '#B00369', 'LCI': '#D97706',
  'LCA': '#65A30D', 'Ações': '#DC2626', 'FII': '#7C3AED', 'ETF': '#0891B2',
  'Cripto': '#EA580C', 'Poupança': '#0EA5E9', 'Previdência': '#9333EA', 'Outro': '#64748B',
};
function goalColor(goals, goalId) {
  const idx = (goals || []).findIndex(g => String(g.id) === String(goalId));
  return GOAL_PALETTE[((idx < 0 ? 0 : idx) % GOAL_PALETTE.length)];
}
function goalAporteTx(state) {
  return (state.transactions || []).filter(t => t.goalId != null && t.amount < 0);
}
function goalAporteYears(state) {
  const set = new Set();
  goalAporteTx(state).forEach(t => set.add(yearOf(ymKey(t.date))));
  set.add(String(new Date().getFullYear()));
  return Array.from(set).sort().reverse();
}
// Per-month aportes for all goals in a year: [{ ymk, label, perGoal:{id:amt}, total }]
function goalsAportesPerMonth(state, year) {
  const tx = goalAporteTx(state);
  return monthsInYear(year).map((k, i) => {
    const perGoal = {};
    let total = 0;
    tx.forEach(t => {
      if (ymKey(t.date) !== k) return;
      const amt = Math.abs(t.amount);
      perGoal[t.goalId] = (perGoal[t.goalId] || 0) + amt;
      total += amt;
    });
    return { ymk: k, label: MONTHS_ABBR[i], perGoal, total };
  });
}
// Per-month aportes for a single goal in a year: [{ ymk, label, value }]
function goalAportesPerMonthForGoal(state, goalId, year) {
  const tx = goalAporteTx(state).filter(t => String(t.goalId) === String(goalId));
  return monthsInYear(year).map((k, i) => {
    let value = 0;
    tx.forEach(t => { if (ymKey(t.date) === k) value += Math.abs(t.amount); });
    return { ymk: k, label: MONTHS_ABBR[i], value };
  });
}
// Accumulated current value per investment type, across all goals: [{ type, value, color }]
function investmentTypeAllocation(state) {
  const map = {};
  (state.goals || []).forEach(g => (g.holdings || []).forEach(h => {
    map[h.type] = (map[h.type] || 0) + (h.currentValue || 0);
  }));
  return Object.keys(map)
    .map(type => ({ type, value: map[type], color: INVTYPE_PALETTE[type] || '#64748B' }))
    .filter(x => x.value > 0)
    .sort((a, b) => b.value - a.value);
}

// ── FORECASTS ────────────────────────────────────────────────
function pendingForecasts(state, kind = null) {
  return (state.forecasts || []).filter(f => f.status === 'pending' && (kind == null || (f.kind || 'expense') === kind));
}
function forecastsInMonth(state, ymk, kind = null) {
  return pendingForecasts(state, kind).filter(f => ymKey(f.dueDate) === ymk);
}
function upcomingForecasts(state, days = 60, kind = null) {
  const now = new Date();
  const limit = new Date(now); limit.setDate(now.getDate() + days);
  return pendingForecasts(state, kind)
    .filter(f => {
      const d = new Date(f.dueDate);
      return d >= new Date(now.getFullYear(), now.getMonth(), now.getDate()) && d <= limit;
    })
    .sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate));
}
function forecastedOutflow(state, ymk) {
  return forecastsInMonth(state, ymk).filter(f => (f.kind || 'expense') === 'expense').reduce((s, f) => s + Math.abs(f.amount), 0);
}
function forecastedInflow(state, ymk) {
  return forecastsInMonth(state, ymk, 'income').reduce((s, f) => s + Math.abs(f.amount), 0);
}
// Aportes previstos do mês — separados de saídas, pois não são despesa.
function forecastedTransfers(state, ymk) {
  return forecastsInMonth(state, ymk).filter(f => f.kind === 'transfer').reduce((s, f) => s + Math.abs(f.amount), 0);
}
// Roll a recurring forecast forward by one cycle (monthly / yearly)
function nextRecurrence(iso, recurrence) {
  const d = new Date(iso);
  if (recurrence === 'monthly') d.setMonth(d.getMonth() + 1);
  else if (recurrence === 'yearly') d.setFullYear(d.getFullYear() + 1);
  else if (recurrence === 'weekly') d.setDate(d.getDate() + 7);
  return d.toISOString();
}

// ── EXPORTS ──────────────────────────────────────────────────
window.LedgerStore = {
  saveToFirestore, loadFromFirestore, mergeCloudData,
  CATEGORIES, INCOME_SOURCES, getCategoriesWithCustom, PAYMENT_METHODS, INVESTMENT_TYPES, INVESTMENT_TYPE_ICON,
  loadState, saveState, clearAllData, seedSampleData, defaultState,
  hashPassword, randomSalt,
  fmtMoney, fmtMoneyShort, fmtPct, fmtDate, ymKey, ymLabel,
  transactionsInMonth, monthTotals, byCategory, bySubcategoryTree, bySubcategoryTreeYear, getStartingBalance, monthsSeries,
  yearOf, monthsInYear, yearTotals, yearMonthsSeries, byCategoryYear, byCategoryPerMonth, yearsAvailable, yearEndingBalance, MONTHS_ABBR,
  catLookup, subLookup,
  goalHoldingsCurrent, goalHoldingsInvested, goalUnallocated, goalYield, holdingYield,
  newHoldingId, applyGoalAporte, reverseGoalAporte, updateHoldingValue, removeHolding,
  goalColor, goalAporteYears, goalsAportesPerMonth, goalAportesPerMonthForGoal, investmentTypeAllocation,
  pendingForecasts, forecastsInMonth, upcomingForecasts, forecastedOutflow, forecastedInflow, forecastedTransfers, nextRecurrence,
};
