// Transactions page — full list with filters, search, sort, group-by-day

function TxnsPage() {
  const { setDrawerTxn, dataVersion } = useApp();
  const [q, setQ] = useState('');
  const [catFilter, setCatFilter] = useState('all');
  const [sourceFilter, setSourceFilter] = useState('all');
  const [sort, setSort] = useState('date-desc');
  // Default to current month index (the most recent in D.months[])
  const [monthIdx, setMonthIdx] = useState(() => Math.max(0, (D.months?.length || 1) - 1));

  // When data refreshes (e.g. after a scrape), keep monthIdx in range and
  // jump to the most recent month so the user sees freshly-pulled data.
  useEffect(() => {
    const len = D.months?.length || 0;
    if (len === 0) return;
    if (monthIdx >= len) setMonthIdx(len - 1);
  }, [dataVersion]);

  const months = D.months || [];
  const activeMonth = months[monthIdx] || D.current;

  const txns = useMemo(() => {
    let arr = (activeMonth?.txns || []).slice();
    if (q) {
      const lq = q.toLowerCase();
      arr = arr.filter(t => t.description.toLowerCase().includes(lq) || t.category.includes(q));
    }
    if (catFilter !== 'all') arr = arr.filter(t => t.category === catFilter);
    if (sourceFilter !== 'all') arr = arr.filter(t => t.source === sourceFilter);
    if (sort === 'date-desc') arr.sort((a,b) => b.date.localeCompare(a.date));
    if (sort === 'date-asc') arr.sort((a,b) => a.date.localeCompare(b.date));
    if (sort === 'amount-desc') arr.sort((a,b) => a.amount - b.amount);
    if (sort === 'amount-asc')  arr.sort((a,b) => b.amount - a.amount);
    return arr;
  }, [q, catFilter, sourceFilter, sort, monthIdx, dataVersion]);

  const grouped = useMemo(() => {
    const g = {};
    txns.forEach(t => { (g[t.date] ||= []).push(t); });
    return Object.entries(g);
  }, [txns]);

  const totalShown = txns.filter(t => t.amount < 0).reduce((s,t) => s + (-t.amount), 0);

  return (
    <div className="fade-in" style={{ padding: '32px 40px 60px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 22 }}>
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>עסקאות</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 4 }}>
            {activeMonth?.label || ''} · {txns.length} עסקאות · סך {fmtILS(totalShown)}
          </div>
        </div>
      </div>

      {/* Month picker — horizontal scroll of all loaded months */}
      <div style={{
        display: 'flex', gap: 6, marginBottom: 14, overflowX: 'auto', paddingBottom: 6,
        scrollbarWidth: 'thin',
      }}>
        {months.map((m, i) => {
          const active = i === monthIdx;
          const isEmpty = (m.txns?.length || 0) === 0;
          return (
            <button
              key={`${m.year}-${m.month}`}
              onClick={() => setMonthIdx(i)}
              disabled={isEmpty}
              title={isEmpty ? 'אין עסקאות בחודש זה' : m.label}
              style={{
                padding: '6px 12px', borderRadius: 8,
                background: active ? 'var(--ink)' : 'var(--surface)',
                color: active ? 'var(--bg)' : (isEmpty ? 'var(--ink-soft)' : 'var(--ink)'),
                border: '0.5px solid var(--rule)',
                fontSize: 12, fontWeight: active ? 600 : 500,
                cursor: isEmpty ? 'not-allowed' : 'pointer',
                opacity: isEmpty ? 0.4 : 1,
                whiteSpace: 'nowrap',
                fontFeatureSettings: '"tnum"',
              }}>
              {m.shortLabel} {String(m.year).slice(-2)}
              {!isEmpty && (
                <span style={{ marginInlineStart: 6, fontSize: 10.5, opacity: .7 }}>·{m.txns.length}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Filter bar */}
      <Surface padded={false} style={{ marginBottom: 16, padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 180 }}>
          <span style={{ position: 'absolute', insetInlineStart: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-soft)', fontSize: 12 }}>⌕</span>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="חיפוש לפי שם, סכום, קטגוריה…"
                 style={{ width: '100%', padding: '8px 32px 8px 12px', border: '0.5px solid var(--rule)',
                          borderRadius: 9, background: 'var(--bg-deep)', fontSize: 13, outline: 'none' }} />
        </div>
        <FilterSelect value={catFilter} onChange={setCatFilter}
          options={[{value:'all',label:'כל הקטגוריות'}, ...Object.keys(D.categories).map(c => ({value:c, label:c}))]} />
        <FilterSelect value={sourceFilter} onChange={setSourceFilter}
          options={[{value:'all',label:'כל המקורות'},{value:'max',label:'Max'},{value:'visaCal',label:'Visa Cal'},{value:'isracard',label:'Isracard'}]} />
        <Segmented options={[
          {value:'date-desc',label:'חדש'},{value:'date-asc',label:'ישן'},
          {value:'amount-desc',label:'גבוה'},{value:'amount-asc',label:'נמוך'},
        ]} value={sort} onChange={setSort} />
      </Surface>

      <Surface padded={false}>
        {grouped.length === 0 && <EmptyState icon="⌕" title="אין תוצאות" sub="נסה לשנות את הפילטרים או החיפוש." />}
        {grouped.map(([date, items]) => {
          const dayTotal = items.filter(t => t.amount < 0).reduce((s,t) => s + (-t.amount), 0);
          return (
            <div key={date}>
              <div style={{
                padding: '10px 22px', background: 'var(--bg-deep)', display: 'flex', justifyContent: 'space-between',
                fontSize: 11.5, color: 'var(--ink-soft)', borderBottom: '0.5px solid var(--rule)', position: 'sticky', top: 0,
              }}>
                <span style={{ fontWeight: 600, color: 'var(--ink-2)' }}>{fmtDate(date)}</span>
                <span className="tnum" style={{ fontFamily: 'var(--font-mono)' }}>{items.length} · {fmtILS(-dayTotal)}</span>
              </div>
              {items.map(t => {
                const c = D.categories[t.category] || {};
                return (
                  <div key={t.id} onClick={() => setDrawerTxn(t)} style={{
                    display: 'grid', gridTemplateColumns: '40px 1fr 130px 80px 100px',
                    gap: 14, alignItems: 'center', padding: '10px 22px',
                    borderBottom: '0.5px solid var(--rule)', cursor: 'pointer',
                  }} onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-deep)'}
                     onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                    <div style={{ width: 32, height: 32, borderRadius: 9, background: `${c.color}22`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13 }}>{c.icon}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {t.anomaly && <span style={{ color: 'var(--alert)', marginInlineEnd: 5 }}>!</span>}
                        {t.description}
                      </div>
                      <div style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{t.recurring && '↻ קבוע · '}{t.id}</div>
                    </div>
                    <div>
                      <span style={{ fontSize: 11, padding: '3px 9px', background: 'var(--bg-deep)',
                                     border: '0.5px solid var(--rule)', borderRadius: 999, color: 'var(--ink-2)' }}>{t.category}</span>
                    </div>
                    <div style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-soft)', textTransform: 'uppercase' }}>{t.source}</div>
                    <div className="tnum" style={{ fontSize: 14, fontWeight: 600, textAlign: 'left', color: t.amount > 0 ? 'var(--positive)' : 'var(--ink)' }}>
                      {fmtILS(t.amount)}
                    </div>
                  </div>
                );
              })}
            </div>
          );
        })}
      </Surface>
    </div>
  );
}

function FilterSelect({ value, onChange, options }) {
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      padding: '7px 28px 7px 10px', borderRadius: 9, background: 'var(--bg-deep)',
      border: '0.5px solid var(--rule)', fontSize: 12.5, cursor: 'pointer', outline: 'none',
    }}>
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  );
}

window.TxnsPage = TxnsPage;
