// Transactions view — centralized feed across all sources
(function() {
  const { useState, useMemo } = React;
  const { CatPill, Amount, AccountTag, Confidence } = window.UI;

  function SourceMap() {
    const srcs = DATA.sources;
    return (
      <div className="panel">
        <div className="panel-head">
          <span className="panel-title">Sources · {srcs.length} connected</span>
          <button className="btn">+ Add Source</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--line)' }}>
          {srcs.map(s => (
            <div key={s.id} style={{
              background: 'var(--bg-1)', padding: '10px 12px',
              display: 'flex', flexDirection: 'column', gap: 4,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: 12, color: 'var(--fg-0)' }}>{s.name}</span>
                <span className="dot" style={{
                  color: s.status === 'live' ? 'var(--pos)' : 'var(--cat-amber)'
                }} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{s.kind}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>sync {s.last}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function FilterBar({ filter, setFilter }) {
    const chips = [
      { id: 'all',   label: 'All' },
      { id: 'uncat', label: 'Uncategorized · 7' },
      { id: 'pend',  label: 'Pending · 2' },
      { id: 'out',   label: 'Outflows' },
      { id: 'in',    label: 'Inflows' },
      { id: 'large', label: '> $1,000' },
    ];
    return (
      <div style={{ display: 'flex', gap: 6, padding: '0 var(--pad-x)', height: 34, alignItems: 'center', borderBottom: '1px solid var(--line)', background: 'var(--bg-1)' }}>
        {chips.map(c => (
          <button key={c.id}
            onClick={() => setFilter(c.id)}
            className="btn"
            style={{
              background: filter === c.id ? 'var(--accent-bg)' : 'var(--bg-2)',
              color: filter === c.id ? 'var(--accent)' : 'var(--fg-1)',
              borderColor: filter === c.id ? 'var(--accent)' : 'var(--line-2)',
            }}>
            {c.label}
          </button>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          <input placeholder="fuzzy search · /regex/ · amount:>100 · cat:infra" style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, width: 340,
            padding: '4px 8px', border: '1px solid var(--line-2)', background: 'var(--bg-2)', color: 'var(--fg-0)'
          }} />
          <button className="btn">Group by ▾</button>
          <button className="btn">Export</button>
        </div>
      </div>
    );
  }

  function TxnRow({ t, selected, onSelect }) {
    const a = DATA.accounts.find(x => x.id === t.account);
    return (
      <tr style={{ background: selected ? 'var(--bg-2)' : 'transparent', cursor: 'pointer' }} onClick={onSelect}>
        <td><input type="checkbox" style={{ accentColor: 'var(--accent)' }} /></td>
        <td><span className="mono" style={{ color: 'var(--fg-3)', fontSize: 10 }}>{t.ts}</span></td>
        <td>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span>{t.merchant}{t.pending && <span className="chip warn" style={{ marginLeft: 8 }}>pending</span>}</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{t.raw}</span>
          </div>
        </td>
        <td><span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{a.source} · {a.mask}</span></td>
        <td><CatPill cat={t.cat} /></td>
        <td><Confidence c={t.conf} /></td>
        <td className="num" style={{ color: t.amount < 0 ? 'var(--fg-0)' : 'var(--pos)', fontWeight: Math.abs(t.amount) > 5000 ? 500 : 400 }}>
          {t.amount < 0 ? '−$' : '+$'}{Math.abs(t.amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
        </td>
      </tr>
    );
  }

  function Inspector({ t, onClose }) {
    if (!t) return null;
    const a = DATA.accounts.find(x => x.id === t.account);
    return (
      <aside style={{
        width: 360, borderLeft: '1px solid var(--line)',
        background: 'var(--bg-1)', overflow: 'auto',
        display: 'flex', flexDirection: 'column',
      }}>
        <div className="panel-head">
          <span className="panel-title">Transaction · {t.id}</span>
          <button className="btn" onClick={onClose}>✕</button>
        </div>
        <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <div className="caps">Merchant</div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, marginTop: 2 }}>{t.merchant}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{t.raw}</div>
          </div>
          <div>
            <div className="caps">Amount</div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, color: t.amount < 0 ? 'var(--fg-0)' : 'var(--pos)' }}>
              {t.amount < 0 ? '−$' : '+$'}{Math.abs(t.amount).toLocaleString('en-US', { minimumFractionDigits: 2 })}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><div className="caps">Account</div><div style={{ fontSize: 12 }}>{a.name}</div></div>
            <div><div className="caps">Source</div><div style={{ fontSize: 12 }}>{a.source}</div></div>
            <div><div className="caps">Posted</div><div className="mono" style={{ fontSize: 11 }}>{t.ts}</div></div>
            <div><div className="caps">Confidence</div><div style={{ fontSize: 12 }}><Confidence c={t.conf} /></div></div>
          </div>

          <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14 }}>
            <div className="caps" style={{ marginBottom: 6 }}>Smart Suggestions</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <div style={{ padding: '6px 8px', background: 'var(--bg-2)', border: '1px solid var(--line-2)', fontSize: 11, display: 'flex', justifyContent: 'space-between' }}>
                <span>Rename <span style={{ color: 'var(--fg-3)' }}>“{t.raw.split(' ')[0]}”</span> → <span style={{ color: 'var(--accent)' }}>“{t.merchant}”</span></span>
                <span className="mono" style={{ color: 'var(--fg-3)', fontSize: 10 }}>applies to 14 txns</span>
              </div>
              <div style={{ padding: '6px 8px', background: 'var(--bg-2)', border: '1px solid var(--line-2)', fontSize: 11, display: 'flex', justifyContent: 'space-between' }}>
                <span>Auto-categorize as <CatPill cat={t.cat} small /></span>
                <span className="mono" style={{ color: 'var(--pos)', fontSize: 10 }}>99% match</span>
              </div>
              <div style={{ padding: '6px 8px', background: 'var(--bg-2)', border: '1px solid var(--line-2)', fontSize: 11 }}>
                Create rule: <span className="mono" style={{ color: 'var(--accent)' }}>merchant ~= /AWS/ → infra</span>
              </div>
            </div>
          </div>

          <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14 }}>
            <div className="caps" style={{ marginBottom: 6 }}>Ledger Entries</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-1)', lineHeight: 1.7, background: 'var(--bg-0)', padding: 10, border: '1px solid var(--line)' }}>
              <div><span style={{ color: 'var(--fg-3)' }}>dr</span> 5100 · Cloud Infra &nbsp;&nbsp; <span style={{ float: 'right' }}>${Math.abs(t.amount).toFixed(2)}</span></div>
              <div><span style={{ color: 'var(--fg-3)' }}>cr</span> 1002 · Chase Ink &nbsp;&nbsp; <span style={{ float: 'right' }}>${Math.abs(t.amount).toFixed(2)}</span></div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn">Split</button>
            <button className="btn">Attach Receipt</button>
            <button className="btn">View Raw JSON</button>
          </div>
        </div>
      </aside>
    );
  }

  function Transactions() {
    const [filter, setFilter] = useState('all');
    const [sel, setSel] = useState(DATA.transactions[0]);

    const filtered = useMemo(() => {
      let t = DATA.transactions;
      if (filter === 'uncat') t = t.filter(x => x.conf < 0.8);
      else if (filter === 'pend') t = t.filter(x => x.pending);
      else if (filter === 'out') t = t.filter(x => x.amount < 0);
      else if (filter === 'in') t = t.filter(x => x.amount > 0);
      else if (filter === 'large') t = t.filter(x => Math.abs(x.amount) > 1000);
      return t;
    }, [filter]);

    return (
      <div style={{ display: 'flex', height: '100%', flexDirection: 'column' }}>
        <div style={{ padding: '20px 20px 12px' }}>
          <div className="page-head">
            <div>
              <div className="crumb">workspace<span className="sep">›</span>transactions</div>
              <h1 className="display">Transaction Hub</h1>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 6, letterSpacing: '0.1em' }}>
                {DATA.transactions.length} visible · 11 sources · last sync 2s ago · 7 uncategorized
              </div>
            </div>
          </div>
          <SourceMap />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', flex: 1, minHeight: 0, borderTop: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            <FilterBar filter={filter} setFilter={setFilter} />
            <div style={{ overflow: 'auto', flex: 1 }}>
              <table className="data">
                <thead>
                  <tr>
                    <th style={{ width: 28 }}></th>
                    <th style={{ width: 80 }}>Time</th>
                    <th>Merchant</th>
                    <th>Source</th>
                    <th>Category</th>
                    <th>Conf</th>
                    <th className="num">Amount</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map(t => (
                    <TxnRow key={t.id} t={t} selected={sel && sel.id === t.id} onSelect={() => setSel(t)} />
                  ))}
                </tbody>
              </table>
            </div>
          </div>
          <Inspector t={sel} onClose={() => setSel(null)} />
        </div>
      </div>
    );
  }

  window.TransactionsView = Transactions;
})();
