/* ============================================================================
   FSC tabs B — Comparativo & Câmbio, Contas & Cartões, Entidades, Transações
   ============================================================================ */
const FSCb = window.FSC, FCHb = window.FSCCharts, UIb = window.FSCUI, IcoB = window.FSCIcon;
const { fmt: fmtB } = FSCb;
const { Card: CardB, Money: MoneyB, Pill: PillB, Select: SelectB, EmptyState } = UIb;
const { LineChart: LineB, BarsChart: BarsB, Sparkline, PALETTE: PAL } = FCHb;

const ENTITIES = ['Sasaki Coelho', 'Kaninchen', 'Treiben', 'Miya', 'Penny', 'Sogros', 'Pessoal'];

/* ---------------------- COMPARATIVO & CÂMBIO ---------------------- */
function CompareTab({ data, months }) {
  const yearData = FSCb.byYear(data);
  const yl = yearData.map((y) => String(y.year));
  const topCats = FSCb.byCategory(data.transactions, 'despesa').slice(0, 6).map((c) => c.category);
  const catYear = topCats.map((cat) => ({
    cat,
    vals: data.years.map((y) => data.transactions.filter((t) => t.year === y && t.category === cat && t.type === 'despesa').reduce((s, t) => s + -t.amount, 0)),
  }));
  const fxAll = data.fx;
  const rec = FSCb.recurringDescriptions(data, months).slice(0, 10);

  return (
    <div className="stack">
      <CardB title="Receita, despesa e saldo por ano" subtitle="Comparativo anual (todo o histórico)">
        <BarsB labels={yl} series={[
          { name: 'Receita', color: 'var(--green-600)', values: yearData.map((y) => y.receita) },
          { name: 'Despesa', color: 'var(--clay-600)', values: yearData.map((y) => y.despesa) },
          { name: 'Saldo', color: 'var(--ink-900)', values: yearData.map((y) => y.saldo) },
        ]} height={270} yFormat={fmtB.compact} />
      </CardB>

      <div className="grid-2">
        <CardB title="Top categorias ano a ano" subtitle="Despesa anual por categoria">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 70px 1fr', gap: 12, fontSize: 11, color: 'var(--text-muted)', fontWeight: 600, padding: '0 0 8px', borderBottom: '1px solid var(--border-subtle)', textTransform: 'uppercase', letterSpacing: '.04em' }}>
              <span>Categoria</span><span>Tendência</span><span style={{ textAlign: 'right' }}>Total</span>
            </div>
            {catYear.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.3fr 70px 1fr', gap: 12, alignItems: 'center', padding: '9px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 500, color: 'var(--text-secondary)' }}>
                  <span style={{ width: 9, height: 9, borderRadius: 2, background: PAL[i % PAL.length] }} />{r.cat}
                </span>
                <Sparkline values={r.vals} width={70} height={24} color={PAL[i % PAL.length]} />
                <span style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 13 }}>{fmtB.brl0(r.vals.reduce((a, b) => a + b, 0))}</span>
              </div>
            ))}
          </div>
        </CardB>
        <CardB title="Câmbio EUR/BRL" subtitle="Média mensal — histórico completo">
          <LineB series={[{ name: 'EUR/BRL', color: 'var(--cat-7)', values: fxAll.map((f) => f.rate) }]} labels={fxAll.map((f) => fmtB.monthShort(f.ym))} height={230} yFormat={(v) => fmtB.rate(v)} />
        </CardB>
      </div>

      <CardB title="Despesas recorrentes" subtitle="Descrições presentes em 3+ meses do período">
        {rec.length === 0 ? <EmptyState>Sem recorrentes no período selecionado.</EmptyState> : (
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 80px 1fr', gap: 12, fontSize: 11, color: 'var(--text-muted)', fontWeight: 600, padding: '0 0 8px', borderBottom: '1px solid var(--border-subtle)', textTransform: 'uppercase', letterSpacing: '.04em' }}>
              <span>Descrição</span><span>Categoria</span><span style={{ textAlign: 'center' }}>Meses</span><span style={{ textAlign: 'right' }}>Média/mês</span>
            </div>
            {rec.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 80px 1fr', gap: 12, alignItems: 'center', padding: '9px 0', borderBottom: '1px solid var(--border-subtle)', fontSize: 13 }}>
                <span style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{r.description}</span>
                <span style={{ color: 'var(--text-muted)' }}>{r.category}</span>
                <span style={{ textAlign: 'center' }}><PillB>{r.monthsActive}</PillB></span>
                <span style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{fmtB.brl0(r.avg)}</span>
              </div>
            ))}
          </div>
        )}
      </CardB>
    </div>
  );
}

