// disbursement.jsx — Disbursement Management Page for Hibank QRIS BackOffice
function DisbursementPage({ merchants, primary, secondary, merchantView = false }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  // State
  const [payouts, setPayouts] = React.useState([
    { id: 'DISB-2606-0012', mid: 'MRC-00244', name: 'Batik Lestari Pekalongan', bank: 'Bank Mandiri', account: '1310022419', gross: 8500000, mdr: 59500, net: 8440500, time: '2026-06-24T11:00:00', mode: 'Batch', status: 'success', refNo: 'REF-MND-8812739' },
    { id: 'DISB-2606-0013', mid: 'MRC-00245', name: 'Toko Bangunan Maju Jaya', bank: 'Bank BCA', account: '0127889123', gross: 12500000, mdr: 87500, net: 12412500, time: '2026-06-24T11:15:00', mode: 'Batch', status: 'success', refNo: 'REF-BCA-8812741' },
    { id: 'DISB-2606-0014', mid: 'MRC-00246', name: 'Kopi Senja Nusantara', bank: 'Bank Hibank', account: '8820145566', gross: 3500000, mdr: 24500, net: 3475500, time: '2026-06-24T11:20:00', mode: 'Instant', status: 'failed', refNo: '—', failReason: 'API Gateway timeout from destination bank' },
    { id: 'DISB-2606-0010', mid: 'MRC-00244', name: 'Batik Lestari Pekalongan', bank: 'Bank Mandiri', account: '1310022419', gross: 6200000, mdr: 43400, net: 6156600, time: '2026-06-23T11:00:00', mode: 'Batch', status: 'success', refNo: 'REF-MND-8811091' },
    { id: 'DISB-2606-0011', mid: 'MRC-00245', name: 'Toko Bangunan Maju Jaya', bank: 'Bank BCA', account: '0127889123', gross: 10400000, mdr: 72800, net: 10327200, time: '2026-06-23T11:15:00', mode: 'Batch', status: 'success', refNo: 'REF-BCA-8811105' }
  ]);

  const [selectedPayout, setSelectedPayout] = React.useState(null);
  const [showFormModal, setShowFormModal] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  // Form states
  const [formMerchantId, setFormMerchantId] = React.useState('');
  const [formAmount, setFormAmount] = React.useState('');
  const [formNotes, setFormNotes] = React.useState('');

  const activeMerchants = merchants ? merchants.filter(m => m.status === 'approved' || m.status === 'active' || m.status === 'pending_l2') : [];

  const fmtRp = (v) => {
    if (v === null || v === undefined) return '—';
    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' });
  };

  const triggerToast = (msg, kind = 'success') => {
    setToast({ msg, kind });
    setTimeout(() => setToast(null), 3000);
  };

  // Action: Retry failed payout
  const handleRetryPayout = (payoutId) => {
    setPayouts(prev => prev.map(p => {
      if (p.id !== payoutId) return p;
      return { ...p, status: 'processing', failReason: null };
    }));
    triggerToast(`Memproses ulang pencairan ${payoutId}...`, 'info');

    // Simulate success after 1.5 seconds
    setTimeout(() => {
      setPayouts(prev => prev.map(p => {
        if (p.id !== payoutId) return p;
        const randRef = 'REF-' + Math.random().toString(36).substring(2, 9).toUpperCase();
        return { ...p, status: 'success', refNo: randRef };
      }));
      triggerToast(`Pencairan ${payoutId} sukses dikirim ke bank tujuan.`, 'success');
    }, 1500);
  };

  // Action: Submit manual instant payout
  const handleInstantPayoutSubmit = (e) => {
    e.preventDefault();
    if (!formMerchantId || !formAmount.trim()) return;

    const m = activeMerchants.find(merchant => merchant.id === formMerchantId);
    if (!m) return;

    const gross = Number(formAmount);
    // MDR simulation: 0.7% standard
    const mdr = Math.round(gross * 0.007);
    const net = gross - mdr;
    const newId = 'DISB-2606-' + Math.floor(1000 + Math.random() * 9000);

    const newPayout = {
      id: newId,
      mid: m.id,
      name: m.merchantName,
      bank: m.bankName || 'Bank Hibank',
      account: m.accountNumber || '8820145566',
      gross: gross,
      mdr: mdr,
      net: net,
      time: new Date().toISOString(),
      mode: 'Instant',
      status: 'processing',
      refNo: '—'
    };

    setPayouts(prev => [newPayout, ...prev]);
    setShowFormModal(false);
    triggerToast(`Mengirim pencairan dana instan untuk ${m.merchantName}...`, 'info');

    // Reset Form
    setFormMerchantId('');
    setFormAmount('');
    setFormNotes('');

    // Simulate success after 2 seconds
    setTimeout(() => {
      setPayouts(prev => prev.map(p => {
        if (p.id !== newId) return p;
        const randRef = 'REF-' + Math.random().toString(36).substring(2, 9).toUpperCase();
        return { ...p, status: 'success', refNo: randRef };
      }));
      triggerToast(`Dana instan ${newId} berhasil ditransfer.`, 'success');
    }, 2000);
  };

  // Totals calculations
  const visiblePayouts = merchantView ? payouts.filter(p => p.status === 'success') : payouts;
  const totalVolume = visiblePayouts.filter(p => p.status === 'success').reduce((acc, curr) => acc + curr.net, 0);
  const successCount = visiblePayouts.filter(p => p.status === 'success').length;
  const processingCount = visiblePayouts.filter(p => p.status === 'processing').length;
  const failedCount = visiblePayouts.filter(p => p.status === 'failed').length;

  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Settlement Operations</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>{merchantView ? 'Disbursement — Dana Tercairkan' : 'Pencairan Dana (Disbursement)'}</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>{merchantView ? 'Riwayat dana settlement QRIS Anda yang berhasil dicairkan ke rekening bank terdaftar.' : 'Kelola transfer hasil transaksi QRIS (settlement) ke rekening bank terdaftar merchant secara instan maupun terjadwal.'}</p>
        </div>
        {!merchantView && (
          <button 
            onClick={() => setShowFormModal(true)}
            style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms' }}
            onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
            onMouseLeave={e => e.currentTarget.style.background = TEAL}
          >
            <i className="bx bx-plus-circle" style={{ fontSize: 16 }} /> Pencairan Instan
          </button>
        )}
      </div>

      {/* Stats Summary Cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Volume Pencairan', value: fmtRp(totalVolume), sub: 'Dana sukses didepositkan', icon: 'bx-wallet', color: TEAL },
          { label: 'Disbursement Sukses', value: `${successCount} Batch`, sub: 'Transaksi pencairan sukses', icon: 'bx-check-double', color: GREEN },
          { label: 'Payout Processing', value: processingCount, sub: 'Dana sedang ditransfer', icon: 'bx-loader-circle bx-spin', color: AMBER },
          { label: 'Payout Gagal', value: failedCount, sub: 'Butuh transfer ulang manual', icon: 'bx-error-circle', color: failedCount > 0 ? RED : '#a7a8a8' }
        ].map((card, i) => (
          <div key={i} style={{ background: '#fff', padding: '18px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 200 }}>
            <div style={{ width: 44, height: 44, borderRadius: '50%', background: `${card.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`bx ${card.icon}`} style={{ fontSize: 20, color: card.color }} />
            </div>
            <div>
              <div style={{ fontSize: 12, color: '#a7a8a8', fontWeight: 600 }}>{card.label}</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: '#171919', marginTop: 4, lineHeight: 1 }}>{card.value}</div>
              <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Payout Table */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid #efefef', background: '#fafafa' }}>
          <h3 style={{ fontSize: 14, fontWeight: 800, color: '#171919', margin: 0 }}>Antrean & Riwayat Pencairan Dana</h3>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
          <thead>
            <tr style={{ background: '#fff', borderBottom: '1px solid #efefef' }}>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 140 }}>ID Batch</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nama Merchant</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Rekening Tujuan</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal Bersih (Net)</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu Disburse</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Metode</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center', width: 180 }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {visiblePayouts.map(p => {
              const isSuccess = p.status === 'success';
              const isFailed = p.status === 'failed';
              const isProcessing = p.status === 'processing';

              return (
                <tr key={p.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 20px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{p.id}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <div style={{ fontWeight: 700, color: '#171919' }}>{p.name}</div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{p.mid}</div>
                  </td>
                  <td style={{ padding: '14px 20px', color: '#515252' }}>
                    <div style={{ fontWeight: 600, color: '#171919' }}>{p.bank}</div>
                    <div style={{ fontSize: 12, fontFamily: 'monospace', color: '#515252', marginTop: 2 }}>{p.account}</div>
                  </td>
                  <td style={{ padding: '14px 20px', fontWeight: 700, color: '#171919' }}>
                    {fmtRp(p.net)}
                    <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 400, marginTop: 2 }}>Kotor: {fmtRp(p.gross)}</div>
                  </td>
                  <td style={{ padding: '14px 20px', color: '#a7a8a8' }}>{fmtDate(p.time)}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <span style={{ display: 'inline-block', background: p.mode === 'Instant' ? `${ORANGE}10` : '#f0f4fa', color: p.mode === 'Instant' ? ORANGE : TEAL, fontSize: 11, fontWeight: 700, borderRadius: 4, padding: '3px 8px' }}>
                      {p.mode}
                    </span>
                  </td>
                  <td style={{ padding: '14px 20px' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: isSuccess ? 'rgba(116,181,12,0.12)' : (isFailed ? 'rgba(237,49,81,0.1)' : 'rgba(217,146,11,0.12)'), color: isSuccess ? '#74b50c' : (isFailed ? '#ed3151' : '#d9920b'), fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 9px' }}>
                      <i className={`bx ${isSuccess ? 'bx-check-circle' : (isFailed ? 'bx-x-circle' : 'bx-loader bx-spin')}`} />
                      {p.status.toUpperCase()}
                    </span>
                  </td>
                  <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                    <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
                      <button 
                        onClick={() => setSelectedPayout(p)}
                        style={{ background: '#fff', border: `1.5px solid #efefef`, borderRadius: 6, padding: '6px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', fontFamily: 'inherit', color: '#515252' }}
                        onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                        onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                      >
                        Detail
                      </button>

                      {isFailed && (
                        <button 
                          onClick={() => handleRetryPayout(p.id)}
                          style={{ background: GREEN, color: '#fff', border: 'none', borderRadius: 6, padding: '7px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, transition: 'all 150ms', fontFamily: 'inherit', boxShadow: '0 2px 6px rgba(116,181,12,0.15)' }}
                          onMouseEnter={e => { e.currentTarget.style.background = '#639c0a'; }}
                          onMouseLeave={e => { e.currentTarget.style.background = GREEN; }}
                        >
                          <i className="bx bx-refresh" /> Retry
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Modal: Payout Detail Receipt */}
      {selectedPayout && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setSelectedPayout(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(2px)' }} />
          <div style={{ position: 'relative', width: 460, background: '#fff', borderRadius: 14, boxShadow: '0 12px 36px rgba(23,25,25,0.15)', padding: '28px', animation: 'fadeIn 180ms ease' }}>
            {/* Logo and Close */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #efefef', paddingBottom: 16, marginBottom: 20 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="bx bx-receipt" style={{ fontSize: 22, color: TEAL }} />
                <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', margin: 0 }}>Bukti Pencairan Dana (Disbursement)</h3>
              </div>
              <button onClick={() => setSelectedPayout(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 22 }} /></button>
            </div>

            {/* Receipt Content */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Receipt status header */}
              <div style={{ textAlign: 'center', background: '#fafafa', border: '1px solid #efefef', borderRadius: 10, padding: '16px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase', marginBottom: 4 }}>ID Batch Pencairan</div>
                <div style={{ fontSize: 17, fontWeight: 800, color: '#171919', fontFamily: 'monospace' }}>{selectedPayout.id}</div>
                <div style={{ marginTop: 8 }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: selectedPayout.status === 'success' ? 'rgba(116,181,12,0.12)' : (selectedPayout.status === 'failed' ? 'rgba(237,49,81,0.1)' : 'rgba(217,146,11,0.12)'), color: selectedPayout.status === 'success' ? '#74b50c' : (selectedPayout.status === 'failed' ? '#ed3151' : '#d9920b'), fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 10px' }}>
                    {selectedPayout.status.toUpperCase()}
                  </span>
                </div>
              </div>

              {/* Payout Details */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, borderBottom: '1px solid #efefef', paddingBottom: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: '#a7a8a8' }}>Nama Merchant</span>
                  <strong style={{ color: '#171919', textAlign: 'right' }}>{selectedPayout.name}</strong>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: '#a7a8a8' }}>Bank Tujuan</span>
                  <strong style={{ color: '#171919' }}>{selectedPayout.bank}</strong>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: '#a7a8a8' }}>Rekening Penerima</span>
                  <strong style={{ color: '#171919', fontFamily: 'monospace' }}>{selectedPayout.account}</strong>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: '#a7a8a8' }}>Waktu Eksekusi</span>
                  <strong style={{ color: '#171919' }}>{fmtDate(selectedPayout.time)}</strong>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: '#a7a8a8' }}>Metode Pencairan</span>
                  <strong style={{ color: '#171919' }}>{selectedPayout.mode} Settlement</strong>
                </div>
              </div>

              {/* Financial calculations */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, background: '#fafbff', border: '1px solid #eef2fb', borderRadius: 10, padding: '14px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#515252' }}>
                  <span>Volume Transaksi Kotor (Gross)</span>
                  <span>{fmtRp(selectedPayout.gross)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: RED }}>
                  <span>Potongan MDR (0.7%)</span>
                  <span>-{fmtRp(selectedPayout.mdr)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#515252' }}>
                  <span>Biaya Administrasi Bank</span>
                  <span>Rp 0</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, fontWeight: 800, color: '#171919', borderTop: '1px dashed #dfe3ea', paddingTop: 8, marginTop: 4 }}>
                  <span>Nominal Pencairan Bersih (Net)</span>
                  <span style={{ color: GREEN }}>{fmtRp(selectedPayout.net)}</span>
                </div>
              </div>

              {/* Audit reference trail */}
              <div style={{ fontSize: 12, color: '#a7a8a8', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>No. Referensi Bank</span>
                <strong style={{ fontFamily: 'monospace', color: '#515252' }}>{selectedPayout.refNo}</strong>
              </div>

              {selectedPayout.status === 'failed' && (
                <div style={{ background: 'rgba(237,49,81,0.06)', border: `1px solid rgba(237,49,81,0.15)`, borderRadius: 10, padding: '12px', fontSize: 12, color: RED, lineHeight: 1.4 }}>
                  <strong>Kegagalan Transfer:</strong> {selectedPayout.failReason || 'Gagal tersambung ke jaringan switching core.'}
                </div>
              )}
            </div>

            <div style={{ marginTop: 24, display: 'flex', gap: 10 }}>
              {selectedPayout.status === 'failed' && (
                <button 
                  onClick={() => { handleRetryPayout(selectedPayout.id); setSelectedPayout(null); }}
                  style={{ flex: 1, background: GREEN, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 0', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, boxShadow: '0 4px 12px rgba(116,181,12,0.2)' }}
                >
                  <i className="bx bx-refresh" /> Coba Payout Lagi
                </button>
              )}
              <button 
                onClick={() => setSelectedPayout(null)}
                style={{ flex: 1, background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '10px 0', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', textAlign: 'center' }}
              >
                Tutup Bukti
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal: Instant Payout Trigger Form */}
      {showFormModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setShowFormModal(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(2px)' }} />
          <div style={{ position: 'relative', width: 440, background: '#fff', borderRadius: 14, boxShadow: '0 12px 36px rgba(23,25,25,0.15)', padding: '24px', animation: 'fadeIn 180ms ease' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #efefef', paddingBottom: 12, marginBottom: 16 }}>
              <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', margin: 0 }}>Trigger Pencairan Dana Instan</h3>
              <button onClick={() => setShowFormModal(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 20 }} /></button>
            </div>

            <form onSubmit={handleInstantPayoutSubmit}>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Pilih Merchant QRIS</label>
                <select 
                  required
                  value={formMerchantId}
                  onChange={e => {
                    setFormMerchantId(e.target.value);
                    // Autofill a mock unpaid balance between Rp 1.000.000 and Rp 8.000.000
                    const randAmt = Math.floor(10 + Math.random() * 70) * 100000;
                    setFormAmount(String(randAmt));
                  }}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                >
                  <option value="">-- Pilih Merchant --</option>
                  {activeMerchants.map(m => (
                    <option key={m.id} value={m.id}>{m.merchantName} ({m.id})</option>
                  ))}
                </select>
              </div>

              {formMerchantId && (
                <>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nominal Payout Kotor (Gross)</label>
                    <div style={{ position: 'relative' }}>
                      <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 13, color: '#a7a8a8', fontWeight: 600 }}>Rp</span>
                      <input 
                        type="number"
                        required
                        value={formAmount}
                        onChange={e => setFormAmount(e.target.value)}
                        placeholder="Masukkan nominal pencairan..."
                        style={{ width: '100%', padding: '10px 12px 10px 32px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none' }}
                        onFocus={e => e.target.style.borderColor = TEAL}
                        onBlur={e => e.target.style.borderColor = '#efefef'}
                      />
                    </div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>Nominal net transfer akan dipotong MDR sebesar 0.7% secara otomatis.</div>
                  </div>

                  <div style={{ marginBottom: 20 }}>
                    <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Berita Payout / Catatan Transfer</label>
                    <textarea 
                      rows="3"
                      value={formNotes}
                      onChange={e => setFormNotes(e.target.value)}
                      placeholder="Masukkan berita transfer (opsional)..."
                      style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', resize: 'none', fontFamily: 'inherit' }}
                      onFocus={e => e.target.style.borderColor = TEAL}
                      onBlur={e => e.target.style.borderColor = '#efefef'}
                    />
                  </div>
                </>
              )}

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setShowFormModal(false)} style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '9px 16px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer' }}>Batal</button>
                <button type="submit" disabled={!formMerchantId} style={{ background: formMerchantId ? TEAL : '#dfe3ea', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: formMerchantId ? 'pointer' : 'not-allowed', boxShadow: formMerchantId ? '0 4px 12px rgba(0,86,210,0.15)' : 'none' }}>Kirim Pencairan</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Toast notifications */}
      {toast && (
        <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-check-shield" style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 750 }}>{toast.msg}</span>
        </div>
      )}

    </div>
  );
}

Object.assign(window, { DisbursementPage });
