// refund-management.jsx — Refund Request & Monitor Pages for Hibank QRIS BackOffice

// Share state wrapper using localStorage or window global to sync data between Request and Monitor
const getRefundRequests = () => {
  const defaultReqs = [
    { id: 'REQ-RFD-7011', txId: 'TX-260624-9981', mid: 'MRC-00244', name: 'Batik Lestari Pekalongan', customer: 'Reza Firmansyah', amount: 120000, time: '2026-06-24T09:30:00', reason: 'Salah nominal transfer', status: 'pending', checker: '—', refNo: '—' },
    { id: 'REQ-RFD-7012', txId: 'TX-260624-9982', mid: 'MRC-00245', name: 'Toko Bangunan Maju Jaya', customer: 'Rina Marlina', amount: 250000, time: '2026-06-24T10:12:00', reason: 'Barang kosong', status: 'assigned', checker: 'Chandra Wijaya (Checker)', refNo: '—' },
    { id: 'REQ-RFD-7013', txId: 'TX-260624-9983', mid: 'MRC-00246', name: 'Kopi Senja Nusantara', customer: 'Hendra Wijaya', amount: 85000, time: '2026-06-24T10:15:00', reason: 'Double payment by customer', status: 'approved', checker: 'Arief Budiman (Checker)', refNo: 'REF-RFD-8812903' },
    { id: 'REQ-RFD-7010', txId: 'TX-260623-8109', mid: 'MRC-00244', name: 'Batik Lestari Pekalongan', customer: 'Dian Sastro', amount: 150000, time: '2026-06-23T14:45:00', reason: 'Double payment by customer', status: 'rejected', checker: 'Arief Budiman (Checker)', refNo: '—', rejectReason: 'Transaksi sah dan sudah di-settle' }
  ];
  
  if (!window.__refundRequests) {
    window.__refundRequests = defaultReqs;
  }
  return window.__refundRequests;
};

const saveRefundRequests = (data) => {
  window.__refundRequests = data;
};

