// merchant-management.jsx — Merchant Management page
function MerchantManagementPage({ onLogout, onNavigate, merchants, setMerchants, primary, secondary, sidebarColor, pendingApproval = 0, role = 'super', user }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c', RED = '#ed3151', AMBER = '#d9920b';

  const [sidebarOpen, setSidebarOpen] = React.useState(true);
  const [filter, setFilter] = React.useState('all'); // all | active | suspended | pending
  const [search, setSearch] = React.useState('');
  const [selectedMerchant, setSelectedMerchant] = React.useState(null); // for detail drawer
  const [qrisModal, setQrisModal] = React.useState(null); // for QRIS modal popup
  const [view, setView] = React.useState('list'); // 'list' | 'biz_config' | 'integration'
  const [activeMerchantId, setActiveMerchantId] = React.useState(null); // ID of merchant being configured
  const [sortCol, setSortCol] = React.useState('submittedAt');
  const [sortAsc, setSortAsc] = React.useState(false);

  // Formatting helpers
  const fmtRp = (v) => {
    const n = String(v).replace(/[^0-9]/g, '');
    return n ? 'Rp ' + Number(n).toLocaleString('id-ID') : '—';
  };
  const fmtDate = (iso) => new Date(iso).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });

  // Status handler: toggle between approved (Active) and suspended
  const toggleStatus = (id) => {
    setMerchants(prev => prev.map(m => {
      if (m.id !== id) return m;
      const newStatus = m.status === 'approved' ? 'suspended' : 'approved';
      return { ...m, status: newStatus };
    }));
  };

  const handleSaveBizConfig = (merchantId, updatedConfig) => {
    setMerchants(prev => prev.map(m => {
      if (m.id !== merchantId) return m;
      return {
        ...m,
        configList: updatedConfig.configList
      };
    }));
  };

  const handleSaveIntegration = (merchantId, updatedConfig) => {
    setMerchants(prev => prev.map(m => {
      if (m.id !== merchantId) return m;
      return {
        ...m,
        clientId: updatedConfig.clientId,
        clientSecret: updatedConfig.clientSecret,
        integrationMode: updatedConfig.integrationMode,
        webhookUrl: updatedConfig.webhookUrl,
        posList: updatedConfig.posList
      };
    }));
  };

  // Status details
  const getStatusInfo = (status) => {
    switch (status) {
      case 'approved':
        return { label: 'Aktif', color: GREEN, bg: 'rgba(116,181,12,0.12)', icon: 'bx-check-circle' };
      case 'suspended':
        return { label: 'Ditangguhkan', color: RED, bg: 'rgba(237,49,81,0.10)', icon: 'bx-block' };
      case 'pending_l1':
      case 'pending_l2':
        return { label: 'Pending Approval', color: AMBER, bg: 'rgba(217,146,11,0.12)', icon: 'bx-time-five' };
      case 'rejected':
        return { label: 'Ditolak', color: '#777', bg: 'rgba(161,168,168,0.15)', icon: 'bx-x-circle' };
      default:
        return { label: status, color: '#777', bg: '#efefef', icon: 'bx-help-circle' };
    }
  };

  // Stats calculation
  const stats = [
    { label: 'Total Merchant', value: merchants.length, icon: 'bx-store', color: TEAL },
    { label: 'Merchant Aktif', value: merchants.filter(m => m.status === 'approved').length, icon: 'bx-check-circle', color: GREEN },
    { label: 'Ditangguhkan', value: merchants.filter(m => m.status === 'suspended').length, icon: 'bx-block', color: RED },
    { label: 'Menunggu Approval', value: merchants.filter(m => m.status === 'pending_l1' || m.status === 'pending_l2').length, icon: 'bx-time', color: AMBER },
  ];

  // Filtering and searching logic
  const filteredMerchants = merchants
    .filter(m => {
      if (filter === 'active') return m.status === 'approved';
      if (filter === 'suspended') return m.status === 'suspended';
      if (filter === 'pending') return m.status === 'pending_l1' || m.status === 'pending_l2';
      return true; // all
    })
    .filter(m => {
      if (!search) return true;
      const q = search.toLowerCase();
      return (
        m.id.toLowerCase().includes(q) ||
        m.merchantName.toLowerCase().includes(q) ||
        m.picName.toLowerCase().includes(q) ||
        (m.mKabupaten && m.mKabupaten.toLowerCase().includes(q))
      );
    })
    .sort((a, b) => {
      const av = a[sortCol] || '', bv = b[sortCol] || '';
      if (av < bv) return sortAsc ? -1 : 1;
      if (av > bv) return sortAsc ? 1 : -1;
      return 0;
    });

  const handleSort = (col) => {
    if (sortCol === col) setSortAsc(!sortAsc);
    else { setSortCol(col); setSortAsc(true); }
  };

  const SortIcon = ({ col }) => {
    if (sortCol !== col) return <i className="bx bx-sort-alt-2" style={{ fontSize: 12, opacity: 0.3 }} />;
    return <i className={`bx bx-sort-${sortAsc ? 'up' : 'down'}`} style={{ fontSize: 12, color: TEAL }} />;
  };

  const activeMerchant = merchants.find(m => m.id === activeMerchantId);

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden', fontFamily: "'Open Sans', sans-serif" }}>
      <Sidebar activeNav="merchant_management" setActiveNav={(id) => onNavigate(id)} sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} onLogout={onLogout} pendingApproval={pendingApproval} primary={TEAL} secondary={ORANGE} sidebarBg={sidebarColor} role={role} 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: 18 }} />
          </button>
          <div style={{ flex: 1 }}>
            {view === 'list' && (
              <>
                <span style={{ fontSize: 15, fontWeight: 700, color: '#171919' }}>Merchant Management</span>
                <span style={{ fontSize: 12, color: '#a7a8a8', marginLeft: 8 }}>Kelola status operasional, parameter, dan kode QRIS merchant</span>
              </>
            )}
            {view === 'biz_config' && (
              <>
                <span style={{ fontSize: 15, fontWeight: 700, color: '#171919' }}>Konfigurasi Bisnis</span>
                <span style={{ fontSize: 12, color: '#a7a8a8', marginLeft: 8 }}>Pengaturan parameter operasional & biaya merchant</span>
              </>
            )}
            {view === 'integration' && (
              <>
                <span style={{ fontSize: 15, fontWeight: 700, color: '#171919' }}>Integrasi API & POS</span>
                <span style={{ fontSize: 12, color: '#a7a8a8', marginLeft: 8 }}>Kelola kredensial pengembang dan terminal POS merchant</span>
              </>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 32, height: 32, borderRadius: '50%', background: `linear-gradient(135deg, ${TEAL}, #0041A8)`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ color: '#fff', fontWeight: 700, fontSize: 12 }}>AB</span>
            </div>
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '28px 32px 56px' }}>
          
          {view === 'list' && (
            <>
              {/* 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: 6 }}>Katalog Merchant</div>
              <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Kelola Data Merchant</h1>
              <p style={{ fontSize: 14, color: '#515252', marginTop: 4, marginBottom: 0 }}>Aktifkan, tangguhkan, atau tinjau QRIS & profil keuangan merchant terdaftar.</p>
            </div>
            <button
              onClick={() => onNavigate('onboarding_portal')}
              style={{
                background: TEAL, color: '#fff', border: 'none', borderRadius: 100,
                padding: '12px 24px', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${TEAL}25`,
                transition: 'all 150ms'
              }}
              onMouseEnter={e => e.currentTarget.style.background = '#3A7EE0'}
              onMouseLeave={e => e.currentTarget.style.background = TEAL}
            >
              <i className="bx bx-plus" style={{ fontSize: 16 }} /> Daftarkan Merchant Baru
            </button>
          </div>

          {/* STATS */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
            {stats.map((s, i) => (
              <div key={i} style={{ background: '#fff', borderRadius: 14, padding: '20px 18px', border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#515252' }}>{s.label}</span>
                  <div style={{ width: 34, height: 34, borderRadius: '50%', background: `${s.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <i className={`bx ${s.icon}`} style={{ fontSize: 18, color: s.color }} />
                  </div>
                </div>
                <div style={{ fontSize: 28, fontWeight: 800, color: '#171919', lineHeight: 1 }}>{s.value}</div>
              </div>
            ))}
          </div>

          {/* TABLE CONTAINER */}
          <div style={{ background: '#fff', borderRadius: 15, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', overflow: 'hidden' }}>
            
            {/* Filter and search bar */}
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #efefef', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
              {/* Filter Dropdown */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: '#515252' }}>Status:</span>
                <div style={{ position: 'relative' }}>
                  <select
                    value={filter}
                    onChange={e => setFilter(e.target.value)}
                    style={{
                      padding: '6px 32px 6px 12px',
                      borderRadius: 8,
                      border: '1.5px solid #efefef',
                      fontSize: 12.5,
                      fontWeight: 600,
                      color: '#171919',
                      fontFamily: 'inherit',
                      background: '#fff',
                      cursor: 'pointer',
                      outline: 'none',
                      appearance: 'none',
                      transition: 'border-color 150ms',
                    }}
                    onFocus={e => e.target.style.borderColor = TEAL}
                    onBlur={e => e.target.style.borderColor = '#efefef'}
                  >
                    <option value="all">Semua ({merchants.length})</option>
                    <option value="active">Aktif ({merchants.filter(m => m.status === 'approved').length})</option>
                    <option value="suspended">Ditangguhkan ({merchants.filter(m => m.status === 'suspended').length})</option>
                    <option value="pending">Menunggu Approval ({merchants.filter(m => m.status === 'pending_l1' || m.status === 'pending_l2').length})</option>
                  </select>
                  <i className="bx bx-chevron-down" style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', fontSize: 16, color: '#a7a8a8', pointerEvents: 'none' }} />
                </div>
              </div>

              {/* Search input */}
              <div style={{ position: 'relative', width: 260 }}>
                <i className="bx bx-search" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 16, color: '#a7a8a8' }} />
                <input
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  placeholder="Cari ID, nama merchant, kota..."
                  style={{
                    width: '100%', padding: '9px 12px 9px 36px', borderRadius: 8, border: '1.5px solid #efefef',
                    fontSize: 12.5, outline: 'none', fontFamily: 'inherit', transition: 'all 150ms'
                  }}
                  onFocus={e => e.target.style.borderColor = TEAL}
                  onBlur={e => e.target.style.borderColor = '#efefef'}
                />
              </div>
            </div>

            {/* Merchant Table */}
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
                <thead>
                  <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
                    {[
                      { key: 'id', label: 'MID' },
                      { key: 'merchantName', label: 'Nama Merchant' },
                      { key: 'businessType', label: 'Jenis Usaha' },
                      { key: 'monthlyOmset', label: 'Omset/Bulan' },
                      { key: 'mKabupaten', label: 'Kota/Kabupaten' },
                      { key: 'status', label: 'Status' },
                      { key: 'actions', label: 'Aksi' }
                    ].map(col => {
                      const canSort = col.key !== 'actions';
                      return (
                        <th
                          key={col.key}
                          onClick={() => canSort && handleSort(col.key)}
                          style={{
                            padding: '14px 20px', textAlign: 'left', fontSize: 11, fontWeight: 700,
                            color: '#a7a8a8', letterSpacing: '0.04em', textTransform: 'uppercase',
                            cursor: canSort ? 'pointer' : 'default', userSelect: 'none'
                          }}
                        >
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                            {col.label} {canSort && <SortIcon col={col.key} />}
                          </span>
                        </th>
                      );
                    })}
                  </tr>
                </thead>
                <tbody>
                  {filteredMerchants.length === 0 ? (
                    <tr>
                      <td colSpan="7" style={{ padding: '48px 24px', textAlign: 'center', color: '#a7a8a8' }}>
                        <i className="bx bx-store-alt" style={{ fontSize: 40, display: 'block', marginBottom: 12 }} />
                        Tidak ada merchant terdaftar dalam filter ini
                      </td>
                    </tr>
                  ) : filteredMerchants.map(m => {
                    const st = getStatusInfo(m.status);
                    const isPending = m.status === 'pending_l1' || m.status === 'pending_l2';
                    const isRejected = m.status === 'rejected';

                    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'}
                      >
                        {/* MID */}
                        <td style={{ padding: '16px 20px', fontWeight: 600, color: TEAL, fontSize: 12.5, fontFamily: 'monospace' }}>
                          {m.id}
                        </td>

                        {/* Name */}
                        <td style={{ padding: '16px 20px' }}>
                          <div style={{ fontWeight: 700, color: '#171919' }}>{m.merchantName}</div>
                          <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>PIC: {m.picName}</div>
                        </td>

                        {/* Business Type */}
                        <td style={{ padding: '16px 20px', color: '#515252' }}>
                          {m.businessType || '—'}
                        </td>

                        {/* Monthly Omset */}
                        <td style={{ padding: '16px 20px', fontWeight: 600, color: '#171919' }}>
                          {fmtRp(m.monthlyOmset)}
                        </td>

                        {/* City */}
                        <td style={{ padding: '16px 20px', color: '#515252' }}>
                          {m.mKabupaten || m.mProvinsi || '—'}
                        </td>

                        {/* Status */}
                        <td style={{ padding: '16px 20px' }}>
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: st.bg, color: st.color, fontSize: 11.5, fontWeight: 600, borderRadius: 100, padding: '4px 11px', whiteSpace: 'nowrap' }}>
                            <i className={`bx ${st.icon}`} style={{ fontSize: 13 }} /> {st.label}
                          </span>
                        </td>

                        {/* Actions */}
                        <td style={{ padding: '16px 20px', whiteSpace: 'nowrap' }}>
                          <div style={{ display: 'flex', gap: 8 }}>
                            <button
                              onClick={() => setSelectedMerchant(m)}
                              style={{
                                border: '1.5px solid #efefef', background: '#fff', color: '#515252',
                                borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                                cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                                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-show" /> Detail
                            </button>

                            {m.status === 'approved' || m.status === 'suspended' ? (
                              <>
                                <button
                                  onClick={() => { setActiveMerchantId(m.id); setView('biz_config'); }}
                                  style={{
                                    border: '1.5px solid #efefef', background: '#fff', color: '#515252',
                                    borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                                    cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                                    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-slider-alt" /> Business Config
                                </button>

                                <button
                                  onClick={() => { setActiveMerchantId(m.id); setView('integration'); }}
                                  style={{
                                    border: '1.5px solid #efefef', background: '#fff', color: '#515252',
                                    borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                                    cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                                    transition: 'all 150ms'
                                  }}
                                  onMouseEnter={e => { e.currentTarget.style.borderColor = '#4F46E5'; e.currentTarget.style.color = '#4F46E5'; }}
                                  onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                                >
                                  <i className="bx bx-code-curly" /> Integration
                                </button>

                                <button
                                  onClick={() => setQrisModal(m)}
                                  style={{
                                    border: '1.5px solid #efefef', background: '#fff', color: '#515252',
                                    borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                                    cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                                    transition: 'all 150ms'
                                  }}
                                  onMouseEnter={e => { e.currentTarget.style.borderColor = ORANGE; e.currentTarget.style.color = ORANGE; }}
                                  onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                                >
                                  <i className="bx bx-qr-scan" /> QRIS
                                </button>

                                <button
                                  onClick={() => toggleStatus(m.id)}
                                  style={{
                                    border: 'none', borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                                    cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                                    background: m.status === 'approved' ? 'rgba(237,49,81,0.1)' : 'rgba(116,181,12,0.1)',
                                    color: m.status === 'approved' ? RED : GREEN,
                                    transition: 'all 150ms'
                                  }}
                                  onMouseEnter={e => {
                                    e.currentTarget.style.background = m.status === 'approved' ? RED : GREEN;
                                    e.currentTarget.style.color = '#fff';
                                  }}
                                  onMouseLeave={e => {
                                    e.currentTarget.style.background = m.status === 'approved' ? 'rgba(237,49,81,0.1)' : 'rgba(116,181,12,0.1)';
                                    e.currentTarget.style.color = m.status === 'approved' ? RED : GREEN;
                                  }}
                                >
                                  <i className={`bx ${m.status === 'approved' ? 'bx-block' : 'bx-play'}`} />
                                  {m.status === 'approved' ? 'Tangguhkan' : 'Aktifkan'}
                                </button>
                              </>
                            ) : (
                              <span style={{ fontSize: 11.5, color: '#a7a8a8', padding: '6px 0', fontStyle: 'italic' }}>
                                {isRejected ? 'Tinjauan Ditolak' : 'Proses Approval'}
                              </span>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {/* Pagination Footer */}
            <div style={{ padding: '16px 24px', borderTop: '1px solid #efefef', display: 'flex', justifyBetween: 'space-between', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: '#a7a8a8' }}>
                Menampilkan {filteredMerchants.length} dari {merchants.length} merchant terdaftar
              </span>
              <div style={{ display: 'flex', gap: 4 }}>
                <button style={{ width: 28, height: 28, borderRadius: 6, border: 'none', background: TEAL, color: '#fff', fontSize: 12, fontWeight: 600 }}>1</button>
              </div>
            </div>

          </div>
          </>
        )}

        {view === 'biz_config' && activeMerchant && (
          <BusinessConfigPage
            merchant={activeMerchant}
            onBack={() => setView('list')}
            onSave={handleSaveBizConfig}
            primary={TEAL}
            secondary={ORANGE}
          />
        )}

        {view === 'integration' && activeMerchant && (
          <IntegrationPage
            merchant={activeMerchant}
            onBack={() => setView('list')}
            onSave={handleSaveIntegration}
            primary={TEAL}
            secondary={ORANGE}
          />
        )}

        </div>
      </div>

      {/* DETAIL DRAWER */}
      {selectedMerchant && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1200, display: 'flex', justifyContent: 'flex-end' }}>
          <div onClick={() => setSelectedMerchant(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 200ms ease' }} />
          <div style={{ position: 'relative', width: 500, maxWidth: '90vw', height: '100%', background: '#fff', boxShadow: '-16px 0 48px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideInRight 280ms cubic-bezier(0.22, 0.61, 0.36, 1)' }}>
            
            {/* Drawer Header */}
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #efefef', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(0,86,210,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i className="bx bx-store-alt" style={{ fontSize: 20, color: TEAL }} />
                </div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: '#171919' }}>{selectedMerchant.merchantName}</div>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', fontFamily: 'monospace' }}>{selectedMerchant.id}</div>
                </div>
              </div>
              <button onClick={() => setSelectedMerchant(null)} style={{ background: '#f6f6f6', border: 'none', borderRadius: 8, width: 32, height: 32, cursor: 'pointer', color: '#515252', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i className="bx bx-x" style={{ fontSize: 20 }} />
              </button>
            </div>

            {/* Drawer Body */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '24px' }}>
              
              {/* Profile Card */}
              <div style={{ background: 'rgba(0,86,210,0.04)', border: '1px solid rgba(0,86,210,0.1)', borderRadius: 12, padding: 16, marginBottom: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                  <span style={{ fontSize: 11.5, fontWeight: 700, color: '#a7a8a8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Status Merchant</span>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: getStatusInfo(selectedMerchant.status).bg, color: getStatusInfo(selectedMerchant.status).color, fontSize: 11, fontWeight: 700, borderRadius: 6, padding: '3px 8px' }}>
                    {getStatusInfo(selectedMerchant.status).label}
                  </span>
                </div>
                
                {/* MID Info */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div>
                    <span style={{ fontSize: 11, color: '#a7a8a8' }}>NMID</span>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>NMID{selectedMerchant.id.slice(-8)}</div>
                  </div>
                  <div>
                    <span style={{ fontSize: 11, color: '#a7a8a8' }}>Tanggal Gabung</span>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>{fmtDate(selectedMerchant.submittedAt)}</div>
                  </div>
                </div>
              </div>

              {/* Data Usaha */}
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#a7a8a8', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12, borderBottom: '1.5px solid #efefef', paddingBottom: 6 }}>
                  Informasi Usaha
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Kategori (MCC)</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919', textAlign: 'right' }}>{selectedMerchant.mcc || '—'} (Code: {selectedMerchant.mccCode})</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Tipe Bisnis</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919' }}>{selectedMerchant.businessType || '—'}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>NPWP Usaha</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919', fontFamily: 'monospace' }}>{selectedMerchant.npwp || '—'}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Omset Bulanan</span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>{fmtRp(selectedMerchant.monthlyOmset)}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8', flexShrink: 0 }}>Alamat Lengkap</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919', textAlign: 'right', lineHeight: 1.4 }}>
                      {selectedMerchant.mAddress}, {selectedMerchant.mKelurahan}, {selectedMerchant.mKecamatan}, {selectedMerchant.mKabupaten}, {selectedMerchant.mProvinsi} {selectedMerchant.mPostal}
                    </span>
                  </div>
                </div>
              </div>

              {/* Data PIC */}
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#a7a8a8', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12, borderBottom: '1.5px solid #efefef', paddingBottom: 6 }}>
                  Penanggung Jawab (PIC)
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Nama PIC</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919' }}>{selectedMerchant.picName}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>No. Telepon</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919', fontFamily: 'monospace' }}>+62 {selectedMerchant.picPhone}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>NIK e-KTP</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919', fontFamily: 'monospace' }}>{selectedMerchant.nik || '—'}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Alamat Email</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919' }}>{selectedMerchant.email}</span>
                  </div>
                </div>
              </div>

              {/* Data Rekening */}
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#a7a8a8', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12, borderBottom: '1.5px solid #efefef', paddingBottom: 6 }}>
                  Rekening Pencairan
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Nama Bank</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919' }}>{selectedMerchant.bankName}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #f9f9f9', paddingBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Nomor Rekening</span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: TEAL, fontFamily: 'monospace' }}>{selectedMerchant.accountNumber}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 12.5, color: '#a7a8a8' }}>Nama Pemilik</span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: '#171919' }}>{selectedMerchant.accountHolder}</span>
                  </div>
                </div>
              </div>

            </div>

            {/* Drawer Footer */}
            <div style={{ padding: '16px 24px', borderTop: '1px solid #efefef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <button onClick={() => setSelectedMerchant(null)} style={{ background: '#f6f6f6', border: 'none', borderRadius: 8, padding: '10px 18px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer' }}>
                Tutup
              </button>
            </div>

          </div>
        </div>
      )}

      {/* QRIS MODAL */}
      {qrisModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1300, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(23,25,25,0.5)', backdropFilter: 'blur(4px)', animation: 'fadeIn 200ms ease' }} onClick={() => setQrisModal(null)}>
          <div style={{ background: '#fff', borderRadius: 16, padding: '24px', width: 380, maxWidth: '90%', display: 'flex', flexDirection: 'column', alignItems: 'center', boxShadow: '0 24px 48px rgba(0,0,0,0.2)', animation: 'slideUp 300ms cubic-bezier(0.22, 0.68, 0, 1.1)' }} onClick={e => e.stopPropagation()}>
            
            {/* Modal Header */}
            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
              <span style={{ fontSize: 14, fontWeight: 800, color: '#171919' }}>QRIS Code Merchant</span>
              <button onClick={() => setQrisModal(null)} style={{ background: '#f6f6f6', border: 'none', borderRadius: '50%', width: 28, height: 28, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#515252' }}>
                <i className="bx bx-x" style={{ fontSize: 18 }} />
              </button>
            </div>

            {/* QRIS STICKER CARD (Simulated CSS) */}
            <div style={{
              width: 320, background: '#fff', border: '2px solid #efefef', borderRadius: 16,
              overflow: 'hidden', display: 'flex', flexDirection: 'column', alignItems: 'center',
              boxShadow: '0 8px 16px rgba(0,0,0,0.06)', position: 'relative'
            }}>
              
              {/* Yellow Sticker Header */}
              <div style={{ width: '100%', background: '#FCD116', padding: '12px 16px', display: 'flex', flexDirection: 'column', alignItems: 'center', borderBottom: '2px solid #e0b60d' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ fontSize: 22, fontWeight: 900, color: '#0056D2', letterSpacing: '-1px', fontStyle: 'italic' }}>QR</span>
                  <span style={{ fontSize: 22, fontWeight: 900, color: '#ed3151', letterSpacing: '-1px', fontStyle: 'italic' }}>IS</span>
                </div>
                <span style={{ fontSize: 8, fontWeight: 800, color: '#171919', textTransform: 'uppercase', letterSpacing: '0.15em', marginTop: 2 }}>QR Code Indonesian Standard</span>
              </div>

              {/* Merchant Title Block */}
              <div style={{ width: '100%', padding: '16px 16px 12px', textAlign: 'center' }}>
                <div style={{ fontSize: 15, fontWeight: 800, color: '#171919', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{qrisModal.merchantName}</div>
                <div style={{ fontSize: 10, color: '#a7a8a8', marginTop: 4, fontFamily: 'monospace' }}>NMID: NMID{qrisModal.id.slice(-8)}</div>
              </div>

              {/* QR Code Graphic Box */}
              <div style={{
                width: 200, height: 200, border: '4px solid #171919', borderRadius: 12,
                display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fff',
                marginBottom: 16, padding: 8, position: 'relative'
              }}>
                {/* Stylized QR icon representing high-fidelity mockup */}
                <i className="bx bx-qr-scan" style={{ fontSize: 160, color: '#171919' }} />
                
                {/* Floating miniature hibank logo in center of QR */}
                <div style={{
                  position: 'absolute', width: 42, height: 42, background: '#fff',
                  border: '3px solid #171919', borderRadius: 8, display: 'flex',
                  alignItems: 'center', justifyContent: 'center', zIndex: 5
                }}>
                  <span style={{ color: TEAL, fontWeight: 900, fontSize: 14 }}>hi</span>
                </div>
              </div>

              {/* Acceptance Notice */}
              <div style={{ width: '100%', padding: '0 16px 16px', textAlign: 'center' }}>
                <div style={{ fontSize: 9, fontWeight: 700, color: '#515252', lineHeight: 1.4, margin: '0 auto', maxWidth: 220 }}>
                  Dapat Menerima Pembayaran GPN Melalui Semua Penyedia Jasa Pembayaran Elektronik
                </div>
                
                {/* Small Payment Badges */}
                <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 12 }}>
                  {['hi-payment', 'GPN', 'OVO', 'GOPAY', 'DANA'].map(net => (
                    <span key={net} style={{ fontSize: 7.5, fontWeight: 800, color: '#777', border: '1px solid #efefef', borderRadius: 4, padding: '2px 5px', background: '#fafafa' }}>
                      {net}
                    </span>
                  ))}
                </div>
              </div>

            </div>

            {/* Modal Actions */}
            <div style={{ width: '100%', display: 'flex', gap: 10, marginTop: 20 }}>
              <button
                onClick={() => { alert(`Mengunduh QRIS sticker untuk ${qrisModal.merchantName}`); setQrisModal(null); }}
                style={{
                  flex: 1, background: TEAL, color: '#fff', border: 'none', borderRadius: 8,
                  padding: '10px', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  boxShadow: `0 4px 12px ${TEAL}25`
                }}
              >
                <i className="bx bx-download" /> Unduh QRIS (PNG)
              </button>
              <button
                onClick={() => setQrisModal(null)}
                style={{
                  background: '#f6f6f6', color: '#515252', border: 'none', borderRadius: 8,
                  padding: '10px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer'
                }}
              >
                Tutup
              </button>
            </div>

          </div>
        </div>
      )}

    </div>
  );
}

// ── BUSINESS CONFIGURATION SUB-PAGE ──
function BusinessConfigPage({ merchant, onBack, onSave, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';

  // Initialize config list with defaults if not present
  const defaultConfigs = [
    { id: 'CFG-001', name: 'Siklus Settlement', value: merchant.settlementCycle || 'H+1', desc: 'Siklus pemindahan bukuan dana hasil transaksi QRIS ke rekening pencairan merchant.' },
    { id: 'CFG-002', name: 'MDR Fee QRIS', value: merchant.mdrFee || '0.7%', desc: 'Persentase potongan biaya per transaksi untuk QRIS Reguler.' },
    { id: 'CFG-003', name: 'Limit per Transaksi', value: merchant.trxLimit !== undefined ? 'Rp ' + Number(merchant.trxLimit).toLocaleString('id-ID') : 'Rp 10.000.000', desc: 'Batas maksimal nominal pembayaran dalam satu kali scan QRIS.' },
    { id: 'CFG-004', name: 'Limit Akumulasi Harian', value: merchant.dailyLimit !== undefined ? 'Rp ' + Number(merchant.dailyLimit).toLocaleString('id-ID') : 'Rp 100.000.000', desc: 'Batas kumulatif penerimaan dana QRIS dalam satu hari kalender.' },
    { id: 'CFG-005', name: 'Metode QRIS Standard', value: 'Aktif', desc: 'Scan e-wallet / mobile banking (Gopay, OVO, Dana, LinkAja).' },
    { id: 'CFG-006', name: 'Metode GPN Debit', value: 'Aktif', desc: 'Gerbang Pembayaran Nasional untuk kartu debit kartu fisik.' }
  ];

  const [configList, setConfigList] = React.useState(merchant.configList || defaultConfigs);

  // Modal / popup states
  const [showAddModal, setShowAddModal] = React.useState(false);
  const [editingConfig, setEditingConfig] = React.useState(null); // holds the config item being edited

  // Form states
  const [formName, setFormName] = React.useState('');
  const [formValue, setFormValue] = React.useState('');
  const [formDesc, setFormDesc] = React.useState('');

  const [showSuccessToast, setShowSuccessToast] = React.useState(false);

  // Setup form for editing
  const startEdit = (cfg) => {
    setEditingConfig(cfg);
    setFormName(cfg.name);
    setFormValue(cfg.value);
    setFormDesc(cfg.desc);
  };

  const handleSaveEdit = () => {
    if (!formName.trim() || !formValue.trim()) return;
    setConfigList(prev => prev.map(cfg => {
      if (cfg.id !== editingConfig.id) return cfg;
      return {
        ...cfg,
        name: formName.trim(),
        value: formValue.trim(),
        desc: formDesc.trim()
      };
    }));
    setEditingConfig(null);
    clearForm();
  };

  // Add new custom parameter
  const handleAddConfig = () => {
    if (!formName.trim() || !formValue.trim()) return;
    const nextSeq = configList.length + 1;
    const newId = `CFG-${String(nextSeq).padStart(3, '0')}`;
    const newCfg = {
      id: newId,
      name: formName.trim(),
      value: formValue.trim(),
      desc: formDesc.trim()
    };
    setConfigList(prev => [...prev, newCfg]);
    setShowAddModal(false);
    clearForm();
  };

  const clearForm = () => {
    setFormName('');
    setFormValue('');
    setFormDesc('');
  };

  const handleDeleteConfig = (id) => {
    setConfigList(prev => prev.filter(cfg => cfg.id !== id));
  };

  const handleSaveAll = () => {
    onSave(merchant.id, {
      configList
    });
    setShowSuccessToast(true);
    setTimeout(() => {
      setShowSuccessToast(false);
      onBack();
    }, 1500);
  };

  return (
    <div style={{ animation: 'fadeIn 200ms ease' }}>
      
      {/* Breadcrumb & Navigation */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <button onClick={onBack} 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' }}>
          Merchant Management / <span style={{ color: '#515252', fontWeight: 600 }}>{merchant.merchantName}</span> / <span style={{ color: TEAL, fontWeight: 700 }}>Konfigurasi Bisnis</span>
        </div>
      </div>

      {/* Header Info */}
      <div style={{ background: '#fff', borderRadius: 12, padding: '20px 24px', border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 48, height: 48, borderRadius: 10, background: `${TEAL}10`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i className="bx bx-store-alt" style={{ fontSize: 24, color: TEAL }} />
          </div>
          <div>
            <h2 style={{ fontSize: 18, fontWeight: 800, color: '#171919', margin: 0 }}>{merchant.merchantName}</h2>
            <div style={{ fontSize: 12, color: '#a7a8a8', marginTop: 4, fontFamily: 'monospace' }}>MID: {merchant.id} | PIC: {merchant.picName}</div>
          </div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: merchant.status === 'approved' ? 'rgba(116,181,12,0.12)' : 'rgba(237,49,81,0.1)', color: merchant.status === 'approved' ? '#74b50c' : '#ed3151', fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '4px 10px' }}>
          <i className={`bx ${merchant.status === 'approved' ? 'bx-check-circle' : 'bx-block'}`} /> {merchant.status === 'approved' ? 'Merchant Aktif' : 'Merchant Ditangguhkan'}
        </span>
      </div>

      {/* TABULAR CONFIG LIST CARD */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', overflow: 'hidden', marginBottom: 24 }}>
        <div style={{ padding: '18px 24px', borderBottom: '1px solid #efefef', background: '#fafafa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h3 style={{ fontSize: 14, fontWeight: 800, color: '#171919', margin: 0 }}>Daftar Parameter Konfigurasi Bisnis</h3>
            <p style={{ fontSize: 12, color: '#a7a8a8', margin: '4px 0 0' }}>Pengaturan parameter operasional & biaya merchant terstruktur dalam tabel.</p>
          </div>
          <button onClick={() => { clearForm(); setShowAddModal(true); }} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '9px 16px', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit', boxShadow: `0 4px 10px ${TEAL}20` }}>
            <i className="bx bx-plus" /> Tambah Parameter
          </button>
        </div>

        {/* Configurations Table */}
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
            <thead>
              <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'left', width: '120px' }}>Parameter ID</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'left', width: '220px' }}>Nama Parameter</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'left', width: '180px' }}>Nilai Konfigurasi</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'left' }}>Deskripsi</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center', width: '150px' }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {configList.length === 0 ? (
                <tr>
                  <td colSpan="5" style={{ padding: '32px', textAlign: 'center', color: '#a7a8a8' }}>
                    Belum ada parameter konfigurasi yang terdaftar.
                  </td>
                </tr>
              ) : configList.map(cfg => {
                const isCustom = !['CFG-001', 'CFG-002', 'CFG-003', 'CFG-004', 'CFG-005', 'CFG-006'].includes(cfg.id);
                return (
                  <tr key={cfg.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    {/* ID */}
                    <td style={{ padding: '14px 20px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>
                      {cfg.id}
                    </td>

                    {/* Name */}
                    <td style={{ padding: '14px 20px', fontWeight: 700, color: '#171919' }}>
                      {cfg.name}
                    </td>

                    {/* Value Badge */}
                    <td style={{ padding: '14px 20px' }}>
                      <span style={{ background: `${TEAL}10`, color: TEAL, fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '4px 10px', display: 'inline-block' }}>
                        {cfg.value}
                      </span>
                    </td>

                    {/* Description */}
                    <td style={{ padding: '14px 20px', color: '#515252', lineHeight: 1.4, fontSize: 12.5 }}>
                      {cfg.desc}
                    </td>

                    {/* Actions */}
                    <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                      <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
                        <button onClick={() => startEdit(cfg)} style={{ border: '1.5px solid #efefef', background: '#fff', color: '#515252', borderRadius: 6, padding: '5px 10px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 3 }}
                          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-edit" /> Edit
                        </button>
                        {isCustom && (
                          <button onClick={() => handleDeleteConfig(cfg.id)} style={{ border: 'none', background: 'rgba(237,49,81,0.08)', color: '#ed3151', borderRadius: 6, padding: '5px 10px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 3 }}
                            onMouseEnter={e => { e.currentTarget.style.background = '#ed3151'; e.currentTarget.style.color = '#fff'; }}
                            onMouseLeave={e => { e.currentTarget.style.background = 'rgba(237,49,81,0.08)'; e.currentTarget.style.color = '#ed3151'; }}>
                            <i className="bx bx-trash" /> Hapus
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Action Footer */}
      <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', background: '#fff', border: '1px solid #efefef', borderRadius: 12, padding: 16 }}>
        <button onClick={onBack} style={{ background: '#f6f6f6', border: 'none', borderRadius: 8, padding: '12px 24px', fontSize: 13.5, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>
          Batal & Kembali
        </button>
        <button onClick={handleSaveAll} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '12px 28px', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', boxShadow: `0 4px 12px ${TEAL}20` }}>
          Simpan Konfigurasi
        </button>
      </div>

      {/* Success Toast */}
      {showSuccessToast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1500, 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-circle" style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 700 }}>Konfigurasi Bisnis berhasil diperbarui!</span>
        </div>
      )}

      {/* ADD PARAMETER MODAL */}
      {showAddModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1400, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 150ms ease' }} onClick={() => setShowAddModal(false)}>
          <div style={{ background: '#fff', borderRadius: 12, padding: 24, width: 420, maxWidth: '90%', boxShadow: '0 20px 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideUp 250ms cubic-bezier(0.22, 0.68, 0, 1.1)' }} onClick={e => e.stopPropagation()}>
            
            <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', marginTop: 0, marginBottom: 16 }}>Tambah Parameter Konfigurasi</h3>
            
            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nama Parameter</label>
            <input type="text" placeholder="Contoh: Limit QRIS Internasional" value={formName} onChange={e => setFormName(e.target.value)} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />

            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nilai Konfigurasi</label>
            <input type="text" placeholder="Contoh: Rp 5.000.000 atau Aktif" value={formValue} onChange={e => setFormValue(e.target.value)} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />

            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Deskripsi</label>
            <textarea rows="3" placeholder="Jelaskan fungsi dari konfigurasi ini..." value={formDesc} onChange={e => setFormDesc(e.target.value)} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', resize: 'none', marginBottom: 20 }} />

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button onClick={() => setShowAddModal(false)} style={{ background: '#f6f6f6', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>Batal</button>
              <button onClick={handleAddConfig} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>Tambah Parameter</button>
            </div>
          </div>
        </div>
      )}

      {/* EDIT PARAMETER MODAL */}
      {editingConfig && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1400, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 150ms ease' }} onClick={() => setEditingConfig(null)}>
          <div style={{ background: '#fff', borderRadius: 12, padding: 24, width: 420, maxWidth: '90%', boxShadow: '0 20px 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideUp 250ms cubic-bezier(0.22, 0.68, 0, 1.1)' }} onClick={e => e.stopPropagation()}>
            
            <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', marginTop: 0, marginBottom: 16 }}>Edit Parameter Konfigurasi</h3>
            
            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nama Parameter</label>
            <input type="text" readOnly value={formName} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', background: '#fafafa', fontSize: 13, color: '#515252', outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />

            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nilai Konfigurasi</label>
            <input type="text" placeholder="Masukkan nilai..." value={formValue} onChange={e => setFormValue(e.target.value)} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />

            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Deskripsi</label>
            <textarea rows="3" placeholder="Jelaskan fungsi dari konfigurasi ini..." value={formDesc} onChange={e => setFormDesc(e.target.value)} style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', resize: 'none', marginBottom: 20 }} />

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button onClick={() => setEditingConfig(null)} style={{ background: '#f6f6f6', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>Batal</button>
              <button onClick={handleSaveEdit} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>Simpan Perubahan</button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}


// ── DEVELOPER INTEGRATION & POS SUB-PAGE ──
function IntegrationPage({ merchant, onBack, onSave, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';

  // Credentials states
  const [mode, setMode] = React.useState(merchant.integrationMode || 'sandbox');
  const [clientId] = React.useState(merchant.clientId || `cid_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_hb`);
  const [clientSecret, setClientSecret] = React.useState(merchant.clientSecret || `csec_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${Math.random().toString(36).slice(2, 10)}`);
  const [showSecret, setShowSecret] = React.useState(false);
  const [webhookUrl, setWebhookUrl] = React.useState(merchant.webhookUrl || `https://api.${merchant.merchantName.toLowerCase().replace(/[^a-z0-9]/g, '')}.co.id/v1/webhook`);

  // POS list state
  const [posList, setPosList] = React.useState(() => {
    if (merchant.posList && merchant.posList.length > 0) {
      return merchant.posList.map((pos, idx) => ({
        ...pos,
        clientId: pos.clientId || `cid_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${String(idx + 1).padStart(3, '0')}`
      }));
    }
    return [
      { id: 'POS-001', name: 'Kasir Utama (Lantai 1)', status: 'active', clientId: `cid_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_001`, publicKey: `pk_live_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_001_8a7d6e` },
      { id: 'POS-002', name: 'Kasir Cabang (Drive-thru)', status: 'active', clientId: `cid_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_002`, publicKey: `pk_live_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_002_4b5c2a` },
      { id: 'POS-003', name: 'POS Mobile Waiter', status: 'inactive', clientId: `cid_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_003`, publicKey: `pk_live_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_003_1f9e2d` }
    ];
  });

  // UI state
  const [showNewPosModal, setShowNewPosModal] = React.useState(false);
  const [newPosName, setNewPosName] = React.useState('');
  const [copiedKey, setCopiedKey] = React.useState(null);
  const [visibleKeys, setVisibleKeys] = React.useState([]);
  const [rotateConfirmPosId, setRotateConfirmPosId] = React.useState(null);
  const [showRotateConfirmSecret, setShowRotateConfirmSecret] = React.useState(false);
  const [showSuccessToast, setShowSuccessToast] = React.useState(false);

  // Copy helper
  const handleCopy = (text, fieldId) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(fieldId);
    setTimeout(() => setCopiedKey(null), 1500);
  };

  // Toggle public key visibility
  const toggleKeyVisibility = (posId) => {
    setVisibleKeys(prev => 
      prev.includes(posId) ? prev.filter(id => id !== posId) : [...prev, posId]
    );
  };

  // Regenerate public key for a POS
  const handleRegeneratePosKey = (posId) => {
    const randomHex = Math.random().toString(36).slice(2, 8);
    setPosList(prev => prev.map(pos => {
      if (pos.id !== posId) return pos;
      return {
        ...pos,
        publicKey: `pk_live_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${pos.id.replace('POS-', '')}_${randomHex}`
      };
    }));
    setRotateConfirmPosId(null);
  };

  // Toggle POS active status
  const togglePosStatus = (posId) => {
    setPosList(prev => prev.map(pos => {
      if (pos.id !== posId) return pos;
      return { ...pos, status: pos.status === 'active' ? 'inactive' : 'active' };
    }));
  };

  // Add new POS register
  const handleAddPos = () => {
    if (!newPosName.trim()) return;
    const nextSeq = posList.length + 1;
    const posId = `POS-${String(nextSeq).padStart(3, '0')}`;
    const randomHex = Math.random().toString(36).slice(2, 8);
    const newPos = {
      id: posId,
      name: newPosName.trim(),
      status: 'active',
      clientId: `cid_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${String(nextSeq).padStart(3, '0')}`,
      publicKey: `pk_live_pos_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${String(nextSeq).padStart(3, '0')}_${randomHex}`
    };
    setPosList(prev => [...prev, newPos]);
    setNewPosName('');
    setShowNewPosModal(false);
  };

  const handleRotateSecret = () => {
    const newSecret = `csec_${merchant.id.toLowerCase().replace(/[^a-z0-9]/g, '')}_${Math.random().toString(36).slice(2, 10)}${Math.random().toString(36).slice(2, 6)}`;
    setClientSecret(newSecret);
    setShowRotateConfirmSecret(false);
  };

  const handleSave = () => {
    onSave(merchant.id, {
      clientId,
      clientSecret,
      integrationMode: mode,
      webhookUrl,
      posList
    });
    setShowSuccessToast(true);
    setTimeout(() => {
      setShowSuccessToast(false);
      onBack();
    }, 1500);
  };

  return (
    <div style={{ animation: 'fadeIn 200ms ease' }}>
      
      {/* Breadcrumb */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <button onClick={onBack} 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' }}>
          Merchant Management / <span style={{ color: '#515252', fontWeight: 600 }}>{merchant.merchantName}</span> / <span style={{ color: '#4F46E5', fontWeight: 700 }}>Integrasi API & POS</span>
        </div>
      </div>

      {/* Header Info */}
      <div style={{ background: '#fff', borderRadius: 12, padding: '20px 24px', border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.04)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 48, height: 48, borderRadius: 10, background: 'rgba(79,70,229,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i className="bx bx-code-curly" style={{ fontSize: 24, color: '#4F46E5' }} />
          </div>
          <div>
            <h2 style={{ fontSize: 18, fontWeight: 800, color: '#171919', margin: 0 }}>{merchant.merchantName}</h2>
            <div style={{ fontSize: 12, color: '#a7a8a8', marginTop: 4, fontFamily: 'monospace' }}>MID: {merchant.id} | PIC: {merchant.picName}</div>
          </div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: merchant.status === 'approved' ? 'rgba(116,181,12,0.12)' : 'rgba(237,49,81,0.1)', color: merchant.status === 'approved' ? '#74b50c' : '#ed3151', fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '4px 10px' }}>
          <i className={`bx ${merchant.status === 'approved' ? 'bx-check-circle' : 'bx-block'}`} /> {merchant.status === 'approved' ? 'Merchant Aktif' : 'Merchant Ditangguhkan'}
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 24, marginBottom: 24 }}>

        {/* CARD: LIST POS MERCHANT */}
        <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: 'flex-start', marginBottom: 16 }}>
            <div>
              <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', margin: 0, display: 'flex', alignItems: 'center', gap: 6 }}>
                <i className="bx bx-cabinet" style={{ color: '#4F46E5' }} /> List POS Merchant & Public Keys
              </h3>
              <p style={{ fontSize: 12, color: '#a7a8a8', margin: '4px 0 0', lineHeight: 1.4 }}>
                Konfigurasi terminal kasir (POS) merchant. Setiap POS terdaftar memiliki Client ID dan Public Key khusus untuk verifikasi tanda tangan digital.
              </p>
            </div>
            <button onClick={() => setShowNewPosModal(true)} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '8px 16px', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit', boxShadow: `0 4px 10px ${TEAL}15` }}>
              <i className="bx bx-plus" /> Tambah Terminal POS
            </button>
          </div>

          {/* POS Table */}
          <div style={{ overflowX: 'auto', border: '1px solid #efefef', borderRadius: 10 }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
              <thead>
                <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Terminal ID</th>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Client ID</th>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nama POS / Outlet</th>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status</th>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Public Key POS</th>
                  <th style={{ padding: '12px 16px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Aksi</th>
                </tr>
              </thead>
              <tbody>
                {posList.length === 0 ? (
                  <tr>
                    <td colSpan="6" style={{ padding: '32px 16px', textAlign: 'center', color: '#a7a8a8' }}>
                      <i className="bx bx-info-circle" style={{ fontSize: 24, display: 'block', marginBottom: 6 }} />
                      Belum ada terminal POS yang terdaftar untuk merchant ini.
                    </td>
                  </tr>
                ) : posList.map(pos => {
                  const showKey = visibleKeys.includes(pos.id);
                  const isCopied = copiedKey === pos.id;

                  return (
                    <tr key={pos.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      {/* POS ID */}
                      <td style={{ padding: '14px 16px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>
                        {pos.id}
                      </td>

                      {/* Client ID */}
                      <td style={{ padding: '14px 16px', minWidth: 220 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <span style={{ fontFamily: 'monospace', fontWeight: 600, color: '#515252', background: '#fafafa', border: '1px solid #efefef', borderRadius: 4, padding: '4px 8px', fontSize: 12 }}>
                            {pos.clientId}
                          </span>
                          <button onClick={() => handleCopy(pos.clientId, `${pos.id}_client_id`)} style={{ background: 'none', border: 'none', width: 24, height: 24, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a7a8a8' }} title="Salin Client ID">
                            <i className="bx bx-copy" style={{ fontSize: 14 }} />
                          </button>
                          {copiedKey === `${pos.id}_client_id` && <span style={{ fontSize: 11, color: '#10B981', fontWeight: 600, whiteSpace: 'nowrap' }}>Tersalin!</span>}
                        </div>
                      </td>

                      {/* Name */}
                      <td style={{ padding: '14px 16px', fontWeight: 700, color: '#171919' }}>
                        {pos.name}
                      </td>

                      {/* Status */}
                      <td style={{ padding: '14px 16px' }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: pos.status === 'active' ? 'rgba(116,181,12,0.12)' : '#f6f6f6', color: pos.status === 'active' ? '#74b50c' : '#777', fontSize: 11.5, fontWeight: 600, borderRadius: 100, padding: '3px 9px' }}>
                          <span style={{ width: 6, height: 6, borderRadius: '50%', background: pos.status === 'active' ? '#74b50c' : '#777' }} />
                          {pos.status === 'active' ? 'Aktif' : 'Non-aktif'}
                        </span>
                      </td>

                      {/* Public Key Display */}
                      <td style={{ padding: '14px 16px', minWidth: 320 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <div style={{ display: 'flex', position: 'relative', flex: 1 }}>
                            <input
                              type={showKey ? 'text' : 'password'}
                              readOnly
                              value={pos.publicKey}
                              style={{
                                width: '100%', padding: '6px 64px 6px 10px', borderRadius: 6, border: '1px solid #efefef',
                                background: '#fafafa', fontSize: 12, fontFamily: 'monospace', color: '#515252', outline: 'none'
                              }}
                            />
                            <div style={{ position: 'absolute', right: 4, top: '50%', transform: 'translateY(-50%)', display: 'flex', gap: 2 }}>
                              <button onClick={() => toggleKeyVisibility(pos.id)} style={{ background: 'none', border: 'none', width: 24, height: 24, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a7a8a8' }}>
                                <i className={`bx ${showKey ? 'bx-hide' : 'bx-show'}`} style={{ fontSize: 14 }} />
                              </button>
                              <button onClick={() => handleCopy(pos.publicKey, pos.id)} style={{ background: 'none', border: 'none', width: 24, height: 24, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a7a8a8' }}>
                                <i className="bx bx-copy" style={{ fontSize: 14 }} />
                              </button>
                            </div>
                          </div>
                          {isCopied && <span style={{ fontSize: 11, color: '#10B981', fontWeight: 600, whiteSpace: 'nowrap' }}>Tersalin!</span>}
                        </div>

                        {/* Inline key rotation confirmation */}
                        {rotateConfirmPosId === pos.id ? (
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, background: 'rgba(237,49,81,0.04)', padding: '6px 8px', borderRadius: 4, border: '1px dashed rgba(237,49,81,0.2)' }}>
                            <span style={{ fontSize: 10.5, color: '#ed3151', fontWeight: 600 }}>Yakin regenerasi Public Key terminal ini?</span>
                            <button onClick={() => handleRegeneratePosKey(pos.id)} style={{ background: '#ed3151', color: '#fff', border: 'none', borderRadius: 3, padding: '2px 6px', fontSize: 9.5, cursor: 'pointer', fontWeight: 600 }}>Ya</button>
                            <button onClick={() => setRotateConfirmPosId(null)} style={{ background: '#fff', border: '1px solid #efefef', borderRadius: 3, padding: '2px 6px', fontSize: 9.5, color: '#515252', cursor: 'pointer', fontWeight: 600 }}>Batal</button>
                          </div>
                        ) : null}
                      </td>

                      {/* Actions */}
                      <td style={{ padding: '14px 16px', textAlign: 'center' }}>
                        <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
                          <button
                            onClick={() => togglePosStatus(pos.id)}
                            style={{
                              border: 'none', background: pos.status === 'active' ? 'rgba(237,49,81,0.08)' : 'rgba(116,181,12,0.08)',
                              color: pos.status === 'active' ? '#ed3151' : '#74b50c', borderRadius: 6, padding: '5px 10px',
                              fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 3
                            }}
                          >
                            <i className={`bx ${pos.status === 'active' ? 'bx-block' : 'bx-play-circle'}`} />
                            {pos.status === 'active' ? 'Deaktivasi' : 'Aktivasi'}
                          </button>
                          <button
                            onClick={() => setRotateConfirmPosId(pos.id)}
                            style={{
                              border: '1px solid #efefef', background: '#fff', color: '#515252', borderRadius: 6,
                              padding: '5px 8px', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                              display: 'flex', alignItems: 'center', gap: 3
                            }}
                            onMouseEnter={e => { e.currentTarget.style.borderColor = ORANGE; e.currentTarget.style.color = ORANGE; }}
                            onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                          >
                            <i className="bx bx-refresh" /> Rotate Key
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

      </div>

      {/* Action Footer */}
      <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', background: '#fff', border: '1px solid #efefef', borderRadius: 12, padding: 16 }}>
        <button onClick={onBack} style={{ background: '#f6f6f6', border: 'none', borderRadius: 8, padding: '12px 24px', fontSize: 13.5, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>
          Batal & Kembali
        </button>
        <button onClick={handleSave} style={{ background: '#4F46E5', color: '#fff', border: 'none', borderRadius: 8, padding: '12px 28px', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', boxShadow: '0 4px 12px rgba(79, 70, 229, 0.2)' }}>
          Simpan Kredensial & POS
        </button>
      </div>

      {/* Success Toast */}
      {showSuccessToast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1500, 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-circle" style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 700 }}>Integrasi & POS berhasil disimpan!</span>
        </div>
      )}

      {/* NEW POS MODAL (OVERLAY) */}
      {showNewPosModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1400, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(3px)', animation: 'fadeIn 150ms ease' }} onClick={() => setShowNewPosModal(false)}>
          <div style={{ background: '#fff', borderRadius: 12, padding: 24, width: 380, maxWidth: '90%', boxShadow: '0 20px 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', animation: 'slideUp 250ms cubic-bezier(0.22, 0.68, 0, 1.1)' }} onClick={e => e.stopPropagation()}>
            <h3 style={{ fontSize: 15, fontWeight: 800, color: '#171919', marginTop: 0, marginBottom: 16 }}>Tambah Terminal POS Baru</h3>
            <label style={{ fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nama POS / Kasir</label>
            <input
              type="text"
              placeholder="Contoh: Kasir Utama Belakang"
              value={newPosName}
              onChange={e => setNewPosName(e.target.value)}
              style={{ padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit', marginBottom: 20 }}
            />
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button onClick={() => setShowNewPosModal(false)} style={{ background: '#f6f6f6', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>Batal</button>
              <button onClick={handleAddPos} style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 6, padding: '8px 16px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>Tambah Terminal</button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

Object.assign(window, { MerchantManagementPage });
