// ─────────────────────────────────────────────────────────────
// ledger-screen.jsx — Transaction Ledger (sortable list)
// ─────────────────────────────────────────────────────────────
const { LedgerIcon, LedgerButton, LedgerPageHeader, LedgerSegmented, LedgerChip } = window;

function LedgerTransactionsScreen({ state, setState, onNavigate, filterCategory, setFilterCategory, initialMonth }) {
  const S = window.LedgerStore;
  const { isMobile, isNarrow } = window.useViewport();
  const stack = isNarrow;
  const [query, setQuery] = React.useState('');
  const [typeFilter, setTypeFilter] = React.useState('all');   // all | income | expense
  const [sortKey, setSortKey] = React.useState('date');         // 'date' | 'amount' | 'counterparty'
  const [sortDir, setSortDir] = React.useState('desc');
  const [focus, setFocus] = React.useState(null);
  const [monthFilter, setMonthFilter] = React.useState(initialMonth || 'all');  // 'all' | 'YYYY-MM'

  // Quando chega um mês vindo do dashboard (clique em categoria), aplica o filtro
  React.useEffect(() => {
    if (initialMonth) setMonthFilter(initialMonth);
  }, [initialMonth]);
  const PAGE = 20;
  const [visibleCount, setVisibleCount] = React.useState(PAGE);
  const [editingTx, setEditingTx] = React.useState(null);
  const [copyingTx, setCopyingTx] = React.useState(null);
  const [bulkEdit, setBulkEdit] = React.useState(false);
  const [bulkDrafts, setBulkDrafts] = React.useState({});
  const loadMoreRef = React.useRef(null);

  // Lista de meses disponíveis (dos lançamentos existentes), mais recente primeiro
  const availableMonths = React.useMemo(() => {
    const set = new Set();
    (state.transactions || []).forEach(t => { if (t.date) set.add(t.date.slice(0, 7)); });
    return Array.from(set).sort().reverse();
  }, [state.transactions]);

  function sortBy(key) {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir(key === 'amount' ? 'desc' : 'desc'); }
  }

  const rows = React.useMemo(() => {
    let list = state.transactions.slice();
    if (monthFilter !== 'all') list = list.filter(t => (t.date || '').slice(0, 7) === monthFilter);
    if (filterCategory) list = list.filter(t => t.categoryId === filterCategory);
    if (typeFilter === 'transfer') list = list.filter(t => !!t.transfer);
    else if (typeFilter !== 'all') list = list.filter(t => t.type === typeFilter && !t.transfer);
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter(t => {
        const cat = S.catLookup(t.categoryId);
        const sub = S.subLookup(t.categoryId, t.subcategoryId);
        return (t.note || '').toLowerCase().includes(q)
          || (t.source || '').toLowerCase().includes(q)
          || (cat && cat.name.toLowerCase().includes(q))
          || (sub && sub.name.toLowerCase().includes(q));
      });
    }
    list.sort((a, b) => {
      let av, bv;
      if (sortKey === 'date')         { av = new Date(a.date); bv = new Date(b.date); }
      else if (sortKey === 'amount')  { av = a.amount; bv = b.amount; }
      else                            { av = (a.note || ''); bv = (b.note || ''); }
      if (av < bv) return sortDir === 'asc' ? -1 : 1;
      if (av > bv) return sortDir === 'asc' ?  1 : -1;
      return 0;
    });
    return list;
  }, [state.transactions, monthFilter, filterCategory, typeFilter, query, sortKey, sortDir]);

  // Reinicia a paginação quando qualquer filtro muda
  React.useEffect(() => { setVisibleCount(PAGE); }, [monthFilter, filterCategory, typeFilter, query, sortKey, sortDir]);

  // Lançamentos efetivamente exibidos (paginados)
  const visibleRows = bulkEdit ? rows : rows.slice(0, visibleCount);
  const hasMore = !bulkEdit && rows.length > visibleCount;

  // Scroll infinito: carrega mais quando o sentinel entra na tela
  React.useEffect(() => {
    if (!hasMore || !loadMoreRef.current) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) setVisibleCount(c => c + PAGE);
    }, { rootMargin: '200px' });
    obs.observe(loadMoreRef.current);
    return () => obs.disconnect();
  }, [hasMore, visibleCount, rows.length]);

  function removeTx(id) {
    const tx = state.transactions.find(t => t.id === id);
    let nextGoals = state.goals;
    // Se a transação for um aporte vinculado a uma meta, devolve o valor à meta
    if (tx && tx.goalId) {
      nextGoals = S.reverseGoalAporte(state.goals, tx.goalId, Math.abs(tx.amount), tx.holdingId || null);
    }
    const next = { ...state, transactions: state.transactions.filter(t => t.id !== id), goals: nextGoals };
    setState(next);
  }

  function copyTxToDate(tx, newDateStr) {
    const copy = {
      ...tx,
      id: Date.now() + Math.floor(Math.random() * 1000),
      date: new Date(newDateStr + 'T12:00:00').toISOString(),
      // Cópias não herdam vínculo de previsão nem de aporte realizado
      fromForecastId: undefined,
      realizedTxId: undefined,
    };
    setState({ ...state, transactions: [copy, ...state.transactions] });
    setCopyingTx(null);
  }

  function saveTx(updated) {
    const next = { ...state, transactions: state.transactions.map(t => t.id === updated.id ? updated : t) };
    setState(next);
    setEditingTx(null);
  }

  function enterBulkEdit() {
    const drafts = {};
    rows.forEach(r => { drafts[r.id] = {
      note: r.note || '',
      date: r.date ? r.date.slice(0, 10) : '',
      amount: String(Math.abs(r.amount)),
      categoryId: r.categoryId || 'basic',
      subcategoryId: r.subcategoryId || '',
      source: r.source || '',
    }; });
    setBulkDrafts(drafts);
    setBulkEdit(true);
  }

  function saveBulkEdits() {
    const updated = state.transactions.map(t => {
      const d = bulkDrafts[t.id];
      if (!d) return t;
      const n = parseFloat((d.amount || '').replace(',', '.'));
      const isIncome = t.type === 'income';
      const fallbackName = isIncome
        ? d.source
        : (S.subLookup(d.categoryId, d.subcategoryId, state)?.name || S.catLookup(d.categoryId)?.name || 'Lançamento');
      return {
        ...t,
        note: (d.note || '').trim() || fallbackName,
        date: new Date(d.date + 'T12:00:00').toISOString(),
        amount: t.amount > 0 ? Math.abs(n) : -Math.abs(n),
        categoryId: t.type === 'income' ? null : d.categoryId,
        subcategoryId: t.type === 'income' ? null : d.subcategoryId,
        source: t.type === 'income' ? d.source : t.source,
      };
    });
    setState({ ...state, transactions: updated });
    setBulkEdit(false);
    setBulkDrafts({});
  }

  const sortIndicator = (k) => sortKey === k ? (sortDir === 'asc' ? ' ↑' : ' ↓') : '';

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1280, margin: '0 auto' }} data-screen-label="Ledger">
      <LedgerPageHeader
        eyebrow="O Arquivo"
        title="Lançamentos"
        actions={
          <>
            <div style={{ position: 'relative' }}>
              <input
                placeholder="Buscar nos lançamentos…"
                value={query}
                onChange={e => setQuery(e.target.value)}
                onFocus={() => setFocus('q')} onBlur={() => setFocus(null)}
                style={{
                  fontFamily: 'var(--font-body)', fontSize: 13, padding: '9px 14px 9px 36px', width: 240,
                  border: `1px solid ${focus === 'q' ? 'var(--slate-400)' : 'var(--border)'}`, borderRadius: 'var(--r-3)',
                  background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
                  boxShadow: focus === 'q' ? 'var(--shadow-focus)' : 'none',
                  transition: 'all var(--dur-fast) var(--ease-out)',
                }}
              />
              <span style={{ position: 'absolute', left: 12, top: 10 }}>
                <LedgerIcon name="search" size={16} color="var(--fg-2)" />
              </span>
            </div>
            {!bulkEdit && <LedgerButton variant="secondary" icon="table-2" onClick={enterBulkEdit}>Editar em lote</LedgerButton>}
            <LedgerButton variant="primary" icon="plus" onClick={() => onNavigate('add')}>Nova Entrada</LedgerButton>
          </>
        }
      />

      {/* Filter bar */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <LedgerSegmented
            options={[{ label: 'Todas', value: 'all' }, { label: 'Saídas', value: 'expense' }, { label: 'Entradas', value: 'income' }, { label: 'Aportes', value: 'transfer' }]}
            value={typeFilter}
            onChange={setTypeFilter}
          />
          <select
            value={monthFilter}
            onChange={e => setMonthFilter(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',
            }}
          >
            <option value="all">Todos os meses</option>
            {availableMonths.map(m => {
              const [y, mo] = m.split('-');
              const nome = new Date(Number(y), Number(mo) - 1, 1).toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
              return <option key={m} value={m}>{nome.charAt(0).toUpperCase() + nome.slice(1)}</option>;
            })}
          </select>
          {filterCategory && (
            <button onClick={() => setFilterCategory(null)} style={{
              all: 'unset', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px',
              borderRadius: 'var(--r-3)', background: 'var(--brand-magenta-100)',
              color: 'var(--brand-magenta-700)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12,
            }}>
              {S.catLookup(filterCategory).name}
              <LedgerIcon name="x" size={12} color="var(--brand-magenta-700)" />
            </button>
          )}
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)' }}>
          {rows.length} {rows.length === 1 ? 'lançamento' : 'lançamentos'}
        </div>
      </div>

      {bulkEdit && (
        <div style={{
          background: 'var(--bg-elevated)', borderRadius: 'var(--r-4)', padding: '14px 20px',
          border: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <LedgerIcon name="table-2" size={16} color="var(--brand-magenta)" />
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--fg-strong)' }}>
              Modo edição em lote — {rows.length} lançamentos
            </span>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <LedgerButton variant="secondary" onClick={() => { setBulkEdit(false); setBulkDrafts({}); }}>Cancelar</LedgerButton>
            <LedgerButton variant="primary" icon="check" onClick={saveBulkEdits}>Salvar alterações</LedgerButton>
          </div>
        </div>
      )}

      <div style={{ background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)', overflow: 'hidden', border: '1px solid var(--border)' }}>
        {!stack && (
        <div style={{
          display: 'grid', gridTemplateColumns: '96px minmax(0,1fr) 150px 130px 116px',
          padding: '14px 28px', background: 'var(--bg-muted)',
          fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
          color: 'var(--fg-3)', textTransform: 'uppercase',
        }}>
          <ColHeader label={'Data' + sortIndicator('date')} onClick={() => sortBy('date')} />
          <ColHeader label={'Descrição' + sortIndicator('counterparty')} onClick={() => sortBy('counterparty')} />
          <div>Categoria</div>
          <ColHeader align="right" label={'Valor' + sortIndicator('amount')} onClick={() => sortBy('amount')} />
          <div />
        </div>
        )}
        {stack && (
          <div style={{
            padding: '12px 16px', background: 'var(--bg-muted)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8,
            borderBottom: '1px solid var(--border)',
          }}>
            <span className="meta" style={{ color: 'var(--fg-3)' }}>ORDENAR POR</span>
            <div style={{ display: 'flex', gap: 6 }}>
              {['date','amount'].map(k => (
                <button key={k} onClick={() => sortBy(k)} style={{
                  all: 'unset', cursor: 'pointer',
                  padding: '5px 10px', borderRadius: 'var(--r-2)',
                  background: sortKey === k ? 'var(--bg-elevated)' : 'transparent',
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11,
                  color: sortKey === k ? 'var(--fg-strong)' : 'var(--fg-2)',
                  border: sortKey === k ? '1px solid var(--border)' : '1px solid transparent',
                }}>{k === 'date' ? 'Data' : 'Valor'}{sortKey === k ? (sortDir === 'asc' ? ' ↑' : ' ↓') : ''}</button>
              ))}
            </div>
          </div>
        )}
        {bulkEdit && !stack && (
          <div style={{
            display: 'grid', gridTemplateColumns: '100px minmax(0,1fr) 140px 120px 90px 60px',
            padding: '10px 20px', background: 'var(--bg-muted)',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
            color: 'var(--fg-3)', textTransform: 'uppercase', borderBottom: '1px solid var(--border)',
          }}>
            <div>Data</div><div>Descrição</div><div>Categoria</div><div>Subcategoria</div><div style={{textAlign:'right'}}>Valor</div><div/>
          </div>
        )}

        {bulkEdit && rows.map((r, idx) => {
          const S = window.LedgerStore;
          const d = bulkDrafts[r.id] || {};
          const isIncome = r.type === 'income';
          const cat = S.catLookup(d.categoryId || r.categoryId);
          const cellStyle = {
            fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg)',
            border: '1px solid var(--border)', borderRadius: 'var(--r-2)',
            background: 'var(--bg-elevated)', outline: 'none', padding: '6px 10px',
            width: '100%', boxSizing: 'border-box',
          };
          const selStyle = { ...cellStyle, cursor: 'pointer', appearance: 'none' };
          const update = (patch) => setBulkDrafts(prev => ({ ...prev, [r.id]: { ...prev[r.id], ...patch } }));
          return (
            <div key={r.id} style={{
              display: stack ? 'flex' : 'grid',
              flexDirection: stack ? 'column' : undefined,
              gridTemplateColumns: stack ? undefined : '100px minmax(0,1fr) 140px 120px 90px 60px',
              gap: 6, padding: stack ? '14px 16px' : '8px 20px',
              borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
              alignItems: 'center',
              background: 'var(--bg-elevated)',
            }}>
              <input type="date" value={d.date || ''} onChange={e => update({ date: e.target.value })} style={cellStyle} />
              <input value={d.note || ''} onChange={e => update({ note: e.target.value })}
                placeholder="Descrição" style={cellStyle} />
              {isIncome ? (
                <select value={d.source || ''} onChange={e => update({ source: e.target.value })} style={selStyle}>
                  {S.INCOME_SOURCES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              ) : (
                <select value={d.categoryId || ''} onChange={e => update({ categoryId: e.target.value, subcategoryId: S.catLookup(e.target.value)?.subs[0]?.id || '' })} style={selStyle}>
                  {allCategories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              )}
              {isIncome ? (
                <div style={{ ...cellStyle, color: 'var(--fg-3)' }}>—</div>
              ) : (
                <select value={d.subcategoryId || ''} onChange={e => update({ subcategoryId: e.target.value })} style={selStyle}>
                  {cat && cat.subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              )}
              <input value={d.amount || ''} onChange={e => update({ amount: e.target.value })}
                inputMode="decimal" placeholder="0,00"
                style={{ ...cellStyle, textAlign: 'right', fontWeight: 700,
                  color: isIncome ? 'var(--fg-positive)' : 'var(--brand-magenta)' }} />
              <button onClick={() => removeTx(r.id)} style={{
                all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)',
                color: 'var(--fg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = 'var(--brand-magenta-100)'; e.currentTarget.style.color = 'var(--brand-magenta-700)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}>
                <LedgerIcon name="trash-2" size={14} color="currentColor" />
              </button>
            </div>
          );
        })}

        {!bulkEdit && rows.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            Nenhum lançamento corresponde a esses filtros ainda.
          </div>
        )}
        {!bulkEdit && visibleRows.map((r, idx) => {
          const cat = S.catLookup(r.categoryId);
          const sub = S.subLookup(r.categoryId, r.subcategoryId);
          const isIncome = r.amount > 0;
          const isTransfer = !!r.transfer;
          const rowColor = isTransfer ? 'var(--info-500)' : (isIncome ? 'var(--fg-positive)' : 'var(--fg-strong)');
          const rowIconBg = isTransfer ? 'var(--info-100)' : (isIncome ? 'var(--positive-50)' : 'var(--bg-muted)');
          const rowIconColor = isTransfer ? 'var(--info-500)' : (isIncome ? 'var(--positive-700)' : 'var(--fg)');
          const rowIconName = isTransfer ? 'trending-up' : (isIncome ? 'arrow-down-left' : (cat ? cat.icon : 'circle-dollar-sign'));
          if (stack) {
            return (
              <div key={r.id} style={{
                padding: '14px 16px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
                display: 'flex', flexDirection: 'column', gap: 10,
              }}>
                {/* Linha 1: ícone + descrição + valor */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 'var(--r-3)',
                    background: rowIconBg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <LedgerIcon
                      name={rowIconName}
                      size={18}
                      color={rowIconColor}
                    />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {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: 2 }}>
                      {S.fmtDate(r.date, { short: true })}
                    </div>
                  </div>
                  <div className="num" style={{
                    fontSize: 16, fontWeight: 700,
                    color: rowColor,
                    textAlign: 'right', flexShrink: 0, whiteSpace: 'nowrap',
                  }}>
                    {S.fmtMoney(r.amount, { signed: true })}
                  </div>
                </div>
                {/* Linha 2: categoria/chip à esquerda + ações à direita */}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, paddingLeft: 50 }}>
                  <div style={{ minWidth: 0, overflow: 'hidden' }}>
                    {isTransfer
                      ? <LedgerChip tone="growth">APORTE</LedgerChip>
                      : isIncome
                      ? <LedgerChip tone="income">ENTRADA</LedgerChip>
                      : cat ? <LedgerChip tone={cat.chipTone}>{cat.name}</LedgerChip> : <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>—</span>}
                  </div>
                  <div style={{ display: 'flex', gap: 2, flexShrink: 0 }}>
                    <button onClick={() => setEditingTx(r)} style={{
                      all: 'unset', cursor: 'pointer',
                      width: 34, height: 34, borderRadius: 'var(--r-2)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'var(--fg-3)',
                    }} title="Editar lançamento">
                      <LedgerIcon name="pencil" size={16} color="currentColor" />
                    </button>
                    <button onClick={() => setCopyingTx(r)} style={{
                      all: 'unset', cursor: 'pointer',
                      width: 34, height: 34, borderRadius: 'var(--r-2)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'var(--fg-3)',
                    }} title="Copiar para outra data">
                      <LedgerIcon name="copy" size={16} color="currentColor" />
                    </button>
                    <button onClick={() => removeTx(r.id)} style={{
                      all: 'unset', cursor: 'pointer',
                      width: 34, height: 34, borderRadius: 'var(--r-2)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'var(--fg-3)',
                    }} title="Remover lançamento">
                      <LedgerIcon name="trash-2" size={16} color="currentColor" />
                    </button>
                  </div>
                </div>
              </div>
            );
          }
          // — versão DESKTOP da linha abaixo —
          return (
            <div key={r.id} style={{
              display: 'grid', gridTemplateColumns: '96px minmax(0,1fr) 150px 130px 116px',
              padding: '16px 28px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
              alignItems: 'center', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--fg)',
              transition: 'background var(--dur-fast)',
            }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div className="mono" style={{ color: 'var(--fg-3)', fontSize: 12 }}>{S.fmtDate(r.date, { short: true })}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 'var(--r-2)',
                  background: rowIconBg,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <LedgerIcon
                    name={rowIconName}
                    size={16}
                    color={rowIconColor}
                  />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {r.note || (isIncome ? r.source : sub && sub.name) || (cat && cat.name) || 'Sem título'}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                    {isTransfer
                      ? `Aporte${r.goalId ? ' · → ' + ((state.goals || []).find(g => String(g.id) === String(r.goalId))?.name || 'meta') : ''}`
                      : isIncome
                      ? (r.source ? `Fonte · ${r.source}` : 'Entrada')
                      : `${sub ? sub.name : '—'}${r.fixed ? ' · Fixo' : ''}${r.paymentMethod ? ' · ' + (S.PAYMENT_METHODS.find(p => p.id === r.paymentMethod)?.name || '') : ''}${r.goalId ? ' · → ' + ((state.goals || []).find(g => String(g.id) === String(r.goalId))?.name || 'meta') : ''}`}
                  </div>
                </div>
              </div>
              <div>
                {isTransfer
                  ? <LedgerChip tone="growth">APORTE</LedgerChip>
                  : isIncome
                  ? <LedgerChip tone="income">ENTRADA</LedgerChip>
                  : cat
                    ? <LedgerChip tone={cat.chipTone}>{cat.name}</LedgerChip>
                    : <LedgerChip tone="neutral">—</LedgerChip>}
              </div>
              <div className="num" style={{
                textAlign: 'right', fontSize: 16,
                color: rowColor,
              }}>
                {S.fmtMoney(r.amount, { signed: true })}
              </div>
              <div style={{ display: 'flex', gap: 4, justifySelf: 'end' }}>
                <button onClick={() => setEditingTx(r)} style={{
                  all: 'unset', cursor: 'pointer',
                  padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
                  transition: 'all var(--dur-fast)',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-muted)'; e.currentTarget.style.color = 'var(--fg)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
                title="Editar lançamento">
                  <LedgerIcon name="pencil" size={14} color="currentColor" />
                </button>
                <button onClick={() => setCopyingTx(r)} style={{
                  all: 'unset', cursor: 'pointer',
                  padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
                  transition: 'all var(--dur-fast)',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-muted)'; e.currentTarget.style.color = 'var(--fg)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
                title="Copiar para outra data">
                  <LedgerIcon name="copy" size={14} color="currentColor" />
                </button>
                <button onClick={() => removeTx(r.id)} style={{
                  all: 'unset', cursor: 'pointer',
                  padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
                  transition: 'all var(--dur-fast)',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--brand-magenta-100)'; e.currentTarget.style.color = 'var(--brand-magenta-700)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
                title="Remover lançamento">
                  <LedgerIcon name="trash-2" size={14} color="currentColor" />
                </button>
              </div>
            </div>
          );
        })}
        {hasMore && (
          <div ref={loadMoreRef} style={{ padding: '18px 28px', textAlign: 'center', borderTop: '1px solid var(--border)' }}>
            <LedgerButton variant="secondary" size="sm" onClick={() => setVisibleCount(c => c + PAGE)}>
              Carregar mais ({rows.length - visibleCount} restantes)
            </LedgerButton>
          </div>
        )}
      </div>
      {editingTx && (
        <EditTxModal
          tx={editingTx}
          state={state}
          onSave={saveTx}
          onClose={() => setEditingTx(null)}
        />
      )}
      {copyingTx && (
        <CopyTxModal
          tx={copyingTx}
          state={state}
          onCopy={copyTxToDate}
          onClose={() => setCopyingTx(null)}
        />
      )}
    </div>
  );
}

function ColHeader({ label, onClick, align = 'left' }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', textAlign: align,
      fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
      color: 'var(--fg-3)', textTransform: 'uppercase',
    }}>{label}</button>
  );
}

