/* ============================================================================
   BetPrince Sportsbook — Transaction History Screen
   Full ledger: deposits, withdrawals, bet settlements, cashouts, bonuses.
   Depends on sb-atoms.jsx + sb-info-screens.jsx (InfoHeader, SectionTitle).
   ============================================================================ */

const TRANSACTION_TYPES = {
  deposit:    { label: 'Deposit',    icon: 'arrow-down-left', color: 'var(--green)',      bg: 'rgba(22,163,74,0.1)' },
  withdrawal: { label: 'Withdrawal', icon: 'arrow-up-right',  color: 'var(--live)',       bg: 'rgba(239,68,68,0.1)' },
  bet_placed: { label: 'Bet Placed', icon: 'receipt-text',    color: 'var(--blue)',       bg: 'var(--blue-tint)' },
  bet_won:    { label: 'Bet Won',    icon: 'trophy',          color: 'var(--green)',      bg: 'rgba(22,163,74,0.1)' },
  bet_lost:   { label: 'Bet Lost',   icon: 'circle-x',       color: 'var(--ink-3)',      bg: 'var(--card-2)' },
  cashout:    { label: 'Cashout',    icon: 'banknote',        color: 'var(--green)',      bg: 'rgba(22,163,74,0.1)' },
  bonus:      { label: 'Bonus',      icon: 'gift',            color: 'var(--gold-strong)',bg: 'rgba(247,197,61,0.14)' },
};

/* Seed transactions — realistic NGN amounts for a sportsbook user */
const SEED_TRANSACTIONS = [
  // Today
  { id: 't01', type: 'bet_placed', amount: -2000,   status: 'completed', time: '20:34', date: '2026-06-04',
    desc: 'Single — Galatasaray vs Fenerbahçe', ref: 'C3F0A12D' },
  { id: 't02', type: 'deposit',    amount: 50000,   status: 'completed', time: '19:12', date: '2026-06-04',
    desc: 'Bank Transfer · Paystack', ref: 'PAY-8A3F21' },
  { id: 't03', type: 'bet_placed', amount: -1000,   status: 'completed', time: '15:40', date: '2026-06-04',
    desc: 'Single — Haiti vs New Zealand', ref: '16B6E1F1' },

  // Yesterday
  { id: 't04', type: 'bet_won',    amount: 41800,   status: 'completed', time: '23:10', date: '2026-06-03',
    desc: 'Single — Correct Score 2-1', ref: 'A7C2D90F' },
  { id: 't05', type: 'bet_placed', amount: -5000,   status: 'completed', time: '21:15', date: '2026-06-03',
    desc: 'Single — Galatasaray vs Fenerbahçe', ref: 'A7C2D90F' },
  { id: 't06', type: 'withdrawal', amount: -100000, status: 'completed', time: '16:30', date: '2026-06-03',
    desc: 'GTBank · ****4821', ref: 'WD-6E9C01' },
  { id: 't07', type: 'deposit',    amount: 200000,  status: 'completed', time: '14:05', date: '2026-06-03',
    desc: 'Bank Transfer · Paystack', ref: 'PAY-2B11F7' },
  { id: 't08', type: 'bonus',      amount: 200000,  status: 'completed', time: '14:05', date: '2026-06-03',
    desc: 'First Deposit Bonus ×2', ref: 'BNS-001' },

  // Jun 2
  { id: 't09', type: 'bet_won',    amount: 251000,  status: 'completed', time: '22:45', date: '2026-06-02',
    desc: 'Multiple — 2 selections', ref: 'E8A4CC17' },
  { id: 't10', type: 'bet_placed', amount: -10000,  status: 'completed', time: '20:00', date: '2026-06-02',
    desc: 'Multiple — Real Madrid, PSG', ref: 'E8A4CC17' },
  { id: 't11', type: 'bet_lost',   amount: -3000,   status: 'completed', time: '18:30', date: '2026-06-02',
    desc: 'Single — Over 2.5 Goals', ref: 'B8C4E210' },

  // Jun 1
  { id: 't12', type: 'deposit',    amount: 100000,  status: 'completed', time: '10:22', date: '2026-06-01',
    desc: 'Crypto · USDT (TRC-20)', ref: 'CRY-4F0A12' },
  { id: 't13', type: 'cashout',    amount: 14000,   status: 'completed', time: '09:45', date: '2026-06-01',
    desc: 'Cashout — Ceuta vs Castellón', ref: '7A0E33B2' },
  { id: 't14', type: 'bet_placed', amount: -5000,   status: 'completed', time: '08:30', date: '2026-06-01',
    desc: 'Single — Ceuta vs Castellón', ref: '7A0E33B2' },

  // May 31
  { id: 't15', type: 'withdrawal', amount: -50000,  status: 'pending',   time: '22:00', date: '2026-05-31',
    desc: 'Access Bank · ****2917', ref: 'WD-1C3A45' },
  { id: 't16', type: 'bet_won',    amount: 18500,   status: 'completed', time: '20:15', date: '2026-05-31',
    desc: 'Single — Enyimba vs Kano Pillars', ref: '92F4A5B1' },
  { id: 't17', type: 'bet_placed', amount: -5000,   status: 'completed', time: '17:00', date: '2026-05-31',
    desc: 'Single — Enyimba vs Kano Pillars', ref: '92F4A5B1' },
];

