// approval.jsx — Merchant Onboarding Approval (2-level maker-checker workflow)
function ApprovalPage({ onLogout, onNavigate, merchants, setMerchants, primary, secondary, sidebarColor, role: userRole = 'super', user }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const DARK = '#001F5B';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const [sidebarOpen, setSidebarOpen] = React.useState(true);
  const [role, setRole] = React.useState('l1'); // 'l1' = Verifikator, 'l2' = Approver
  const [activeTab, setActiveTab] = React.useState('pending'); // 'pending' | 'history'
  const [selected, setSelected] = React.useState(null); // merchant id open in detailed subpage
  const [note, setNote] = React.useState('');
  const [toast, setToast] = React.useState(null);

  const fmtRp = (v) => {
    const n = String(v).replace(/[^0-9]/g, '');
    return n ? 'Rp ' + Number(n).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' });
  };

  // ── status meta ──
  const STATUS = {
    pending_l1: { label: 'Menunggu Verifikasi L1', color: AMBER, bg: 'rgba(217,146,11,0.12)', icon: 'bx-time-five' },
    pending_l2: { label: 'Menunggu Persetujuan L2', color: TEAL, bg: 'rgba(0,86,210,0.10)', icon: 'bx-time-five' },
    approved: { label: 'Disetujui', color: GREEN, bg: 'rgba(116,181,12,0.12)', icon: 'bx-check-circle' },
    rejected: { label: 'Ditolak', color: RED, bg: 'rgba(237,49,81,0.10)', icon: 'bx-x-circle' },
  };

  const counts = {
    pending_l1: merchants.filter(m => m.status === 'pending_l1').length,
    pending_l2: merchants.filter(m => m.status === 'pending_l2').length,
    approved: merchants.filter(m => m.status === 'approved').length,
    rejected: merchants.filter(m => m.status === 'rejected').length,
  };

  // which stage can current role act on
  const myStage = role === 'l1' ? 'pending_l1' : 'pending_l2';
  const pendingCount = role === 'l1' ? counts.pending_l1 : counts.pending_l2;
  const canAct = (m) => m.status === myStage;

  const visible = merchants.filter(m => {
    if (activeTab === 'pending') return m.status === myStage;
    return m.status === 'approved' || m.status === 'rejected';
  });

  const sel = merchants.find(m => m.id === selected);

  const showToast = (msg, kind) => {
    setToast({ msg, kind });
    setTimeout(() => setToast(null), 2800);
  };

  const decide = (decision) => {
    if (!sel) return;
    if (decision === 'reject' && !note.trim()) return;

    const now = new Date().toISOString();
    const reviewer = role === 'l1' ? 'Dewi Anggraini (Verifikator)' : 'Arief Budiman (Approver)';

    setMerchants(prev => prev.map(m => {
      if (m.id !== sel.id) return m;
      const rec = { by: reviewer, at: now, note: note.trim() || (decision === 'approve' ? 'Disetujui' : 'Ditolak'), decision };
      if (role === 'l1') {
        return { ...m, l1: rec, status: decision === 'approve' ? 'pending_l2' : 'rejected' };
      } else {
        return { ...m, l2: rec, status: decision === 'approve' ? 'approved' : 'rejected' };
      }
    }));

    showToast(
      decision === 'approve'
        ? (role === 'l1' ? 'Diteruskan ke Approver L2' : 'Merchant disetujui & diaktifkan')
        : 'Pengajuan merchant ditolak',
      decision === 'approve' ? 'success' : 'reject'
    );
    setNote('');
    setSelected(null);
  };

  const Badge = ({ status }) => {
    const s = STATUS[status];
    if (!s) return null;
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: s.bg, color: s.color, fontSize: 11.5, fontWeight: 600, borderRadius: 100, padding: '4px 11px', whiteSpace: 'nowrap' }}>
        <i className={`bx ${s.icon}`} style={{ fontSize: 14 }} /> {s.label}
      </span>
    );
  };

  // approval timeline node
  const Step = ({ n, title, rec, pending, active }) => (
    <div style={{ display: 'flex', gap: 12 }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <div style={{
          width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
          background: rec ? (rec.decision === 'approve' ? GREEN : RED) : active ? '#fff' : '#fff',
          border: rec ? 'none' : active ? `2px solid ${TEAL}` : '2px solid #efefef',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          {rec
            ? <i className={`bx ${rec.decision === 'approve' ? 'bx-check' : 'bx-x'}`} style={{ color: '#fff', fontSize: 18 }} />
            : <span style={{ fontSize: 12, fontWeight: 700, color: active ? TEAL : '#a7a8a8' }}>{n}</span>}
        </div>
        {n === 1 && <div style={{ width: 2, flex: 1, minHeight: 28, background: rec ? '#dfe6f5' : '#efefef', marginTop: 2 }} />}
      </div>
      <div style={{ paddingBottom: 18 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919' }}>{title}</div>
        {rec ? (
          <>
            <div style={{ fontSize: 12, color: '#515252', marginTop: 2 }}>
              {rec.decision === 'approve' ? 'Disetujui' : 'Ditolak'} oleh <strong>{rec.by}</strong>
            </div>
            <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 1 }}>{fmtDate(rec.at)}</div>
            {rec.note && <div style={{ fontSize: 12, color: '#515252', marginTop: 6, padding: '8px 10px', background: '#f6f6f6', borderRadius: 8, fontStyle: 'italic' }}>"{rec.note}"</div>}
          </>
        ) : (
          <div style={{ fontSize: 12, color: active ? TEAL : '#a7a8a8', marginTop: 2, fontWeight: active ? 600 : 400 }}>
            {active ? 'Menunggu tindakan Anda' : pending ? 'Menunggu langkah sebelumnya' : '—'}
          </div>
        )}
      </div>
    </div>
  );

  const Row = ({ label, value, mono }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '8px 0', borderBottom: '1px solid #f3f3f3' }}>
      <span style={{ fontSize: 12.5, color: '#a7a8a8', flexShrink: 0 }}>{label}</span>
      <span style={{ fontSize: 13, color: '#171919', fontWeight: 500, textAlign: 'right', fontFamily: mono ? 'monospace' : 'inherit' }}>{value || '—'}</span>
    </div>
  );

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden', fontFamily: "'Open Sans', sans-serif" }}>
      <Sidebar
        activeNav="approval"
        setActiveNav={(id) => onNavigate(id)}
        sidebarOpen={sidebarOpen}
        setSidebarOpen={setSidebarOpen}
        onLogout={onLogout}
        pendingApproval={counts.pending_l1 + counts.pending_l2}
        primary={TEAL}
        secondary={ORANGE}
        sidebarBg={sidebarColor}
        role={userRole}
        user={user}
      />

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', background: '#f6f6f6' }}>

        {/* TOPBAR */}
        <div style={{ height: 64, background: '#fff', borderBottom: '1px solid #efefef', display: 'flex', alignItems: 'center', padding: '0 28px', gap: 16, flexShrink: 0, boxShadow: '0 1px 2px rgba(23,25,25,0.04)' }}>
          <button onClick={() => setSidebarOpen(!sidebarOpen)} style={{ background: '#f6f6f6', border: '1px solid #efefef', borderRadius: 8, width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#515252' }}>
            <i className="bx bx-menu" style={{ fontSize: 20 }} />
          </button>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Approval</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#171919' }}>Persetujuan Onboarding Merchant</div>
          </div>


        </div>

        {/* CONTENT */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '24px 32px 56px' }}>
          {sel ? (
            <div style={{ animation: 'fadeIn 200ms ease' }}>
              {/* Breadcrumb */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
                <button
                  onClick={() => setSelected(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' }}>
                  Checker Approval / <span style={{ color: '#515252', fontWeight: 600 }}>Detail Request {sel.id}</span>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 24, alignItems: 'start' }}>
                {/* Left side: Merchant Info */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

                  {/* Card 1: Request Details */}
                  <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 }}>
                          Pemeriksaan Onboarding Merchant
                        </span>
                        <h2 style={{ fontSize: 18, fontWeight: 800, color: '#171919', margin: 0 }}>Merchant ID: {sel.id}</h2>
                      </div>
                      <Badge status={sel.status} />
                    </div>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
                      <div>
                        <div style={{ fontSize: 11, color: '#a7a8a8', textTransform: 'uppercase', fontWeight: 600 }}>Pengusul (Maker)</div>
                        <div style={{ fontSize: 13.5, fontWeight: 700, color: '#171919', marginTop: 4 }}>{sel.submittedBy || 'Arief Budiman'}</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(sel.submittedAt)}</div>
                      </div>
                    </div>

                    <div style={{ borderTop: '1px solid #efefef', paddingTop: 16 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 8 }}>Deskripsi Perubahan:</div>
                      <div style={{ background: '#f6f6f6', borderRadius: 8, padding: '16px', fontSize: 13, lineHeight: 1.5, color: '#171919', borderLeft: `4px solid ${TEAL}` }}>
                        Pemeriksaan kelayakan & validasi dokumen onboarding untuk calon merchant: <strong>{sel.merchantName}</strong> (MID: {sel.id}, Kategori Usaha: {sel.businessType || '—'}).
                      </div>
                    </div>

                    {/* Special Section: Dokumen Onboarding */}
                    <div style={{ marginTop: 24, borderTop: '1.5px dashed #efefef', paddingTop: 20 }}>
                      <h4 style={{ fontSize: 13.5, fontWeight: 800, color: '#171919', marginBottom: 12 }}>Dokumen & Informasi Onboarding Calon Merchant</h4>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        {[
                          { label: 'NPWP Perusahaan/Pemilik', val: sel.npwp || '09.254.812.3-014.000', verified: true },
                          { label: 'NIK Pemilik (e-KTP)', val: sel.nik || '3273011505900002', verified: true },
                          { label: 'Rekening Bank Penerima', val: `${sel.bankName || 'Bank Hibank'} - ${sel.accountNumber || '8820145566'} a/n ${sel.accountHolder || sel.picName}`, verified: true },
                          { label: 'Dokumen Legalitas (SIUP/NIB/Badan Hukum)', val: sel.legalName || 'NIB-812739123-A', verified: true }
                        ].map((doc, idx) => (
                          <div key={idx} style={{ background: '#fafafa', border: '1px solid #efefef', borderRadius: 8, padding: '10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <div style={{ minWidth: 0, flex: 1, paddingRight: 8 }}>
                              <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{doc.label}</div>
                              <div style={{ fontSize: 12, fontWeight: 700, color: '#171919', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{doc.val}</div>
                            </div>
                            <span style={{ background: 'rgba(116,181,12,0.12)', color: '#74b50c', fontSize: 10, fontWeight: 700, borderRadius: 4, padding: '2px 6px', display: 'inline-flex', alignItems: 'center', gap: 2, flexShrink: 0 }}>
                              <i className="bx bx-check-shield" /> Terverifikasi
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Log & Alur Persetujuan */}
                  <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 }}>Log & Alur Persetujuan</h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                      <Step n={1} title="Verifikasi Level 1 — Checker" rec={sel.l1} active={sel.status === 'approve_l1'} />
                      <Step n={2} title="Persetujuan Level 2 — Approver" rec={sel.l2} pending={sel.status === 'pending_l2'} active={sel.status === 'pending_l2'} />
                    </div>
                  </div>

                  {/* Detailed profile layout */}
                  <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', padding: '24px', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <Section title="Informasi Merchant" icon="bx-store-alt">
                      <Row label="Nama Merchant/QR" value={sel.merchantName} />
                      <Row label="Merchant Category" value={sel.mcc} />
                      <Row label="MCC" value={sel.mccCode} mono />
                      <Row label="Jenis Usaha" value={sel.businessType} />
                      <Row label="Nama Badan Hukum" value={sel.legalName} />
                      <Row label="NPWP" value={sel.npwp} mono />
                      <Row label="Omset/bulan" value={fmtRp(sel.monthlyOmset)} />
                    </Section>

                    <Section title="Alamat Merchant" icon="bx-map-alt">
                      <Row label="Alamat" value={sel.mAddress} />
                      <Row label="Kelurahan" value={sel.mKelurahan} />
                      <Row label="Kecamatan" value={sel.mKecamatan} />
                      <Row label="Kab/Kota" value={sel.mKabupaten} />
                      <Row label="Provinsi" value={sel.mProvinsi} />
                      <Row label="Kode Pos" value={sel.mPostal} mono />
                    </Section>

                    <Section title="Penanggung Jawab" icon="bx-user">
                      <Row label="Nama PIC" value={sel.picName} />
                      <Row label="No. HP" value={sel.picPhone} mono />
                      <Row label="NIK e-KTP" value={sel.nik} mono />
                      <Row label="Email" value={sel.email} />
                    </Section>

                    <Section title="Rekening Settlement" icon="bx-credit-card-alt">
                      <Row label="Bank" value={sel.bankName} />
                      <Row label="No. Rekening" value={sel.accountNumber} mono />
                      <Row label="Nama Rekening" value={sel.accountHolder} />
                    </Section>
                  </div>
                </div>

                {/* Right side: Action Form Panel */}
                <div style={{ position: 'sticky', top: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
                  {canAct(sel) ? (
                    <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 }}>
                        Form Otorisasi
                      </h3>

                      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>
                        Catatan {role === 'l1' ? 'Verifikator' : 'Approver'}
                      </label>
                      <textarea
                        value={note}
                        onChange={e => setNote(e.target.value)}
                        rows={4}
                        placeholder="Tulis alasan penolakan (wajib jika ditolak) atau catatan persetujuan..."
                        style={{ width: '100%', padding: '10px 12px', border: '1.5px solid #efefef', borderRadius: 8, fontSize: 13, fontFamily: 'inherit', outline: 'none', resize: 'none', color: '#171919', marginBottom: 16 }}
                      />

                      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        <button
                          onClick={() => decide('approve')}
                          style={{ width: '100%', background: '#74b50c', 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 rgba(116,181,12,0.2)' }}
                        >
                          <i className="bx bx-check-shield" style={{ fontSize: 16 }} />
                          {role === 'l1' ? 'Setujui' : 'Setujui & Aktifkan'}
                        </button>
                        <button
                          onClick={() => decide('reject')}
                          disabled={!note.trim()}
                          style={{
                            width: '100%',
                            background: note.trim() ? '#ed3151' : '#fcd5dc',
                            color: '#fff', border: 'none', borderRadius: 8, padding: '12px 0',
                            fontSize: 13, fontWeight: 700,
                            cursor: note.trim() ? 'pointer' : 'not-allowed',
                            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                            boxShadow: note.trim() ? '0 4px 12px rgba(237,49,81,0.2)' : 'none'
                          }}
                        >
                          <i className="bx bx-x-circle" style={{ fontSize: 16 }} />
                          Tolak Pengajuan (Reject)
                        </button>
                      </div>
                    </div>
                  ) : (
                    <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', padding: '20px', textAlign: 'center' }}>
                      <i className={`bx ${sel.status === 'approved' ? 'bx-check-shield' : (sel.status === 'rejected' ? 'bx-x-circle' : 'bx-time-five')}`} style={{ fontSize: 44, color: sel.status === 'approved' ? '#74b50c' : (sel.status === 'rejected' ? '#ed3151' : AMBER), marginBottom: 12 }} />
                      <h4 style={{ margin: 0, fontSize: 14.5, fontWeight: 800, color: '#171919' }}>Pemeriksaan Selesai</h4>
                      <p style={{ fontSize: 12.5, color: '#a7a8a8', marginTop: 4, marginBottom: 0, lineHeight: 1.4 }}>
                        {sel.status === 'approved' ? 'Merchant telah disetujui & aktif.'
                          : sel.status === 'rejected' ? 'Pendaftaran merchant telah ditolak.'
                            : `Menunggu tindakan ${sel.status === 'pending_l1' ? 'Verifikator L1' : 'Approver L2'}.`}
                      </p>
                    </div>
                  )}

                  <button
                    onClick={() => setSelected(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>
          ) : (
            <>
              {/* Header */}
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Approval (4 Eyes)</div>
                <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Otorisasi Persetujuan</h1>
                <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Verifikasi dan otorisasi persetujuan request.</p>
              </div>

              {/* STATS SUMMARY CARDS */}
              <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
                {[
                  { label: 'Menunggu Persetujuan', value: pendingCount },
                  { label: 'Selesai Disetujui', value: counts.approved },
                  { label: 'Pengajuan Ditolak', value: counts.rejected }
                ].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>

              {/* TABS NAVIGATION */}
              <div style={{ display: 'flex', borderBottom: '2.5px solid #efefef', marginBottom: 20, gap: 24 }}>
                {[
                  { id: 'pending', label: 'Inbox Persetujuan', icon: 'bx-envelope' },
                  { id: 'history', label: 'Riwayat Otorisasi', icon: 'bx-history' }
                ].map(tab => {
                  const isActive = activeTab === tab.id;
                  const isPendingTab = tab.id === 'pending';
                  const countBadge = isPendingTab ? pendingCount : 0;
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id)}
                      style={{
                        background: 'none', border: 'none', padding: '12px 4px', fontSize: 13.5, fontWeight: isActive ? 750 : 600,
                        color: isActive ? TEAL : '#a7a8a8', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
                        borderBottom: isActive ? `3.5px solid ${TEAL}` : '3.5px solid transparent', marginBottom: -3,
                        transition: 'all 150ms', fontFamily: 'inherit'
                      }}
                    >
                      <i className={`bx ${tab.icon}`} style={{ fontSize: 17 }} />
                      {tab.label}
                      {countBadge > 0 && (
                        <span style={{ display: 'inline-flex', background: ORANGE, color: '#fff', fontSize: 10.5, fontWeight: 700, borderRadius: 100, width: 18, height: 18, alignItems: 'center', justifyContent: 'center' }}>
                          {countBadge}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>

              {/* QUEUE 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', width: 140 }}>MID Merchant</th>
                      <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nama Merchant</th>
                      <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Jenis Usaha & Kategori</th>
                      <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Jenis Request</th>
                      <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu Pengajuan</th>
                      {activeTab !== 'pending' && (
                        <>
                          <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Pemeriksa</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: 140 }}>Aksi</th>
                    </tr>
                  </thead>
                  <tbody>
                    {visible.length === 0 ? (
                      <tr>
                        <td colSpan={activeTab === 'pending' ? '6' : '8'} style={{ padding: '40px 18px', textAlign: 'center', color: '#a7a8a8' }}>
                          <i className="bx bx-check-double" style={{ fontSize: 32, display: 'block', marginBottom: 8 }} />
                          {activeTab === 'pending' ? 'Semua pengajuan onboarding telah disetujui.' : 'Belum ada riwayat onboarding.'}
                        </td>
                      </tr>
                    ) : visible.map(m => {
                      const isApproved = m.status === 'approved';
                      const isRejected = m.status === 'rejected';

                      let reviewerInfo = '—';
                      let reviewTime = '';
                      if (m.l2) {
                        reviewerInfo = m.l2.by;
                        reviewTime = m.l2.at;
                      } else if (m.l1) {
                        reviewerInfo = m.l1.by;
                        reviewTime = m.l1.at;
                      }

                      return (
                        <tr key={m.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 }}>{m.id}</td>
                          <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{m.merchantName}</td>
                          <td style={{ padding: '14px 18px', color: '#515252', lineHeight: 1.4 }}>
                            <div>{m.businessType || '—'}</div>
                            <div style={{ fontSize: 11, color: '#a7a8a8' }}>{m.mcc || '—'} ({m.mccCode})</div>
                          </td>
                          <td style={{ padding: '14px 18px', color: '#515252' }}>{m.submittedBy || 'Arief Budiman'}</td>
                          <td style={{ padding: '14px 18px', color: '#a7a8a8' }}>{fmtDate(m.submittedAt)}</td>

                          {activeTab !== 'pending' && (
                            <>
                              <td style={{ padding: '14px 18px', color: '#515252' }}>
                                <div>{reviewerInfo}</div>
                                {reviewTime && <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{fmtDate(reviewTime)}</div>}
                              </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)' : 'rgba(0,86,210,0.10)'),
                                  color: isApproved ? '#74b50c' : (isRejected ? '#ed3151' : TEAL),
                                  fontSize: 11.5, fontWeight: 700, borderRadius: 4, padding: '3px 8px'
                                }}>
                                  {isApproved ? 'Approved' : (isRejected ? 'Rejected' : 'Pending L2')}
                                </span>
                              </td>
                            </>
                          )}

                          <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                            <button
                              onClick={() => { setSelected(m.id); setNote(''); }}
                              style={{
                                background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '6px 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}
                            >
                              <i className="bx bx-show" /> Detail
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 300,
          background: '#171919', color: '#fff', padding: '13px 22px', borderRadius: 100, fontSize: 13.5, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 9, boxShadow: '0 12px 32px rgba(23,25,25,0.25)', animation: 'slideUp 240ms ease'
        }}>
          <i className={`bx ${toast.kind === 'success' ? 'bx-check-circle' : 'bx-x-circle'}`} style={{ fontSize: 18, color: toast.kind === 'success' ? '#9be35a' : '#ff8095' }} />
          {toast.msg}
        </div>
      )}
    </div>
  );
}

// section wrapper
function Section({ title, icon, children }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <i className={`bx ${icon}`} style={{ fontSize: 16, color: '#0056D2' }} />
        <span style={{ fontSize: 13, fontWeight: 700, color: '#171919' }}>{title}</span>
      </div>
      <div>{children}</div>
    </div>
  );
}

Object.assign(window, { ApprovalPage });