// ── EDIT TRANSACTION MODAL ──────────────────────────────────
function EditTxModal({ tx, state, onSave, onClose }) {
  const S = window.LedgerStore;
  const isIncome = tx.type === 'income';
  const [amount, setAmount]             = React.useState(String(Math.abs(tx.amount)).replace('.', ','));
  const [date, setDate]                 = React.useState(tx.date ? tx.date.slice(0, 10) : '');
  const [note, setNote]                 = React.useState(tx.note || '');
  const [categoryId, setCategoryId]     = React.useState(tx.categoryId || 'basic');
  const [subcategoryId, setSubcategoryId] = React.useState(tx.subcategoryId || '');
  const [paymentMethod, setPaymentMethod] = React.useState(tx.paymentMethod || 'debit');
  const [source, setSource]             = React.useState(tx.source || 'Salário');
  const [fixed, setFixed]               = React.useState(!!tx.fixed);
  const [error, setError]               = React.useState('');
  const [focus, setFocus]               = React.useState(null);

  const allCategories = S.getCategoriesWithCustom(state);
  const cat = allCategories.find(c => c.id === categoryId) || S.catLookup(categoryId);

  const inputStyle = (id) => ({
    fontFamily: 'var(--font-body)', fontSize: 14, padding: '10px 14px', width: '100%', boxSizing: 'border-box',
    border: `1px solid ${focus === id ? 'var(--slate-400)' : 'var(--border)'}`,
    borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
    boxShadow: focus === id ? 'var(--shadow-focus)' : 'none',
    transition: 'all var(--dur-fast) var(--ease-out)',
  });

  function handleSave(e) {
    e.preventDefault();
    const n = parseFloat((amount || '').replace(',', '.'));
    if (!n || isNaN(n) || n <= 0) { setError('Entre um valor positivo.'); return; }
    // Quando a descrição fica vazia, usa o nome da subcategoria/categoria (despesa)
    // ou a fonte (entrada) como fallback, em vez de salvar em branco.
    const fallbackName = isIncome
      ? source
      : (S.subLookup(categoryId, subcategoryId, state)?.name || S.catLookup(categoryId)?.name || 'Lançamento');
    const finalNote = note.trim() || fallbackName;
    const updated = {
      ...tx,
      amount: isIncome ? Math.abs(n) : -Math.abs(n),
      date: new Date(date + 'T12:00:00').toISOString(),
      note: finalNote,
      categoryId: isIncome ? null : categoryId,
      subcategoryId: isIncome ? null : subcategoryId,
      paymentMethod: isIncome ? null : paymentMethod,
      source: isIncome ? source : null,
      fixed: isIncome ? false : fixed,
    };
    onSave(updated);
  }

  const labelStyle = {
    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10,
    letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)',
    display: 'block', marginBottom: 6,
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
      backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center',
      justifyContent: 'center', zIndex: 200, padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 520, maxWidth: '100%', background: 'var(--bg-elevated)',
        borderRadius: 'var(--r-5)', padding: 32, boxShadow: 'var(--shadow-pop)',
        display: 'flex', flexDirection: 'column', gap: 20,
        maxHeight: '90vh', overflowY: 'auto',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>
            Editar Lançamento
          </h2>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: 'var(--fg-3)', padding: 4 }}>
            <LedgerIcon name="x" size={20} color="currentColor" />
          </button>
        </div>

        {error && (
          <div style={{ padding: '10px 12px', borderRadius: 'var(--r-3)', display: 'flex', alignItems: 'center', gap: 10,
            background: 'var(--brand-magenta-100)', border: '1px solid rgba(176,3,105,0.22)',
            color: 'var(--brand-magenta-700)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13 }}>
            <LedgerIcon name="alert-circle" size={16} color="var(--brand-magenta-700)" /> {error}
          </div>
        )}

        <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Valor */}
          <div>
            <span style={labelStyle}>Valor</span>
            <div style={{
              display: 'flex', alignItems: 'stretch',
              border: `1px solid ${focus === 'amt' ? 'var(--slate-400)' : 'var(--border)'}`,
              borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)',
            }}>
              <span style={{
                display: 'flex', alignItems: 'center', padding: '0 14px',
                fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
                color: isIncome ? 'var(--fg-positive)' : 'var(--brand-magenta)',
                borderRight: '1px solid var(--border)',
              }}>{isIncome ? '+' : '−'} R$</span>
              <input value={amount} onChange={e => setAmount(e.target.value)}
                onFocus={() => setFocus('amt')} onBlur={() => setFocus(null)}
                inputMode="decimal"
                style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 16, padding: '11px 14px',
                  border: 'none', background: 'transparent', color: 'var(--fg)', outline: 'none' }} />
            </div>
          </div>

          {/* Data */}
          <div>
            <span style={labelStyle}>Data</span>
            <input type="date" value={date} onChange={e => setDate(e.target.value)}
              onFocus={() => setFocus('dt')} onBlur={() => setFocus(null)}
              style={inputStyle('dt')} />
          </div>

          {/* Descrição */}
          <div>
            <span style={labelStyle}>Descrição</span>
            <input value={note} onChange={e => setNote(e.target.value)}
              onFocus={() => setFocus('nt')} onBlur={() => setFocus(null)}
              placeholder="Ex: Almoço, Conta de luz..."
              style={inputStyle('nt')} />
          </div>

          {isIncome ? (
            <div>
              <span style={labelStyle}>Fonte</span>
              <select value={source} onChange={e => setSource(e.target.value)} style={inputStyle('src')}>
                {S.INCOME_SOURCES.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
          ) : (
            <>
              <div>
                <span style={labelStyle}>Categoria</span>
                <select value={categoryId} onChange={e => { setCategoryId(e.target.value); setSubcategoryId((allCategories.find(c => c.id === e.target.value) || S.catLookup(e.target.value))?.subs[0]?.id || ''); }} style={inputStyle('cat')}>
                  {allCategories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              {cat && (
                <div>
                  <span style={labelStyle}>Subcategoria</span>
                  <select value={subcategoryId} onChange={e => setSubcategoryId(e.target.value)} style={inputStyle('sub')}>
                    {cat.subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                  </select>
                </div>
              )}
              <div>
                <span style={labelStyle}>Forma de pagamento</span>
                <select value={paymentMethod} onChange={e => setPaymentMethod(e.target.value)} style={inputStyle('pm')}>
                  {S.PAYMENT_METHODS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </div>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--fg)' }}>
                <input type="checkbox" checked={fixed} onChange={e => setFixed(e.target.checked)} />
                Despesa fixa (recorrente)
              </label>
            </>
          )}

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
            <LedgerButton type="button" variant="secondary" onClick={onClose}>Cancelar</LedgerButton>
            <LedgerButton type="submit" variant="primary" icon="check">Salvar alterações</LedgerButton>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── COPY TRANSACTION MODAL ──────────────────────────────────
function CopyTxModal({ tx, state, onCopy, onClose }) {
  const S = window.LedgerStore;
  const isIncome = tx.amount > 0;
  // Sugere o mesmo dia no próximo mês
  const suggested = (() => {
    const d = tx.date ? new Date(tx.date) : new Date();
    d.setMonth(d.getMonth() + 1);
    return d.toISOString().slice(0, 10);
  })();
  const [date, setDate] = React.useState(suggested);
  const [focus, setFocus] = React.useState(false);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
      backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center',
      justifyContent: 'center', zIndex: 200, padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 440, maxWidth: '100%', background: 'var(--bg-elevated)',
        borderRadius: 'var(--r-5)', padding: 32, boxShadow: 'var(--shadow-pop)',
        display: 'flex', flexDirection: 'column', gap: 20,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>
            Copiar Lançamento
          </h2>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: 'var(--fg-3)', padding: 4 }}>
            <LedgerIcon name="x" size={20} color="currentColor" />
          </button>
        </div>

        <div style={{
          padding: '14px 16px', borderRadius: 'var(--r-3)', background: 'var(--bg-muted)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {tx.note || (isIncome ? tx.source : S.subLookup(tx.categoryId, tx.subcategoryId, state)?.name) || S.catLookup(tx.categoryId)?.name || 'Lançamento'}
            </div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
              Original: {S.fmtDate(tx.date)}
            </div>
          </div>
          <div className="num" style={{ fontSize: 15, fontWeight: 700, whiteSpace: 'nowrap',
            color: isIncome ? 'var(--fg-positive)' : 'var(--brand-magenta)' }}>
            {S.fmtMoney(tx.amount, { signed: true })}
          </div>
        </div>

        <div>
          <span style={{
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10,
            letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)',
            display: 'block', marginBottom: 6,
          }}>Nova data</span>
          <input type="date" value={date} onChange={e => setDate(e.target.value)}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
            style={{
              fontFamily: 'var(--font-body)', fontSize: 14, padding: '10px 14px', width: '100%', boxSizing: 'border-box',
              border: `1px solid ${focus ? 'var(--slate-400)' : 'var(--border)'}`,
              borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
              boxShadow: focus ? 'var(--shadow-focus)' : 'none', transition: 'all var(--dur-fast)',
            }} />
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 6 }}>
            Uma cópia idêntica será criada nessa data, mantendo valor, categoria e forma de pagamento.
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <LedgerButton variant="secondary" onClick={onClose}>Cancelar</LedgerButton>
          <LedgerButton variant="primary" icon="copy" onClick={() => onCopy(tx, date)}>Criar cópia</LedgerButton>
        </div>
      </div>
    </div>
  );
}

window.LedgerTransactionsScreen = LedgerTransactionsScreen;