/* Group transactions by display date */
function groupByDate(txns) {
  const today = '2026-06-04';
  const yesterday = '2026-06-03';
  const groups = {};
  txns.forEach(t => {
    let label;
    if (t.date === today) label = 'Today';
    else if (t.date === yesterday) label = 'Yesterday';
    else {
      const d = new Date(t.date + 'T00:00:00');
      const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      label = months[d.getMonth()] + ' ' + d.getDate();
    }
    if (!groups[label]) groups[label] = [];
    groups[label].push(t);
  });
  return Object.entries(groups);
}

/* Format amount with sign */
function fmtAmount(amount) {
  const abs = Math.abs(amount);
  const formatted = abs.toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return (amount >= 0 ? '+' : '−') + '₦' + formatted;
}

/* ---- Single transaction row ------------------------------------------------ */
function TxnRow({ txn, isLast }) {
  const meta = TRANSACTION_TYPES[txn.type];
  const isPositive = txn.amount > 0;
  const [expanded, setExpanded] = useState(false);

  return (
    <div>
      <button onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%',
          padding: '14px 16px', background: 'transparent', border: 'none',
          borderBottom: (!isLast && !expanded) ? '1px solid var(--line)' : 'none',
          cursor: 'pointer', textAlign: 'left' }}>
        {/* Icon */}
        <span style={{ width: 40, height: 40, borderRadius: 12, background: meta.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={meta.icon} size={18} color={meta.color} />
        </span>

        {/* Label + desc */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
              color: 'var(--ink)' }}>{meta.label}</span>
            {txn.status === 'pending' && (
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 10.5,
                padding: '2px 7px', borderRadius: 999, background: 'rgba(247,197,61,0.2)',
                color: 'var(--gold-strong)' }}>Pending</span>
            )}
          </div>
          <div style={{ fontFamily: 'var(--font-text)', fontSize: 12.5, color: 'var(--ink-3)',
            marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {txn.desc}
          </div>
        </div>

        {/* Amount + time */}
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div className="sb-num" style={{ fontWeight: 700, fontSize: 14.5,
            color: isPositive ? 'var(--green)' : (txn.type === 'bet_lost' ? 'var(--ink-3)' : 'var(--ink)'),
            whiteSpace: 'nowrap' }}>
            {fmtAmount(txn.amount)}
          </div>
          <div className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>
            {txn.time}
          </div>
        </div>
      </button>

      {/* Expanded detail */}
      {expanded && (
        <div style={{ padding: '0 16px 14px', borderBottom: !isLast ? '1px solid var(--line)' : 'none' }}>
          <div style={{ background: 'var(--card-2)', borderRadius: 12, border: '1px solid var(--line)',
            padding: '12px 14px' }}>
            {[
              ['Type', meta.label],
              ['Amount', fmtAmount(txn.amount)],
              ['Status', txn.status === 'completed' ? 'Completed' : 'Pending'],
              ['Reference', txn.ref],
              ['Date', txn.date + ' · ' + txn.time],
            ].map(([k, v], i) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '7px 0', borderBottom: i < 4 ? '1px solid var(--line)' : 'none' }}>
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13,
                  color: 'var(--ink-3)' }}>{k}</span>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 13,
                  color: k === 'Status'
                    ? (txn.status === 'completed' ? 'var(--green)' : 'var(--gold-strong)')
                    : k === 'Amount'
                      ? (txn.amount >= 0 ? 'var(--green)' : 'var(--ink)')
                      : 'var(--ink)' }}>
                  {v}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- Summary stat card ----------------------------------------------------- */
function SummaryStat({ icon, label, value, color, bg }) {
  return (
    <div style={{ flex: 1, background: 'var(--card)', borderRadius: 14, border: '1px solid var(--line)',
      padding: '14px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ width: 32, height: 32, borderRadius: 10, background: bg,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={16} color={color} />
      </span>
      <div>
        <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 11.5,
          color: 'var(--ink-3)', marginBottom: 3 }}>{label}</div>
        <div className="sb-num" style={{ fontWeight: 700, fontSize: 16, color: 'var(--ink)',
          letterSpacing: '-0.01em' }}>{value}</div>
      </div>
    </div>
  );
}

/* ============================================================================
   TRANSACTION HISTORY SCREEN
   ============================================================================ */
