// transaction-monitor.jsx — Transaction Monitor page for Hibank QRIS BackOffice
function TransactionMonitorPage({ merchants, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';

  // Seed initial mock transactions
  const [transactions, setTransactions] = React.useState([
    { id: 'TX-260624-8831', time: '2026-06-24T11:05:12', merchantId: 'MRC-00246', merchantName: 'Kopi Senja Nusantara', type: 'QRIS MPM (GoPay)', amount: 45000, mdr: 315, net: 44685, status: 'success', customerName: 'Aditya Pratama', rrn: '992817283912', terminalId: 'POS-001', issuer: 'GoPay' },
    { id: 'TX-260624-8830', time: '2026-06-24T10:58:44', merchantId: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan', type: 'QRIS MPM (BCA)', amount: 285000, mdr: 1995, net: 283005, status: 'success', customerName: 'Siti Aminah', rrn: '992817283911', terminalId: 'POS-002', issuer: 'BCA Mobile' },
    { id: 'TX-260624-8829', time: '2026-06-24T10:42:15', merchantId: 'MRC-00245', merchantName: 'Toko Bangunan Maju Jaya', type: 'QRIS MPM (Dana)', amount: 1540000, mdr: 10780, net: 1529220, status: 'success', customerName: 'Hendra Wijaya', rrn: '992817283910', terminalId: 'POS-001', issuer: 'Dana' },
    { id: 'TX-260624-8828', time: '2026-06-24T10:30:00', merchantId: 'MRC-00246', merchantName: 'Kopi Senja Nusantara', type: 'QRIS MPM (OVO)', amount: 28000, mdr: 196, net: 27804, status: 'pending', customerName: 'Fajar Nugraha', rrn: '992817283909', terminalId: 'POS-003', issuer: 'OVO' },
    { id: 'TX-260624-8827', time: '2026-06-24T10:15:33', merchantId: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan', type: 'QRIS MPM (ShopeePay)', amount: 450000, mdr: 3150, net: 446850, status: 'failed', customerName: 'Rina Marlina', rrn: '992817283908', terminalId: 'POS-001', issuer: 'ShopeePay' },
    { id: 'TX-260624-8826', time: '2026-06-24T09:55:12', merchantId: 'MRC-00246', merchantName: 'Kopi Senja Nusantara', type: 'QRIS CPM (Hibank)', amount: 120000, mdr: 840, net: 119160, status: 'success', customerName: 'Budi Santoso', rrn: '992817283907', terminalId: 'POS-002', issuer: 'LinkAja' },
    { id: 'TX-260624-8825', time: '2026-06-24T09:41:00', merchantId: 'MRC-00245', merchantName: 'Toko Bangunan Maju Jaya', type: 'QRIS MPM (Hibank)', amount: 75000, mdr: 525, net: 74475, status: 'refunded', customerName: 'Dewi Lestari', rrn: '992817283906', terminalId: 'POS-002', issuer: 'GoPay' },
    { id: 'TX-260624-8824', time: '2026-06-24T09:12:05', merchantId: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan', type: 'QRIS MPM (Hibank)', amount: 95000, mdr: 665, net: 94335, status: 'success', customerName: 'Joko Widodo', rrn: '992817283905', terminalId: 'POS-003', issuer: 'OVO' }
  ]);

  // Filters state
  const [searchTerm, setSearchTerm] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [merchantFilter, setMerchantFilter] = React.useState('all');

  // Modal / Drawer state
  const [selectedTx, setSelectedTx] = React.useState(null);
  const [showRefundModal, setShowRefundModal] = React.useState(false);
  const [refundReason, setRefundReason] = React.useState('');
  const [toastMessage, setToastMessage] = React.useState(null);

  // Formatting helpers
  const fmtRp = (v) => {
    return 'Rp ' + Number(v).toLocaleString('id-ID');
  };

  const fmtDate = (iso) => {
    const d = new Date(iso);
    return d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }) + ' ' +
      d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  };

  // Helper: Trigger toast message
  const triggerToast = (msg) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(null), 3000);
  };

  // Process Refund action
  const handleRefund = () => {
    if (!selectedTx || !refundReason.trim()) return;
    setTransactions(prev => prev.map(t => {
      if (t.id !== selectedTx.id) return t;
      return {
        ...t,
        status: 'refunded',
        refundReason: refundReason.trim(),
        refundAt: new Date().toISOString()
      };
    }));
    triggerToast(`Transaksi ${selectedTx.id} berhasil di-refund.`);
    setShowRefundModal(false);
    setSelectedTx(null);
    setRefundReason('');
  };

  // Simulator: Generate a random transaction
  const handleSimulateTransaction = () => {
    const randomMerchants = approvedMerchants.length > 0 ? approvedMerchants : [
      { id: 'MRC-00246', merchantName: 'Kopi Senja Nusantara' },
      { id: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan' },
      { id: 'MRC-00245', merchantName: 'Toko Bangunan Maju Jaya' }
    ];
    const merchant = randomMerchants[Math.floor(Math.random() * randomMerchants.length)];
    const issuers = ['GoPay', 'OVO', 'Dana', 'ShopeePay', 'BCA Mobile', 'LinkAja', 'HiBank'];
    const issuer = issuers[Math.floor(Math.random() * issuers.length)];
    const types = [`QRIS MPM (${issuer})`, `QRIS CPM (${issuer})`];
    const type = types[Math.floor(Math.random() * types.length)];
    const statuses = ['success', 'success', 'success', 'pending', 'failed'];
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const amount = Math.floor(Math.random() * 45 + 1) * 10000; // 10k to 450k
    const mdr = Math.floor(amount * 0.007);
    const net = amount - mdr;
    const txId = `TX-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${Math.floor(Math.random() * 9000 + 1000)}`;
    const names = ['Andi', 'Siti', 'Budi', 'Rina', 'Dedi', 'Lina', 'Hendra', 'Dewi', 'Ahmad', 'Mega'];
    const customerName = names[Math.floor(Math.random() * names.length)] + ' ' + ['Wijaya', 'Rahayu', 'Santoso', 'Marlina', 'Kurniawan', 'Lestari'][Math.floor(Math.random() * 6)];
    const rrn = Math.floor(Math.random() * 900000000000 + 100000000000).toString();
    const terminalId = `POS-00${Math.floor(Math.random() * 3 + 1)}`;

    const newTx = {
      id: txId,
      time: new Date().toISOString(),
      merchantId: merchant.id,
      merchantName: merchant.merchantName,
      type,
      amount,
      mdr,
      net,
      status,
      customerName,
      rrn,
      terminalId,
      issuer
    };

    setTransactions(prev => [newTx, ...prev]);
    triggerToast(`Transaksi baru masuk: ${fmtRp(amount)} di ${merchant.merchantName} (${status.toUpperCase()})`);
  };

  // Find approved merchants list for dropdown filter
  const approvedMerchants = merchants ? merchants.filter(m => m.status === 'approved') : [];

  // Filtered transactions
  const filteredTxs = transactions.filter(t => {
    const matchesSearch = t.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
      t.customerName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      t.rrn.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'all' || t.status === statusFilter;
    const matchesMerchant = merchantFilter === 'all' || t.merchantId === merchantFilter;
    return matchesSearch && matchesStatus && matchesMerchant;
  });

  // Calculate statistics
  const totalVolume = transactions.filter(t => t.status === 'success').reduce((sum, t) => sum + t.amount, 0);
  const successCount = transactions.filter(t => t.status === 'success').length;
  const totalCount = transactions.filter(t => t.status !== 'failed').length;
  const successRate = totalCount > 0 ? ((successCount / totalCount) * 100).toFixed(1) : '100';
  const pendingVolume = transactions.filter(t => t.status === 'pending').reduce((sum, t) => sum + t.amount, 0);

  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>

      {/* Header & Simulator Button */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Transaction Monitor</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Monitor Transaksi QRIS</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Pantau seluruh transaksi QRIS merchant secara real-time dan kelola pembatalan/refund dana.</p>
        </div>

        {/* Live Simulator Button */}
        <button
          onClick={handleSimulateTransaction}
          style={{
            background: `linear-gradient(135deg, ${TEAL}, #0041A8)`, color: '#fff', border: 'none', borderRadius: 8,
            padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center',
            gap: 8, boxShadow: `0 4px 14px ${TEAL}25`, transition: 'all 200ms'
          }}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
        >
          <i className="bx bx-play-circle" style={{ fontSize: 18 }} />
          Simulasikan Transaksi Baru
        </button>
      </div>

      {/* ── STATS SUMMARY CARDS ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16, marginBottom: 24 }}>
        {[
          { label: 'Volume Transaksi Sukses', value: fmtRp(totalVolume), sub: 'Dana terkumpul bersih', icon: 'bx-wallet', color: TEAL },
          { label: 'Tingkat Keberhasilan', value: `${successRate}%`, sub: 'Rasio transaksi berhasil', icon: 'bx-trending-up', color: '#74b50c' },
          { label: 'Transaksi Menunggu (Pending)', value: fmtRp(pendingVolume), sub: 'Proses verifikasi gateway', icon: 'bx-time-five', color: '#d9920b' },
          { label: 'Total Transaksi Masuk', value: `${transactions.length} Trx`, sub: 'Termasuk gagal & refund', icon: 'bx-transfer', color: ORANGE }
        ].map((card, i) => (
          <div
            key={i}
            style={{
              background: '#fff', padding: 20, borderRadius: 14, border: '1px solid #efefef',
              boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16
            }}
          >
            <div style={{ width: 44, height: 44, borderRadius: 10, background: `${card.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`bx ${card.icon}`} style={{ fontSize: 22, color: card.color }} />
            </div>
            <div>
              <div style={{ fontSize: 12, color: '#a7a8a8', fontWeight: 600 }}>{card.label}</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: '#171919', marginTop: 4 }}>{card.value}</div>
              <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── FILTERS PANEL ── */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', padding: 20, marginBottom: 24 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16 }}>

          {/* Search Input */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#f6f6f6', border: '1.5px solid #efefef', borderRadius: 8, padding: '8px 12px' }}>
            <i className="bx bx-search" style={{ color: '#a7a8a8' }} />
            <input
              type="text"
              placeholder="Cari ID Transaksi, RRN, Customer..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 13, color: '#171919', width: '100%', fontFamily: 'inherit' }}
            />
          </div>

          {/* Status Filter */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#f6f6f6', border: '1.5px solid #efefef', borderRadius: 8, padding: '8px 12px' }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', whiteSpace: 'nowrap' }}>Status:</span>
            <select
              value={statusFilter}
              onChange={e => setStatusFilter(e.target.value)}
              style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 13, color: '#171919', cursor: 'pointer', width: '100%', fontFamily: 'inherit' }}
            >
              <option value="all">Semua Status</option>
              <option value="success">Sukses</option>
              <option value="pending">Pending</option>
              <option value="failed">Gagal</option>
              <option value="refunded">Refunded</option>
            </select>
          </div>

          {/* Merchant Filter */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#f6f6f6', border: '1.5px solid #efefef', borderRadius: 8, padding: '8px 12px' }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', whiteSpace: 'nowrap' }}>Merchant:</span>
            <select
              value={merchantFilter}
              onChange={e => setMerchantFilter(e.target.value)}
              style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 13, color: '#171919', cursor: 'pointer', width: '100%', fontFamily: 'inherit' }}
            >
              <option value="all">Semua Merchant</option>
              {approvedMerchants.map(m => (
                <option key={m.id} value={m.id}>{m.merchantName}</option>
              ))}
            </select>
          </div>

        </div>
      </div>

      {/* ── TRANSACTION LIST TABLE ── */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
          <thead>
            <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>ID Transaksi</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Merchant</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Sumber / Metode</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'right' }}>Nominal Gross</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'right' }}>MDR (0.7%)</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'right' }}>Net Settlement</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Status</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {filteredTxs.length === 0 ? (
              <tr>
                <td colSpan="9" style={{ padding: '40px 18px', textAlign: 'center', color: '#a7a8a8' }}>
                  <i className="bx bx-receipt" style={{ fontSize: 32, display: 'block', marginBottom: 8 }} />
                  Tidak ada transaksi yang cocok dengan kriteria filter.
                </td>
              </tr>
            ) : filteredTxs.map(tx => {
              const isSuccess = tx.status === 'success';
              const isPending = tx.status === 'pending';
              const isFailed = tx.status === 'failed';
              const isRefunded = tx.status === 'refunded';

              let statusBg = '#f6f6f6', statusColor = '#777', statusLabel = tx.status.toUpperCase();
              if (isSuccess) { statusBg = 'rgba(116,181,12,0.12)'; statusColor = '#74b50c'; statusLabel = 'Sukses'; }
              else if (isPending) { statusBg = 'rgba(217,146,11,0.12)'; statusColor = '#d9920b'; statusLabel = 'Pending'; }
              else if (isFailed) { statusBg = 'rgba(237,49,81,0.1)'; statusColor = '#ed3151'; statusLabel = 'Gagal'; }
              else if (isRefunded) { statusBg = 'rgba(79,70,229,0.12)'; statusColor = '#4F46E5'; statusLabel = 'Refunded'; }

              return (
                <tr key={tx.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '14px 18px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{tx.id}</td>
                  <td style={{ padding: '14px 18px', color: '#515252', fontSize: 12.5 }}>{fmtDate(tx.time)}</td>
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ fontWeight: 700, color: '#171919' }}>{tx.merchantName}</div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2, fontFamily: 'monospace' }}>MID: {tx.merchantId}</div>
                  </td>
                  <td style={{ padding: '14px 18px', color: '#515252' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      <i className="bx bx-qr-scan" style={{ color: TEAL }} />
                      {tx.type}
                    </span>
                  </td>
                  <td style={{ padding: '14px 18px', textAlign: 'right', fontWeight: 700, color: '#171919' }}>{fmtRp(tx.amount)}</td>
                  <td style={{ padding: '14px 18px', textAlign: 'right', color: '#ed3151' }}>{fmtRp(tx.mdr)}</td>
                  <td style={{ padding: '14px 18px', textAlign: 'right', fontWeight: 700, color: '#74b50c' }}>{fmtRp(tx.net)}</td>

                  {/* Status Badge */}
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: statusBg, color: statusColor, fontSize: 11.5, fontWeight: 700, borderRadius: 100, padding: '3px 10px' }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: statusColor }} />
                      {statusLabel}
                    </span>
                  </td>

                  {/* Actions */}
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
                      <button
                        onClick={() => setSelectedTx(tx)}
                        style={{ background: '#fff', border: '1px solid #efefef', borderRadius: 6, padding: '5px 8px', fontSize: 11.5, fontWeight: 600, color: '#515252', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 3 }}
                      >
                        <i className="bx bx-show" /> Detail
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* ── TOAST NOTIFICATION ── */}
      {toastMessage && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#10B981', color: '#fff', padding: '16px 24px', borderRadius: 10, boxShadow: '0 8px 24px rgba(16,185,129,0.25)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
          <i className="bx bx-bell" style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 700 }}>{toastMessage}</span>
        </div>
      )}

      {/* ── DETAIL DRAWER (SLIDE IN FROM RIGHT) ── */}
      {selectedTx && !showRefundModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1400, display: 'flex', justifyContent: 'flex-end' }}>
          <div onClick={() => setSelectedTx(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 200ms ease' }} />
          <div style={{ position: 'relative', width: 440, maxWidth: '90vw', height: '100%', background: '#fff', boxShadow: '-16px 0 48px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideInRight 280ms cubic-bezier(0.22, 0.61, 0.36, 1)' }}>

            {/* Drawer Header */}
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #efefef', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontSize: 15.5, fontWeight: 800, color: '#171919', margin: 0 }}>Struk & Rincian Transaksi</h3>
              <button onClick={() => setSelectedTx(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, color: '#a7a8a8', display: 'flex', alignItems: 'center' }}>
                <i className="bx bx-x" />
              </button>
            </div>

            {/* Drawer Content */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '24px' }}>

              {/* Receipt Visual Style */}
              <div style={{ border: '1.5px dashed #efefef', borderRadius: 12, padding: 20, background: '#fafafa', position: 'relative', overflow: 'hidden', marginBottom: 24 }}>
                <div style={{ textAlign: 'center', borderBottom: '1px dashed #efefef', paddingBottom: 16, marginBottom: 16 }}>
                  <div style={{ fontSize: 10, color: '#a7a8a8', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700 }}>QRIS hibank Payment Gateway</div>
                  <h4 style={{ margin: '8px 0 2px', fontSize: 15, fontWeight: 800, color: '#171919' }}>{selectedTx.merchantName}</h4>
                  <div style={{ fontSize: 11, color: '#a7a8a8', fontFamily: 'monospace' }}>MID: {selectedTx.merchantId} | POS: {selectedTx.terminalId}</div>

                  <div style={{ fontSize: 26, fontWeight: 850, color: selectedTx.status === 'success' ? '#74b50c' : (selectedTx.status === 'failed' ? '#ed3151' : TEAL), margin: '16px 0 4px' }}>
                    {fmtRp(selectedTx.amount)}
                  </div>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: '#a7a8a8' }}>
                    Status: <span style={{ color: selectedTx.status === 'success' ? '#74b50c' : (selectedTx.status === 'failed' ? '#ed3151' : TEAL) }}>{selectedTx.status.toUpperCase()}</span>
                  </div>
                </div>

                {/* Info List */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 12.5 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>ID Transaksi</span>
                    <span style={{ fontFamily: 'monospace', fontWeight: 700, color: '#171919' }}>{selectedTx.id}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>RRN (Ref Number)</span>
                    <span style={{ fontFamily: 'monospace', fontWeight: 700, color: '#171919' }}>{selectedTx.rrn}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>Waktu Transaksi</span>
                    <span style={{ fontWeight: 600, color: '#171919' }}>{fmtDate(selectedTx.time)}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>Metode Bayar</span>
                    <span style={{ fontWeight: 600, color: '#171919' }}>{selectedTx.type}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>Sumber Dana / Issuer</span>
                    <span style={{ fontWeight: 700, color: TEAL }}>{selectedTx.issuer}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#a7a8a8' }}>Nama Pelanggan</span>
                    <span style={{ fontWeight: 600, color: '#171919' }}>{selectedTx.customerName}</span>
                  </div>

                  <div style={{ borderTop: '1px dashed #efefef', paddingTop: 12, marginTop: 4, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#a7a8a8' }}>Nominal Kotor (Gross)</span>
                      <span style={{ fontWeight: 600, color: '#171919' }}>{fmtRp(selectedTx.amount)}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#a7a8a8' }}>MDR Fee Bank (0.7%)</span>
                      <span style={{ fontWeight: 600, color: '#ed3151' }}>-{fmtRp(selectedTx.mdr)}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, borderTop: '1px solid #efefef', paddingTop: 8 }}>
                      <span style={{ fontWeight: 700, color: '#171919' }}>Net Settlement</span>
                      <span style={{ fontWeight: 800, color: '#74b50c' }}>{fmtRp(selectedTx.net)}</span>
                    </div>
                  </div>

                  {selectedTx.status === 'refunded' && (
                    <div style={{ marginTop: 12, padding: '12px 14px', borderRadius: 8, background: 'rgba(79,70,229,0.06)', border: '1px solid rgba(79,70,229,0.1)' }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: '#4F46E5', textTransform: 'uppercase' }}>Informasi Refund</div>
                      <div style={{ fontSize: 12, color: '#515252', marginTop: 4 }}><strong>Alasan:</strong> {selectedTx.refundReason || '—'}</div>
                      {selectedTx.refundAt && <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}><strong>Waktu:</strong> {fmtDate(selectedTx.refundAt)}</div>}
                    </div>
                  )}

                </div>
              </div>

            </div>

            {/* Drawer Footer */}
            <div style={{ padding: '16px 24px', borderTop: '1px solid #efefef', display: 'flex', gap: 12 }}>
              <button
                onClick={() => setSelectedTx(null)}
                style={{ flex: 1, background: '#f6f6f6', border: 'none', borderRadius: 8, padding: '12px 0', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'center' }}
              >
                Tutup
              </button>

            </div>

          </div>
        </div>
      )}

      {/* ── REFUND MODAL ── */}
      {showRefundModal && selectedTx && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1500, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 150ms ease' }} onClick={() => setShowRefundModal(false)}>
          <div style={{ background: '#fff', borderRadius: 12, padding: 24, width: 400, maxWidth: '90%', boxShadow: '0 20px 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideUp 250ms cubic-bezier(0.22, 0.68, 0, 1.1)' }} onClick={e => e.stopPropagation()}>
            <h3 style={{ fontSize: 15.5, fontWeight: 800, color: '#ed3151', marginTop: 0, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
              <i className="bx bx-undo" /> Ajukan Refund QRIS
            </h3>
            <p style={{ fontSize: 13, color: '#515252', lineHeight: 1.4, margin: '0 0 16px' }}>
              Anda akan memproses refund dana sebesar <strong>{fmtRp(selectedTx.amount)}</strong> untuk transaksi <strong>{selectedTx.id}</strong> di merchant <strong>{selectedTx.merchantName}</strong>.
            </p>

            <label style={{ fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Alasan Refund / Pembatalan</label>
            <textarea
              rows="3"
              placeholder="Masukkan alasan pengembalian dana (contoh: Transaksi ganda, Kesalahan nominal)"
              value={refundReason}
              onChange={e => setRefundReason(e.target.value)}
              style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', marginBottom: 20, resize: 'none' }}
            />

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button
                onClick={() => { setShowRefundModal(false); setRefundReason(''); }}
                style={{ background: '#f6f6f6', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}
              >
                Batal
              </button>
              <button
                onClick={handleRefund}
                disabled={!refundReason.trim()}
                style={{
                  background: refundReason.trim() ? '#ed3151' : '#fcd5dc',
                  color: '#fff', border: 'none', borderRadius: 6, padding: '8px 16px',
                  fontSize: 12, fontWeight: 600, cursor: refundReason.trim() ? 'pointer' : 'not-allowed',
                  fontFamily: 'inherit'
                }}
              >
                Proses Refund Dana
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

Object.assign(window, { TransactionMonitorPage });