// ── 1. REFUND REQUEST PAGE ──
function RefundRequestPage({ merchants, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const [requests, setRequests] = React.useState(getRefundRequests());
  const [view, setView] = React.useState('list'); // 'list' | 'detail'
  const [selectedReq, setSelectedReq] = React.useState(null);
  const [assigningReq, setAssigningReq] = React.useState(null);
  const [selectedChecker, setSelectedChecker] = React.useState('');
  const [toast, setToast] = React.useState(null);

  const checkersList = [
    'Arief Budiman (Checker)',
    'Chandra Wijaya (Checker)',
    'Bambang Pamungkas (Checker)'
  ];

  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) => {
    setToast(msg);
    setTimeout(() => setToast(null), 3000);
  };

  // Action: Assign Checker
  const handleAssignSubmit = (e) => {
    e.preventDefault();
    if (!assigningReq || !selectedChecker) return;

    const updated = requests.map(r => {
      if (r.id !== assigningReq.id) return r;
      return { ...r, status: 'assigned', checker: selectedChecker };
    });

    setRequests(updated);
    saveRefundRequests(updated);
    
    triggerToast(`Request ${assigningReq.id} berhasil ditugaskan ke ${selectedChecker}.`);
    
    // Close modal
    setAssigningReq(null);
    setSelectedChecker('');
  };

  const counts = {
    total: requests.length,
    pending: requests.filter(r => r.status === 'pending').length,
    assigned: requests.filter(r => r.status === 'assigned').length,
    completed: requests.filter(r => r.status === 'approved' || r.status === 'rejected').length
  };

  // ── SUB-PAGE: DETAIL REQUEST ──
  if (view === 'detail' && selectedReq) {
    const freshReq = requests.find(r => r.id === selectedReq.id) || selectedReq;
    const isPending = freshReq.status === 'pending';
    const isAssigned = freshReq.status === 'assigned';
    const isApproved = freshReq.status === 'approved';
    const isRejected = freshReq.status === 'rejected';

    return (
      <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
        {/* Breadcrumb */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <button 
            onClick={() => { setView('list'); setSelectedReq(null); }} 
            style={{ 
              display: 'flex', alignItems: 'center', gap: 6, background: '#fff', border: '1.5px solid #efefef', 
              borderRadius: 8, padding: '8px 14px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', transition: 'all 150ms' 
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
          >
            <i className="bx bx-left-arrow-alt" style={{ fontSize: 18 }} /> Kembali
          </button>
          <div style={{ fontSize: 13, color: '#a7a8a8' }}>
            Refund Management / <span style={{ color: '#515252', fontWeight: 600 }}>Detail Request {freshReq.id}</span>
          </div>
        </div>

        {/* Layout Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 24, alignItems: 'start' }}>
          
          {/* Left: Info Card */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', padding: '24px' }}>
              
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #efefef', paddingBottom: 16, marginBottom: 16 }}>
                <div>
                  <span style={{ display: 'inline-block', background: `${TEAL}10`, color: TEAL, fontSize: 11, fontWeight: 700, borderRadius: 4, padding: '3px 8px', marginBottom: 6 }}>
                    Permohonan Pengembalian Dana Merchant
                  </span>
                  <h2 style={{ fontSize: 18, fontWeight: 800, color: '#171919', margin: 0 }}>Request ID: {freshReq.id}</h2>
                </div>
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  background: isApproved ? 'rgba(116,181,12,0.12)' : (isRejected ? 'rgba(237,49,81,0.1)' : (isAssigned ? 'rgba(0,86,210,0.1)' : 'rgba(217,146,11,0.12)')),
                  color: isApproved ? '#74b50c' : (isRejected ? '#ed3151' : (isAssigned ? TEAL : '#d9920b')),
                  fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '4px 10px'
                }}>
                  {freshReq.status.toUpperCase()}
                </span>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
                <div>
                  <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Nama Merchant</div>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919', marginTop: 4 }}>{freshReq.name}</div>
                  <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{freshReq.mid}</div>
                </div>
                <div>
                  <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Waktu Pengajuan</div>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919', marginTop: 4 }}>{fmtDate(freshReq.time)}</div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, borderTop: '1px solid #efefef', paddingTop: 16, marginBottom: 16 }}>
                <div>
                  <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>ID Transaksi (Original)</div>
                  <div style={{ fontSize: 13, fontFamily: 'monospace', fontWeight: 700, color: '#171919', marginTop: 4 }}>{freshReq.txId}</div>
                </div>
                <div>
                  <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Nama Pelanggan (Customer)</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#171919', marginTop: 4 }}>{freshReq.customer}</div>
                </div>
              </div>

              <div style={{ borderTop: '1px solid #efefef', paddingTop: 16 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 8 }}>Alasan Refund & Detail:</div>
                <div style={{ background: '#f6f6f6', borderRadius: 8, padding: '16px', fontSize: 13, lineHeight: 1.5, color: '#171919', borderLeft: `4px solid ${TEAL}` }}>
                  Nominal yang diajukan: <strong>{fmtRp(freshReq.amount)}</strong><br/>
                  Keterangan: "{freshReq.reason}"
                </div>
              </div>
            </div>

            {/* Checker logs */}
            {!isPending && (
              <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', padding: '24px' }}>
                <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', marginTop: 0, marginBottom: 16 }}>Status Otorisasi Checker</h3>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                  <div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Petugas Pemeriksa (Checker)</div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: '#171919', marginTop: 4 }}>{freshReq.checker}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Status Pemeriksaan</div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: isApproved ? GREEN : (isRejected ? RED : TEAL), marginTop: 4 }}>
                      {isApproved ? 'DISETUJUI (APPROVED)' : (isRejected ? 'DITOLAK (REJECTED)' : 'SEDANG DIPERIKSA')}
                    </div>
                  </div>
                </div>
                {isApproved && (
                  <div style={{ borderTop: '1px solid #efefef', paddingTop: 16 }}>
                    <div style={{ fontSize: 12, color: '#a7a8a8' }}>Nomor Referensi Refund</div>
                    <div style={{ fontSize: 13, fontFamily: 'monospace', fontWeight: 700, color: '#171919', marginTop: 4 }}>{freshReq.refNo}</div>
                  </div>
                )}
                {isRejected && (
                  <div style={{ borderTop: '1px solid #efefef', paddingTop: 16 }}>
                    <div style={{ fontSize: 12, color: RED, fontWeight: 700 }}>Alasan Penolakan Audit</div>
                    <div style={{ fontSize: 13, background: 'rgba(237,49,81,0.05)', border: `1px solid rgba(237,49,81,0.12)`, padding: 12, borderRadius: 8, color: '#515252', marginTop: 6, fontStyle: 'italic' }}>
                      "{freshReq.rejectReason || '—'}"
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Right: Actions Sidebar */}
          <div style={{ position: 'sticky', top: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', padding: '20px' }}>
              <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', marginTop: 0, marginBottom: 12 }}>Tindakan Pengurus</h3>
              
              {isPending ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <p style={{ fontSize: 12.5, color: '#515252', lineHeight: 1.4, margin: 0, marginBottom: 10 }}>Permohonan ini belum ditugaskan ke petugas pemeriksa (Checker).</p>
                  <button 
                    onClick={() => setAssigningReq(freshReq)}
                    style={{ width: '100%', background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '12px 0', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, boxShadow: `0 4px 12px ${TEAL}25` }}
                  >
                    <i className="bx bx-user-voice" style={{ fontSize: 16 }} />
                    Tugaskan Checker (Assign)
                  </button>
                </div>
              ) : isAssigned ? (
                <div style={{ textAlign: 'center', padding: '10px 0' }}>
                  <i className="bx bx-loader-circle bx-spin" style={{ fontSize: 32, color: TEAL, marginBottom: 8 }} />
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919' }}>Menunggu Review Checker</div>
                  <p style={{ fontSize: 12, color: '#a7a8a8', marginTop: 4, lineHeight: 1.4, marginBottom: 0 }}>Sedang diperiksa oleh <strong>{freshReq.checker}</strong>.</p>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '10px 0' }}>
                  <i className={`bx ${isApproved ? 'bx-check-circle' : 'bx-block'}`} style={{ fontSize: 32, color: isApproved ? GREEN : RED, marginBottom: 8 }} />
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919' }}>Pemeriksaan Selesai</div>
                  <p style={{ fontSize: 12, color: '#a7a8a8', marginTop: 4, lineHeight: 1.4, marginBottom: 0 }}>Otorisasi oleh <strong>{freshReq.checker}</strong> selesai.</p>
                </div>
              )}
            </div>

            <button 
              onClick={() => { setView('list'); setSelectedReq(null); }}
              style={{ width: '100%', background: '#fff', border: '1px solid #efefef', borderRadius: 8, padding: '12px 0', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'center' }}
            >
              Kembali ke Daftar
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── MAIN LIST VIEW ──
  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Refund Management</div>
        <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Refund Requests Queue</h1>
        <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Kelola alur penugasan verifikator dan checker untuk pengembalian dana QRIS merchant.</p>
      </div>

      {/* Stats Summary Cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Permohonan', value: counts.total, sub: 'Total pengajuan masuk', icon: 'bx-git-pull-request', color: TEAL },
          { label: 'Belum Ditugaskan', value: counts.pending, sub: 'Perlu penetapan checker', icon: 'bx-user-plus', color: counts.pending > 0 ? ORANGE : '#a7a8a8' },
          { label: 'Dalam Pemeriksaan', value: counts.assigned, sub: 'Oleh checker aktif', icon: 'bx-loader-circle', color: counts.assigned > 0 ? AMBER : '#a7a8a8' },
          { label: 'Otorisasi Selesai', value: counts.completed, sub: 'Approved & Rejected', icon: 'bx-badge-check', color: GREEN }
        ].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: 22, 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>

      {/* Request Table Queue */}
      <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', width: 140 }}>ID Request</th>
              <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' }}>Merchant</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal Refund</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu Diajukan</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Petugas Checker</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center', width: 220 }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {requests.map(req => {
              const isPending = req.status === 'pending';
              const isAssigned = req.status === 'assigned';
              const isApproved = req.status === 'approved';
              const isRejected = req.status === 'rejected';

              return (
                <tr key={req.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 }}>{req.id}</td>
                  <td style={{ padding: '14px 18px', fontFamily: 'monospace', color: '#515252' }}>{req.txId}</td>
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ fontWeight: 700, color: '#171919' }}>{req.name}</div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{req.mid}</div>
                  </td>
                  <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(req.amount)}</td>
                  <td style={{ padding: '14px 18px', color: '#a7a8a8' }}>{fmtDate(req.time)}</td>
                  <td style={{ padding: '14px 18px', fontWeight: 600, color: '#515252' }}>
                    {isPending ? (
                      <span style={{ color: '#a7a8a8', fontStyle: 'italic', fontWeight: 400 }}>Belum Ditugaskan</span>
                    ) : (
                      <span>{req.checker}</span>
                    )}
                  </td>
                  <td style={{ padding: '14px 18px' }}>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      background: isApproved ? 'rgba(116,181,12,0.12)' : (isRejected ? 'rgba(237,49,81,0.1)' : (isAssigned ? 'rgba(0,86,210,0.1)' : 'rgba(217,146,11,0.12)')),
                      color: isApproved ? '#74b50c' : (isRejected ? '#ed3151' : (isAssigned ? TEAL : '#d9920b')),
                      fontSize: 11.5, fontWeight: 700, borderRadius: 4, padding: '3px 8px'
                    }}>
                      {req.status === 'pending' ? 'Unassigned' : req.status.toUpperCase()}
                    </span>
                  </td>
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
                      <button 
                        onClick={() => { setSelectedReq(req); setView('detail'); }}
                        style={{ 
                          background: '#fff', border: '1.5px solid #efefef', borderRadius: 6, padding: '6px 12px', 
                          fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', 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>

                      {isPending ? (
                        <button 
                          onClick={() => setAssigningReq(req)}
                          style={{ 
                            background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '7px 12px', 
                            fontSize: 11.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex', 
                            alignItems: 'center', gap: 4, boxShadow: `0 2px 6px ${TEAL}15`, transition: 'all 150ms',
                            fontFamily: 'inherit'
                          }}
                          onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
                          onMouseLeave={e => e.currentTarget.style.background = TEAL}
                        >
                          Assign Checker
                        </button>
                      ) : (
                        <button 
                          disabled
                          style={{ 
                            background: '#f5f5f5', color: '#a7a8a8', border: 'none', borderRadius: 6, padding: '7px 12px', 
                            fontSize: 11.5, fontWeight: 750, cursor: 'not-allowed', fontFamily: 'inherit'
                          }}
                        >
                          Assign Checker
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Modal: Assign Checker */}
      {assigningReq && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setAssigningReq(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(2px)' }} />
          <div style={{ position: 'relative', width: 400, 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 }}>Tugaskan Checker Refund</h3>
              <button onClick={() => setAssigningReq(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 20 }} /></button>
            </div>

            <form onSubmit={handleAssignSubmit}>
              <div style={{ background: '#f6f6f6', borderRadius: 8, padding: '12px', fontSize: 12.5, color: '#515252', marginBottom: 16, lineHeight: 1.4 }}>
                <div>Request ID: <strong>{assigningReq.id}</strong></div>
                <div>Merchant: <strong>{assigningReq.name}</strong></div>
                <div>Nominal Refund: <strong>{fmtRp(assigningReq.amount)}</strong></div>
              </div>

              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Pilih Petugas Checker</label>
                <select 
                  required
                  value={selectedChecker}
                  onChange={e => setSelectedChecker(e.target.value)}
                  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 Checker --</option>
                  {checkersList.map(c => (
                    <option key={c} value={c}>{c}</option>
                  ))}
                </select>
              </div>

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setAssigningReq(null)} 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={!selectedChecker} style={{ background: selectedChecker ? TEAL : '#dfe3ea', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: selectedChecker ? 'pointer' : 'not-allowed', boxShadow: selectedChecker ? '0 4px 12px rgba(0,86,210,0.15)' : 'none' }}>Tugaskan Checker</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Toast Alert */}
      {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}</span>
        </div>
      )}

    </div>
  );
}


// ── 2. REFUND MONITOR PAGE ──
function RefundMonitorPage({ merchants, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const [requests] = React.useState(getRefundRequests());

  const fmtRp = (v) => {
    if (v === null || v === undefined) return '—';
    return 'Rp ' + Number(v).toLocaleString('id-ID');
  };

  const getWorkflowStep = (status) => {
    if (status === 'pending') return 1;
    if (status === 'assigned') return 2;
    if (status === 'approved' || status === 'rejected') return 3;
    return 1;
  };

  // Workflow steps definitions
  const steps = [
    { n: 1, label: 'Pengajuan Merchant' },
    { n: 2, label: 'Pemeriksaan Checker' },
    { n: 3, label: 'Otorisasi Akhir (Selesai)' }
  ];

  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Refund Management</div>
        <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Refund Monitoring Dashboard</h1>
        <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Lacak progress persetujuan workflow pengembalian dana QRIS merchant secara real-time.</p>
      </div>

      {/* Monitor list cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {requests.map(req => {
          const currentStep = getWorkflowStep(req.status);
          const isApproved = req.status === 'approved';
          const isRejected = req.status === 'rejected';

          return (
            <div key={req.id} style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Card top */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
                <div>
                  <span style={{ fontSize: 12, fontWeight: 700, color: TEAL, fontFamily: 'monospace' }}>{req.id}</span>
                  <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', margin: '4px 0 0' }}>{req.name}</h3>
                  <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>Tx ID: {req.txId} · Nominal: {fmtRp(req.amount)}</div>
                </div>

                <div style={{ textAlign: 'right' }}>
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    background: isApproved ? 'rgba(116,181,12,0.12)' : (isRejected ? 'rgba(237,49,81,0.1)' : (req.status === 'assigned' ? 'rgba(0,86,210,0.1)' : 'rgba(217,146,11,0.12)')),
                    color: isApproved ? '#74b50c' : (isRejected ? '#ed3151' : (req.status === 'assigned' ? TEAL : '#d9920b')),
                    fontSize: 11.5, fontWeight: 700, borderRadius: 100, padding: '3px 9px'
                  }}>
                    {req.status.toUpperCase()}
                  </span>
                  <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>Pemeriksa: <strong>{req.checker}</strong></div>
                </div>
              </div>

              {/* Stepper Progress bar */}
              <div style={{ borderTop: '1px dashed #efefef', paddingTop: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative' }}>
                
                {/* Stepper line */}
                <div style={{ position: 'absolute', top: 31, left: '10%', right: '10%', height: 3, background: '#efefef', zIndex: 1 }} />
                <div style={{ position: 'absolute', top: 31, left: '10%', width: currentStep === 1 ? '0%' : currentStep === 2 ? '40%' : '80%', height: 3, background: isRejected ? RED : GREEN, zIndex: 2, transition: 'width 0.4s ease' }} />

                {steps.map(step => {
                  const isPast = currentStep > step.n;
                  const isCurrent = currentStep === step.n;
                  const isFinal = step.n === 3;
                  
                  let dotBg = '#fff';
                  let borderCol = '#efefef';
                  let textCol = '#a7a8a8';
                  let checkIcon = null;

                  if (isPast) {
                    dotBg = GREEN;
                    borderCol = GREEN;
                    textCol = '#171919';
                    checkIcon = <i className="bx bx-check" style={{ color: '#fff', fontSize: 13 }} />;
                  } else if (isCurrent) {
                    dotBg = '#fff';
                    borderCol = isRejected ? RED : (isApproved ? GREEN : TEAL);
                    textCol = isRejected ? RED : (isApproved ? GREEN : TEAL);
                    checkIcon = <div style={{ width: 6, height: 6, borderRadius: '50%', background: isRejected ? RED : TEAL }} />;
                  }

                  if (isFinal && isCurrent) {
                    dotBg = isRejected ? RED : GREEN;
                    borderCol = isRejected ? RED : GREEN;
                    textCol = isRejected ? RED : GREEN;
                    checkIcon = <i className={`bx ${isRejected ? 'bx-x' : 'bx-check'}`} style={{ color: '#fff', fontSize: 13 }} />;
                  }

                  return (
                    <div key={step.n} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '25%', textAlign: 'center', zIndex: 3 }}>
                      <div style={{
                        width: 32, height: 32, borderRadius: '50%', background: dotBg,
                        border: `2px solid ${borderCol}`, display: 'flex', alignItems: 'center', justifyContent: 'center',
                        boxShadow: '0 2px 6px rgba(0,0,0,0.03)'
                      }}>
                        {checkIcon || <span style={{ fontSize: 11, fontWeight: 700, color: '#a7a8a8' }}>{step.n}</span>}
                      </div>
                      <span style={{ fontSize: 12, fontWeight: isCurrent || isPast ? 700 : 500, color: textCol, marginTop: 8 }}>{step.label}</span>
                    </div>
                  );
                })}

              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Register components globally
Object.assign(window, { RefundRequestPage, RefundMonitorPage });