/* ---------------------- CONTAS & CARTÕES ---------------------- */
function AccountsTab({ data, months }) {
  const txs = FSCb.inMonths(data, months);
  const accs = FSCb.byAccount(txs);
  const maxFlow = Math.max(1, ...accs.map((a) => Math.max(a.despesa, a.receita)));

  return (
    <div className="stack">
      <div className="grid-3">
        {accs.map((a, i) => (
          <CardB key={i} pad={16}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 600, fontSize: 14 }}>
                <IcoB name={a.account.toLowerCase().includes('cart') ? 'creditCard' : 'wallet'} size={16} color="var(--text-muted)" />{a.account}
              </span>
              <PillB tone={a.currency === 'EUR' ? 'positive' : 'neutral'}>{a.currency}</PillB>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', fontWeight: 600, marginBottom: 2 }}>Despesa</div>
            <div style={{ marginBottom: 10 }}><MoneyB value={-a.despesa} signed={false} /></div>
            <div style={{ height: 6, background: 'var(--sand-50)', borderRadius: 999, overflow: 'hidden', marginBottom: 12 }}>
              <div style={{ width: `${(a.despesa / maxFlow) * 100}%`, height: '100%', background: 'var(--clay-600)', borderRadius: 999 }} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'var(--text-secondary)' }}>
              <span>Receita <b style={{ fontFamily: 'var(--font-mono)', color: 'var(--positive)' }}>{fmtB.brl0(a.receita)}</b></span>
              <span>{a.count} mov.</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'var(--text-secondary)', marginTop: 4, paddingTop: 8, borderTop: '1px solid var(--border-subtle)' }}>
              <span>Saldo líquido</span><span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, color: a.saldo >= 0 ? 'var(--positive)' : 'var(--negative)' }}>{fmtB.brl0(a.saldo)}</span>
            </div>
          </CardB>
        ))}
      </div>
      <CardB title="Despesa por conta" subtitle="Comparação entre contas e cartões no período">
        <BarsB labels={accs.map((a) => a.account.replace('Cartão ', '').slice(0, 10))} series={[{ name: 'Despesa', color: 'var(--clay-600)', values: accs.map((a) => a.despesa) }]} height={240} yFormat={fmtB.compact} />
      </CardB>
    </div>
  );
}

/* ---------------------- ENTIDADES ---------------------- */
function EntitiesTab({ data, months }) {
  const ent = FSCb.byEntity(data, months, ENTITIES);
  const maxAbs = Math.max(1, ...ent.map((e) => Math.max(e.receita, e.despesa)));
  return (
    <div className="stack">
      <CardB title="Saldo líquido por entidade" subtitle="Receita − despesa, por pessoa/entidade (categoria contém o nome)">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {ent.map((e, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 130px', gap: 16, alignItems: 'center' }}>
              <span style={{ fontWeight: 600, fontSize: 13.5 }}>{e.name}</span>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <div style={{ height: 9, background: 'var(--sand-50)', borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: `${(e.receita / maxAbs) * 100}%`, height: '100%', background: 'var(--green-600)', borderRadius: 999 }} />
                </div>
                <div style={{ height: 9, background: 'var(--sand-50)', borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: `${(e.despesa / maxAbs) * 100}%`, height: '100%', background: 'var(--clay-600)', borderRadius: 999 }} />
                </div>
              </div>
              <span style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 15, color: e.net >= 0 ? 'var(--positive)' : 'var(--negative)' }}>{fmtB.brl0(e.net)}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 18, marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--border-subtle)' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--text-secondary)' }}><span style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--green-600)' }} /> Receita</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--text-secondary)' }}><span style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--clay-600)' }} /> Despesa</span>
        </div>
      </CardB>
    </div>
  );
}

