// fds.jsx — Fraud Detection System (FDS) Dashboard & Sub-pages for Hibank QRIS BackOffice

const getInitialFdsAlerts = () => {
  const defaultAlerts = [
    { id: 'ALT-9901', txId: 'TX-260624-7701', time: '2026-06-24T14:10:00', merchant: 'Kopi Senja Nusantara', location: 'Bandung, ID', amount: 45000, score: 92, rule: 'Velocity Check: >5 transaksi dlm 1 menit', status: 'pending' },
    { id: 'ALT-9902', txId: 'TX-260624-7708', time: '2026-06-24T14:05:00', merchant: 'Batik Lestari Pekalongan', location: 'Jakarta, ID', amount: 5200000, score: 87, rule: 'Amount Outlier: >10x nominal rata-rata bulanan', status: 'investigating' },
    { id: 'ALT-9903', txId: 'TX-260624-7681', time: '2026-06-24T13:48:00', merchant: 'Toko Bangunan Maju Jaya', location: 'Surabaya, ID', amount: 1500000, score: 68, rule: 'Location Anomaly: Login & Trx bersamaan di 2 kota', status: 'approved' },
    { id: 'ALT-9904', txId: 'TX-260624-7540', time: '2026-06-24T12:15:00', merchant: 'Kopi Senja Nusantara', location: 'Medan, ID', amount: 25000, score: 55, rule: 'Velocity Check: Berulang dlm waktu sangat singkat', status: 'blocked' }
  ];

  if (!window.__fdsAlerts) {
    window.__fdsAlerts = defaultAlerts;
  }
  return window.__fdsAlerts;
};