function TransactionHistoryScreen({ onBack, transactions }) {
  const [filter, setFilter] = useState('All');
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const searchRef = useRef(null);

  useEffect(() => {
    if (searchOpen && searchRef.current) searchRef.current.focus();
  }, [searchOpen]);

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  const FILTERS = ['All', 'Deposits', 'Withdrawals', 'Bets', 'Bonuses'];

  const filterMap = {
    'All':         null,
    'Deposits':    ['deposit'],
    'Withdrawals': ['withdrawal'],
    'Bets':        ['bet_placed', 'bet_won', 'bet_lost', 'cashout'],
    'Bonuses':     ['bonus'],
  };

  const source = transactions && transactions.length > 0 ? transactions : SEED_TRANSACTIONS;
  let filtered = source;
  if (filterMap[filter]) {
    filtered = filtered.filter(t => filterMap[filter].includes(t.type));
  }
  if (searchQuery.trim()) {
    const q = searchQuery.trim().toLowerCase();
    filtered = filtered.filter(t =>
      (t.desc || '').toLowerCase().includes(q) ||
      (t.ref || '').toLowerCase().includes(q) ||
      (TRANSACTION_TYPES[t.type] && TRANSACTION_TYPES[t.type].label.toLowerCase().includes(q))
    );
  }

  const groups = groupByDate(filtered);

  /* Summary calculations */
  const totalIn = source.filter(t => t.amount > 0).reduce((s, t) => s + t.amount, 0);
  const totalOut = source.filter(t => t.amount < 0).reduce((s, t) => s + Math.abs(t.amount), 0);

  const fmtShort = (n) => {
    if (n >= 1000000) return '₦' + (n / 1000000).toFixed(1) + 'M';
    if (n >= 1000) return '₦' + (n / 1000).toFixed(0) + 'K';
    return '₦' + n.toLocaleString('en-NG');
  };

  return (
    <div style={{ minHeight: '100%', background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
        background: 'var(--header-bg)' }}>
        <button onClick={onBack} style={{ width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.16)', color: 'var(--header-ink)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="chevron-left" size={20} />
        </button>
        <span style={{ flex: 1, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17,
          color: 'var(--header-ink)' }}>Transactions</span>
        <button onClick={() => { setSearchOpen(!searchOpen); if (searchOpen) setSearchQuery(''); }}
          style={{ width: 36, height: 36, borderRadius: 999, border: 'none',
            background: searchOpen ? 'rgba(255,255,255,0.28)' : 'rgba(255,255,255,0.16)',
            color: 'var(--header-ink)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={searchOpen ? 'x' : 'search'} size={18} />
        </button>
      </div>

      {/* Search bar (collapsible) */}
      {searchOpen && (
        <div style={{ padding: '12px 14px 6px', background: 'var(--bg)' }}>
          <div style={{ position: 'relative' }}>
            <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
              color: 'var(--ink-3)', display: 'flex' }}>
              <Icon name="search" size={16} />
            </span>
            <input ref={searchRef} type="text" placeholder="Search by description or reference…"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              style={{ width: '100%', padding: '12px 14px 12px 40px',
                fontFamily: 'var(--font-text)', fontWeight: 500, fontSize: 14,
                color: 'var(--ink)', background: 'var(--card)',
                border: '1.5px solid var(--line-2)', borderRadius: 12, outline: 'none',
                boxSizing: 'border-box', caretColor: 'var(--blue)' }}
              onFocus={(e) => { e.target.style.borderColor = 'var(--blue)'; }}
              onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
            />
          </div>
        </div>
      )}



      {/* Filter chips */}
      <div className="sb-hx" style={{ display: 'flex', gap: 8, padding: '14px 14px 6px',
        overflowX: 'auto', scrollbarWidth: 'none' }}>
        {FILTERS.map(f => (
          <Chip key={f} on={filter === f} onClick={() => setFilter(f)}>{f}</Chip>
        ))}
      </div>

      {/* Transaction groups */}
      <div style={{ padding: '6px 14px 100px' }}>
        {groups.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 30px', color: 'var(--ink-3)' }}>
            <Icon name="search-x" size={40} color="var(--ink-3)" />
            <div style={{ marginTop: 14, fontFamily: 'var(--font-text)', fontWeight: 600,
              fontSize: 15, color: 'var(--ink-2)' }}>
              No transactions found
            </div>
            <div style={{ marginTop: 4, fontSize: 13 }}>
              {searchQuery ? 'Try a different search term.' : 'No transactions match this filter.'}
            </div>
          </div>
        ) : groups.map(([dateLabel, txns]) => (
          <div key={dateLabel}>
            {/* Date group header */}
            <div style={{ padding: '16px 2px 8px' }}>
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 800, fontSize: 11.5,
                letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                {dateLabel}
              </span>
            </div>

            {/* Transactions card */}
            <div style={{ borderRadius: 14, overflow: 'hidden', border: '1px solid var(--line)',
              boxShadow: 'var(--shadow-card)', background: 'var(--card)' }}>
              {txns.map((txn, i) => (
                <TxnRow key={txn.id} txn={txn} isLast={i === txns.length - 1} />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TransactionHistoryScreen });