/* ---------------------- TRANSAÇÕES ---------------------- */
function TransactionsTab({ data, months, txFilter, setTxFilter, moeda }) {
  const [sort, setSort] = React.useState({ field: 'date', dir: 'desc' });
  const base = FSCb.inMonths(data, months);
  const cats = ['all', ...Array.from(new Set(data.transactions.map((t) => t.category))).sort()];
  const accsList = ['all', ...Array.from(new Set(data.transactions.map((t) => t.account))).sort()];

  let rows = base.filter((t) => {
    if (txFilter.category !== 'all' && t.category !== txFilter.category) return false;
    if (txFilter.account !== 'all' && t.account !== txFilter.account) return false;
    if (txFilter.type !== 'all' && t.type !== txFilter.type) return false;
    if (txFilter.search) {
      const q = txFilter.search.toLowerCase();
      if (!t.description.toLowerCase().includes(q) && !t.category.toLowerCase().includes(q)) return false;
    }
    return true;
  });
  rows.sort((a, b) => {
    const dir = sort.dir === 'asc' ? 1 : -1;
    if (sort.field === 'amount') return (a.amount - b.amount) * dir;
    return (a.date < b.date ? -1 : a.date > b.date ? 1 : 0) * dir;
  });
  const total = rows.length;
  const sum = rows.reduce((s, t) => s + (t.type === 'transferencia' ? 0 : t.amount), 0);
  const shown = rows.slice(0, 400);
  const set = (k, v) => setTxFilter({ ...txFilter, [k]: v });
  const toggleSort = (field) => setSort((s) => ({ field, dir: s.field === field && s.dir === 'desc' ? 'asc' : 'desc' }));

  const typeColor = { despesa: 'var(--clay-600)', receita: 'var(--green-600)', transferencia: 'var(--text-muted)' };

  return (
    <div className="stack">
      <CardB pad={16}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: '1 1 220px', minWidth: 180 }}>
            <span style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }}><IcoB name="search" size={16} /></span>
            <input value={txFilter.search} onChange={(e) => set('search', e.target.value)} placeholder="Buscar descrição ou categoria…"
              style={{ width: '100%', height: 38, border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-md)', padding: '0 12px 0 34px', font: '400 13.5px var(--font-sans)', background: 'var(--surface-card)', color: 'var(--text-primary)' }} />
          </div>
          <SelectB value={txFilter.category} onChange={(v) => set('category', v)} icon="pieChart" width={180}
            options={cats.map((c) => ({ value: c, label: c === 'all' ? 'Todas categorias' : c }))} />
          <SelectB value={txFilter.account} onChange={(v) => set('account', v)} icon="wallet" width={170}
            options={accsList.map((c) => ({ value: c, label: c === 'all' ? 'Todas contas' : c }))} />
          <SelectB value={txFilter.type} onChange={(v) => set('type', v)} width={150}
            options={[{ value: 'all', label: 'Todos os tipos' }, { value: 'receita', label: 'Receita' }, { value: 'despesa', label: 'Despesa' }, { value: 'transferencia', label: 'Transferência' }]} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, fontSize: 12.5, color: 'var(--text-muted)' }}>
          <span><b style={{ color: 'var(--text-primary)' }}>{fmtB.num(total)}</b> transações{total > 400 ? ' · mostrando 400' : ''}</span>
          <span>Soma (excl. transferências): <b style={{ fontFamily: 'var(--font-mono)', color: sum >= 0 ? 'var(--positive)' : 'var(--negative)' }}>{fmtB.brl(sum)}</b></span>
        </div>
      </CardB>

      <CardB pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--sand-50)' }}>
                {[['date', 'Data', 'left'], ['description', 'Descrição', 'left'], ['category', 'Categoria', 'left'], ['account', 'Conta', 'left'], ['amount', 'Valor', 'right']].map(([f, lbl, al]) => (
                  <th key={f} onClick={() => (f === 'date' || f === 'amount') && toggleSort(f)}
                    style={{ textAlign: al, padding: '11px 16px', font: '600 11px var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--text-muted)', cursor: (f === 'date' || f === 'amount') ? 'pointer' : 'default', whiteSpace: 'nowrap', position: 'sticky', top: 0 }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, justifyContent: al === 'right' ? 'flex-end' : 'flex-start' }}>
                      {lbl}{(f === 'date' || f === 'amount') && <IcoB name="sort" size={13} color={sort.field === f ? 'var(--ink-900)' : 'var(--ink-300)'} />}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {shown.map((t, i) => (
                <tr key={i} style={{ borderTop: '1px solid var(--border-subtle)' }}>
                  <td style={{ padding: '10px 16px', fontFamily: 'var(--font-mono)', color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{fmtB.dateBR(t.date)}</td>
                  <td style={{ padding: '10px 16px', fontWeight: 500, color: 'var(--text-primary)' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 6, height: 6, borderRadius: 999, background: typeColor[t.type], flexShrink: 0 }} />{t.description}
                    </span>
                  </td>
                  <td style={{ padding: '10px 16px', color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>{t.category}</td>
                  <td style={{ padding: '10px 16px', color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{t.account}</td>
                  <td style={{ padding: '10px 16px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 600, whiteSpace: 'nowrap', color: t.type === 'receita' ? 'var(--positive)' : (t.type === 'transferencia' ? 'var(--text-muted)' : 'var(--text-primary)') }}>
                    {t.amount > 0 ? '+' : ''}{fmtB.brl(t.amount)}
                    {moeda !== 'EUR' && t.currency === 'EUR' && <span style={{ display: 'block', fontSize: 10.5, color: 'var(--text-faint)', fontWeight: 500 }}>€ {fmtB.num(Math.abs(t.amountOrig))}</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {total === 0 && <EmptyState>Nenhuma transação encontrada com esses filtros.</EmptyState>}
        </div>
      </CardB>
    </div>
  );
}

window.FSCTabsB = { CompareTab, AccountsTab, EntitiesTab, TransactionsTab };
