// screen-transactions.jsx — Transaksi list + filters

function ScreenTransactions({ theme, accent, scenario, onOpenSheet, auth }) {
  const [realTx, setRealTx] = React.useState(null);
  const [currentMonth] = React.useState(new Date());
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId || !window.sbGetTransactions) return;
    sbGetTransactions(familyId, currentMonth).then(function(r) {
      if (!r.error) setRealTx(r.data||[]);
    });
  }, [familyId]);
  function norm(t) {
    // Map category name → CATEGORIES key
    var rawCat = t.category ? (t.category.name||'').toLowerCase().replace(/\s+/g,'_') : '';
    var kind = t.type||t.kind||'expense';
    var catKey = rawCat;
    if (rawCat && !CATEGORIES[catKey]) {
      catKey = rawCat + '_ex';
      if (!CATEGORIES[catKey]) catKey = rawCat + '_in';
    }
    if (!catKey || !CATEGORIES[catKey]) catKey = kind==='income' ? 'lainnya_in' : 'lainnya_ex';
    return {id:t.id, kind:kind, amount:t.amount,
      cat:catKey, catLabel:(t.category&&t.category.name)||catKey,
      by:t.user_id||t.by, note:t.note, date:t.date,
      account_id:t.account_id,
      categoryObj:t.category, profileObj:t.profile};
  }
  const [filter, setFilter] = React.useState('all'); // all | income | expense
  const [memberFilter, setMemberFilter] = React.useState('all');

  const isAuth = !!(auth && auth.family);
  const allTx = isAuth ? (realTx || []).map(norm) : scenario.transactions;
  let txs = allTx;
  if (filter !== 'all') txs = txs.filter(function(t){ return t.kind===filter; });
  if (memberFilter !== 'all') txs = txs.filter(function(t){ return t.by===memberFilter; });

  // group by relative day
  const groups = {};
  txs.forEach((t) => {
    const key = fmtRelDay(t.date);
    (groups[key] = groups[key] || []).push(t);
  });

  const totals = {
    income:  allTx.filter(function(t){return t.kind==='income';}).reduce(function(a,t){return a+t.amount;},0),
    expense: allTx.filter(function(t){return t.kind==='expense';}).reduce(function(a,t){return a+t.amount;},0),
  };

  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ padding: '56px 20px 16px' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          marginBottom: 4,
        }}>
          <h1 style={{
            margin: 0, fontSize: 28, fontWeight: 800, color: theme.fg1,
            letterSpacing: '-0.025em',
          }}>Transaksi</h1>
          <button style={iconBtn2(theme)}>
            <Icon name="sliders-horizontal" size={18} color={theme.fg1} stroke={1.8} />
          </button>
        </div>
        <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500 }}>
          {allTx.length} entri · Bulan ini
        </div>
      </div>

      {/* Income / Expense totals */}
      <div style={{ padding: '0 20px 16px', display: 'flex', gap: 10 }}>
        <TxSummaryPill theme={theme} kind="income" label="Masuk" amount={totals.income} />
        <TxSummaryPill theme={theme} kind="expense" label="Keluar" amount={totals.expense} />
      </div>

      {/* Filter tabs */}
      <div style={{ padding: '0 20px 12px', display: 'flex', gap: 8 }}>
        {[
          { id: 'all', label: 'Semua' },
          { id: 'income', label: 'Pemasukan' },
          { id: 'expense', label: 'Pengeluaran' },
        ].map((t) => (
          <Chip key={t.id} active={filter === t.id}
                onClick={() => setFilter(t.id)} theme={theme}>{t.label}</Chip>
        ))}
      </div>

      {/* Member filter chips */}
      <div style={{
        padding: '0 20px 16px', display: 'flex', gap: 8,
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        <button onClick={() => setMemberFilter('all')} style={{
          appearance: 'none', border: `1px solid ${memberFilter === 'all' ? theme.fg1 : theme.border}`,
          background: memberFilter === 'all' ? theme.fg1 : 'transparent',
          color: memberFilter === 'all' ? theme.surface : theme.fg2,
          padding: '6px 12px', borderRadius: 999,
          fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <Icon name="users" size={13} stroke={1.85} />
          Semua anggota
        </button>
        {(isAuth
            ? (auth.profile ? [{ id: auth.profile.id, name: auth.profile.full_name||'Kamu', short: (auth.profile.full_name||'').split(' ')[0], color: '#10b981' }] : [])
            : scenario.members
          ).map((m) => {
          const on = memberFilter === m.id;
          return (
            <button key={m.id} onClick={() => setMemberFilter(m.id)} style={{
              appearance: 'none', border: `1px solid ${on ? m.color : theme.border}`,
              background: on ? m.color + '14' : 'transparent',
              padding: '4px 12px 4px 4px', borderRadius: 999,
              fontSize: 12, fontWeight: 600,
              color: on ? m.color : theme.fg2,
              cursor: 'pointer', whiteSpace: 'nowrap',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <Avatar member={m} size={20} />
              {m.short}
            </button>
          );
        })}
      </div>

      {/* Grouped transactions */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {Object.entries(groups).map(([day, items]) => {
          const dayTotal = items.reduce((a, t) => a + (t.kind === 'expense' ? -t.amount : t.amount), 0);
          return (
            <div key={day}>
              <div style={{
                padding: '0 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: theme.fg2,
                              letterSpacing: '0.04em', textTransform: 'uppercase' }}>{day}</div>
                <div style={{
                  fontSize: 11, color: dayTotal < 0 ? theme.fg2 : theme.success,
                  fontWeight: 600, fontVariantNumeric: 'tabular-nums',
                }}>{fmtRp(dayTotal, { sign: true, short: true })}</div>
              </div>
              <div style={{ padding: '0 20px' }}>
                <Card theme={theme} padding={4} radius={16}>
                  {items.map((tx, i) => (
                    <TxRow key={tx.id} tx={tx} scenario={scenario} theme={theme}
                           accent={accent} divider={i < items.length - 1} />
                  ))}
                </Card>
              </div>
            </div>
          );
        })}

        {Object.keys(groups).length === 0 && (
          <EmptyState theme={theme} icon="inbox" title="Belum ada transaksi"
                      hint="Coba ubah filter atau tambahkan transaksi baru." />
        )}
      </div>
    </div>
  );
}

function iconBtn2(theme) {
  return {
    appearance: 'none', border: 0, cursor: 'pointer',
    width: 38, height: 38, borderRadius: 12,
    background: theme.surface,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: theme.shadow1,
    border: `0.5px solid ${theme.border}`,
  };
}

function TxSummaryPill({ theme, kind, label, amount }) {
  const isIncome = kind === 'income';
  return (
    <div style={{
      flex: 1, background: theme.surface,
      border: `0.5px solid ${theme.border}`,
      borderRadius: 14, padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: theme.shadow1,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 10,
        background: isIncome ? theme.successSoft : theme.dangerSoft,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={isIncome ? 'arrow-down-left' : 'arrow-up-right'}
              size={16} stroke={2.1}
              color={isIncome ? theme.success : theme.danger} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500 }}>{label}</div>
        <div style={{
          fontSize: 14, fontWeight: 800, color: theme.fg1,
          letterSpacing: '-0.015em', fontVariantNumeric: 'tabular-nums',
          whiteSpace: 'nowrap',
        }}>{fmtRp(amount, { short: true })}</div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenTransactions, iconBtn2, TxSummaryPill });
