// Transactions page — filterable, sortable list with running totals.
function TransactionsPage({ store, onOpenTxn, onAddTxn }) {
  const { transactions, houses, year, setYear } = store;
  const [houseFilter, setHouseFilter] = React.useState('all');
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [catFilter, setCatFilter] = React.useState('all');
  const [sourceFilter, setSourceFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [sortBy, setSortBy] = React.useState({ key: 'date', dir: 'desc' });

  let txns = filterByYear(transactions, year);
  if (houseFilter !== 'all') txns = txns.filter(t => t.houseId === houseFilter);
  if (typeFilter !== 'all') txns = txns.filter(t => t.type === typeFilter);
  if (catFilter !== 'all') txns = txns.filter(t => t.category === catFilter);
  if (sourceFilter !== 'all') txns = txns.filter(t => (t.source || 'manual') === sourceFilter);
  if (query.trim()) {
    const q = query.toLowerCase();
    txns = txns.filter(t => t.description.toLowerCase().includes(q) || t.category.toLowerCase().includes(q));
  }

  txns = txns.slice().sort((a, b) => {
    const dir = sortBy.dir === 'asc' ? 1 : -1;
    if (sortBy.key === 'date') return a.date.localeCompare(b.date) * dir;
    if (sortBy.key === 'amount') return (a.amount - b.amount) * dir;
    return 0;
  });

  const totalIn = txns.filter(t => t.type === 'income').reduce((s, t) => s + t.amount, 0);
  const totalEx = txns.filter(t => t.type === 'expense').reduce((s, t) => s + t.amount, 0);
  const allCats = [...new Set([...CATEGORIES.income, ...CATEGORIES.expense])];
  const sourcesPresent = SOURCES_LIST.filter(s => transactions.some(t => (t.source || 'manual') === s));

  const SortHeader = ({ label, k, align = 'left' }) => (
    <th style={{ cursor: 'default', textAlign: align }} onClick={() => setSortBy({ key: k, dir: sortBy.key === k && sortBy.dir === 'desc' ? 'asc' : 'desc' })}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        {label}
        {sortBy.key === k && (sortBy.dir === 'desc' ? '↓' : '↑')}
      </span>
    </th>
  );

  return (
    <>
      <Topbar title="Transactions" subtitle={`${txns.length} ${txns.length === 1 ? 'transaction' : 'transactions'}`}>
        <YearFilter value={year} onChange={setYear}/>
        <button className="btn accent" onClick={onAddTxn}>{Icon.plus} Add transaction</button>
      </Topbar>

      <div className="content">
        <div className="card" style={{ overflow: 'hidden' }}>
          {/* Filter bar */}
          <div style={{ padding: 16, borderBottom: '1px solid var(--border)', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ position: 'relative', flex: 1, minWidth: 220, maxWidth: 320 }}>
              <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-tertiary)' }}>
                {React.cloneElement(Icon.search, { style: { width: 14, height: 14 } })}
              </span>
              <input className="input" placeholder="Search transactions…" value={query}
                     onChange={e => setQuery(e.target.value)} style={{ height: 32, paddingLeft: 32, fontSize: 13 }}/>
            </div>
            <select className="select" value={houseFilter} onChange={e => setHouseFilter(e.target.value)}
                    style={{ width: 'auto', height: 32, fontSize: 13 }}>
              <option value="all">All houses</option>
              {houses.map(h => <option key={h.id} value={h.id}>{h.name}</option>)}
            </select>
            <select className="select" value={typeFilter} onChange={e => setTypeFilter(e.target.value)}
                    style={{ width: 'auto', height: 32, fontSize: 13 }}>
              <option value="all">All types</option>
              <option value="income">Income</option>
              <option value="expense">Expense</option>
            </select>
            <select className="select" value={catFilter} onChange={e => setCatFilter(e.target.value)}
                    style={{ width: 'auto', height: 32, fontSize: 13 }}>
              <option value="all">All categories</option>
              {allCats.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
            <select className="select" value={sourceFilter} onChange={e => setSourceFilter(e.target.value)}
                    style={{ width: 'auto', height: 32, fontSize: 13 }}>
              <option value="all">All sources</option>
              {sourcesPresent.map(s => <option key={s} value={s}>{SOURCE_LABELS[s] || s}</option>)}
            </select>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center', fontSize: 12, color: 'var(--text-secondary)' }}>
              <span>Income <span className="tabular" style={{ color: 'var(--income)', fontWeight: 500 }}>{fmt$(totalIn, { compact: true })}</span></span>
              <span>Expenses <span className="tabular" style={{ color: 'var(--expense)', fontWeight: 500 }}>{fmt$(totalEx, { compact: true })}</span></span>
              <span style={{ borderLeft: '1px solid var(--border)', paddingLeft: 12 }}>
                Net <span className="tabular" style={{ fontWeight: 600, color: 'var(--text)' }}>{fmt$(totalIn - totalEx, { compact: true })}</span>
              </span>
            </div>
          </div>

          <table className="table">
            <thead>
              <tr>
                <SortHeader label="Date" k="date"/>
                <th>House</th>
                <th>Source</th>
                <th>Type</th>
                <th>Category</th>
                <th>Description</th>
                <th style={{ width: 48 }}></th>
                <SortHeader label="Amount" k="amount" align="right"/>
              </tr>
            </thead>
            <tbody>
              {txns.slice(0, 80).map(t => {
                const h = houses.find(x => x.id === t.houseId);
                return (
                  <tr key={t.id} onClick={() => onOpenTxn(t)}>
                    <td style={{ color: 'var(--text-secondary)', fontSize: 12.5, width: 90 }} className="tabular">{fmtDate(t.date, { year: true })}</td>
                    <td style={{ width: 150 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className="dot" style={{ background: h?.accentColor }}/>
                        <span>{h?.name}</span>
                      </div>
                    </td>
                    <td style={{ width: 80 }}>
                      <SourceTag source={t.source || 'manual'}/>
                    </td>
                    <td style={{ width: 86 }}>
                      <span className={`pill ${t.type}`}>{t.type}</span>
                    </td>
                    <td style={{ width: 130 }}>
                      <span className="chip">{t.category}</span>
                    </td>
                    <td>
                      <span>{t.description}</span>
                    </td>
                    <td style={{ width: 44 }}>{t.receiptUrl && <ReceiptThumb small/>}</td>
                    <td className="num tabular" style={{ width: 110, fontWeight: 500, color: t.type === 'income' ? 'var(--income)' : 'var(--text)' }}>
                      {t.type === 'income' ? '+' : '-'}{fmt$(t.amount)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {txns.length > 80 && (
            <div style={{ padding: 16, textAlign: 'center', fontSize: 12, color: 'var(--text-tertiary)', borderTop: '1px solid var(--border)' }}>
              Showing 80 of {txns.length} · <span style={{ color: 'var(--accent)', fontWeight: 500 }}>Load more</span>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { TransactionsPage });
