// recon-settlement.jsx — Recon & Settlement Page for Hibank QRIS BackOffice
function ReconSettlementPage({ merchants, primary, secondary, merchantView = false }) {
  const TEAL = primary || '#0056D2';
  const ORANGE = secondary || '#cf5a27';
  const GREEN = '#74b50c';
  const RED = '#ed3151';
  const AMBER = '#d9920b';

  // State Utama
  const [view, setView] = React.useState('list'); // 'list' | 'detail' | 'investigate'
  const [selectedDay, setSelectedDay] = React.useState(null);
  const [toast, setToast] = React.useState(null);

  // State Form Kelengkapan Dokumen / Berita Acara (BARU)
  const [investigateNote, setInvestigateNote] = React.useState('');
  const [uploadedFile, setUploadedFile] = React.useState(null);

  // Custom adjustment modal state
  const [adjustingTx, setAdjustingTx] = React.useState(null);
  const [adjustAmount, setAdjustAmount] = React.useState('');
  const [adjustNote, setAdjustNote] = React.useState('');

  // Seed progress data
  const [progress, setProgress] = React.useState([
    { date: '2026-06-24', total: 1250, matched: 1247, suspect: 3, status: 'investigate', volume: 85240000 },
    { date: '2026-06-23', total: 1100, matched: 1100, status: 'success', volume: 74120000 },
    { date: '2026-06-22', total: 950, matched: 948, suspect: 2, status: 'success', volume: 61500000 },
    { date: '2026-06-21', total: 1320, matched: 1320, status: 'success', volume: 92800000 },
    { date: '2026-06-20', total: 1050, matched: 1050, status: 'success', volume: 71050000 }
  ]);

  // Seed suspect data
  const [suspects, setSuspects] = React.useState([
    { id: 'TX-260624-9912', date: '2026-06-24', mid: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan', coreAmount: 150000, switchAmount: 155000, type: 'selisih_nominal', desc: 'Selisih nominal core QRIS vs switching', resolution: null },
    { id: 'TX-260624-9913', date: '2026-06-24', mid: 'MRC-00245', merchantName: 'Toko Bangunan Maju Jaya', coreAmount: 75000, switchAmount: null, type: 'gantung_switch', desc: 'Transaksi tercatat di Core tetapi tidak ditemukan di switching', resolution: null },
    { id: 'TX-260624-9914', date: '2026-06-24', mid: 'MRC-00246', merchantName: 'Kopi Senja Nusantara', coreAmount: null, switchAmount: 45000, type: 'gantung_core', desc: 'Transaksi tercatat di switching tetapi belum ada di Core', resolution: null },
    { id: 'TX-260622-8141', date: '2026-06-22', mid: 'MRC-00244', merchantName: 'Batik Lestari Pekalongan', coreAmount: 320000, switchAmount: 320000, type: 'gantung_switch', desc: 'Settle manual — resolved', resolution: 'resolved_success', resolutionNote: 'Dilunaskan manual via rekon' },
    { id: 'TX-260622-8142', date: '2026-06-22', mid: 'MRC-00245', merchantName: 'Toko Bangunan Maju Jaya', coreAmount: 50000, switchAmount: null, type: 'gantung_switch', desc: 'Settle manual — resolved', resolution: 'resolved_failed', resolutionNote: 'Dibatalkan manual via rekon' }
  ]);

  // Seed matched transaction detail data for 2026-06-24
  const matchedTxSeed = [
    { id: 'TX-260624-8831', mid: 'MRC-00244', name: 'Batik Lestari', time: '2026-06-24T10:15:00', amount: 45000, issuer: 'ShopeePay', status: 'Matched' },
    { id: 'TX-260624-8832', mid: 'MRC-00245', name: 'Maju Jaya', time: '2026-06-24T10:20:00', amount: 125000, issuer: 'OVO', status: 'Matched' },
    { id: 'TX-260624-8833', mid: 'MRC-00246', name: 'Kopi Senja', time: '2026-06-24T10:24:00', amount: 35000, issuer: 'Gopay', status: 'Matched' },
    { id: 'TX-260624-8834', mid: 'MRC-00244', name: 'Batik Lestari', time: '2026-06-24T10:30:00', amount: 500000, issuer: 'Dana', status: 'Matched' },
    { id: 'TX-260624-8835', mid: 'MRC-00246', name: 'Kopi Senja', time: '2026-06-24T10:45:00', amount: 18000, issuer: 'LinkAja', status: 'Matched' },
    { id: 'TX-260624-8836', mid: 'MRC-00245', name: 'Maju Jaya', time: '2026-06-24T10:50:00', amount: 24000, issuer: 'QRIS BCA', status: 'Matched' },
    { id: 'TX-260624-8837', mid: 'MRC-00244', name: 'Batik Lestari', time: '2026-06-24T11:02:00', amount: 120000, issuer: 'QRIS Hibank', status: 'Matched' }
  ];

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

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

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

  // Action: Resolve suspect transaction
  const handleResolveSuspect = (txId, resolutionType, customNote = '') => {
    let noteText = '';
    if (resolutionType === 'resolved_success') {
      noteText = 'Dilunaskan manual via rekon';
    } else if (resolutionType === 'resolved_failed') {
      noteText = 'Dibatalkan manual via rekon';
    } else if (resolutionType === 'resolved_adjusted') {
      noteText = customNote || 'Penyesuaian nominal selisih';
    } else {
      noteText = null;
    }

    setSuspects(prev => prev.map(s => {
      if (s.id !== txId) return s;
      return { ...s, resolution: resolutionType, resolutionNote: noteText };
    }));

    if (resolutionType === null) {
      triggerToast(`Status transaksi ${txId} dikembalikan ke Belum Selesai.`, 'amber');
    } else {
      triggerToast(`Transaksi ${txId} berhasil diperbarui.`, 'success');
    }

    setTimeout(() => {
      setSuspects(currentSuspects => {
        const targetTx = currentSuspects.find(s => s.id === txId);
        if (!targetTx) return currentSuspects;

        const targetDay = targetTx.date;
        const remainingSuspects = currentSuspects.filter(s => s.date === targetDay && s.resolution === null).length;

        setProgress(prevProg => prevProg.map(p => {
          if (p.date !== targetDay) return p;
          if (remainingSuspects === 0) {
            return { ...p, status: 'success', suspect: 0 };
          } else {
            return { ...p, status: 'investigate', suspect: remainingSuspects };
          }
        }));
        return currentSuspects;
      });
    }, 50);
  };

  // Action: Sesuaikan Dana
  const handleAdjustFunds = (e) => {
    e.preventDefault();
    if (!adjustingTx || !adjustAmount.trim()) return;

    const formattedNote = `Nominal disesuaikan sebesar Rp ${Number(adjustAmount).toLocaleString('id-ID')}. ${adjustNote}`.trim();
    handleResolveSuspect(adjustingTx.id, 'resolved_adjusted', formattedNote);

    setAdjustingTx(null);
    setAdjustAmount('');
    setAdjustNote('');
  };

  // Action: Simpan Berita Acara & Catatan Akhir (BARU)
  const handleSaveInvestigationForm = (e) => {
    e.preventDefault();

    // Validasi file berita acara
    if (!uploadedFile) {
      triggerToast('Gagal simpan! Dokumen Berita Acara (BAR) wajib diupload.', 'error');
      return;
    }

    triggerToast(`Berita Acara & Berkas Investigasi untuk tanggal ${selectedDay.date} sukses disimpan ke log sistem.`, 'success');

    // Reset state form & kembali ke daftar utama
    setInvestigateNote('');
    setUploadedFile(null);
    setView('list');
    setSelectedDay(null);
  };

  // Calculations
  const stats = {
    volume: progress.reduce((acc, curr) => acc + curr.volume, 0),
    successRate: 99.88,
    totalSuspects: suspects.filter(s => s.resolution === null).length,
    settledDays: progress.filter(p => p.status === 'success').length
  };

  // ── MERCHANT VIEW: SETTLEMENT-ONLY (dana yang telah settled ke merchant) ──
  if (merchantView) {
    const MDR_RATE = 0.007;
    const settledDays = progress.filter(p => p.status === 'success');
    const totalNet = settledDays.reduce((a, p) => a + Math.round(p.volume * (1 - MDR_RATE)), 0);
    const totalGross = settledDays.reduce((a, p) => a + p.volume, 0);
    const totalMdr = totalGross - totalNet;
    const acctName = 'Bank Hibank · 8820145566';

    return (
      <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
        {/* Header */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Settlement</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Dana Settlement Anda</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Rincian dana transaksi QRIS yang telah berhasil di-settle dan dikreditkan ke rekening settlement Anda.</p>
        </div>

        {/* Summary cards */}
        <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
          {[
            { label: 'Total Dana Settled', value: fmtRp(totalNet), sub: 'Bersih setelah MDR', icon: 'bx-wallet', color: GREEN },
            { label: 'Total Volume Bruto', value: fmtRp(totalGross), sub: 'Sebelum potongan', icon: 'bx-line-chart', color: TEAL },
            { label: 'Total Potongan MDR', value: fmtRp(totalMdr), sub: '0,7% per transaksi', icon: 'bx-receipt', color: ORANGE },
            { label: 'Batch Settled', value: `${settledDays.length} Hari`, sub: 'Periode aktif', icon: 'bx-calendar-check', color: AMBER }
          ].map((card, i) => (
            <div key={i} style={{ background: '#fff', padding: '18px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 200 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: `${card.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <i className={`bx ${card.icon}`} style={{ fontSize: 20, color: card.color }} />
              </div>
              <div>
                <div style={{ fontSize: 12, color: '#a7a8a8', fontWeight: 600 }}>{card.label}</div>
                <div style={{ fontSize: 20, fontWeight: 800, color: '#171919', marginTop: 4, lineHeight: 1 }}>{card.value}</div>
                <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>{card.sub}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Settled table */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid #efefef', background: '#fafafa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 14, fontWeight: 800, color: '#171919', margin: 0 }}>Riwayat Settlement Harian</h3>
            <span style={{ fontSize: 12, color: '#515252' }}>Rekening tujuan: <strong style={{ color: '#171919' }}>{acctName}</strong></span>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
            <thead>
              <tr style={{ background: '#fff', borderBottom: '1px solid #efefef' }}>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Tanggal Settlement</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>No. Referensi</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Total Trx</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Volume Bruto</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Potongan MDR</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Dana Settled (Net)</th>
                <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status</th>
              </tr>
            </thead>
            <tbody>
              {settledDays.map(row => {
                const net = Math.round(row.volume * (1 - MDR_RATE));
                const mdr = row.volume - net;
                return (
                  <tr key={row.date} style={{ borderBottom: '1px solid #f3f3f3' }}>
                    <td style={{ padding: '14px 20px', fontWeight: 700, color: '#171919' }}>{row.date}</td>
                    <td style={{ padding: '14px 20px', fontFamily: 'monospace', color: TEAL, fontWeight: 700 }}>STL-{row.date.replace(/-/g, '').slice(2)}</td>
                    <td style={{ padding: '14px 20px', color: '#515252' }}>{row.total} Trx</td>
                    <td style={{ padding: '14px 20px', color: '#171919', fontWeight: 600 }}>{fmtRp(row.volume)}</td>
                    <td style={{ padding: '14px 20px', color: RED }}>-{fmtRp(mdr)}</td>
                    <td style={{ padding: '14px 20px', color: GREEN, fontWeight: 800 }}>{fmtRp(net)}</td>
                    <td style={{ padding: '14px 20px' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: 'rgba(116,181,12,0.12)', color: GREEN, fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 9px' }}>
                        <i className="bx bx-check-circle" /> Settled
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ── SUB-PAGE: DETAIL TRANSAKSI YANG DIREKON ──
  if (view === 'detail' && selectedDay) {
    return (
      <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
        {/* Breadcrumb */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <button
            onClick={() => { setView('list'); setSelectedDay(null); }}
            style={{
              display: 'flex', alignItems: 'center', gap: 6, background: '#fff', border: '1.5px solid #efefef',
              borderRadius: 8, padding: '8px 14px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', transition: 'all 150ms'
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = TEAL; e.currentTarget.style.color = TEAL; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#efefef'; e.currentTarget.style.color = '#515252'; }}
          >
            <i className="bx bx-left-arrow-alt" style={{ fontSize: 18 }} /> Kembali
          </button>
          <div style={{ fontSize: 13, color: '#a7a8a8' }}>
            Recon & Settlement / <span style={{ color: '#515252', fontWeight: 600 }}>Detail Progress Recon {selectedDay.date}</span>
          </div>
        </div>

        {/* Title */}
        <div style={{ marginBottom: 24 }}>
          <h1 style={{ fontSize: 22, fontWeight: 800, color: '#171919', margin: 0 }}>Detail Transaksi Reconciled</h1>
          <p style={{ fontSize: 13, color: '#515252', marginTop: 4 }}>Daftar transaksi yang sukses dipadankan dengan pembukuan core bank pada {selectedDay.date}.</p>
        </div>

        {/* Stats card */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', padding: '20px 24px', display: 'flex', gap: 40, marginBottom: 24, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Tanggal Rekon</div>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#171919', marginTop: 4 }}>{selectedDay.date}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Total Transaksi</div>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#171919', marginTop: 4 }}>{selectedDay.total} Transaksi</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Volume Recon</div>
            <div style={{ fontSize: 16, fontWeight: 700, color: TEAL, marginTop: 4 }}>{fmtRp(selectedDay.volume)}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Status</div>
            <div style={{ marginTop: 4 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: selectedDay.status === 'success' ? 'rgba(116,181,12,0.12)' : 'rgba(217,146,11,0.12)', color: selectedDay.status === 'success' ? '#74b50c' : '#d9920b', fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 9px' }}>
                <i className={`bx ${selectedDay.status === 'success' ? 'bx-check-circle' : 'bx-time-five'}`} /> {selectedDay.status === 'success' ? 'Selesai' : 'Perlu Investigasi'}
              </span>
            </div>
          </div>
        </div>

        {/* Reconciled 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' }}>ID Transaksi</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>MID Merchant</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nama Outlet</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Waktu Transaksi</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Issuer QRIS</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' }}>Status Recon</th>
              </tr>
            </thead>
            <tbody>
              {matchedTxSeed.map(tx => (
                <tr key={tx.id} style={{ borderBottom: '1px solid #f3f3f3' }}>
                  <td style={{ padding: '14px 18px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>{tx.id}</td>
                  <td style={{ padding: '14px 18px', color: '#515252' }}>{tx.mid}</td>
                  <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{tx.name}</td>
                  <td style={{ padding: '14px 18px', color: '#a7a8a8' }}>{fmtDate(tx.time)}</td>
                  <td style={{ padding: '14px 18px' }}>
                    <span style={{ background: '#f6f6f6', borderRadius: 4, padding: '3px 8px', fontSize: 11.5, color: '#171919', fontWeight: 600 }}>{tx.issuer}</span>
                  </td>
                  <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(tx.amount)}</td>
                  <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: 'rgba(116,181,12,0.1)', color: '#74b50c', fontSize: 11.5, fontWeight: 700, borderRadius: 4, padding: '2px 8px' }}>
                      <i className="bx bx-check" /> {tx.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ── SUB-PAGE: INVESTIGASI SUSPECT WORKBENCH ──
  if (view === 'investigate' && selectedDay) {
    const daySuspects = suspects.filter(s => s.date === selectedDay.date);
    const unresolvedCount = daySuspects.filter(s => s.resolution === null).length;

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

        {/* Title */}
        <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 800, color: '#171919', margin: 0 }}>Investigasi Transaksi Suspect</h1>
            <p style={{ fontSize: 13, color: '#515252', marginTop: 4 }}>Penyelesaian perbedaan data nominal atau status gantung antara Core Bank dan Switch.</p>
          </div>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: unresolvedCount > 0 ? 'rgba(237,49,81,0.1)' : 'rgba(116,181,12,0.12)', color: unresolvedCount > 0 ? '#ed3151' : '#74b50c', fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '6px 12px' }}>
            <i className={`bx ${unresolvedCount > 0 ? 'bx-error' : 'bx-check-circle'}`} /> {unresolvedCount} Suspect Belum Selesai
          </span>
        </div>

        {/* Card Ringkasan Harian Investigasi (BARU) */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', padding: '16px 20px', display: 'flex', gap: 40, marginBottom: 24, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Tanggal Log Buku</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#171919', marginTop: 4 }}>{selectedDay.date}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Volume Kliring Harian</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: TEAL, marginTop: 4 }}>{fmtRp(selectedDay.volume)}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#a7a8a8', fontWeight: 600, textTransform: 'uppercase' }}>Total Antrean Suspect</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#171919', marginTop: 4 }}>{daySuspects.length} Kasus</div>
          </div>
        </div>

        {/* Suspect list table */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
            <thead>
              <tr style={{ background: '#fafafa', borderBottom: '1px solid #efefef' }}>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 140 }}>ID Transaksi</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nama Merchant</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Penyebab Suspect</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal Core</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Nominal Switch</th>
                <th style={{ padding: '12px 18px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', width: 210, textAlign: 'center' }}>Aksi Rekon</th>
              </tr>
            </thead>
            <tbody>
              {daySuspects.map(s => {
                let selectColor = '#515252';
                let selectBorder = '#efefef';
                if (s.resolution === 'resolved_success') { selectColor = GREEN; selectBorder = GREEN; }
                else if (s.resolution === 'resolved_failed') { selectColor = RED; selectBorder = RED; }
                else if (s.resolution === 'resolved_adjusted') { selectColor = TEAL; selectBorder = TEAL; }

                return (
                  <tr key={s.id} style={{ borderBottom: '1px solid #f3f3f3', transition: 'background 150ms' }}>
                    <td style={{ padding: '14px 18px', fontFamily: 'monospace', fontWeight: 700, color: TEAL }}>
                      {s.id}
                      <div style={{ fontSize: 10.5, color: '#a7a8a8', fontWeight: 400, marginTop: 2 }}>{s.mid}</div>
                    </td>
                    <td style={{ padding: '14px 18px', fontWeight: 600, color: '#171919' }}>{s.merchantName}</td>
                    <td style={{ padding: '14px 18px', color: '#515252', maxWidth: 180, lineHeight: 1.4 }}>
                      <span style={{ display: 'block', fontWeight: 700, fontSize: 11.5, color: s.resolution ? '#a7a8a8' : RED, marginBottom: 3 }}>
                        {s.type === 'selisih_nominal' ? 'Nominal Selisih' : s.type === 'gantung_switch' ? 'Gantung di Switch' : 'Gantung di Core'}
                      </span>
                      {s.desc}
                    </td>
                    <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(s.coreAmount)}</td>
                    <td style={{ padding: '14px 18px', fontWeight: 700, color: '#171919' }}>{fmtRp(s.switchAmount)}</td>
                    <td style={{ padding: '14px 18px', textAlign: 'center' }}>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'center' }}>
                        <select
                          value={s.resolution || ""}
                          onChange={(e) => {
                            const action = e.target.value;
                            if (action === "") {
                              handleResolveSuspect(s.id, null);
                            } else if (action === 'resolved_success') {
                              handleResolveSuspect(s.id, 'resolved_success');
                            } else if (action === 'resolved_failed') {
                              handleResolveSuspect(s.id, 'resolved_failed');
                            } else if (action === 'resolved_adjusted') {
                              setAdjustingTx(s);
                              setAdjustAmount(String(Math.abs((s.coreAmount || 0) - (s.switchAmount || 0))));
                            }
                          }}
                          style={{
                            width: '175px',
                            padding: '6px 10px',
                            borderRadius: 6,
                            border: `1.5px solid ${selectBorder}`,
                            background: '#fff',
                            fontSize: '12px',
                            fontWeight: 700,
                            color: selectColor,
                            outline: 'none',
                            cursor: 'pointer',
                            fontFamily: 'inherit',
                            transition: 'all 150ms'
                          }}
                        >
                          <option value="">⏳ Belum Selesai</option>
                          <option value="resolved_success" style={{ color: GREEN }}>✅ Lunaskan</option>
                          <option value="resolved_failed" style={{ color: RED }}>❌ Batalkan</option>
                          <option value="resolved_adjusted" style={{ color: TEAL }}>⚙️ Sesuaikan Dana</option>
                        </select>

                        {s.resolution && (
                          <span style={{ fontSize: 11, color: '#a7a8a8', fontStyle: 'italic', maxWidth: '175px', display: 'block', lineHeight: 1.3 }}>
                            "{s.resolutionNote}"
                          </span>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* ── SECTION FORM DOCUMENT KELENGKAPAN & BERITA ACARA (BARU) ── */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', padding: '24px', marginTop: 24, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
          <h3 style={{ fontSize: 14, fontWeight: 800, color: '#171919', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 6 }}>
            <i className="bx bx-folder-open" style={{ fontSize: 18, color: TEAL }} /> Otorisasi Dokumen & Catatan Audit
          </h3>

          <form onSubmit={handleSaveInvestigationForm}>
            <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', marginBottom: 24 }}>
              {/* Kolom Catatan */}
              <div style={{ flex: 1, minWidth: 280 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Catatan Kronologis Hasil Investigasi</label>
                <textarea
                  rows="4"
                  value={investigateNote}
                  onChange={(e) => setInvestigateNote(e.target.value)}
                  placeholder="Masukkan berita acara singkat pencocokan log suspect, alasan selisih nominal, atau memo internal pemadanan buku kerja..."
                  style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none', resize: 'none', fontFamily: 'inherit', lineHeight: 1.4 }}
                  onFocus={e => e.target.style.borderColor = TEAL}
                  onBlur={e => e.target.style.borderColor = '#efefef'}
                />
              </div>

              {/* Kolom Upload File BAR */}
              <div style={{ flex: 1, minWidth: 280 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Berkas Berita Acara Rekonsiliasi (BAR) <span style={{ color: RED }}>*</span></label>
                <div style={{ border: '1.5px dashed #d9d9d9', padding: '20px', borderRadius: 8, textAlign: 'center', background: '#fafafa', position: 'relative', height: '102px', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 150ms' }}>
                  <input
                    type="file"
                    accept=".pdf,.docx,.doc,.xlsx"
                    id="ba-file-input"
                    onChange={(e) => setUploadedFile(e.target.files[0])}
                    style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}
                  />
                  <div>
                    <i className={`bx ${uploadedFile ? 'bx-file-check' : 'bx-cloud-upload'}`} style={{ fontSize: 28, color: uploadedFile ? GREEN : TEAL, marginBottom: 4 }} />
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: '#171919' }}>
                      {uploadedFile ? uploadedFile.name : 'Tarik berkas atau klik untuk upload dokumen'}
                    </div>
                    <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 2 }}>Mendukung format PDF, Word, Excel (Max. 5MB)</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Garis Pembatas Sesi Aksi */}
            <hr style={{ border: 'none', borderTop: '1px solid #efefef', margin: '0 0 20px' }} />

            {/* Tombol Simpan & Kembali di bawah halaman */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button
                type="button"
                onClick={() => { setView('list'); setSelectedDay(null); setInvestigateNote(''); setUploadedFile(null); }}
                style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer', transition: 'all 150ms' }}
                onMouseEnter={e => e.currentTarget.style.borderColor = '#d9920b'}
                onMouseLeave={e => e.currentTarget.style.borderColor = '#efefef'}
              >
                Kembali ke List
              </button>

              <button
                type="submit"
                style={{
                  background: TEAL,
                  color: '#fff',
                  border: 'none',
                  borderRadius: 8,
                  padding: '10px 24px',
                  fontSize: 13,
                  fontWeight: 700,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 6,
                  boxShadow: `0 4px 12px rgba(0,86,210,0.15)`
                }}
              >
                <i className="bx bx-save" style={{ fontSize: 16 }} /> Simpan & Sinkronisasi
              </button>
            </div>
          </form>
        </div>

        {/* Modal: Sesuaikan Dana */}
        {adjustingTx && (
          <div style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div onClick={() => setAdjustingTx(null)} 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 }}>Form Penyesuaian Dana Rekon</h3>
                <button onClick={() => setAdjustingTx(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#515252', padding: 4 }}><i className="bx bx-x" style={{ fontSize: 20 }} /></button>
              </div>

              <form onSubmit={handleAdjustFunds}>
                <div style={{ background: '#f6f6f6', borderRadius: 8, padding: '12px', fontSize: 12, lineHeight: 1.4, color: '#515252', marginBottom: 16 }}>
                  <div>ID Transaksi: <strong>{adjustingTx.id}</strong></div>
                  <div style={{ marginTop: 4 }}>Nominal Core: <strong>{fmtRp(adjustingTx.coreAmount)}</strong></div>
                  <div>Nominal Switch: <strong>{fmtRp(adjustingTx.switchAmount)}</strong></div>
                </div>

                <div style={{ marginBottom: 16 }}>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#515252', marginBottom: 6 }}>Nominal Penyesuaian (Selisih)</label>
                  <div style={{ position: 'relative' }}>
                    <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 13, color: '#a7a8a8', fontWeight: 600 }}>Rp</span>
                    <input
                      type="number"
                      required
                      value={adjustAmount}
                      onChange={e => setAdjustAmount(e.target.value)}
                      placeholder="Masukkan nominal penyesuaian..."
                      style={{ width: '100%', padding: '10px 12px 10px 32px', borderRadius: 8, border: '1.5px solid #efefef', fontSize: 13, color: '#171919', outline: 'none' }}
                      onFocus={e => e.target.style.borderColor = TEAL}
                      onBlur={e => e.target.style.borderColor = '#efefef'}
                    />
                  </div>
                </div>

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

                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                  <button type="button" onClick={() => setAdjustingTx(null)} style={{ background: '#fff', border: '1.5px solid #efefef', borderRadius: 8, padding: '9px 16px', fontSize: 13, fontWeight: 600, color: '#515252', cursor: 'pointer' }}>Batal</button>
                  <button type="submit" style={{ background: TEAL, color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', boxShadow: '0 4px 12px rgba(0,86,210,0.15)' }}>Sesuaikan Dana</button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    );
  }

  // ── MAIN LIST VIEW: PROGRESS RECON PER HARI ──
  return (
    <div style={{ padding: '24px 32px 56px', animation: 'fadeIn 200ms ease' }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: TEAL, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Settlement Operations</div>
        <h1 style={{ fontSize: 24, fontWeight: 700, color: '#171919', letterSpacing: '-0.01em', margin: 0 }}>Recon & Settlement</h1>
        <p style={{ fontSize: 13, color: '#515252', marginTop: 4, marginBottom: 0 }}>Pantau proses rekonsiliasi harian antara Core Banking System (CBS) dengan QRIS Switch log.</p>
      </div>

      {/* Stats Summary Cards */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { label: 'Total Volume Rekon', value: fmtRp(stats.volume), sub: 'Semua hari kerja aktif', icon: 'bx-wallet', color: TEAL },
          { label: 'Keberhasilan Rate', value: `${stats.successRate}%`, sub: 'Pencocokan sistem otomatis', icon: 'bx-check-double', color: GREEN },
          { label: 'Transaksi Suspect', value: stats.totalSuspects, sub: 'Butuh penyelesaian manual', icon: 'bx-error-circle', color: stats.totalSuspects > 0 ? RED : '#a7a8a8' },
          { label: 'Hari Selesai Rekon', value: stats.settledDays, sub: 'Dari total hari kerja', icon: 'bx-calendar-check', color: AMBER }
        ].map((card, i) => (
          <div key={i} style={{ background: '#fff', padding: '18px 20px', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(23,25,25,0.03)', display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 200 }}>
            <div style={{ width: 44, height: 44, borderRadius: '50%', background: `${card.color}10`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`bx ${card.icon}`} style={{ fontSize: 20, color: card.color }} />
            </div>
            <div>
              <div style={{ fontSize: 12, color: '#a7a8a8', fontWeight: 600 }}>{card.label}</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: '#171919', marginTop: 4, lineHeight: 1 }}>{card.value}</div>
              <div style={{ fontSize: 11, color: '#a7a8a8', marginTop: 4 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Progress Recon Per Hari Table */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #efefef', boxShadow: '0 2px 8px rgba(0,0,0,0.02)', overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid #efefef', background: '#fafafa' }}>
          <h3 style={{ fontSize: 14, fontWeight: 800, color: '#171919', margin: 0 }}>Progress Recon Harian</h3>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left' }}>
          <thead>
            <tr style={{ background: '#fff', borderBottom: '1px solid #efefef' }}>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Tanggal Kerja</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Total Trx</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Volume Transaksi</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Cocok (Match)</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Selisih (Suspect)</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase' }}>Status Rekon</th>
              <th style={{ padding: '12px 20px', color: '#a7a8a8', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', textAlign: 'center', width: 220 }}>Aksi</th>
            </tr>
          </thead>
          <tbody>
            {progress.map(row => {
              const isInvestigate = row.status === 'investigate';
              return (
                <tr key={row.date} style={{ borderBottom: '1px solid #f3f3f3' }}>
                  <td style={{ padding: '14px 20px', fontWeight: 700, color: '#171919' }}>{row.date}</td>
                  <td style={{ padding: '14px 20px', color: '#515252' }}>{row.total} Trx</td>
                  <td style={{ padding: '14px 20px', color: '#171919', fontWeight: 600 }}>{fmtRp(row.volume)}</td>
                  <td style={{ padding: '14px 20px', color: GREEN, fontWeight: 600 }}>{row.matched}</td>
                  <td style={{ padding: '14px 20px', color: row.suspect > 0 ? RED : '#515252', fontWeight: 600 }}>{row.suspect}</td>
                  <td style={{ padding: '14px 20px' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: isInvestigate ? 'rgba(237,49,81,0.1)' : 'rgba(116,181,12,0.12)', color: isInvestigate ? RED : '#74b50c', fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '3px 9px' }}>
                      <i className={`bx ${isInvestigate ? 'bx-error-circle' : 'bx-check-circle'}`} />
                      {isInvestigate ? 'Perlu Investigasi' : 'Selesai'}
                    </span>
                  </td>
                  <td style={{ padding: '14px 20px', textAlign: 'center' }}>
                    <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
                      <button
                        onClick={() => { setSelectedDay(row); setView('detail'); }}
                        style={{ background: '#fff', border: `1.5px solid ${TEAL}`, color: TEAL, borderRadius: 6, padding: '6px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', fontFamily: 'inherit' }}
                        onMouseEnter={e => { e.currentTarget.style.background = `${TEAL}10`; }}
                        onMouseLeave={e => { e.currentTarget.style.background = '#fff'; }}
                      >
                        Detail
                      </button>

                      {row.total - row.matched > 0 || isInvestigate ? (
                        <button
                          onClick={() => { setSelectedDay(row); setView('investigate'); }}
                          style={{ background: ORANGE, color: '#fff', border: 'none', borderRadius: 6, padding: '7px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'pointer', transition: 'all 150ms', fontFamily: 'inherit', boxShadow: `0 2px 6px ${ORANGE}15` }}
                          onMouseEnter={e => { e.currentTarget.style.background = '#cf5a27'; }}
                          onMouseLeave={e => { e.currentTarget.style.background = ORANGE; }}
                        >
                          Investigasi
                        </button>
                      ) : (
                        <button
                          disabled
                          style={{ background: '#f5f5f5', color: '#a7a8a8', border: 'none', borderRadius: 6, padding: '7px 12px', fontSize: 11.5, fontWeight: 750, cursor: 'not-allowed', fontFamily: 'inherit' }}
                        >
                          Investigasi
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Toast Alert */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 24, right: 24, zIndex: 1600,
          background: toast.kind === 'error' ? RED : (toast.kind === 'amber' ? AMBER : '#10B981'),
          color: '#fff', padding: '16px 24px', borderRadius: 10,
          boxShadow: `0 8px 24px ${toast.kind === 'error' ? 'rgba(237,49,81,0.25)' : (toast.kind === 'amber' ? 'rgba(217,146,11,0.25)' : 'rgba(16,185,129,0.25)')}`,
          display: 'flex', alignItems: 'center', gap: 10, animation: 'slideUp 200ms ease'
        }}>
          <i className={`bx ${toast.kind === 'error' ? 'bx-x-circle' : (toast.kind === 'amber' ? 'bx-info-circle' : 'bx-check-shield')}`} style={{ fontSize: 20 }} />
          <span style={{ fontSize: 13.5, fontWeight: 750 }}>{toast.msg}</span>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ReconSettlementPage });