const saveFdsAlerts = (data) => {
  window.__fdsAlerts = data;
};

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

  const [alerts, setAlerts] = React.useState(getInitialFdsAlerts());
  const [toast, setToast] = React.useState(null);
  const [activeAlertDetail, setActiveAlertDetail] = React.useState(null);

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

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

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

  const handleSimulateAlert = () => {
    const names = ['Kopi Senja Nusantara', 'Batik Lestari Pekalongan', 'Toko Bangunan Maju Jaya'];
    const rules = [
      'Velocity Check: >5 transaksi dlm 1 menit',
      'Amount Outlier: >10x nominal rata-rata bulanan',
      'Card Bin Suspicious: Transaksi luar negeri dlm volume berulang',
      'Location Anomaly: Pergerakan lokasi tidak wajar dlm 10 menit'
    ];
    const cities = ['Makassar, ID', 'Palembang, ID', 'Semarang, ID', 'Denpasar, ID'];
    const randomName = names[Math.floor(Math.random() * names.length)];
    const randomRule = rules[Math.floor(Math.random() * rules.length)];
    const randomCity = cities[Math.floor(Math.random() * cities.length)];
    const randomAmount = Math.floor(Math.random() * 500) * 10000 + 50000;
    const randomScore = Math.floor(Math.random() * 35) + 65; // score between 65 and 99

    const newAlert = {
      id: 'ALT-' + (Math.floor(Math.random() * 9000) + 1000),
      txId: 'TX-260624-' + (Math.floor(Math.random() * 9000) + 1000),
      time: new Date().toISOString(),
      merchant: randomName,
      location: randomCity,
      amount: randomAmount,
      score: randomScore,
      rule: randomRule,
      status: 'pending'
    };

    const updated = [newAlert, ...alerts];
    setAlerts(updated);
    saveFdsAlerts(updated);
    triggerToast(`Alert baru raised! Score: ${randomScore} (Risiko Tinggi)`);
  };

  const handleUpdateStatus = (id, newStatus) => {
    const updated = alerts.map(a => {
      if (a.id !== id) return a;
      return { ...a, status: newStatus };
    });
    setAlerts(updated);
    saveFdsAlerts(updated);
    if (activeAlertDetail && activeAlertDetail.id === id) {
      setActiveAlertDetail({ ...activeAlertDetail, status: newStatus });
    }
    triggerToast(`Status alert ${id} diubah ke ${newStatus.toUpperCase()}`);
  };

  const counts = {
    total: alerts.length,
    pending: alerts.filter(a => a.status === 'pending').length,
    investigating: alerts.filter(a => a.status === 'investigating').length,
    resolved: alerts.filter(a => a.status === 'approved' || a.status === 'blocked').length,
    blocked: alerts.filter(a => a.status === 'blocked').length
  };

  // Threat Vector indicators
  const threatVectors = [
    { label: 'Velocity Trx Exceeded', pct: 68, color: RED },
    { label: 'Outlier Transaction Amount', pct: 45, color: AMBER },
    { label: 'Location & IP Anomaly', pct: 28, color: TEAL },
    { label: 'Suspicious BIN / Card Present', pct: 15, color: '#64748b' }
  ];

  return (
    <div style={{ padding: '28px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase' }}>FDS Dashboard</span>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'rgba(16,185,129,0.12)', color: '#10B981', padding: '2px 8px', borderRadius: 100, fontSize: 10.5, fontWeight: 700 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#10B981' }} />
              PROTECTION ACTIVE
            </div>
          </div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Fraud Detection System</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Pantau ancaman penipuan, deteksi anomali real-time, dan respon cepat alert mencurigakan.</p>
        </div>

        <button
          onClick={handleSimulateAlert}
          style={{
            background: `linear-gradient(135deg, ${RED} 0%, #B91C1C 100%)`,
            color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px',
            fontSize: 12.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex',
            alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${RED}25`, transition: 'all 150ms',
            fontFamily: 'inherit'
          }}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'none'}
        >
          <i className="bx bx-run" style={{ fontSize: 16 }} />
          Simulasikan Percobaan Fraud
        </button>
      </div>

      {/* Stats Summary Cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Checked Trx', value: '142.842', sub: 'Semua transaksi terfilter', icon: 'bx-shield-quarter', color: TEAL },
          { label: 'Alert Aktif (Warning)', value: counts.pending + counts.investigating, sub: 'Butuh respon segera', icon: 'bx-error-circle', color: counts.pending > 0 ? RED : '#a7a8a8' },
          { label: 'Transaksi Diblokir', value: counts.blocked, sub: 'Pencegahan fraud berhasil', icon: 'bx-block', color: counts.blocked > 0 ? RED : '#a7a8a8' }
        ].map((card, i) => (
          <div key={i} style={{ background: '#fff', padding: '18px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 220 }}>
            <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>

      {/* Threat Vectors Breakdown */}
      <div style={{ background: '#fff', borderRadius: 14, padding: '20px 24px', border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', marginBottom: 24 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: '#171919', marginBottom: 4 }}>Threat Vectors Breakdown</div>
        <div style={{ fontSize: 12, color: '#a7a8a8', marginBottom: 20 }}>Distribusi anomali fraud yang paling sering mendominasi sistem</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {threatVectors.map((v, i) => (
            <div key={i}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ fontSize: 13.5, color: '#515252', fontWeight: 600 }}>{v.label}</span>
                <span style={{ fontSize: 13, fontWeight: 700, color: '#171919' }}>{v.pct}%</span>
              </div>
              <div style={{ height: 8, borderRadius: 100, background: '#efefef', overflow: 'hidden' }}>
                <div style={{ height: '100%', borderRadius: 100, background: v.color, width: `${v.pct}%`, transition: 'width .6s cubic-bezier(0.22,0.61,0.36,1)' }} />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Real-time Suspect Alerts table */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
        <div style={{ padding: '18px 24px', borderBottom: '1px solid #efefef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#171919' }}>Antrean Alert Suspicious Real-Time</div>
            <div style={{ fontSize: 12, color: '#a7a8a8', marginTop: 2 }}>Menampilkan log transaksi mencurigakan dengan nilai score anomali tinggi</div>
          </div>
        </div>

        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
          <thead>
            <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>ID Alert</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Merchant</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Lokasi & Trx</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Trigger Rule</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Risk Score</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' }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {alerts.map(a => {
              const isHigh = a.score >= 80;
              const isMedium = a.score >= 60 && a.score < 80;
              const scoreColor = isHigh ? RED : isMedium ? AMBER : TEAL;

              return (
                <tr key={a.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 }}>{a.id}</td>
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ fontWeight: 700, color: '#171919' }}>{a.merchant}</div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{a.txId}</div>
                  </td>
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ color: '#171919' }}>{a.location}</div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{fmtDate(a.time)}</div>
                  </td>
                  <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(a.amount)}</td>
                  <td style={{ padding: '14px 18px', color: '#515252', maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={a.rule}>{a.rule}</td>
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <span style={{
                      display: 'inline-flex', alignSelf: 'center',
                      background: `${scoreColor}10`, color: scoreColor,
                      fontSize: 12.5, fontWeight: 800, borderRadius: 6, padding: '3px 8px',
                      border: `1px solid ${scoreColor}25`
                    }}>
                      {a.score}
                    </span>
                  </td>
                  <td style={{ padding: '14px 18px' }}>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      background: a.status === 'blocked' ? 'rgba(237,49,81,0.1)' : (a.status === 'approved' ? 'rgba(116,181,12,0.12)' : (a.status === 'investigating' ? 'rgba(217,146,11,0.12)' : 'rgba(0,86,210,0.1)')),
                      color: a.status === 'blocked' ? RED : (a.status === 'approved' ? GREEN : (a.status === 'investigating' ? AMBER : TEAL)),
                      fontSize: 11, fontWeight: 700, borderRadius: 4, padding: '2px 7px'
                    }}>
                      {a.status.toUpperCase()}
                    </span>
                  </td>
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <button
                      onClick={() => setActiveAlertDetail(a)}
                      style={{
                        background: '#fff', border: '1.5px solid #efefef', borderRadius: 6, padding: '6px 12px',
                        fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', color: '#515252'
                      }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                    >
                      Periksa
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Drawer Detail Alert */}
      {activeAlertDetail && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1100, display: 'flex', justifyContent: 'flex-end' }}>
          <div onClick={() => setActiveAlertDetail(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(1.5px)' }} />

          <div style={{
            position: 'relative', width: 440, height: '100%', background: '#fff',
            boxShadow: '-8px 0 32px rgba(23,25,25,0.12)', display: 'flex', flexDirection: 'column',
            animation: 'slideInRight 220ms cubic-bezier(0.22, 0.61, 0.36, 1)'
          }}>
            {/* Header */}
            <div style={{ padding: '24px 28px', borderBottom: '1px solid #efefef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <span style={{ fontSize: 11, fontWeight: 700, color: TEAL, fontFamily: 'monospace' }}>{activeAlertDetail.id}</span>
                <h3 style={{ fontSize: 16, fontWeight: 800, color: '#171919', margin: '4px 0 0' }}>Detail Temuan Suspicious</h3>
              </div>
              <button onClick={() => setActiveAlertDetail(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 24 }} /></button>
            </div>

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

              {/* Risk Level Alert */}
              <div style={{ background: `${activeAlertDetail.score >= 80 ? RED : AMBER}10`, border: `1.5px solid ${activeAlertDetail.score >= 80 ? RED : AMBER}20`, borderRadius: 10, padding: '16px', display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
                <div style={{ width: 40, height: 40, borderRadius: '50%', background: activeAlertDetail.score >= 80 ? RED : AMBER, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className="bx bx-shield-quarter" style={{ fontSize: 20, color: '#fff' }} />
                </div>
                <div>
                  <div style={{ fontSize: 11, color: activeAlertDetail.score >= 80 ? RED : AMBER, fontWeight: 700, textTransform: 'uppercase' }}>Anomali HIGH RISK</div>
                </div>
              </div>

              {/* Transaction Data */}
              <div style={{ background: '#f6f6f6', borderRadius: 10, padding: '18px', display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #efefef', paddingBottom: 8 }}>
                  <span style={{ fontSize: 12, color: '#a7a8a8' }}>ID Transaksi</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: '#171919', fontFamily: 'monospace' }}>{activeAlertDetail.txId}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #efefef', paddingBottom: 8 }}>
                  <span style={{ fontSize: 12, color: '#a7a8a8' }}>Nama Merchant</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: '#171919' }}>{activeAlertDetail.merchant}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #efefef', paddingBottom: 8 }}>
                  <span style={{ fontSize: 12, color: '#a7a8a8' }}>Nominal Transaksi</span>
                  <span style={{ fontSize: 13, fontWeight: 750, color: '#171919' }}>{fmtRp(activeAlertDetail.amount)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #efefef', paddingBottom: 8 }}>
                  <span style={{ fontSize: 12, color: '#a7a8a8' }}>Lokasi / IP asal</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>{activeAlertDetail.location}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ fontSize: 12, color: '#a7a8a8' }}>Waktu Deteksi</span>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: '#171919' }}>{fmtDate(activeAlertDetail.time)}</span>
                </div>
              </div>

              {/* Trigger Rule Card */}
              <div style={{ background: '#fafafa', border: '1px solid #efefef', borderRadius: 10, padding: '16px', marginBottom: 24 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Aturan FDS yang Terlanggar</div>
                <p style={{ fontSize: 13, color: '#171919', lineHeight: 1.4, margin: 0, fontWeight: 600 }}>{activeAlertDetail.rule}</p>
              </div>

              {/* Action Buttons for investigation */}
              {activeAlertDetail.status === 'pending' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <button
                    onClick={() => handleUpdateStatus(activeAlertDetail.id, 'investigating')}
                    style={{ width: '100%', padding: '12px', background: AMBER, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer', boxShadow: `0 4px 12px ${AMBER}25` }}
                  >
                    Mulai Investigasi
                  </button>
                  <button
                    onClick={() => handleUpdateStatus(activeAlertDetail.id, 'blocked')}
                    style={{ width: '100%', padding: '12px', background: RED, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer', boxShadow: `0 4px 12px ${RED}25` }}
                  >
                    Blokir Permanen & Batalkan Trx
                  </button>
                </div>
              )}

              {activeAlertDetail.status === 'investigating' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <button
                    onClick={() => handleUpdateStatus(activeAlertDetail.id, 'approved')}
                    style={{ width: '100%', padding: '12px', background: GREEN, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer', boxShadow: `0 4px 12px ${GREEN}25` }}
                  >
                    Nyatakan Aman & Lunaskan
                  </button>
                  <button
                    onClick={() => handleUpdateStatus(activeAlertDetail.id, 'blocked')}
                    style={{ width: '100%', padding: '12px', background: RED, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer', boxShadow: `0 4px 12px ${RED}25` }}
                  >
                    Tolak / Blokir Transaksi
                  </button>
                </div>
              )}

              {(activeAlertDetail.status === 'approved' || activeAlertDetail.status === 'blocked') && (
                <div style={{ background: '#f6f6f6', borderRadius: 8, padding: '12px', textAlign: 'center', fontSize: 13, color: '#a7a8a8', fontStyle: 'italic' }}>
                  Alert telah diselesaikan sebagai <strong>{activeAlertDetail.status.toUpperCase()}</strong>. Tidak ada aksi lanjutan.
                </div>
              )}

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

      {/* Toast Alert */}
      {toast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#171919', color: '#fff', padding: '14px 22px', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
          <i className="bx bxs-info-circle" style={{ fontSize: 18, color: ORANGE }} />
          <span style={{ fontSize: 13, fontWeight: 650 }}>{toast}</span>
        </div>
      )}
    </div>
  );
}


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

  const defaultScans = [
    { id: 'SCN-1082', txId: 'TX-260624-9102', time: '2026-06-24T14:48:00', merchant: 'Kopi Senja Nusantara', location: 'Bandung, ID', ip: '182.16.24.8', amount: 35000, score: 12, result: 'safe', rule: '—', cardBin: '4512 88xx', issuer: 'Bank Mandiri' },
    { id: 'SCN-1081', txId: 'TX-260624-9098', time: '2026-06-24T14:45:00', merchant: 'Toko Bangunan Maju Jaya', location: 'Surakarta, ID', ip: '103.24.120.12', amount: 890000, score: 28, result: 'safe', rule: '—', cardBin: '5264 12xx', issuer: 'Bank BNI' },
    { id: 'SCN-1080', txId: 'TX-260624-9041', time: '2026-06-24T14:32:00', merchant: 'Batik Lestari Pekalongan', location: 'Jakarta, ID', ip: '36.85.12.98', amount: 4800000, score: 78, result: 'flagged', rule: 'Amount Outlier: >5x nominal rata-rata bulanan', cardBin: '4218 09xx', issuer: 'Bank BCA' },
    { id: 'SCN-1079', txId: 'TX-260624-8991', time: '2026-06-24T14:28:00', merchant: 'Kopi Senja Nusantara', location: 'Singapore, SG', ip: '202.164.88.9', amount: 120000, score: 92, result: 'blocked', rule: 'Geo Mismatch: Login & Trx bersamaan di 2 negara dlm 5 mnt', cardBin: '4624 33xx', issuer: 'DBS Bank' },
    { id: 'SCN-1078', txId: 'TX-260624-8840', time: '2026-06-24T14:15:00', merchant: 'Batik Lestari Pekalongan', location: 'Pekalongan, ID', ip: '110.138.9.15', amount: 150000, score: 8, result: 'safe', rule: '—', cardBin: '4512 88xx', issuer: 'Bank Mandiri' },
    { id: 'SCN-1077', txId: 'TX-260624-8730', time: '2026-06-24T13:58:00', merchant: 'Kopi Senja Nusantara', location: 'Medan, ID', ip: '180.244.11.45', amount: 25000, score: 58, result: 'flagged', rule: 'Velocity Check: >3 transaksi dlm 1 menit', cardBin: '4512 88xx', issuer: 'Bank Mandiri' }
  ];

  const [scans, setScans] = React.useState(() => {
    if (!window.__fdsScans) {
      window.__fdsScans = defaultScans;
    }
    return window.__fdsScans;
  });

  const [searchQuery, setSearchQuery] = React.useState('');
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [filterRisk, setFilterRisk] = React.useState('all');
  const [selectedTx, setSelectedTx] = React.useState(null);
  const [toast, setToast] = React.useState(null);

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

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

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

  const handleSimulateTrx = () => {
    const names = ['Kopi Senja Nusantara', 'Batik Lestari Pekalongan', 'Toko Bangunan Maju Jaya'];
    const locations = ['Jakarta, ID', 'Bandung, ID', 'Surabaya, ID', 'Medan, ID', 'Kuala Lumpur, MY', 'Tokyo, JP'];
    const ips = ['36.85.12.98', '182.16.24.8', '110.138.9.15', '202.164.88.9', '180.244.11.45'];
    const issuers = ['Bank Mandiri', 'Bank BNI', 'Bank BCA', 'Bank BRI', 'CIMB Niaga'];
    const cardBins = ['4512 88xx', '5264 12xx', '4218 09xx', '4624 33xx', '4912 44xx'];
    const rules = [
      'Velocity Check: >5 transaksi dlm 1 menit',
      'Amount Outlier: >10x nominal rata-rata bulanan',
      'Card Bin Suspicious: Transaksi luar negeri dlm volume berulang',
      'Location Anomaly: Pergerakan lokasi tidak wajar dlm 10 mnt'
    ];

    const randomName = names[Math.floor(Math.random() * names.length)];
    const randomLoc = locations[Math.floor(Math.random() * locations.length)];
    const randomIp = ips[Math.floor(Math.random() * ips.length)];
    const randomIssuer = issuers[Math.floor(Math.random() * issuers.length)];
    const randomBin = cardBins[Math.floor(Math.random() * cardBins.length)];
    const randomAmount = Math.floor(Math.random() * 300) * 15000 + 15000;

    // Determine random FDS result
    const randVal = Math.random();
    let result = 'safe';
    let score = Math.floor(Math.random() * 35) + 5; // 5 to 39
    let rule = '—';

    if (randVal > 0.85) { // 15% chance blocked (High Risk)
      result = 'blocked';
      score = Math.floor(Math.random() * 20) + 80; // 80 to 99
      rule = rules[Math.floor(Math.random() * rules.length)];
    } else if (randVal > 0.65) { // 20% chance flagged (Medium Risk)
      result = 'flagged';
      score = Math.floor(Math.random() * 25) + 50; // 50 to 74
      rule = rules[Math.floor(Math.random() * rules.length)];
    }

    const newScan = {
      id: 'SCN-' + (Math.floor(Math.random() * 9000) + 1000),
      txId: 'TX-260624-' + (Math.floor(Math.random() * 9000) + 1000),
      time: new Date().toISOString(),
      merchant: randomName,
      location: randomLoc,
      ip: randomIp,
      amount: randomAmount,
      score: score,
      result: result,
      rule: rule,
      cardBin: randomBin,
      issuer: randomIssuer
    };

    const updated = [newScan, ...scans];
    setScans(updated);
    window.__fdsScans = updated;

    triggerToast(`Transaksi diproses FDS: ${result.toUpperCase()} (Score: ${score})`);

    // Sync to alerts if flagged or blocked
    if (result === 'flagged' || result === 'blocked') {
      const currentAlerts = window.__fdsAlerts || [];
      const newAlert = {
        id: 'ALT-' + (Math.floor(Math.random() * 9000) + 1000),
        txId: newScan.txId,
        time: newScan.time,
        merchant: newScan.merchant,
        location: newScan.location,
        amount: newScan.amount,
        score: newScan.score,
        rule: newScan.rule,
        status: result === 'blocked' ? 'blocked' : 'pending'
      };
      window.__fdsAlerts = [newAlert, ...currentAlerts];
    }
  };

  const filteredScans = scans.filter(s => {
    const matchesSearch = s.txId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.merchant.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.id.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesStatus = filterStatus === 'all' || s.result === filterStatus;

    let matchesRisk = true;
    if (filterRisk === 'low') matchesRisk = s.score < 50;
    else if (filterRisk === 'medium') matchesRisk = s.score >= 50 && s.score < 80;
    else if (filterRisk === 'high') matchesRisk = s.score >= 80;

    return matchesSearch && matchesStatus && matchesRisk;
  });

  const summary = {
    total: scans.length,
    safe: scans.filter(s => s.result === 'safe').length,
    flagged: scans.filter(s => s.result === 'flagged').length,
    blocked: scans.filter(s => s.result === 'blocked').length
  };

  return (
    <div style={{ padding: '28px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>FDS Monitoring</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Monitoring Transaksi FDS</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Inspeksi real-time untuk seluruh transaksi QRIS yang melewati mesin analisis fraud.</p>
        </div>

        <button
          onClick={handleSimulateTrx}
          style={{
            background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px',
            fontSize: 12.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex',
            alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms',
            fontFamily: 'inherit'
          }}
          onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
          onMouseLeave={e => e.currentTarget.style.background = TEAL}
        >
          <i className="bx bx-plus-circle" style={{ fontSize: 16 }} />
          Simulasikan Transaksi Masuk
        </button>
      </div>

      {/* Mini Stats Summary */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Scanned Trx', value: summary.total, icon: 'bx-shield-quarter', color: TEAL },
          { label: 'SAFE (Passed)', value: summary.safe, icon: 'bx-check-double', color: GREEN },
          { label: 'FLAGGED (Review)', value: summary.flagged, icon: 'bx-error', color: AMBER },
          { label: 'BLOCKED (Tolak)', value: summary.blocked, icon: 'bx-block', color: RED }
        ].map((c, i) => (
          <div key={i} style={{ background: '#fff', padding: '14px 18px', borderRadius: 12, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', display: 'flex', alignItems: 'center', gap: 14, flex: 1, minWidth: 180 }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', background: `${c.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`bx ${c.icon}`} style={{ fontSize: 18, color: c.color }} />
            </div>
            <div>
              <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600 }}>{c.label}</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: '#171919', marginTop: 2, lineHeight: 1 }}>{c.value}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters Bar */}
      <div style={{ background: '#fff', padding: '16px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap', marginBottom: 20 }}>
        {/* Search */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#f6f6f6', border: '1.5px solid #efefef', borderRadius: 8, padding: '8px 12px', minWidth: 260, flex: 1 }}>
          <i className="bx bx-search" style={{ fontSize: 16, color: '#a7a8a8' }} />
          <input
            placeholder="Cari ID Scan, TxID, atau Merchant..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            style={{ border: 'none', background: 'none', outline: 'none', fontSize: 13, color: '#171919', width: '100%', fontFamily: 'inherit' }}
          />
        </div>

        {/* Filter Status */}
        <div>
          <select
            value={filterStatus}
            onChange={e => setFilterStatus(e.target.value)}
            style={{ padding: '9px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#515252', outline: 'none', background: '#fff', fontFamily: 'inherit', minWidth: 150 }}
          >
            <option value="all">Semua Status FDS</option>
            <option value="safe">SAFE (Passed)</option>
            <option value="flagged">FLAGGED (Review)</option>
            <option value="blocked">BLOCKED (Tolak)</option>
          </select>
        </div>

        {/* Filter Risk */}
        <div>
          <select
            value={filterRisk}
            onChange={e => setFilterRisk(e.target.value)}
            style={{ padding: '9px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#515252', outline: 'none', background: '#fff', fontFamily: 'inherit', minWidth: 150 }}
          >
            <option value="all">Semua Tingkat Risiko</option>
            <option value="low">Risiko Rendah (&lt;50)</option>
            <option value="medium">Risiko Sedang (50-79)</option>
            <option value="high">Risiko Tinggi (&ge;80)</option>
          </select>
        </div>
      </div>

      {/* Scans 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: 110 }}>ID Scan</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>ID Transaksi</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Merchant</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Lokasi & IP</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Score</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Hasil</th>
              <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center' }}>Inspeksi</th>
            </tr>
          </thead>
          <tbody>
            {filteredScans.length === 0 ? (
              <tr>
                <td colSpan="8" style={{ padding: '40px', textAlign: 'center', color: '#a7a8a8', fontSize: 13.5, fontStyle: 'italic' }}>
                  Tidak ada data transaksi yang cocok dengan filter pencarian.
                </td>
              </tr>
            ) : (
              filteredScans.map(s => {
                const isHigh = s.score >= 80;
                const isMedium = s.score >= 50 && s.score < 80;
                const scoreColor = isHigh ? RED : isMedium ? AMBER : GREEN;

                return (
                  <tr key={s.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 }}>{s.id}</td>
                    <td style={{ padding: '14px 18px', fontFamily: 'monospace', color: '#515252' }}>{s.txId}</td>
                    <td style={{ padding: '14px 18px' }}>
                      <div style={{ fontWeight: 700, color: '#171919' }}>{s.merchant}</div>
                      <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>{fmtDate(s.time)}</div>
                    </td>
                    <td style={{ padding: '14px 18px' }}>
                      <div style={{ color: '#171919' }}>{s.location}</div>
                      <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>IP: {s.ip}</div>
                    </td>
                    <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(s.amount)}</td>
                    <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                      <span style={{
                        display: 'inline-flex',
                        background: `${scoreColor}10`, color: scoreColor,
                        fontSize: 12, fontWeight: 800, borderRadius: 5, padding: '2px 7px',
                        border: `1px solid ${scoreColor}25`
                      }}>
                        {s.score}
                      </span>
                    </td>
                    <td style={{ padding: '14px 18px' }}>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        background: s.result === 'blocked' ? 'rgba(237,49,81,0.1)' : (s.result === 'flagged' ? 'rgba(217,146,11,0.12)' : 'rgba(116,181,12,0.12)'),
                        color: s.result === 'blocked' ? RED : (s.result === 'flagged' ? AMBER : GREEN),
                        fontSize: 11.5, fontWeight: 700, borderRadius: 4, padding: '3px 8px'
                      }}>
                        {s.result.toUpperCase()}
                      </span>
                    </td>
                    <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                      <button
                        onClick={() => setSelectedTx(s)}
                        style={{
                          background: '#fff', border: '1.5px solid #efefef', borderRadius: 6, padding: '6px 12px',
                          fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', color: '#515252'
                        }}
                        onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                        onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                      >
                        Buka
                      </button>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {/* Drawer: Detailed Inspection Panel */}
      {selectedTx && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1100, display: 'flex', justifyContent: 'flex-end' }}>
          <div onClick={() => setSelectedTx(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(23,25,25,0.4)', backdropFilter: 'blur(1.5px)' }} />

          <div style={{
            position: 'relative', width: 440, height: '100%', background: '#fff',
            boxShadow: '-8px 0 32px rgba(23,25,25,0.12)', display: 'flex', flexDirection: 'column',
            animation: 'slideInRight 220ms cubic-bezier(0.22, 0.61, 0.36, 1)'
          }}>
            {/* Header */}
            <div style={{ padding: '24px 28px', borderBottom: '1px solid #efefef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <span style={{ fontSize: 11, fontWeight: 700, color: TEAL, fontFamily: 'monospace' }}>{selectedTx.id}</span>
                <h3 style={{ fontSize: 16, fontWeight: 800, color: '#171919', margin: '4px 0 0' }}>Inspeksi Audit FDS</h3>
              </div>
              <button onClick={() => setSelectedTx(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 24 }} /></button>
            </div>

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

              {/* Scan Assessment Indicator */}
              <div style={{
                background: selectedTx.result === 'blocked' ? 'rgba(237,49,81,0.06)' : (selectedTx.result === 'flagged' ? 'rgba(217,146,11,0.06)' : 'rgba(116,181,12,0.06)'),
                border: `1.5px solid ${selectedTx.result === 'blocked' ? RED : (selectedTx.result === 'flagged' ? AMBER : GREEN)}20`,
                borderRadius: 10, padding: '16px', display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: '50%',
                  background: selectedTx.result === 'blocked' ? RED : (selectedTx.result === 'flagged' ? AMBER : GREEN),
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                }}>
                  <i className="bx bx-network-chart" style={{ fontSize: 20, color: '#fff' }} />
                </div>
                <div>
                  <div style={{
                    fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
                    color: selectedTx.result === 'blocked' ? RED : (selectedTx.result === 'flagged' ? AMBER : GREEN)
                  }}>
                    Hasil Engine: {selectedTx.result.toUpperCase()}
                  </div>
                  <div style={{ fontSize: 15, fontWeight: 800, color: '#171919', marginTop: 2 }}>Fraud Score: {selectedTx.score} / 100</div>
                </div>
              </div>

              {/* Transaction payload data */}
              <h4 style={{ fontSize: 13, fontWeight: 750, color: '#171919', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
                <i className="bx bx-receipt" style={{ color: TEAL }} />
                Data Transaksi Terkait
              </h4>
              <div style={{ background: '#f6f6f6', borderRadius: 10, padding: '16px', display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 20 }}>
                {[
                  { label: 'ID Transaksi', val: selectedTx.txId, mono: true },
                  { label: 'Merchant Penerima', val: selectedTx.merchant },
                  { label: 'Nominal Rupiah', val: fmtRp(selectedTx.amount), bold: true },
                  { label: 'Lokasi Perangkat', val: selectedTx.location },
                  { label: 'IP Address', val: selectedTx.ip, mono: true },
                  { label: 'Waktu Scan', val: fmtDate(s => s.time) },
                  { label: 'Card BIN / Issuer', val: `${selectedTx.cardBin} (${selectedTx.issuer})` }
                ].map((item, idx) => (
                  <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', borderBottom: idx < 6 ? '1px solid #efefef' : 'none', paddingBottom: idx < 6 ? 8 : 0 }}>
                    <span style={{ fontSize: 12, color: '#a7a8a8' }}>{item.label}</span>
                    <span style={{
                      fontSize: 12.5,
                      fontWeight: item.bold ? 750 : (item.mono ? 500 : 600),
                      color: '#171919',
                      fontFamily: item.mono ? 'monospace' : 'inherit'
                    }}>{item.val}</span>
                  </div>
                ))}
              </div>

              {/* Rules Evaluation */}
              <h4 style={{ fontSize: 13, fontWeight: 750, color: '#171919', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
                <i className="bx bx-slider-alt" style={{ color: TEAL }} />
                Hasil Analisis Aturan (Rules)
              </h4>
              <div style={{ background: '#fafafa', border: '1px solid #efefef', borderRadius: 10, padding: '16px', marginBottom: 24 }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginBottom: 4 }}>Pemicu Rule Warning</div>
                    <div style={{ fontSize: 13, color: '#171919', fontWeight: 600 }}>{selectedTx.rule}</div>
                  </div>
                  <div style={{ borderTop: '1px dashed #efefef', paddingTop: 10 }}>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginBottom: 4 }}>Rekomendasi Tindakan</div>
                    <div style={{ fontSize: 12.5, color: '#515252', fontWeight: 500 }}>
                      {selectedTx.result === 'blocked'
                        ? 'Transaksi telah ditolak secara otomatis untuk mengamankan limit dana merchant.'
                        : (selectedTx.result === 'flagged'
                          ? 'Transaksi memerlukan review manual oleh tim investigasi melalui antrean FDS Dashboard.'
                          : 'Transaksi dinyatakan aman dan sudah diteruskan untuk settlement.')}
                    </div>
                  </div>
                </div>
              </div>

              {/* Close button */}
              <button
                onClick={() => setSelectedTx(null)}
                style={{ width: '100%', padding: '12px', background: TEAL, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer', boxShadow: `0 4px 12px ${TEAL}25` }}
              >
                Selesai Inspeksi
              </button>

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

      {/* Toast Alert */}
      {toast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#171919', color: '#fff', padding: '14px 22px', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
          <i className="bx bxs-info-circle" style={{ fontSize: 18, color: ORANGE }} />
          <span style={{ fontSize: 13, fontWeight: 650 }}>{toast}</span>
        </div>
      )}
    </div>
  );
}


// ── 3. PARAMETER FDS PAGE (Structural Placeholder) ──
// ── 3. PARAMETER FDS PAGE ──
function FdsParameterPage({ merchants, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const [activeTab, setActiveTab] = React.useState('suspect'); // 'limits' | 'suspect' | 'whitelist' | 'blacklist'
  const [toast, setToast] = React.useState(null);
  const [showingForm, setShowingForm] = React.useState(false);

  // ── New Rule Form States ──
  const [ruleName, setRuleName] = React.useState('');
  const [ruleDesc, setRuleDesc] = React.useState('');
  const [ruleCategory, setRuleCategory] = React.useState('Indikasi Gestun / Pencucian Uang');
  const [ruleSeverity, setRuleSeverity] = React.useState('High Risk');
  const [activeChannels, setActiveChannels] = React.useState(['Mobile Banking']);

  // Logical builder groups/conditions:
  const [logicalGroup, setLogicalGroup] = React.useState('AND');
  const [conditions, setConditions] = React.useState([
    {
      dataField: 'A.1',
      thresholdLowMin: '500000', thresholdLowMax: '2000000',
      thresholdMediumMin: '2000000', thresholdMediumMax: '5000000',
      thresholdHigh: '5000000'
    }
  ]);

  // Velocity & Aggregation
  const [aggType, setAggType] = React.useState('Count');
  const [timeWindow, setTimeWindow] = React.useState('30');
  const [timeUnit, setTimeUnit] = React.useState('Minutes');
  const [groupBy, setGroupBy] = React.useState('Account_Number');

  // Action/Decision
  const [ruleAction, setRuleAction] = React.useState('Fraud');
  const [escalationQueue, setEscalationQueue] = React.useState('L2_Investigator');

  // Severity Risk Weight Scores when condition is met
  const [normalScore, setNormalScore] = React.useState('0');
  const [lowRiskScore, setLowRiskScore] = React.useState('15');
  const [mediumRiskScore, setMediumRiskScore] = React.useState('45');
  const [highRiskScore, setHighRiskScore] = React.useState('75');
  const [veryHighRiskScore, setVeryHighRiskScore] = React.useState('99');

  // ── Parameters State ──
  const [suspectParams, setSuspectParams] = React.useState([
    { id: 'SUS-001', name: 'Threshold Alert Score', value: '75', unit: 'score', desc: 'Ambang batas nilai skor kecurigaan untuk memicu antrean alert review manual', conditionsCount: 1 },
    { id: 'SUS-002', name: 'Max Failed Pin Attempts', value: '3', unit: 'kali / 1 jam', desc: 'Batas toleransi kesalahan input PIN kartu/akun sebelum ditandai sebagai indikasi fraud hijack', conditionsCount: 1 },
    { id: 'SUS-003', name: 'Velocity Limit (Trx/Min)', value: '5', unit: 'trx / 1 menit', desc: 'Kecepatan transaksi wajar dari pengguna/kartu yang sama dlm kurun waktu satu menit', conditionsCount: 1 },
    { id: 'SUS-004', name: 'High-Risk Geo Mismatch Window', value: '15', unit: 'menit', desc: 'Rentang waktu minimal perpindahan lokasi jarak jauh yang wajar dlm mendeteksi kloning lokasi', conditionsCount: 1 }
  ]);

  const [limitParams, setLimitParams] = React.useState([
    { id: 'LIM-001', name: 'Max Nominal Single Trx', value: '10000000', unit: 'Rupiah', desc: 'Nominal maksimal yang diperbolehkan untuk satu kali transaksi QRIS merchant' },
    { id: 'LIM-002', name: 'Max Accumulated Daily Limit', value: '50000000', unit: 'Rupiah', desc: 'Akumulasi total nominal transaksi maksimal per hari dlm satu ID pengguna' },
    { id: 'LIM-003', name: 'Max Trx Frequency Hourly', value: '20', unit: 'kali / 1 jam', desc: 'Batas frekuensi transaksi maksimal per jam untuk mencegah penarikan berlebih otomatis' }
  ]);

  const [editingParam, setEditingParam] = React.useState(null);
  const [editingValue, setEditingValue] = React.useState('');
  const [editingDesc, setEditingDesc] = React.useState('');

  // ── Whitelist & Blacklist State ──
  const [whitelist, setWhitelist] = React.useState([
    { id: 'WHL-01', type: 'Merchant MID', value: 'MRC-00244', desc: 'Merchant VIP dengan transaksi volume besar terpercaya', date: '2026-06-20T09:00:00', by: 'Arief Budiman' },
    { id: 'WHL-02', type: 'IP Address', value: '127.0.0.1', desc: 'IP local server monitoring IT hibank', date: '2026-06-21T10:15:00', by: 'System Admin' },
    { id: 'WHL-03', type: 'Card BIN', value: '4512 88xx', desc: 'BIN kartu debit internal Bank hibank', date: '2026-06-22T11:30:00', by: 'Bambang P' }
  ]);

  const [blacklist, setBlacklist] = React.useState([
    { id: 'BLK-01', type: 'IP Address', value: '203.0.113.50', desc: 'Terindikasi server bot spamming trx', date: '2026-06-18T16:45:00', by: 'System FDS' },
    { id: 'BLK-02', type: 'Card BIN', value: '4999 11xx', desc: 'BIN teridentifikasi sebagai sumber test card fraud internasional', date: '2026-06-19T08:12:00', by: 'Arief Budiman' }
  ]);

  // Modals for adding trust/block entries
  const [showAddModal, setShowAddModal] = React.useState(false);
  const [addType, setAddType] = React.useState('IP Address');
  const [addValue, setAddValue] = React.useState('');
  const [addDesc, setAddDesc] = React.useState('');

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

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

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

  // Action: Save edited parameter
  const handleSaveParam = (e) => {
    e.preventDefault();
    if (!editingParam) return;

    if (editingParam.isNew) {
      const newParam = {
        id: editingParam.id,
        name: editingParam.name,
        value: editingValue,
        unit: editingParam.unit || 'score',
        desc: editingDesc,
        conditionsCount: 1
      };
      setSuspectParams(prev => [...prev, newParam]);
      triggerToast(`Parameter ${editingParam.name} berhasil ditambahkan.`);
    } else {
      if (editingParam.id.startsWith('SUS')) {
        setSuspectParams(prev => prev.map(p => p.id === editingParam.id ? { ...p, value: editingValue, desc: editingDesc } : p));
      } else {
        setLimitParams(prev => prev.map(p => p.id === editingParam.id ? { ...p, value: editingValue, desc: editingDesc } : p));
      }
      triggerToast(`Parameter ${editingParam.name} berhasil diperbarui.`);
    }

    setEditingParam(null);
    setShowingForm(false);
  };

  const handleEditClick = (p) => {
    setEditingParam(p);
    setEditingValue(p.value);
    setEditingDesc(p.desc);

    if (p.id.startsWith('SUS')) {
      // It's a suspect rule parameter. We want to edit it using the complex rule builder form!
      setRuleName(p.name);
      setRuleDesc(p.ruleDescOnly || p.desc || '');
      setRuleCategory(p.ruleCategory || (
        p.id === 'SUS-002' ? 'Account Takeover (ATO)' :
          p.id === 'SUS-004' ? 'Anomali Perilaku Merchant' : 'Indikasi Gestun / Pencucian Uang'
      ));
      setRuleSeverity(p.ruleSeverity || 'High');
      setActiveChannels(p.activeChannels || (
        p.id === 'SUS-001' || p.id === 'SUS-004' ? ['Mobile Banking', 'Internet Banking', 'API B2B'] : ['Mobile Banking', 'Internet Banking']
      ));
      setLogicalGroup(p.logicalGroup || 'AND');
      setAggType(p.aggType || 'Count');
      setTimeWindow(p.timeWindow || (
        p.id === 'SUS-002' ? '1' :
          p.id === 'SUS-003' ? '1' :
            p.id === 'SUS-004' ? '15' : '5'
      ));
      setTimeUnit(p.timeUnit || (
        p.id === 'SUS-002' ? 'Hours' : 'Minutes'
      ));
      setGroupBy(p.groupBy || (
        p.id === 'SUS-004' ? 'IP_Address' : 'Account_Number'
      ));
      setRuleAction(p.ruleAction || 'Fraud');
      setEscalationQueue(p.escalationQueue || 'FDS Operational');

      if (p.conditions) {
        setConditions(p.conditions);
      } else {
        const defaultField =
          p.id === 'SUS-001' ? 'A.1' :
            p.id === 'SUS-002' ? 'B.2' :
              p.id === 'SUS-003' ? 'C.1' :
                p.id === 'SUS-004' ? 'D.2' : 'A.1';

        const lowMin = p.id === 'SUS-001' ? '25' : (p.id === 'SUS-002' ? '1' : (p.id === 'SUS-003' ? '2' : '5'));
        const lowMax = p.id === 'SUS-001' ? '50' : (p.id === 'SUS-002' ? '2' : (p.id === 'SUS-003' ? '3' : '10'));
        const medMin = p.id === 'SUS-001' ? '50' : (p.id === 'SUS-002' ? '2' : (p.id === 'SUS-003' ? '3' : '10'));
        const medMax = p.id === 'SUS-001' ? '75' : (p.id === 'SUS-002' ? '3' : (p.id === 'SUS-003' ? '5' : '15'));
        const high = p.value;

        setConditions([{
          dataField: defaultField,
          thresholdLowMin: String(lowMin),
          thresholdLowMax: String(lowMax),
          thresholdMediumMin: String(medMin),
          thresholdMediumMax: String(medMax),
          thresholdHigh: String(high)
        }]);
      }
    } else {
      // For non-SUS parameters, reset state
      setConditions([{
        dataField: 'A.1',
        thresholdLowMin: '500000', thresholdLowMax: '2000000',
        thresholdMediumMin: '2000000', thresholdMediumMax: '5000000',
        thresholdHigh: '5000000'
      }]);
    }
    setShowingForm(true);
  };

  // Action: Add Whitelist / Blacklist Entity
  const handleAddSubmit = (e) => {
    e.preventDefault();
    if (!addValue || !addDesc) return;

    const newEntry = {
      id: (activeTab === 'whitelist' ? 'WHL-' : 'BLK-') + (Math.floor(Math.random() * 90) + 10),
      type: addType,
      value: addValue,
      desc: addDesc,
      date: new Date().toISOString(),
      by: 'Arief Budiman'
    };

    if (activeTab === 'whitelist') {
      setWhitelist([newEntry, ...whitelist]);
      triggerToast(`Entitas ${addValue} berhasil ditambahkan ke White List.`);
    } else {
      setBlacklist([newEntry, ...blacklist]);
      triggerToast(`Entitas ${addValue} berhasil ditambahkan ke Black List.`);
    }

    // Reset
    setShowAddModal(false);
    setAddValue('');
    setAddDesc('');
  };

  // Action: Delete from Whitelist / Blacklist
  const handleDeleteEntry = (id, val) => {
    if (activeTab === 'whitelist') {
      setWhitelist(whitelist.filter(w => w.id !== id));
      triggerToast(`Entitas ${val} dihapus dari White List.`);
    } else {
      setBlacklist(blacklist.filter(b => b.id !== id));
      triggerToast(`Entitas ${val} dihapus dari Black List.`);
    }
  };

  // Action: Save suspect rule configuration
  const handleSaveSuspectRule = (e) => {
    e.preventDefault();
    if (!ruleName || !ruleDesc) return;

    // Generate a user-friendly condition description
    const condDesc = conditions.map((c, idx) => {
      const lowVal = c.thresholdLowMin && c.thresholdLowMax ? `${c.thresholdLowMin} - ${c.thresholdLowMax}` : (c.thresholdLowMin || c.thresholdLowMax || '-');
      const medVal = c.thresholdMediumMin && c.thresholdMediumMax ? `${c.thresholdMediumMin} - ${c.thresholdMediumMax}` : (c.thresholdMediumMin || c.thresholdMediumMax || '-');
      const thresholdText = `[Low Threshold: ${lowVal}, Med Threshold: ${medVal}, High Threshold: ${c.thresholdHigh || '-'}]`;
      return `Kondisi #${idx + 1}: ${c.dataField} ${thresholdText}`;
    }).join(` ${logicalGroup} `);

    const needsVelocity = conditions.some(c => ['A.2', 'B.2', 'C.1', 'C.2', 'C.3', 'D.1', 'D.2', 'E.2'].includes(c.dataField));
    const aggregationText = needsVelocity ? ` (${aggType} of ${groupBy} over ${timeWindow} ${timeUnit})` : '';

    const updatedParam = {
      id: editingParam ? editingParam.id : `SUS-00${suspectParams.length + 1}`,
      name: ruleName,
      value: conditions[0]?.thresholdHigh || 'Custom',
      unit: ['A.1', 'A.2', 'E.3'].includes(conditions[0]?.dataField) ? 'Rupiah' : (['B.1', 'B.2', 'C.1', 'C.2', 'C.3'].includes(conditions[0]?.dataField) ? 'Transaksi' : 'unit'),
      desc: `${ruleDesc}. Kategori: ${ruleCategory}. Jalur: ${activeChannels.join(', ')}. ${condDesc}${aggregationText}. Tindakan: ${ruleAction} (${escalationQueue}). Urgensi: ${ruleSeverity}.`,
      conditionsCount: conditions.length,
      conditions: conditions,
      ruleDescOnly: ruleDesc,
      ruleCategory: ruleCategory,
      ruleSeverity: ruleSeverity,
      activeChannels: activeChannels,
      logicalGroup: logicalGroup,
      aggType: aggType,
      timeWindow: timeWindow,
      timeUnit: timeUnit,
      groupBy: groupBy,
      ruleAction: ruleAction,
      escalationQueue: escalationQueue
    };

    if (editingParam) {
      setSuspectParams(prev => prev.map(p => p.id === editingParam.id ? updatedParam : p));
      triggerToast(`Aturan FDS "${ruleName}" berhasil diperbarui.`);
    } else {
      setSuspectParams(prev => [...prev, updatedParam]);
      triggerToast(`Aturan FDS "${ruleName}" berhasil dibuat.`);
    }
    setShowingForm(false);
    setEditingParam(null);
  };

  if (showingForm) {
    const isSimpleParam = editingParam && !editingParam.id.startsWith('SUS');

    return (
      <div style={{ padding: '28px 32px 56px', animation: 'fadeIn 200ms ease' }}>
        {/* Breadcrumb / Back button */}
        <div style={{ marginBottom: 20 }}>
          <button
            onClick={() => { setShowingForm(false); setEditingParam(null); }}
            style={{
              background: 'none', border: 'none', color: '#515252', fontSize: 13, fontWeight: 600,
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, padding: '4px 0'
            }}
          >
            <i className="bx bx-arrow-back" style={{ fontSize: 16 }} /> Kembali ke Parameter FDS
          </button>
        </div>

        <div style={{ marginBottom: 24 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>
            {isSimpleParam ? 'Edit Parameter Threshold' : 'Suspect Rule Engine'}
          </div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>
            {editingParam ? `Edit Parameter — ${editingParam.id}` : 'Buat Parameter Aturan Baru'}
          </h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>
            {isSimpleParam
              ? `Perbarui nilai ambang batas toleransi dan keterangan untuk parameter ${editingParam.name}.`
              : 'Definisikan metadata, kriteria logika kondisi, agregasi temporal, dan aksi penindakan otomatis.'}
          </p>
        </div>

        {isSimpleParam ? (
          <form onSubmit={handleSaveParam}>
            <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', maxWidth: 600, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>

              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12.5, fontWeight: 750, color: '#515252', marginBottom: 6 }}>Nama Parameter</label>
                <input
                  type="text"
                  disabled
                  value={editingParam.name}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#515252', outline: 'none', background: '#fafafa', fontFamily: 'inherit' }}
                />
              </div>

              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12.5, fontWeight: 755, color: '#515252', marginBottom: 6 }}>
                  Nilai Threshold {editingParam.unit ? `(${editingParam.unit})` : ''}
                </label>
                <input
                  type="text"
                  required
                  value={editingValue}
                  onChange={e => setEditingValue(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit' }}
                />
              </div>

              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 12.5, fontWeight: 755, color: '#515252', marginBottom: 6 }}>Keterangan / Rationale Aturan</label>
                <textarea
                  required
                  rows="4"
                  value={editingDesc}
                  onChange={e => setEditingDesc(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.4 }}
                />
              </div>

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', borderTop: '1px solid #efefef', paddingTop: 16 }}>
                <button type="button" onClick={() => { setShowingForm(false); setEditingParam(null); }} style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '9px 16px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}>Batal</button>
                <button type="submit" style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', boxShadow: `0 4px 12px ${TEAL}15`, fontFamily: 'inherit' }}>Simpan Parameter</button>
              </div>
            </div>
          </form>
        ) : (
          <form onSubmit={handleSaveSuspectRule}>

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

              {/* COLUMN 1: Basic Info & Conditions */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

                {/* 1. INFORMASI DASAR */}
                <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
                  <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <i className="bx bx-info-circle" style={{ color: TEAL, fontSize: 18 }} />
                    1. Informasi Dasar (Skenario Metadata)
                  </h3>

                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Skenario Name</label>
                    <input
                      type="text"
                      required
                      placeholder="Contoh: Velocity_Transfer_High_Risk_Night"
                      value={ruleName}
                      onChange={e => setRuleName(e.target.value)}
                      style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', fontFamily: 'inherit' }}
                    />
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Description</label>
                    <textarea
                      required
                      rows="3"
                      placeholder="Penjelasan latar belakang aturan untuk audit..."
                      value={ruleDesc}
                      onChange={e => setRuleDesc(e.target.value)}
                      style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', fontFamily: 'inherit', resize: 'vertical', lineHeight: 1.4 }}
                    />
                  </div>

                  {/* KODE BARU - Hapus layout grid agar elemen menggunakan lebar penuh */}
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Rule Category</label>
                    <select
                      value={ruleCategory}
                      onChange={e => setRuleCategory(e.target.value)}
                      style={{
                        width: '100%',
                        boxSizing: 'border-box', /* Penting agar padding tidak membuat elemen melebihi 100% */
                        padding: '10px 12px',
                        borderRadius: 8,
                        border: '1.5px solid #efefef',
                        fontSize: 13,
                        outline: 'none',
                        background: '#fff',
                        fontFamily: 'inherit'
                      }}
                    >
                      <option value="Indikasi Gestun / Pencucian Uang">1. Indikasi Gesek Tunai (Gestun) atau Pencucian Uang</option>
                      <option value="Promo Abuse">2. Promo Abuse (Penyalahgunaan Promosi)</option>
                      <option value="Account Takeover (ATO)">3. Account Takeover (ATO) / Pengambilalihan Akun</option>
                      <option value="Anomali Perilaku Merchant">4. Anomali Perilaku Merchant (Sisi Acquirer)</option>
                      <option value="Anomali Waktu Operasional">5. Anomali Waktu Operasional (Time-Based Rules)</option>
                    </select>
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 8 }}>Active Channel</label>
                    <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                      {['Mobile Banking', 'Internet Banking', 'API B2B'].map(ch => {
                        const hasCh = activeChannels.includes(ch);
                        return (
                          <label key={ch} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: '#171919', cursor: 'pointer' }}>
                            <input
                              type="checkbox"
                              checked={hasCh}
                              onChange={() => {
                                if (hasCh) {
                                  setActiveChannels(activeChannels.filter(c => c !== ch));
                                } else {
                                  setActiveChannels([...activeChannels, ch]);
                                }
                              }}
                              style={{ width: 16, height: 16, accentColor: TEAL }}
                            />
                            {ch}
                          </label>
                        );
                      })}
                    </div>
                  </div>

                </div>

                {/* 2. PEMBANGUN KONDISI */}
                <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                    <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
                      <i className="bx bx-git-branch" style={{ color: AMBER, fontSize: 18 }} />
                      2. Pembangun Kondisi (Condition Builder)
                    </h3>

                    <div style={{ display: 'flex', background: '#f6f6f6', padding: 3, borderRadius: 6, border: '1px solid #efefef' }}>
                      {['AND', 'OR'].map(grp => (
                        <button
                          key={grp}
                          type="button"
                          onClick={() => setLogicalGroup(grp)}
                          style={{
                            background: logicalGroup === grp ? TEAL : 'transparent',
                            color: logicalGroup === grp ? '#fff' : '#515252',
                            border: 'none', borderRadius: 4, padding: '3px 10px', fontSize: 11, fontWeight: 750,
                            cursor: 'pointer', fontFamily: 'inherit'
                          }}
                        >
                          {grp}
                        </button>
                      ))}
                    </div>
                  </div>

                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {conditions.map((cond, idx) => {
                      return (
                        <div key={idx} style={{ display: 'flex', flexDirection: 'column', gap: 10, background: '#fafafa', padding: 14, borderRadius: 8, border: '1.5px dashed #efefef' }}>
                          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                            <div style={{ flex: 1 }}>
                              <select
                                value={cond.dataField}
                                onChange={(e) => {
                                  const newConds = [...conditions];
                                  newConds[idx].dataField = e.target.value;
                                  setConditions(newConds);
                                }}
                                style={{ width: '100%', padding: '8px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12.5, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                              >
                                <optgroup label="A — NOMINAL TRANSAKSI">
                                  <option value="A.1">A.1 — Nominal Transaksi</option>
                                  <option value="A.2">A.2 — Nominal Top-up Besar</option>
                                </optgroup>
                                <optgroup label="B — WAKTU TRANSAKSI">
                                  <option value="B.1">B.1 — Transaksi Jam Tidak Wajar</option>
                                  <option value="B.2">B.2 — Frekuensi Transaksi Harian</option>
                                </optgroup>
                                <optgroup label="C — FREKUENSI & POLA TRANSAKSI">
                                  <option value="C.1">C.1 — Transaksi Nominal Kecil Berulang</option>
                                  <option value="C.2">C.2 — Multiple Attempts ke 1 Tujuan</option>
                                  <option value="C.3">C.3 — Frekuensi Transaksi Mingguan</option>
                                </optgroup>
                                <optgroup label="D — PERANGKAT & AKSES">
                                  <option value="D.1">D.1 — Pergantian Device ID</option>
                                  <option value="D.2">D.2 — Pergantian IP Address</option>
                                </optgroup>
                                <optgroup label="E — QRIS & CHANNEL">
                                  <option value="E.1">E.1 — Merchant Category Berisiko Tinggi (MCC)</option>
                                  <option value="E.2">E.2 — Scan Frekuensi Tinggi</option>
                                  <option value="E.3">E.3 — Nominal QRIS Melebihi Ketentuan BI</option>
                                </optgroup>
                              </select>
                            </div>

                            {conditions.length > 1 && (
                              <button
                                type="button"
                                onClick={() => setConditions(conditions.filter((_, i) => i !== idx))}
                                style={{ background: 'none', border: 'none', color: RED, cursor: 'pointer', padding: 6, display: 'inline-flex' }}
                              >
                                <i className="bx bx-trash" style={{ fontSize: 16 }} />
                              </button>
                            )}
                          </div>

                          {(() => {
                            const isCurrency = ['A.1', 'A.2', 'E.3'].includes(cond.dataField);
                            const isMCC = cond.dataField === 'E.1';
                            const valPlaceholderMin = isCurrency ? 'Min (e.g. 500000)' : 'Min';
                            const valPlaceholderMax = isCurrency ? 'Max (e.g. 2000000)' : 'Max';

                            return (
                              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, background: '#fff', padding: '14px', borderRadius: 8, border: '1px solid #f1f1f1' }}>

                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                                  {/* THRESHOLD LOW */}
                                  <div style={{ background: '#fafbfc', padding: 12, borderRadius: 8, border: '1px solid #efefef' }}>
                                    <label style={{ display: 'block', fontSize: 10.5, color: '#2e7d32', fontWeight: 800, marginBottom: 8, textTransform: 'uppercase' }}>
                                      <i className="bx bx-shield" style={{ marginRight: 3 }} /> Threshold LOW
                                    </label>
                                    {isMCC ? (
                                      <input
                                        type="text" required placeholder="MCC Low (e.g. -)" value={cond.thresholdLowMin || ''}
                                        onChange={(e) => {
                                          const newConds = [...conditions];
                                          newConds[idx].thresholdLowMin = e.target.value;
                                          setConditions(newConds);
                                        }}
                                        style={{ width: '100%', padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                                      />
                                    ) : (
                                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                        <input
                                          type="text" required placeholder={valPlaceholderMin} value={cond.thresholdLowMin || ''}
                                          onChange={(e) => {
                                            const newConds = [...conditions];
                                            newConds[idx].thresholdLowMin = e.target.value;
                                            setConditions(newConds);
                                          }}
                                          style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', fontFamily: 'inherit' }}
                                        />
                                        <span style={{ fontSize: 11, color: '#888', fontWeight: 700 }}>s/d</span>
                                        <input
                                          type="text" required placeholder={valPlaceholderMax} value={cond.thresholdLowMax || ''}
                                          onChange={(e) => {
                                            const newConds = [...conditions];
                                            newConds[idx].thresholdLowMax = e.target.value;
                                            setConditions(newConds);
                                          }}
                                          style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', fontFamily: 'inherit' }}
                                        />
                                      </div>
                                    )}
                                  </div>

                                  {/* THRESHOLD MEDIUM */}
                                  <div style={{ background: '#fafbfc', padding: 12, borderRadius: 8, border: '1px solid #efefef' }}>
                                    <label style={{ display: 'block', fontSize: 10.5, color: '#d9920b', fontWeight: 800, marginBottom: 8, textTransform: 'uppercase' }}>
                                      <i className="bx bx-error" style={{ marginRight: 3 }} /> Threshold MEDIUM
                                    </label>
                                    {isMCC ? (
                                      <input
                                        type="text" required placeholder="MCC Med (e.g. Watchlist)" value={cond.thresholdMediumMin || ''}
                                        onChange={(e) => {
                                          const newConds = [...conditions];
                                          newConds[idx].thresholdMediumMin = e.target.value;
                                          setConditions(newConds);
                                        }}
                                        style={{ width: '100%', padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                                      />
                                    ) : (
                                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                        <input
                                          type="text" required placeholder={valPlaceholderMin} value={cond.thresholdMediumMin || ''}
                                          onChange={(e) => {
                                            const newConds = [...conditions];
                                            newConds[idx].thresholdMediumMin = e.target.value;
                                            setConditions(newConds);
                                          }}
                                          style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', fontFamily: 'inherit' }}
                                        />
                                        <span style={{ fontSize: 11, color: '#888', fontWeight: 700 }}>s/d</span>
                                        <input
                                          type="text" required placeholder={valPlaceholderMax} value={cond.thresholdMediumMax || ''}
                                          onChange={(e) => {
                                            const newConds = [...conditions];
                                            newConds[idx].thresholdMediumMax = e.target.value;
                                            setConditions(newConds);
                                          }}
                                          style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', fontFamily: 'inherit' }}
                                        />
                                      </div>
                                    )}
                                  </div>
                                </div>

                                {/* THRESHOLD HIGH */}
                                <div style={{ background: '#fafbfc', padding: 12, borderRadius: 8, border: '1px solid #efefef' }}>
                                  <label style={{ display: 'block', fontSize: 10.5, color: '#ed3151', fontWeight: 800, marginBottom: 8, textTransform: 'uppercase' }}>
                                    <i className="bx bx-shield-x" style={{ marginRight: 3 }} /> Threshold HIGH
                                  </label>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <span style={{ fontSize: 13, color: '#515252', fontWeight: 700 }}>{isMCC ? 'Kriteria:' : '>'}</span>
                                    <input
                                      type="text" required placeholder={isCurrency ? 'Batas High (e.g. 5000000)' : (isMCC ? 'MCC Blacklist' : 'Batas High')} value={cond.thresholdHigh || ''}
                                      onChange={(e) => {
                                        const newConds = [...conditions];
                                        newConds[idx].thresholdHigh = e.target.value;
                                        setConditions(newConds);
                                      }}
                                      style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid #efefef', fontSize: 12, outline: 'none', fontFamily: 'inherit' }}
                                    />
                                  </div>
                                </div>

                              </div>
                            );
                          })()}

                        </div>
                      );
                    })}

                    <button
                      type="button"
                      onClick={() => setConditions([...conditions, {
                        dataField: 'A.1',
                        thresholdLowMin: '',
                        thresholdLowMax: '',
                        thresholdMediumMin: '',
                        thresholdMediumMax: '',
                        thresholdHigh: ''
                      }])}
                      style={{
                        background: 'none', border: '1.5px dashed #efefef', borderRadius: 8, padding: '10px',
                        color: TEAL, fontSize: 12, fontWeight: 700, cursor: 'pointer', display: 'flex',
                        alignItems: 'center', gap: 6, justifyContent: 'center', marginTop: 4, fontFamily: 'inherit'
                      }}
                    >
                      <i className="bx bx-plus" /> Tambah Kondisi Kriteria
                    </button>
                  </div>
                </div>

              </div>

              {/* COLUMN 2: Velocity & Rule Action */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

                {/* 3. PARAMETER KECEPATAN & WAKTU */}
                {conditions.some(c => ['A.2', 'B.2', 'C.1', 'C.2', 'C.3', 'D.1', 'D.2', 'E.2'].includes(c.dataField)) && (
                  <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', animation: 'fadeIn 200ms ease' }}>
                    <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                      <i className="bx bx-time-five" style={{ color: GREEN, fontSize: 18 }} />
                      3. Parameter Kecepatan & Waktu (Velocity & Aggregation)
                    </h3>

                    <div style={{ marginBottom: 16 }}>
                      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Aggregation Type</label>
                      <select
                        value={aggType}
                        onChange={e => setAggType(e.target.value)}
                        style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                      >
                        <option value="Count">Count (Frekuensi Transaksi)</option>
                        <option value="Sum">Sum (Total Akumulasi Nominal)</option>
                      </select>
                    </div>

                    <div style={{ marginBottom: 16 }}>
                      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Time Window</label>
                      <div style={{ display: 'flex', gap: 10 }}>
                        <input
                          type="number"
                          required
                          min="1"
                          value={timeWindow}
                          onChange={e => setTimeWindow(e.target.value)}
                          style={{ flex: 1, padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', fontFamily: 'inherit' }}
                        />
                        <select
                          value={timeUnit}
                          onChange={e => setTimeUnit(e.target.value)}
                          style={{ width: 120, padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                        >
                          <option value="Minutes">Minutes</option>
                          <option value="Hours">Hours</option>
                          <option value="Days">Days</option>
                        </select>
                      </div>
                    </div>

                    <div>
                      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Group By</label>
                      <select
                        value={groupBy}
                        onChange={e => setGroupBy(e.target.value)}
                        style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                      >
                        <option value="Account_Number">Account_Number (Nomor Rekening)</option>
                        <option value="Device_ID">Device ID</option>
                        <option value="Merchant_ID">Merchant ID (MID)</option>
                        <option value="IP_Address">IP Address</option>
                      </select>
                    </div>
                  </div>
                )}

                {/* 4. TINDAKAN & KEPUTUSAN */}
                <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
                  <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <i className="bx bx-check-shield" style={{ color: RED, fontSize: 18 }} />
                    4. Tindakan & Keputusan (Rule Action)
                  </h3>

                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Action / Decision</label>
                    <select
                      value={ruleAction}
                      onChange={e => setRuleAction(e.target.value)}
                      style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                    >
                      <option value="Izinkan">Izinkan</option>
                      <option value="Blokir">Blokir</option>
                      <option value="Izinkan dan Notifikasi">Izinkan dan Notifikasi</option>

                    </select>
                  </div>


                  <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', borderTop: '1px solid #efefef', paddingTop: 16 }}>
                    <button
                      type="button"
                      onClick={() => { setShowingForm(false); setEditingParam(null); }}
                      style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '10px 18px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', fontFamily: 'inherit' }}
                    >
                      Batal
                    </button>
                    <button
                      type="submit"
                      style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 22px', fontSize: 13, fontWeight: 700, cursor: 'pointer', boxShadow: `0 4px 12px ${TEAL}25`, fontFamily: 'inherit' }}
                    >
                      {editingParam ? 'Perbarui Aturan FDS' : 'Simpan Aturan FDS'}
                    </button>
                  </div>
                </div>

              </div>

            </div>

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

  return (
    <div style={{ padding: '28px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>FDS Rules Parameter</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Parameter FDS & Reputasi</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Konfigurasi ambang batas indikasi suspect, batasan limit, serta kelola reputasi bypass entitas.</p>
        </div>

        {(activeTab === 'whitelist' || activeTab === 'blacklist') && (
          <button
            onClick={() => setShowAddModal(true)}
            style={{
              background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px',
              fontSize: 12.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex',
              alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms',
              fontFamily: 'inherit'
            }}
            onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
            onMouseLeave={e => e.currentTarget.style.background = TEAL}
          >
            <i className="bx bx-plus-circle" style={{ fontSize: 16 }} />
            Tambah ke {activeTab === 'whitelist' ? 'White List' : 'Black List'}
          </button>
        )}

        {activeTab === 'suspect' && (
          <button
            onClick={() => {
              setShowingForm(true);
              setRuleName('');
              setRuleDesc('');
              setConditions([{
                dataField: 'A.1',
                thresholdLowMin: '500000',
                thresholdLowMax: '2000000',
                thresholdMediumMin: '2000000',
                thresholdMediumMax: '5000000',
                thresholdHigh: '5000000'
              }]);
            }}
            style={{
              background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px',
              fontSize: 12.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex',
              alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms',
              fontFamily: 'inherit'
            }}
            onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
            onMouseLeave={e => e.currentTarget.style.background = TEAL}
          >
            <i className="bx bx-plus-circle" style={{ fontSize: 16 }} />
            Tambah Parameter Suspect
          </button>
        )}
      </div>

      {/* Tabs Switcher */}
      <div style={{ display: 'flex', borderBottom: '2.5px solid #efefef', marginBottom: 24, gap: 24 }}>
        {[
          { id: 'suspect', label: 'Suspect Rules', icon: 'bx-error-circle' },
          { id: 'limits', label: 'Transaction Limits', icon: 'bx-block' },
          { id: 'whitelist', label: 'White List (Bypass)', icon: 'bx-check-circle' },
          { id: 'blacklist', label: 'Black List (Blokir)', icon: 'bx-x-circle' }
        ].map(tab => {
          const isActive = activeTab === tab.id;
          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: 'inline-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}
            </button>
          );
        })}
      </div>

      {/* TAB CONTENT: 1. SUSPECT PARAMETERS */}
      {activeTab === 'suspect' && (
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid #efefef', background: '#fafafa' }}>
            <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', display: 'flex', alignItems: 'center', gap: 8 }}>
              <i className="bx bx-error-circle" style={{ color: AMBER, fontSize: 18 }} />
              Suspect Rules Thresholds
            </h3>
            <p style={{ fontSize: 11.5, color: '#a7a8a8', margin: '4px 0 0' }}>Batas toleransi indikasi anomali sebelum transaksi dinaikkan ke FDS Dashboard Alert.</p>
          </div>

          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid #efefef' }}>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 90 }}>ID</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 280 }}>Nama Skema</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 160 }}>Nilai Jumlah Rules</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8' }}>Keterangan / Deskripsi Aturan</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', textAlign: 'center', width: 120 }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {suspectParams.map(p => (
                <tr key={p.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '16px 24px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{p.id}</td>
                  <td style={{ padding: '16px 24px', fontWeight: 700, color: '#171919' }}>{p.name}</td>
                  <td style={{ padding: '16px 24px' }}>
                    <span style={{ background: 'rgba(0,86,210,0.08)', color: '#0056D2', fontSize: 13, fontWeight: 750, borderRadius: 6, padding: '4px 10px', border: `1px solid rgba(0,86,210,0.15)` }}>
                      {p.conditionsCount || 1} Parameter
                    </span>
                  </td>
                  <td style={{ padding: '16px 24px', color: '#515252', lineHeight: 1.4 }}>{p.desc}</td>
                  <td style={{ padding: '16px 24px', textAlign: 'center' }}>
                    <button
                      onClick={() => handleEditClick(p)}
                      style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 6, padding: '5px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', color: '#515252' }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                    >
                      Edit
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* TAB CONTENT: 2. TRANSACTION LIMIT PARAMETERS */}
      {activeTab === 'limits' && (
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid #efefef', background: '#fafafa' }}>
            <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', display: 'flex', alignItems: 'center', gap: 8 }}>
              <i className="bx bx-block" style={{ color: RED, fontSize: 18 }} />
              Transaction Hard Limits
            </h3>
            <p style={{ fontSize: 11.5, color: '#a7a8a8', margin: '4px 0 0' }}>Aturan batas absolut yang akan langsung menolak (BLOCKED) transaksi jika terlewati.</p>
          </div>

          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid #efefef' }}>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 90 }}>ID</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 280 }}>Nama Parameter</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 160 }}>Batas Maksimal</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8' }}>Keterangan / Deskripsi Aturan</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', textAlign: 'center', width: 120 }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {limitParams.map(p => (
                <tr key={p.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '16px 24px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{p.id}</td>
                  <td style={{ padding: '16px 24px', fontWeight: 700, color: '#171919' }}>{p.name}</td>
                  <td style={{ padding: '16px 24px' }}>
                    <span style={{ background: 'rgba(237,49,81,0.08)', color: RED, fontSize: 13, fontWeight: 750, borderRadius: 6, padding: '4px 10px', border: `1px solid rgba(237,49,81,0.15)` }}>
                      {p.unit === 'Rupiah' ? fmtRp(p.value) : `${p.value} ${p.unit}`}
                    </span>
                  </td>
                  <td style={{ padding: '16px 24px', color: '#515252', lineHeight: 1.4 }}>{p.desc}</td>
                  <td style={{ padding: '16px 24px', textAlign: 'center' }}>
                    <button
                      onClick={() => handleEditClick(p)}
                      style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 6, padding: '5px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', color: '#515252' }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                    >
                      Edit
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* TAB CONTENT: 3. WHITE LIST & 4. BLACK LIST */}
      {(activeTab === 'whitelist' || activeTab === 'blacklist') && (
        <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 24px', color: '#a7a8a8', width: 90 }}>ID</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 180 }}>Jenis Entitas</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 220 }}>Nilai / Value</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8' }}>Keterangan Pembenaran</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 140 }}>Tanggal Ditambahkan</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', width: 140 }}>Petugas</th>
                <th style={{ padding: '12px 24px', color: '#a7a8a8', textAlign: 'center', width: 100 }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {((activeTab === 'whitelist' ? whitelist : blacklist).length === 0) ? (
                <tr>
                  <td colSpan="7" style={{ padding: '40px', textAlign: 'center', color: '#a7a8a8', fontSize: 13.5, fontStyle: 'italic' }}>
                    Daftar reputasi {activeTab === 'whitelist' ? 'White List' : 'Black List'} saat ini kosong.
                  </td>
                </tr>
              ) : (
                (activeTab === 'whitelist' ? whitelist : blacklist).map(entry => (
                  <tr key={entry.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 24px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{entry.id}</td>
                    <td style={{ padding: '14px 24px', fontWeight: 700, color: '#515252' }}>{entry.type}</td>
                    <td style={{ padding: '14px 24px', fontFamily: 'monospace', fontWeight: 700, color: '#171919' }}>{entry.value}</td>
                    <td style={{ padding: '14px 24px', color: '#515252' }}>{entry.desc}</td>
                    <td style={{ padding: '14px 24px', color: '#a7a8a8' }}>{fmtDate(entry.date)}</td>
                    <td style={{ padding: '14px 24px', color: '#515252' }}>{entry.by}</td>
                    <td style={{ padding: '14px 24px', textAlign: 'center' }}>
                      <button
                        onClick={() => handleDeleteEntry(entry.id, entry.value)}
                        style={{ background: 'none', border: 'none', color: RED, cursor: 'pointer', padding: 6, display: 'inline-flex', borderRadius: '50%' }}
                        onMouseEnter={e => e.currentTarget.style.background = '#fef2f2'}
                        onMouseLeave={e => e.currentTarget.style.background = 'none'}
                        title="Hapus Entitas"
                      >
                        <i className="bx bx-trash" style={{ fontSize: 16 }} />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}



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

            <form onSubmit={handleAddSubmit}>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Jenis Entitas</label>
                <select
                  value={addType}
                  onChange={e => setAddType(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                >
                  <option value="IP Address">IP Address</option>
                  <option value="Card BIN">Card BIN (6 Digit)</option>
                  <option value="Merchant MID">Merchant MID</option>
                  <option value="Customer Phone">Customer Phone</option>
                </select>
              </div>

              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nilai / Value</label>
                <input
                  type="text"
                  required
                  placeholder={addType === 'IP Address' ? 'Contoh: 192.168.1.1' : (addType === 'Card BIN' ? 'Contoh: 4512 88' : 'Contoh: MRC-001')}
                  value={addValue}
                  onChange={e => setAddValue(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', fontFamily: 'inherit' }}
                />
              </div>

              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Alasan Pembenaran / Justifikasi</label>
                <textarea
                  required
                  rows="3"
                  placeholder="Berikan alasan logis mengapa entitas ini didaftarkan..."
                  value={addDesc}
                  onChange={e => setAddDesc(e.target.value)}
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.4 }}
                />
              </div>

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setShowAddModal(false)} style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '9px 16px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer' }}>Batal</button>
                <button type="submit" style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', boxShadow: `0 4px 12px ${TEAL}15` }}>Tambah Entitas</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Toast Alert */}
      {toast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#171919', color: '#fff', padding: '14px 22px', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
          <i className="bx bxs-check-shield" style={{ fontSize: 18, color: GREEN }} />
          <span style={{ fontSize: 13, fontWeight: 650 }}>{toast}</span>
        </div>
      )}

    </div>
  );
}


// ── 4. SUSPECT MANAGEMENT PAGE ──
function FdsSuspectPage({ merchants, primary, secondary }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  const [alerts, setAlerts] = React.useState(getInitialFdsAlerts());
  const [searchQuery, setSearchQuery] = React.useState('');
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [filterRisk, setFilterRisk] = React.useState('all');
  const [activeAlertDetail, setActiveAlertDetail] = React.useState(null);
  const [showingDetail, setShowingDetail] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  // Investigation form states
  const [selectedAction, setSelectedAction] = React.useState('Fraud');
  const [investigationNote, setInvestigationNote] = React.useState('');

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

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

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

  const handleSimulateAlert = () => {
    const names = ['Kopi Senja Nusantara', 'Batik Lestari Pekalongan', 'Toko Bangunan Maju Jaya', 'Mart Sejahtera', 'RM Padang Sederhana'];
    const rules = [
      'Velocity Check: >5 transaksi dlm 1 menit',
      'Amount Outlier: >10x nominal rata-rata bulanan',
      'Card Bin Suspicious: Transaksi luar negeri dlm volume berulang',
      'Location Anomaly: Pergerakan lokasi tidak wajar dlm 10 menit',
      'Indikasi Gesek Tunai (Gestun): Transaksi mendekati limit berulang'
    ];
    const cities = ['Makassar, ID', 'Palembang, ID', 'Semarang, ID', 'Denpasar, ID', 'Balikpapan, ID'];
    const randomName = names[Math.floor(Math.random() * names.length)];
    const randomRule = rules[Math.floor(Math.random() * rules.length)];
    const randomCity = cities[Math.floor(Math.random() * cities.length)];
    const randomAmount = Math.floor(Math.random() * 500) * 10000 + 50000;
    const randomScore = Math.floor(Math.random() * 35) + 65; // score between 65 and 99

    const newAlert = {
      id: 'ALT-' + (Math.floor(Math.random() * 9000) + 1000),
      txId: 'TX-260624-' + (Math.floor(Math.random() * 9000) + 1000),
      time: new Date().toISOString(),
      merchant: randomName,
      location: randomCity,
      amount: randomAmount,
      score: randomScore,
      rule: randomRule,
      status: 'pending'
    };

    const updated = [newAlert, ...alerts];
    setAlerts(updated);
    saveFdsAlerts(updated);
    triggerToast(`Alert baru disimulasikan! Score: ${randomScore} (Risiko Tinggi)`);
  };

  const handleUpdateStatus = (id, newStatus) => {
    const updated = alerts.map(a => {
      if (a.id !== id) return a;
      return { ...a, status: newStatus };
    });
    setAlerts(updated);
    saveFdsAlerts(updated);
    if (activeAlertDetail && activeAlertDetail.id === id) {
      setActiveAlertDetail({ ...activeAlertDetail, status: newStatus });
    }
    triggerToast(`Status alert ${id} diubah ke ${newStatus.toUpperCase()}`);
  };

  const handleSubmitDecision = (e) => {
    e.preventDefault();
    if (!activeAlertDetail) return;
    if (!investigationNote.trim()) {
      alert('Mohon masukkan catatan investigasi kronologi kasus.');
      return;
    }

    const isResolvedBlocked = ['Fraud', 'Blacklist'].includes(selectedAction);
    const resolvedStatus = isResolvedBlocked ? 'blocked' : 'approved';

    const updated = alerts.map(a => {
      if (a.id !== activeAlertDetail.id) return a;
      return {
        ...a,
        status: resolvedStatus,
        action: selectedAction,
        note: investigationNote,
        resolvedTime: new Date().toISOString()
      };
    });

    setAlerts(updated);
    saveFdsAlerts(updated);
    triggerToast(`Kasus ${activeAlertDetail.id} berhasil diselesaikan (${selectedAction})`);
    setActiveAlertDetail(null);
    setInvestigationNote('');
    setShowingDetail(false);
  };

  const handleReopenCase = (id) => {
    const updated = alerts.map(a => {
      if (a.id !== id) return a;
      return {
        ...a,
        status: 'investigating',
        action: undefined,
        note: undefined,
        resolvedTime: undefined
      };
    });
    setAlerts(updated);
    saveFdsAlerts(updated);
    if (activeAlertDetail && activeAlertDetail.id === id) {
      setActiveAlertDetail({ ...activeAlertDetail, status: 'investigating', action: undefined, note: undefined, resolvedTime: undefined });
    }
    triggerToast(`Kasus ${id} dibuka kembali untuk investigasi ulang.`);
  };

  // Filter alerts
  const filteredAlerts = alerts.filter(a => {
    const matchesSearch =
      a.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      a.txId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      a.merchant.toLowerCase().includes(searchQuery.toLowerCase()) ||
      a.rule.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesStatus =
      filterStatus === 'all' ? true :
        filterStatus === 'pending' ? a.status === 'pending' :
          filterStatus === 'investigating' ? a.status === 'investigating' :
            filterStatus === 'approved' ? a.status === 'approved' :
              filterStatus === 'blocked' ? a.status === 'blocked' : true;

    const matchesRisk =
      filterRisk === 'all' ? true :
        filterRisk === 'high' ? a.score >= 80 :
          filterRisk === 'medium' ? a.score < 80 : true;

    return matchesSearch && matchesStatus && matchesRisk;
  });

  // Calculate statistics
  const stats = {
    total: alerts.length,
    pending: alerts.filter(a => a.status === 'pending').length,
    investigating: alerts.filter(a => a.status === 'investigating').length,
    resolved: alerts.filter(a => a.status === 'approved' || a.status === 'blocked').length
  };

  if (showingDetail && activeAlertDetail) {
    const isPending = activeAlertDetail.status === 'pending';
    const isInvestigating = activeAlertDetail.status === 'investigating';
    const isResolved = ['approved', 'blocked'].includes(activeAlertDetail.status);

    return (
      <div style={{ padding: '28px 32px 56px', animation: 'fadeIn 200ms ease' }}>
        {/* Breadcrumb / Back button */}
        <div style={{ marginBottom: 20 }}>
          <button
            onClick={() => { setShowingDetail(false); setActiveAlertDetail(null); }}
            style={{
              background: 'none', border: 'none', color: '#515252', fontSize: 13, fontWeight: 600,
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, padding: '4px 0'
            }}
          >
            <i className="bx bx-arrow-back" style={{ fontSize: 16 }} /> Kembali ke Suspect Management
          </button>
        </div>

        {/* Header */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>
            Investigasi Kasus — {activeAlertDetail.id}
          </div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>
            Detail Pemeriksaan Suspect
          </h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>
            Tinjau data transaksi, aturan yang terlanggar, dan submit keputusan penanganan fraud.
          </p>
        </div>

        {/* Layout Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 24, alignItems: 'start' }}>

          {/* Column 1: Info Transaksi & Kriteria Trigger */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

            {/* Score & Urgensi */}
            <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
              <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="bx bx-shield-quarter" style={{ color: activeAlertDetail.score >= 80 ? RED : AMBER, fontSize: 18 }} />
                Hasil FDS
              </h3>
              <div style={{ background: `${activeAlertDetail.score >= 80 ? RED : AMBER}08`, border: `1.5px solid ${activeAlertDetail.score >= 80 ? RED : AMBER}15`, borderRadius: 10, padding: '16px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ width: 44, height: 44, borderRadius: '50%', background: activeAlertDetail.score >= 80 ? RED : AMBER, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className="bx bx-shield-quarter" style={{ fontSize: 22, color: '#fff' }} />
                </div>
                <div>
                  <div style={{ fontSize: 11, color: activeAlertDetail.score >= 80 ? RED : AMBER, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                    {activeAlertDetail.score >= 80 ? 'Anomali Risiko Tinggi' : 'Risiko Sedang'}
                  </div>
                </div>
              </div>
            </div>

            {/* Detail Transaksi */}
            <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
              <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="bx bx-receipt" style={{ color: TEAL, fontSize: 18 }} />
                Informasi Detail Transaksi
              </h3>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div style={{ background: '#f9f9f9', padding: '12px 16px', borderRadius: 8 }}>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', marginBottom: 4 }}>ID Transaksi</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#171919', fontFamily: 'monospace' }}>{activeAlertDetail.txId}</div>
                </div>
                <div style={{ background: '#f9f9f9', padding: '12px 16px', borderRadius: 8 }}>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', marginBottom: 4 }}>Nama Merchant</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#171919' }}>{activeAlertDetail.merchant}</div>
                </div>
                <div style={{ background: '#f9f9f9', padding: '12px 16px', borderRadius: 8 }}>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', marginBottom: 4 }}>Nominal Transaksi</div>
                  <div style={{ fontSize: 14, fontWeight: 800, color: '#171919' }}>{fmtRp(activeAlertDetail.amount)}</div>
                </div>
                <div style={{ background: '#f9f9f9', padding: '12px 16px', borderRadius: 8 }}>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', marginBottom: 4 }}>Lokasi Pengguna</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>{activeAlertDetail.location}</div>
                </div>
                <div style={{ background: '#f9f9f9', padding: '12px 16px', borderRadius: 8, gridColumn: 'span 2' }}>
                  <div style={{ fontSize: 11.5, color: '#a7a8a8', marginBottom: 4 }}>Waktu Deteksi FDS</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#171919' }}>{fmtDate(activeAlertDetail.time)}</div>
                </div>
              </div>
            </div>

            {/* Aturan Terlanggar */}
            <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
              <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="bx bx-error-circle" style={{ color: RED, fontSize: 18 }} />
                Kriteria Trigger Suspect
              </h3>
              <div style={{ background: '#fafafa', border: '1.5px dashed #efefef', borderRadius: 10, padding: 16 }}>
                <div style={{ fontSize: 11.5, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Aturan FDS Terlanggar</div>
                <p style={{ fontSize: 13, color: '#171919', lineHeight: 1.4, margin: 0, fontWeight: 650 }}>{activeAlertDetail.rule}</p>
              </div>
            </div>

          </div>

          {/* Column 2: Alur Penanganan & Form Keputusan */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

            <div style={{ background: '#fff', padding: 24, borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
              <h3 style={{ fontSize: 14.5, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8 }}>
                <i className="bx bx-check-shield" style={{ color: GREEN, fontSize: 18 }} />
                Keputusan & Resolusi
              </h3>

              {['pending', 'investigating'].includes(activeAlertDetail.status) ? (
                <form onSubmit={handleSubmitDecision} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

                  {activeAlertDetail.status === 'pending' && (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                      <p style={{ fontSize: 13, color: '#515252', marginBottom: 16 }}>Kasus suspect ini belum diproses. Silakan klik tombol di bawah untuk memulai investigasi.</p>
                      <button
                        type="button"
                        onClick={() => handleUpdateStatus(activeAlertDetail.id, 'investigating')}
                        style={{
                          width: '100%', padding: '12px', background: TEAL, color: '#fff', border: 'none',
                          borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer',
                          boxShadow: `0 4px 12px ${TEAL}25`, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8
                        }}
                      >
                        <i className="bx bx-play-circle" style={{ fontSize: 16 }} /> Mulai Investigasi Kasus
                      </button>
                    </div>
                  )}

                  {activeAlertDetail.status === 'investigating' && (
                    <>
                      <div>
                        <label style={{ display: 'block', fontSize: 12.5, fontWeight: 755, color: '#515252', marginBottom: 6 }}>Identifikasi</label>
                        <select
                          value={selectedAction}
                          onChange={e => setSelectedAction(e.target.value)}
                          style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                        >
                          <option value="Fraud">Fraud (Tidak Aman)</option>
                          <option value="Tidak Fraud">Tidak Fraud (Aman)</option>
                        </select>
                      </div>


                      <div>
                        <label style={{ display: 'block', fontSize: 12.5, fontWeight: 755, color: '#515252', marginBottom: 6 }}>Tindakan</label>
                        <select


                          style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }}
                        >
                          <option value="Fraud">Masukan Ke Blacklist</option>
                          <option value="Tidak Fraud">Masukan Ke White List</option>
                          <option value="Tidak Fraud">Abaikan & Monitor</option>
                        </select>
                      </div>


                      <div>
                        <label style={{ display: 'block', fontSize: 12.5, fontWeight: 755, color: '#515252', marginBottom: 6 }}>Catatan Analisis Kasus (Kronologi)</label>
                        <textarea
                          required
                          rows="5"
                          placeholder="Masukkan kronologi temuan investigasi..."
                          value={investigationNote}
                          onChange={e => setInvestigationNote(e.target.value)}
                          style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 12.5, outline: 'none', fontFamily: 'inherit', resize: 'vertical', minHeight: 120 }}
                        />
                      </div>

                      <button
                        type="submit"
                        style={{
                          width: '100%', padding: '12px', background: GREEN, color: '#fff', border: 'none',
                          borderRadius: 8, fontSize: 13.5, fontWeight: 750, cursor: 'pointer',
                          boxShadow: `0 4px 12px ${GREEN}25`, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8
                        }}
                      >
                        <i className="bx bx-check-shield" style={{ fontSize: 16 }} /> Kirim Keputusan Akhir
                      </button>
                    </>
                  )}

                </form>
              ) : (
                /* Resolved View */
                <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  <div style={{ background: 'rgba(116,181,12,0.04)', border: '1px solid rgba(116,181,12,0.15)', borderRadius: 10, padding: 16 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: activeAlertDetail.status === 'blocked' ? RED : GREEN, fontWeight: 800, fontSize: 13, marginBottom: 12 }}>
                      <i className="bx bx-check-circle" style={{ fontSize: 16 }} /> KASUS TERESOLUSI ({activeAlertDetail.action?.toUpperCase()})
                    </div>
                    <div style={{ fontSize: 13, color: '#515252', borderBottom: '1px solid #efefef', paddingBottom: 10, marginBottom: 10, lineHeight: 1.5 }}>
                      <strong>Catatan Analisis:</strong><br />
                      {activeAlertDetail.note || 'Tidak ada catatan.'}
                    </div>
                    <div style={{ fontSize: 11.5, color: '#a7a8a8' }}>
                      Diselesaikan pada: {activeAlertDetail.resolvedTime ? fmtDate(activeAlertDetail.resolvedTime) : '—'}
                    </div>
                  </div>

                  <button
                    type="button"
                    onClick={() => handleReopenCase(activeAlertDetail.id)}
                    style={{
                      width: '100%', padding: '11px', background: '#fff', border: '1.5px solid #efefef',
                      color: '#515252', borderRadius: 8, fontSize: 13, fontWeight: 700, cursor: 'pointer',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8
                    }}
                    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-refresh" style={{ fontSize: 16 }} /> Buka Kembali Kasus
                  </button>
                </div>
              )}

            </div>

          </div>

        </div>

        {/* Floating Toast Notification */}
        {toast && (
          <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#171919', color: '#fff', padding: '14px 22px', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
            <i className="bx bxs-check-shield" style={{ fontSize: 18, color: GREEN }} />
            <span style={{ fontSize: 13, fontWeight: 650 }}>{toast}</span>
          </div>
        )}

      </div>
    );
  }

  return (
    <div style={{ padding: '0px 0px 40px 0px', animation: 'fadeIn 200ms ease' }}>

      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Fraud Detection System</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Suspect Management & Investigasi</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Kelola temuan suspect anomali merchant, lakukan investigasi detail, dan ambil tindakan preventif fraud secara real-time.</p>
        </div>

        <button
          onClick={handleSimulateAlert}
          style={{
            background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px',
            fontSize: 12.5, fontWeight: 750, cursor: 'pointer', display: 'inline-flex',
            alignItems: 'center', gap: 8, boxShadow: `0 4px 12px ${TEAL}25`, transition: 'all 150ms',
            fontFamily: 'inherit'
          }}
          onMouseEnter={e => e.currentTarget.style.background = '#0041A8'}
          onMouseLeave={e => e.currentTarget.style.background = TEAL}
        >
          <i className="bx bx-broadcast" style={{ fontSize: 16 }} />
          Simulasikan Temuan Suspect
        </button>
      </div>

      {/* Summary Row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16, marginBottom: 24 }}>
        {[
          { label: 'Total Alerts Suspect', value: stats.total, sub: 'Semua kasus terdeteksi', icon: 'bx-shield', color: TEAL },
          { label: 'Pending Review', value: stats.pending, sub: 'Menunggu penanganan', icon: 'bx-time-five', color: AMBER },
          { label: 'Sedang Diinvestigasi', value: stats.investigating, sub: 'Dalam proses analisis', icon: 'bx-analyse', color: '#0056D2' },
          { label: 'Kasus Diselesaikan', value: stats.resolved, sub: 'Telah diputuskan aksinya', icon: 'bx-check-circle', color: GREEN }
        ].map((card, i) => (
          <div key={i} style={{ background: '#fff', padding: 20, borderRadius: 12, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.01)', display: 'flex', gap: 16, alignItems: 'center' }}>
            <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: 11.5, color: '#a7a8a8', fontWeight: 650 }}>{card.label}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: '#171919', marginTop: 4, lineHeight: 1 }}>{card.value}</div>
              <div style={{ fontSize: 11, color: '#515252', marginTop: 4 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filter & Search Controls */}
      <div style={{ background: '#fff', padding: '16px 20px', borderRadius: 12, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.01)', display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', marginBottom: 20 }}>
        <div style={{ flex: 1, minWidth: 260, position: 'relative' }}>
          <i className="bx bx-search" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#a7a8a8', fontSize: 16 }} />
          <input
            type="text"
            placeholder="Cari merchant, ID alert, atau tipe aturan FDS..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            style={{ width: '100%', padding: '8px 12px 8px 36px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 12.5, outline: 'none', fontFamily: 'inherit' }}
          />
        </div>

        <select
          value={filterStatus}
          onChange={e => setFilterStatus(e.target.value)}
          style={{ padding: '8px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 12.5, outline: 'none', background: '#fff', fontFamily: 'inherit', color: '#515252' }}
        >
          <option value="all">Semua Status Review</option>
          <option value="pending">Pending Review</option>
          <option value="investigating">Dalam Investigasi</option>
          <option value="approved">Aman (Tidak Fraud / White List)</option>
          <option value="blocked">Ditolak (Fraud / Blacklist)</option>
        </select>

        <select
          value={filterRisk}
          onChange={e => setFilterRisk(e.target.value)}
          style={{ padding: '8px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 12.5, outline: 'none', background: '#fff', fontFamily: 'inherit', color: '#515252' }}
        >
          <option value="all">Semua Skala Risiko</option>
          <option value="high">Risiko Tinggi (Score >= 80)</option>
          <option value="medium">Risiko Sedang (Score &lt; 80)</option>
        </select>
      </div>

      {/* Main Alerts 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={{ borderBottom: '1px solid #efefef', background: '#fafafa' }}>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 110 }}>ID Alert</th>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 220 }}>Entitas Merchant / ID</th>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 140 }}>Waktu</th>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 130 }}>Nominal</th>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Pelanggaran Aturan FDS</th>

              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 150, textAlign: 'center' }}>Status</th>
              <th style={{ padding: '14px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 110, textAlign: 'center' }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {filteredAlerts.length === 0 ? (
              <tr>
                <td colSpan="8" style={{ padding: '40px 20px', textAlign: 'center', color: '#a7a8a8' }}>
                  Tidak ada temuan suspect yang cocok dengan kriteria filter.
                </td>
              </tr>
            ) : (
              filteredAlerts.map(a => {
                const isHigh = a.score >= 80;

                // Status mapping to color/text
                let statusBg = 'rgba(217,146,11,0.08)';
                let statusColor = AMBER;
                let statusText = 'MEDIUM RISK';

                if (a.status === 'investigating') {
                  statusBg = 'rgba(0,86,210,0.08)';
                  statusColor = '#0056D2';
                  statusText = 'LOW RISK';
                } else if (a.status === 'approved') {
                  statusBg = 'rgba(116,181,12,0.08)';
                  statusColor = GREEN;
                  statusText = a.action ? a.action.toUpperCase() : 'LOW RISK';
                } else if (a.status === 'blocked') {
                  statusBg = 'rgba(237,49,81,0.08)';
                  statusColor = RED;
                  statusText = a.action ? a.action.toUpperCase() : 'HIGH RISK';
                }

                return (
                  <tr key={a.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }} onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <td style={{ padding: '14px 20px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{a.id}</td>
                    <td style={{ padding: '14px 20px' }}>
                      <div style={{ fontWeight: 750, color: '#171919' }}>{a.merchant}</div>
                      <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2, fontFamily: 'monospace' }}>{a.txId}</div>
                    </td>
                    <td style={{ padding: '14px 20px', fontSize: 12, color: '#515252' }}>{fmtDate(a.time)}</td>
                    <td style={{ padding: '14px 20px', fontWeight: 700, color: '#171919' }}>{fmtRp(a.amount)}</td>
                    <td style={{ padding: '14px 20px', color: '#515252', lineHeight: 1.35 }}>{a.rule}</td>
                    <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                      <span style={{
                        background: statusBg, color: statusColor, fontSize: 10.5, fontWeight: 800,
                        borderRadius: 6, padding: '4px 8px', border: `1px solid ${statusColor}15`,
                        display: 'inline-block', minWidth: 90, textAlign: 'center', letterSpacing: '0.03em'
                      }}>
                        {statusText}
                      </span>
                    </td>
                    <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                      <button
                        onClick={() => {
                          setActiveAlertDetail(a);
                          setSelectedAction(a.action || 'Fraud');
                          setInvestigationNote(a.note || '');
                          setShowingDetail(true);
                        }}
                        style={{
                          background: '#fff', border: '1.5px solid #efefef', borderRadius: 6,
                          padding: '5px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer',
                          transition: 'all 150ms', color: '#515252', width: '100%'
                        }}
                        onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
                        onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
                      >
                        {['approved', 'blocked'].includes(a.status) ? 'Detail' : 'Periksa'}
                      </button>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>



      {/* Floating Toast Notification */}
      {toast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1600, background: '#171919', color: '#fff', padding: '14px 22px', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease' }}>
          <i className="bx bxs-check-shield" style={{ fontSize: 18, color: GREEN }} />
          <span style={{ fontSize: 13, fontWeight: 650 }}>{toast}</span>
        </div>
      )}

    </div>
  );
}

// Register components globally
Object.assign(window, { FdsDashboardPage, FdsMonitoringPage, FdsParameterPage, FdsSuspectPage });
