const { useState, useEffect } = React;
const { encodeBase64, formatDateTime, formatDisplayDateRange, formatCleanAmount, highlightMatchedTags } = window;

function VaMultipleView() {
  const [data, setData] = useState([]);
  const [mutationsData, setMutationsData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  const [tagsRekonMulti, setTagsRekonMulti] = useState([]);
  const [inputRekonMulti, setInputRekonMulti] = useState('');

  const [activeSubTab, setActiveSubTab] = useState('REKON');
  const [copiedMultiId, setCopiedMultiId] = useState(null);
  const [copiedMultiAll, setCopiedMultiAll] = useState(false);
  
  const [tagsAutomate, setTagsAutomate] = useState([]);
  const [inputAutomate, setInputAutomate] = useState('');

  const [tagsRefundMulti, setTagsRefundMulti] = useState([]);
  const [inputRefundMulti, setInputRefundMulti] = useState('');

  const [tagsMutasiMulti, setTagsMutasiMulti] = useState([]);
  const [inputMutasiMulti, setInputMutasiMulti] = useState('');

  const fetchData = async () => {
    setLoading(true); setError(null);
    try {
      const response = await fetch('/api/va-multiple');
      const result = await response.json();
      if (response.ok && result.success) {
        setData(result.data || []);
        setMutationsData(result.mutations || []);
      } else { throw new Error(result.message || 'Gagal memuat data VA Multiple'); }
    } catch (err) { setError(err.message); } finally { setLoading(false); }
  };

  useEffect(() => { fetchData(); }, []);

  const filteredData = data.filter(item => {
    if (tagsRekonMulti.length === 0) return true;

    return tagsRekonMulti.every(tag => {
      const cleanTag = tag.toLowerCase().trim().replace(/[^a-zA-Z0-9]/g, '');
      if (!cleanTag) return true;

      const vaMatch = String(item.va || '').toLowerCase().includes(cleanTag);
      const userMatch = String(item.username || '').toLowerCase().includes(cleanTag);
      const akunMatch = String(item.status_akun || '').toLowerCase().includes(cleanTag);
      const rangeMatch = String(item.tanggal_pencarian || '').toLowerCase().includes(cleanTag);

      const anomalies = Array.isArray(item.sinkronisasi_bank) ? item.sinkronisasi_bank : [];
      const anomalyMatch = anomalies.some(a => {
        const tgl = String(a.tanggal || '').toLowerCase();
        const desc = String(a.deskripsi || '').toLowerCase();
        const nomRaw = String(a.raw_kredit || a.nominal || '').replace(/[^0-9]/g, '');
        const nomFmt = String(a.nominal || '').toLowerCase();
        return tgl.includes(cleanTag) || desc.includes(cleanTag) || nomRaw.includes(cleanTag) || nomFmt.includes(cleanTag);
      });

      return vaMatch || userMatch || akunMatch || rangeMatch || anomalyMatch;
    });
  });

  const getMetabaseMultiLinks = (va, username, tanggalRangeText, isAnomaly, arrayAnomali) => {
    const v = String(va || '').trim().replace(/[^0-9]/g, '');
    const u = String(username || '').trim();
    if (!v) return null;

    const mu_q1 = `{"dataset_query":{"type":"query","query":{"source-table":196,"filter":["and",["=",["field",2315,null],"${v}"]]},"database":3},"display":"table","visualization_settings":{},"original_card_id":null}`;
    const mu_q2 = `{"dataset_query":{"type":"query","query":{"source-table":1778,"filter":["and",["contains",["field",23983,null],"${v}"]]},"database":3},"display":"table","visualization_settings":{},"original_card_id":null}`;
    const mu_q4 = `{"format":"-","dataset_query":{"type":"query","query":{"source-table":193,"filter":["and",["=",["field",2281,null],"${u}"]]},"database":3},"display":"table","visualization_settings":{},"original_card_id":null}`;

    let tglAwal = ''; let tglAkhir = '';
    if (tanggalRangeText && tanggalRangeText !== "-" && String(tanggalRangeText).includes(' s/d ')) {
        const parts = String(tanggalRangeText).split(' s/d ');
        tglAwal = parts[0].trim(); tglAkhir = parts[1].trim(); 
    } else if (tanggalRangeText && tanggalRangeText !== "-") {
        tglAwal = String(tanggalRangeText).trim(); tglAkhir = String(tanggalRangeText).trim();
    }

    const formatMetabaseDateStart = (dateStr) => {
        if (!dateStr) return "";
        const d = new Date(dateStr + "T00:00:00Z");
        if (isNaN(d.getTime())) return "";
        d.setUTCHours(0, 1, 0, 0); 
        d.setUTCHours(d.getUTCHours() - 7);
        return d.toISOString(); 
    };

    const formatMetabaseDateEnd = (dateStr) => {
        if (!dateStr) return "";
        const d = new Date(dateStr + "T00:00:00Z");
        if (isNaN(d.getTime())) return "";
        d.setUTCDate(d.getUTCDate() + 1);
        d.setUTCHours(23, 59, 0, 0); 
        d.setUTCHours(d.getUTCHours() - 7);
        return d.toISOString(); 
    };

    const dtMulai = formatMetabaseDateStart(tglAwal);
    const dtSelesai = formatMetabaseDateEnd(tglAkhir);

    let filterConditions = [["=", ["field", 4019, null], v]];

    if (isAnomaly && arrayAnomali && arrayAnomali.length > 0) {
        const rawNumbers = arrayAnomali.map(a => {
            const val = (a && typeof a === 'object') ? (a.raw_kredit || a.nominal) : a;
            const cleanDigits = String(val || '').replace(/[^0-9]/g, '');
            return cleanDigits ? Number(cleanDigits) : null;
        }).filter(n => n !== null && !isNaN(n) && n > 0);
        
        const uniqueAmts = [...new Set(rawNumbers)]; 
        if (uniqueAmts.length > 1) {
            let orBlocks = uniqueAmts.map(amt => ["=", ["field", 4022, null], amt]);
            filterConditions.push(["or", ...orBlocks]);
        } else if (uniqueAmts.length === 1) {
            filterConditions.push(["=", ["field", 4022, null], uniqueAmts[0]]);
        }
    }

    if (dtMulai && dtSelesai) {
        filterConditions.push(["between", ["field", 4017, null], dtMulai, dtSelesai]);
    }
    
    const mu_q3_obj = {
      "dataset_query": {
        "type": "query",
        "query": {
          "source-table": 320,
          "filter": ["and", ...filterConditions]
        },
        "database": 3
      },
      "display": "table",
      "visualization_settings": {},
      "original_card_id": null
    };

    return {
        urlVA: "https://metabase.danarapay.com/question#" + encodeBase64(mu_q1),
        urlRefund: "https://metabase.danarapay.com/question#" + encodeBase64(mu_q2),
        urlHistory: "https://metabase.danarapay.com/question#" + encodeBase64(JSON.stringify(mu_q3_obj)),
        urlUser: "https://metabase.danarapay.com/question#" + encodeBase64(mu_q4)
    };
  };

  const formatMultiItemText = (item, index, links, anomaliesToUse) => {
    const anomalies = anomaliesToUse || (Array.isArray(item.sinkronisasi_bank) ? item.sinkronisasi_bank : []);
    let anomalyLines = "-";
    if (anomalies.length > 0) {
      anomalyLines = anomalies.map(a => `  • ${a.tanggal} | ${a.deskripsi} | Rp ${a.nominal}`).join('\n');
    }
    const mainText = `VA Multiple Use\n\nno: ${index + 1}\nva : ${item.va || '-'}\nusername : ${item.username || '-'}\nstatus akun : ${item.status_akun || '-'}\ntanggal pencarian (range) : ${formatDisplayDateRange(item.tanggal_pencarian)}\ncount force success : ${item.count_force_success || 0}x\ndetail force success : ${item.detail_force_success || '-'}\ncount refund balance : ${item.count_refund_balance || 0}x\nmasuk list force success : ${item.masuk_list_force_success || '-'}\nterdapat anomali (${anomalies.length} transaksi) :\n${anomalyLines}`;
    return mainText + `\n\n${item.va || '-'} | va_history | b2x_va_tx_history | b2x_balance_adjustment_requests | b2x_users`;
  };

  const formatMultiItemHTML = (item, index, links, anomaliesToUse) => {
    const anomalies = anomaliesToUse || (Array.isArray(item.sinkronisasi_bank) ? item.sinkronisasi_bank : []);
    let anomalyLines = "-";
    if (anomalies.length > 0) {
      anomalyLines = anomalies.map(a => `&nbsp;&nbsp;• ${a.tanggal} | ${a.deskripsi} | Rp ${a.nominal}`).join('<br>');
    }
    const mainText = `VA Multiple Use<br><br>no: ${index + 1}<br>va : ${item.va || '-'}<br>username : ${item.username || '-'}<br>status akun : ${item.status_akun || '-'}<br>tanggal pencarian (range) : ${formatDisplayDateRange(item.tanggal_pencarian)}<br>count force success : ${item.count_force_success || 0}x<br>detail force success : ${String(item.detail_force_success || '-').replace(/\n/g, '<br>')}<br>count refund balance : ${item.count_refund_balance || 0}x<br>masuk list force success : ${item.masuk_list_force_success || '-'}<br>terdapat anomali (${anomalies.length} transaksi) :<br>${anomalyLines}`;
    return mainText + `<br><br>${item.va || '-'} | <a href="${links ? links.urlVA : '#'}">va_history</a> | <a href="${links ? links.urlHistory : '#'}">b2x_va_tx_history</a> | <a href="${links ? links.urlRefund : '#'}">b2x_balance_adjustment_requests</a> | <a href="${links ? links.urlUser : '#'}">b2x_users</a>`;
  };

  const copyMultiToClipboard = async (plainText, htmlText, id) => {
    try {
      const clipboardItem = new ClipboardItem({'text/plain': new Blob([plainText], { type: 'text/plain' }), 'text/html': new Blob([htmlText], { type: 'text/html' }) });
      await navigator.clipboard.write([clipboardItem]);
      setCopiedMultiId(id); setTimeout(() => setCopiedMultiId(null), 2000);
    } catch (err) { navigator.clipboard.writeText(plainText).then(() => { setCopiedMultiId(id); setTimeout(() => setCopiedMultiId(null), 2000); }); }
  };

  const copyAllMultiFiltered = async () => {
    const plainTextArr = []; const htmlTextArr = [];
    filteredData.forEach((item, idx) => {
      const isAnomalyArray = Array.isArray(item.sinkronisasi_bank);
      const anomalies = isAnomalyArray ? item.sinkronisasi_bank : [];
      
      const visibleAnomalies = (tagsRekonMulti.length > 0 && isAnomalyArray) ? anomalies.filter(a => {
        return tagsRekonMulti.every(tag => {
          const cleanTag = tag.toLowerCase().trim().replace(/[^a-zA-Z0-9]/g, '');
          if (!cleanTag) return true;
          const tgl = String(a.tanggal || '').toLowerCase();
          const desc = String(a.deskripsi || '').toLowerCase();
          const nomRaw = String(a.raw_kredit || a.nominal || '').replace(/[^0-9]/g, '');
          const nomFmt = String(a.nominal || '').toLowerCase();
          const vaMatch = String(item.va || '').toLowerCase().includes(cleanTag);
          const userMatch = String(item.username || '').toLowerCase().includes(cleanTag);
          const akunMatch = String(item.status_akun || '').toLowerCase().includes(cleanTag);
          return tgl.includes(cleanTag) || desc.includes(cleanTag) || nomRaw.includes(cleanTag) || nomFmt.includes(cleanTag) || vaMatch || userMatch || akunMatch;
        });
      }) : anomalies;

      const links = getMetabaseMultiLinks(item.va, item.username, item.tanggal_pencarian, isAnomalyArray, visibleAnomalies);
      plainTextArr.push(formatMultiItemText(item, idx, links, visibleAnomalies)); 
      htmlTextArr.push(formatMultiItemHTML(item, idx, links, visibleAnomalies));
    });
    const fullPlainText = plainTextArr.join('\n\n\n'); const fullHtmlText = htmlTextArr.join('<br><br><br>');
    try {
      const clipboardItem = new ClipboardItem({ 'text/plain': new Blob([fullPlainText], { type: 'text/plain' }), 'text/html': new Blob([fullHtmlText], { type: 'text/html' }) });
      await navigator.clipboard.write([clipboardItem]);
      setCopiedMultiAll(true); setTimeout(() => setCopiedMultiAll(false), 2000);
    } catch (err) { navigator.clipboard.writeText(fullPlainText).then(() => { setCopiedMultiAll(true); setTimeout(() => setCopiedMultiAll(false), 2000); }); }
  };

  const automateForceData = [];
  filteredData.forEach(item => {
    const historyId = item.va_history_id || item.id || item.b2x_va_tx_history_va_history_id || '-';
    const vaNum = item.va || item.va_number || '-';
    if (Array.isArray(item.sinkronisasi_bank) && item.sinkronisasi_bank.length > 0) {
      item.sinkronisasi_bank.forEach(a => {
        automateForceData.push({
          va_history_id: historyId,
          va_number: vaNum,
          amount: a.raw_kredit !== undefined ? a.raw_kredit : (a.nominal || a.amount || 0)
        });
      });
    }
  });

  const automateRefundData = [];
  filteredData.forEach(item => {
    const username = item.username || '-';
    const vaNum = item.va || item.va_number || '-';
    if (Array.isArray(item.sinkronisasi_bank) && item.sinkronisasi_bank.length > 0) {
      item.sinkronisasi_bank.forEach(a => {
        const rawAmt = a.raw_kredit !== undefined ? a.raw_kredit : (a.nominal || a.amount || 0);
        automateRefundData.push({
          transaction_id: "",
          username: username,
          transfer_amount: rawAmt,
          admin_fee: 0,
          tax: 0,
          transaction_type: "IN",
          adjustment_type: "IN_VA",
          description: `Refund VA ${vaNum}`,
          va_number: vaNum
        });
      });
    }
  });

  const cleanedMutations = mutationsData.map(row => {
    const cleanedRow = { ...row };
    if (cleanedRow.tgl_tran) cleanedRow.tgl_tran = formatDateTime(cleanedRow.tgl_tran);
    if (cleanedRow.tgl_efektif) cleanedRow.tgl_efektif = formatDateTime(cleanedRow.tgl_efektif);
    if (cleanedRow.mutasi_kredit) cleanedRow.mutasi_kredit = formatCleanAmount(cleanedRow.mutasi_kredit);
    if (cleanedRow.mutasi_debet) cleanedRow.mutasi_debet = formatCleanAmount(cleanedRow.mutasi_debet);
    if (cleanedRow.saldo_awal_mutasi) cleanedRow.saldo_awal_mutasi = formatCleanAmount(cleanedRow.saldo_awal_mutasi);
    if (cleanedRow.saldo_akhir_mutasi) cleanedRow.saldo_akhir_mutasi = formatCleanAmount(cleanedRow.saldo_akhir_mutasi);
    return cleanedRow;
  });

  const handleTagKeyDown = (e, tags, setTags, input, setInput) => {
    if (e.key === 'Enter') {
      e.preventDefault(); const val = input.trim();
      if (val && !tags.includes(val)) setTags([...tags, val]);
      setInput('');
    }
  };
  const removeTag = (tagToRemove, tags, setTags) => setTags(tags.filter(tag => tag !== tagToRemove));
  
  const filteredAutomateData = tagsAutomate.length === 0 ? automateForceData : automateForceData.filter(d => {
    const rowStr = `${d.va_history_id} ${d.va_number} ${d.amount}`.toLowerCase();
    return tagsAutomate.every(t => rowStr.includes(t.toLowerCase().trim()));
  });

  const filteredRefundMultiData = tagsRefundMulti.length === 0 ? automateRefundData : automateRefundData.filter(d => {
    const rowStr = `${d.username} ${d.transfer_amount} ${d.description}`.toLowerCase();
    return tagsRefundMulti.every(t => rowStr.includes(t.toLowerCase().trim()));
  });

  const filteredMutationsMultiData = tagsMutasiMulti.length === 0 ? cleanedMutations : cleanedMutations.filter(row => {
    const rowStr = Object.values(row).map(v => v !== null ? String(v).toLowerCase() : '').join(' ');
    return tagsMutasiMulti.every(t => rowStr.includes(t.toLowerCase().trim()));
  });

  const downloadAutomateExcel = () => {
    if (filteredAutomateData.length === 0) { alert("Tidak ada data anomali untuk diunduh!"); return; }
    const wsData = [["va_history_id", "va_number", "amount"]];
    filteredAutomateData.forEach(d => {
      const cleanAmt = typeof d.amount === 'number' ? d.amount : Number(String(d.amount).replace(/\./g, '').replace(/,/g, '').replace(/[^0-9]/g, ''));
      wsData.push([d.va_history_id, d.va_number, cleanAmt || 0]);
    });
    const today = new Date().toISOString().split('T')[0];
    const ws = window.XLSX.utils.aoa_to_sheet(wsData); 
    const wb = window.XLSX.utils.book_new(); 
    window.XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); 
    window.XLSX.writeFile(wb, `Automate_Force_Success_Multiple_Use_${today}.xlsx`);
  };

  const downloadRefundMultiExcel = () => {
    if (filteredRefundMultiData.length === 0) { alert("Tidak ada data refund anomali untuk diunduh!"); return; }
    const wsData = [["Transaction ID*", "Username*", "Transfer Amount*", "Admin Fee", "Tax", "Transaction Type*", "Adjustment Type*", "Description"]];
    filteredRefundMultiData.forEach(d => {
      const cleanAmt = typeof d.transfer_amount === 'number' ? d.transfer_amount : Number(String(d.transfer_amount).replace(/\./g, '').replace(/,/g, '').replace(/[^0-9]/g, ''));
      wsData.push([d.transaction_id, d.username, cleanAmt || 0, d.admin_fee, d.tax, d.transaction_type, d.adjustment_type, d.description]);
    });
    const today = new Date().toISOString().split('T')[0];
    const ws = window.XLSX.utils.aoa_to_sheet(wsData); 
    const wb = window.XLSX.utils.book_new(); 
    window.XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); 
    window.XLSX.writeFile(wb, `Automate_Refund_Balance_Multiple_Use_${today}.xlsx`);
  };

  const downloadMutationsMultiExcel = () => {
    if (filteredMutationsMultiData.length === 0) { alert("Tidak ada data mutasi untuk diunduh!"); return; }
    const headers = Object.keys(filteredMutationsMultiData[0] || {});
    const wsData = [headers];
    filteredMutationsMultiData.forEach(row => { wsData.push(Object.values(row)); });
    const today = new Date().toISOString().split('T')[0];
    const ws = window.XLSX.utils.aoa_to_sheet(wsData); 
    const wb = window.XLSX.utils.book_new(); 
    window.XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); 
    window.XLSX.writeFile(wb, `Raw_Mutasi_Bank_Multiple_Use_${today}.xlsx`);
  };

  return (
    <div className="w-full space-y-6 pb-12">
      {/* Header VA Multiple */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-cardbg/80 backdrop-blur-md p-6 rounded-2xl border border-slate-700/60 shadow-lg">
        <div>
          <div className="flex items-center space-x-3">
            <span className="p-2 bg-indigo-500/10 text-indigo-400 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 01-2-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg>
            </span>
            <h1 className="text-xl md:text-2xl font-extrabold text-white tracking-tight">VA Multiple Use</h1>
          </div>
          <p className="text-xs md:text-sm text-slate-400 mt-1 pl-11">Monitoring & Deteksi Anomali Transaksi VA Statis (Berulang)</p>
        </div>
        <div className="flex flex-col space-y-2 items-end">
          <div className="flex items-center space-x-2">
            {activeSubTab === 'REKON' && (
              <button onClick={copyAllMultiFiltered} disabled={filteredData.length === 0} className="bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white px-4 py-2.5 rounded-xl font-medium text-xs flex items-center space-x-2 transition shadow-lg shadow-emerald-600/20 active:scale-95">
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path></svg>
                <span>{copiedMultiAll ? 'Tersalin Semua!' : 'Salin Data Rekon'}</span>
              </button>
            )}
            <button onClick={fetchData} className="bg-slate-800 hover:bg-slate-700 text-slate-200 px-4 py-2.5 rounded-xl border border-slate-600/80 text-xs font-medium flex items-center justify-center space-x-2 transition shadow-sm active:scale-95">
              <svg className={`h-4 w-4 text-blue-400 ${loading ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
              <span>Refresh</span>
            </button>
          </div>
        </div>
      </div>

      <div className="flex bg-slate-900/50 p-1.5 rounded-xl w-max border border-slate-700/60 mt-4 mb-2 overflow-x-auto">
        <button onClick={() => setActiveSubTab('REKON')} className={`px-4 md:px-5 py-2 rounded-lg text-xs md:text-sm font-bold transition flex items-center space-x-2 whitespace-nowrap ${activeSubTab === 'REKON' ? 'bg-indigo-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}>
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
          <span>Hasil Rekonsiliasi (Anomali)</span>
        </button>
        <button onClick={() => setActiveSubTab('MUTASI_MULTI')} className={`px-4 md:px-5 py-2 rounded-lg text-xs md:text-sm font-bold transition flex items-center space-x-2 whitespace-nowrap ${activeSubTab === 'MUTASI_MULTI' ? 'bg-emerald-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}>
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 10h18M3 14h18m-9-4v8m-7-4h14M4 6h16a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V7a1 1 0 01-1-1z"></path></svg>
          <span>Raw Mutasi Bank</span>
        </button>
        <button onClick={() => setActiveSubTab('AUTOMATE')} className={`px-4 md:px-5 py-2 rounded-lg text-xs md:text-sm font-bold transition flex items-center space-x-2 whitespace-nowrap ${activeSubTab === 'AUTOMATE' ? 'bg-blue-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}>
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
          <span>Automate Force Success Multiple Use All</span>
        </button>
        <button onClick={() => setActiveSubTab('REFUND_MULTI')} className={`px-4 md:px-5 py-2 rounded-lg text-xs md:text-sm font-bold transition flex items-center space-x-2 whitespace-nowrap ${activeSubTab === 'REFUND_MULTI' ? 'bg-purple-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'}`}>
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
          <span>Auto Refund Balance Multiple Use All</span>
        </button>
      </div>

      {loading ? (
        <div className="flex flex-col items-center justify-center p-16 bg-cardbg rounded-2xl border border-slate-700/60 text-slate-400">
          <svg className="animate-spin h-8 w-8 text-indigo-400 mb-3" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
          <p className="text-sm font-medium">Mendeteksi Anomali Mutasi Bank vs Metabase...</p>
        </div>
      ) : error ? (
        <div className="p-8 bg-red-950/40 border border-red-800/60 text-red-400 rounded-2xl text-center"><p className="font-bold text-base mb-1">Gagal Memuat Data</p><p className="text-sm text-red-300">{error}</p></div>
      ) : activeSubTab === 'MUTASI_MULTI' ? (
        <div className="w-full max-w-7xl mx-auto">
          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-xl flex flex-col min-h-[550px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-emerald-400 font-bold flex items-center text-sm">
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 10h18M3 14h18m-9-4v8m-7-4h14M4 6h16a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V7a1 1 0 01-1-1z"></path></svg>
                Raw Mutasi Bank (VA Multiple Use)
              </h3>
              <button onClick={downloadMutationsMultiExcel} className="p-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-bold transition flex items-center space-x-1.5 shadow-md">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                <span>Download XLSX</span>
              </button>
            </div>
            <div className="p-4 bg-[#0b1329] border-b border-slate-800">
              <div className="flex flex-wrap items-center bg-[#0f172a] border border-slate-700/80 rounded-lg px-2 py-1.5 shadow-inner focus-within:border-emerald-500 transition-all duration-200">
                <svg className="w-4 h-4 text-slate-500 mr-2 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                {tagsMutasiMulti.map((tag, i) => (
                  <span key={i} className="flex items-center bg-slate-800 border border-slate-600 text-slate-200 text-[10px] px-2 py-1 rounded-full mr-1.5 mb-1 mt-1 font-medium">
                    {tag} <button onClick={() => removeTag(tag, tagsMutasiMulti, setTagsMutasiMulti)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik kata kunci (misal No VA, Tanggal, Nominal) lalu Enter" value={inputMutasiMulti} onChange={(e) => setInputMutasiMulti(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsMutasiMulti, setTagsMutasiMulti, inputMutasiMulti, setInputMutasiMulti)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[200px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto max-h-[600px]">
              {filteredMutationsMultiData.length === 0 ? (
                <div className="p-12 text-center text-slate-500 text-xs font-bold uppercase tracking-widest">TIDAK ADA DATA MUTASI BANK</div>
              ) : (
                <table className="w-full text-left text-xs text-slate-300 whitespace-nowrap">
                  <thead className="bg-slate-900 text-slate-400 uppercase tracking-wider text-[11px] font-bold border-b border-slate-800 sticky top-0 z-10">
                    <tr>
                      <th className="py-3 px-4 border-r border-slate-800 text-center">#</th>
                      {Object.keys(filteredMutationsMultiData[0] || {}).map(key => (
                        <th key={key} className="py-3 px-4 border-r border-slate-800">{key.replace(/_/g, ' ')}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800/60 font-mono">
                    {filteredMutationsMultiData.map((row, idx) => (
                      <tr key={idx} className="hover:bg-slate-800/40 transition">
                        <td className="py-2 px-4 border-r border-slate-800 text-slate-500 bg-slate-900/30 text-center font-bold">{idx + 1}</td>
                        {Object.values(row).map((val, i) => (
                          <td key={i} className="py-2 px-4 border-r border-slate-800">{val !== null ? String(val) : '-'}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      ) : activeSubTab === 'AUTOMATE' ? (
        <div className="w-full max-w-5xl mx-auto">
          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-xl flex flex-col min-h-[500px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-blue-400 font-bold flex items-center text-sm">
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                Automate Force Success Multiple Use All
              </h3>
              <button onClick={downloadAutomateExcel} className="p-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-xs font-bold transition flex items-center space-x-1.5 shadow-md">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                <span>Download XLSX</span>
              </button>
            </div>
            <div className="p-4 bg-[#0b1329] border-b border-slate-800">
              <div className="flex flex-wrap items-center bg-[#0f172a] border border-slate-700/80 rounded-lg px-2 py-1.5 shadow-inner focus-within:border-blue-500 transition-all duration-200">
                <svg className="w-4 h-4 text-slate-500 mr-2 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                {tagsAutomate.map((tag, i) => (
                  <span key={i} className="flex items-center bg-slate-800 border border-slate-600 text-slate-200 text-[10px] px-2 py-1 rounded-full mr-1.5 mb-1 mt-1 font-medium">
                    {tag} <button onClick={() => removeTag(tag, tagsAutomate, setTagsAutomate)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik lalu Enter" value={inputAutomate} onChange={(e) => setInputAutomate(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsAutomate, setTagsAutomate, inputAutomate, setInputAutomate)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[120px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto">
              {filteredAutomateData.length === 0 ? (
                <div className="p-12 text-center text-slate-500 text-xs font-bold uppercase tracking-widest">TIDAK ADA DATA ANOMALI</div>
              ) : (
                <table className="w-full text-left text-xs text-slate-300">
                  <thead className="bg-slate-900 text-slate-400 font-bold sticky top-0 border-b border-slate-800 z-10">
                    <tr>
                      <th className="p-3 border-r border-slate-800 w-16 text-center">NO</th>
                      <th className="p-3 border-r border-slate-800">VA_HISTORY_ID</th>
                      <th className="p-3 border-r border-slate-800">VA_NUMBER</th>
                      <th className="p-3">AMOUNT</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800 font-mono">
                    {filteredAutomateData.map((d, i) => (
                      <tr key={i} className="hover:bg-slate-800/30">
                        <td className="p-3 border-r border-slate-800 text-center font-bold text-slate-500">{i+1}</td>
                        <td className="p-3 border-r border-slate-800 text-blue-400 font-bold">{d.va_history_id}</td>
                        <td className="p-3 border-r border-slate-800 font-bold text-white">{d.va_number}</td>
                        <td className="p-3 font-bold text-emerald-400">{formatCleanAmount(d.amount)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      ) : activeSubTab === 'REFUND_MULTI' ? (
        <div className="w-full max-w-6xl mx-auto">
          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-xl flex flex-col min-h-[500px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-purple-400 font-bold flex items-center text-sm">
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                Auto Refund Balance Multiple Use All
              </h3>
              <button onClick={downloadRefundMultiExcel} className="p-2 bg-purple-600 hover:bg-purple-500 text-white rounded-lg text-xs font-bold transition flex items-center space-x-1.5 shadow-md">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                <span>Download XLSX</span>
              </button>
            </div>
            <div className="p-4 bg-[#0b1329] border-b border-slate-800">
              <div className="flex flex-wrap items-center bg-[#0f172a] border border-slate-700/80 rounded-lg px-2 py-1.5 shadow-inner focus-within:border-purple-500 transition-all duration-200">
                <svg className="w-4 h-4 text-slate-500 mr-2 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                {tagsRefundMulti.map((tag, i) => (
                  <span key={i} className="flex items-center bg-slate-800 border border-slate-600 text-slate-200 text-[10px] px-2 py-1 rounded-full mr-1.5 mb-1 mt-1 font-medium">
                    {tag} <button onClick={() => removeTag(tag, tagsRefundMulti, setTagsRefundMulti)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik kata kunci lalu Enter" value={inputRefundMulti} onChange={(e) => setInputRefundMulti(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsRefundMulti, setTagsRefundMulti, inputRefundMulti, setInputRefundMulti)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[120px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto">
              {filteredRefundMultiData.length === 0 ? (
                <div className="p-12 text-center text-slate-500 text-xs font-bold uppercase tracking-widest">TIDAK ADA DATA ANOMALI REFUND</div>
              ) : (
                <table className="w-full text-left text-[10px] text-slate-300 whitespace-nowrap">
                  <thead className="bg-slate-900 text-slate-400 font-bold sticky top-0 border-b border-slate-800 z-10">
                    <tr>
                      <th className="p-3 border-r border-slate-800">NO</th>
                      <th className="p-3 border-r border-slate-800">TRANSACTION ID*</th>
                      <th className="p-3 border-r border-slate-800">USERNAME*</th>
                      <th className="p-3 border-r border-slate-800">TRANSFER AMOUNT*</th>
                      <th className="p-3 border-r border-slate-800">ADMIN FEE</th>
                      <th className="p-3 border-r border-slate-800">TAX</th>
                      <th className="p-3 border-r border-slate-800">TRANSACTION TYPE*</th>
                      <th className="p-3 border-r border-slate-800">ADJUSTMENT TYPE*</th>
                      <th className="p-3">DESCRIPTION</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800 font-mono">
                    {filteredRefundMultiData.map((d, i) => (
                      <tr key={i} className="hover:bg-slate-800/30">
                        <td className="p-3 border-r border-slate-800 text-center font-bold text-slate-500">{i+1}</td>
                        <td className="p-3 border-r border-slate-800">-</td>
                        <td className="p-3 border-r border-slate-800 font-bold text-white">{d.username}</td>
                        <td className="p-3 border-r border-slate-800 font-bold text-emerald-400">{formatCleanAmount(d.transfer_amount)}</td>
                        <td className="p-3 border-r border-slate-800">0</td>
                        <td className="p-3 border-r border-slate-800">0</td>
                        <td className="p-3 border-r border-slate-800">IN</td>
                        <td className="p-3 border-r border-slate-800">IN_VA</td>
                        <td className="p-3">{d.description}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      ) : (
        <div className="w-full space-y-4">
          <div className="p-4 bg-[#0b1329] border border-slate-800 rounded-2xl shadow-lg">
            <div className="flex flex-wrap items-center bg-[#0f172a] border border-slate-700/80 rounded-xl px-3 py-2 shadow-inner focus-within:border-indigo-500 transition-all duration-200">
              <svg className="w-4 h-4 text-slate-500 mr-2.5 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
              {tagsRekonMulti.map((tag, i) => (
                <span key={i} className="flex items-center bg-indigo-900/60 border border-indigo-500/50 text-indigo-200 text-xs px-2.5 py-1 rounded-full mr-2 mb-1 mt-1 font-medium shadow-sm">
                  {tag} <button onClick={() => removeTag(tag, tagsRekonMulti, setTagsRekonMulti)} className="ml-1.5 text-indigo-400 hover:text-rose-400 font-bold">&times;</button>
                </span>
              ))}
              <input type="text" placeholder={tagsRekonMulti.length === 0 ? "Ketik kata kunci (No VA, Username, Tanggal, Nominal) lalu Enter untuk mengerucutkan pencarian..." : "Ketik kata kunci tambahan untuk mengerucutkan data lalu Enter..."} value={inputRekonMulti} onChange={(e) => setInputRekonMulti(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsRekonMulti, setTagsRekonMulti, inputRekonMulti, setInputRekonMulti)} className="bg-transparent text-sm text-white focus:outline-none flex-1 min-w-[220px] py-1" />
            </div>
          </div>

          <div className="bg-cardbg rounded-2xl border border-slate-700/60 overflow-hidden shadow-2xl">
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs md:text-sm text-slate-300">
                <thead className="bg-slate-900/90 text-slate-400 uppercase tracking-wider text-[11px] font-bold border-b border-slate-700/80">
                  <tr>
                    <th className="py-4 px-4 w-12 text-center">NO</th>
                    <th className="py-4 px-4 w-56">VA NUMBER & INFO</th>
                    <th className="py-4 px-4 w-40 whitespace-nowrap">TGL PENCARIAN (RANGE)</th>
                    <th className="py-4 px-4">STATUS SINKRONISASI (ANOMALI)</th>
                    <th className="py-4 px-4 w-48 text-center">FORCE SUCCESS</th>
                    <th className="py-4 px-4 w-24 text-center">REFUND</th>
                    <th className="py-4 px-4 w-40">LIST FORCE SUCCESS</th>
                    <th className="py-4 px-4 w-24 text-center">AKSI</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60">
                  {filteredData.length === 0 ? (
                    <tr><td colSpan="8" className="text-center p-8 text-slate-500 font-medium">✅ Semua Mutasi Bank untuk VA Multiple terpantau sinkron dengan Sistem (Tidak ada anomali atau data cocok).</td></tr>
                  ) : (
                    filteredData.map((item, idx) => {
                      const isAnomalyArray = Array.isArray(item.sinkronisasi_bank);
                      const anomalies = isAnomalyArray ? item.sinkronisasi_bank : [];
                      
                      const visibleAnomalies = (tagsRekonMulti.length > 0 && isAnomalyArray) ? anomalies.filter(a => {
                        return tagsRekonMulti.every(tag => {
                          const cleanTag = tag.toLowerCase().trim().replace(/[^a-zA-Z0-9]/g, '');
                          if (!cleanTag) return true;
                          const tgl = String(a.tanggal || '').toLowerCase();
                          const desc = String(a.deskripsi || '').toLowerCase();
                          const nomRaw = String(a.raw_kredit || a.nominal || '').replace(/[^0-9]/g, '');
                          const nomFmt = String(a.nominal || '').toLowerCase();
                          const vaMatch = String(item.va || '').toLowerCase().includes(cleanTag);
                          const userMatch = String(item.username || '').toLowerCase().includes(cleanTag);
                          const akunMatch = String(item.status_akun || '').toLowerCase().includes(cleanTag);
                          return tgl.includes(cleanTag) || desc.includes(cleanTag) || nomRaw.includes(cleanTag) || nomFmt.includes(cleanTag) || vaMatch || userMatch || akunMatch;
                        });
                      }) : anomalies;

                      const displayRange = formatDisplayDateRange(item.tanggal_pencarian);
                      const links = getMetabaseMultiLinks(item.va, item.username, item.tanggal_pencarian, isAnomalyArray, visibleAnomalies);
                      const plainText = formatMultiItemText(item, idx, links, visibleAnomalies);
                      const htmlText = formatMultiItemHTML(item, idx, links, visibleAnomalies);
                      
                      return (
                        <tr key={idx} className="hover:bg-slate-800/40 transition">
                          <td className="py-4 px-4 text-center font-mono text-slate-500 font-bold align-top">{idx + 1}</td>
                          <td className="py-4 px-4 align-top">
                            <div className="font-extrabold text-white text-sm tracking-wide whitespace-nowrap">
                              {highlightMatchedTags(item.va, tagsRekonMulti)}
                            </div>
                            <div className="text-[11px] text-slate-400 font-mono mt-0.5">
                              Username: <span className="text-slate-200 font-medium">{highlightMatchedTags(item.username || '-', tagsRekonMulti)}</span>
                            </div>
                            <div className="text-[11px] text-slate-400 font-mono mt-0.5 mb-3">
                              Status Akun: <span className="text-slate-300 font-medium">{highlightMatchedTags(item.status_akun || '-', tagsRekonMulti)}</span>
                            </div>
                            {links && (
                              <div className="flex flex-col space-y-1.5 mt-2 pt-2 border-t border-slate-700/50">
                                <a href={links.urlVA} target="_blank" rel="noopener noreferrer" className="inline-flex items-center text-[9px] font-bold text-slate-300 bg-slate-800 hover:bg-slate-700 hover:text-white px-2 py-1 rounded border border-slate-600 transition w-max">
                                  <svg className="w-2.5 h-2.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg> va_history
                                </a>
                                <a href={links.urlHistory} target="_blank" rel="noopener noreferrer" className={`inline-flex items-center text-[9px] font-bold px-2 py-1 rounded border transition w-max ${isAnomalyArray && visibleAnomalies.length > 0 ? 'text-rose-300 bg-rose-500/10 border-rose-500/30 hover:bg-rose-500/20' : 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30 hover:bg-emerald-500/20'}`}>
                                  <svg className="w-2.5 h-2.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg> {isAnomalyArray && visibleAnomalies.length > 0 ? '⚠️ b2x_va_tx_history (Anomali)' : '✅ b2x_va_tx_history (Sinkron)'}
                                </a>
                                <a href={links.urlRefund} target="_blank" rel="noopener noreferrer" className="inline-flex items-center text-[9px] font-bold text-slate-300 bg-slate-800 hover:bg-slate-700 hover:text-white px-2 py-1 rounded border border-slate-600 transition w-max">
                                  <svg className="w-2.5 h-2.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg> b2x_balance_adjustment
                                </a>
                                <a href={links.urlUser} target="_blank" rel="noopener noreferrer" className="inline-flex items-center text-[9px] font-bold text-slate-300 bg-slate-800 hover:bg-slate-700 hover:text-white px-2 py-1 rounded border border-slate-600 transition w-max">
                                  <svg className="w-2.5 h-2.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg> b2x_users
                                </a>
                              </div>
                            )}
                          </td>
                          <td className="py-4 px-4 font-mono text-slate-300 align-top whitespace-nowrap">{displayRange}</td>
                          <td className="py-4 px-4 align-top">
                            {isAnomalyArray && anomalies.length > 0 ? (
                              <div className="bg-[#181124] border border-rose-500/30 rounded-xl p-3 shadow-inner min-w-[360px] xl:min-w-[460px]">
                                <div className="text-rose-400 font-bold mb-2 flex items-center justify-between text-[11px] border-b border-rose-500/20 pb-2">
                                  <span className="flex items-center">
                                    <svg className="w-3.5 h-3.5 mr-1.5 text-rose-400 animate-pulse" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" /></svg>
                                    TERDAPAT ANOMALI: {visibleAnomalies.length} Dari {anomalies.length} Transaksi
                                  </span>
                                </div>
                                <div className="max-h-[280px] overflow-y-auto pr-1 custom-scrollbar">
                                  {visibleAnomalies.length === 0 ? (
                                    <div className="text-center py-4 text-slate-500 text-[11px]">Tidak ada baris anomali yang cocok dengan semua tag pencarian</div>
                                  ) : (
                                    <table className="w-full text-[10px] text-slate-300">
                                      <thead className="text-slate-400 font-bold bg-[#22132d] sticky top-0 z-10 border-b border-rose-500/20">
                                        <tr>
                                          <th className="py-1.5 px-2 text-left">TANGGAL</th>
                                          <th className="py-1.5 px-2 text-left">DESKRIPSI MUTASI</th>
                                          <th className="py-1.5 px-2 text-right">NOMINAL</th>
                                        </tr>
                                      </thead>
                                      <tbody className="divide-y divide-slate-800/60 font-mono">
                                        {visibleAnomalies.map((a, i) => (
                                          <tr key={i} className="hover:bg-rose-500/10 transition">
                                            <td className="py-1.5 px-2 whitespace-nowrap">{highlightMatchedTags(a.tanggal, tagsRekonMulti)}</td>
                                            <td className="py-1.5 px-2 max-w-[200px] truncate" title={a.deskripsi}>{highlightMatchedTags(a.deskripsi, tagsRekonMulti)}</td>
                                            <td className="py-1.5 px-2 text-right font-bold text-rose-300 whitespace-nowrap">Rp {highlightMatchedTags(a.nominal, tagsRekonMulti)}</td>
                                          </tr>
                                        ))}
                                      </tbody>
                                    </table>
                                  )}
                                </div>
                              </div>
                            ) : (
                              <span className="inline-flex px-3 py-1.5 rounded-lg text-[10px] font-bold border bg-emerald-500/10 text-emerald-400 border-emerald-500/30">
                                ✅ DATA SINKRON
                              </span>
                            )}
                          </td>
                          <td className="py-4 px-4 align-top text-center">
                            <span className="inline-block font-extrabold text-xs px-2.5 py-1 rounded-full bg-slate-800 text-white border border-slate-700 shadow-sm">{item.count_force_success}x</span>
                            <div className="max-h-[200px] overflow-y-auto pr-1 mt-2 custom-scrollbar text-[10px] text-slate-400 whitespace-pre-wrap font-mono text-left">
                              {item.detail_force_success}
                            </div>
                          </td>
                          <td className="py-4 px-4 font-bold text-white align-top text-center">
                            <span className="inline-block font-extrabold text-xs px-2.5 py-1 rounded-full bg-slate-800 text-slate-300 border border-slate-700">{item.count_refund_balance}x</span>
                          </td>
                          <td className="py-4 px-4 text-[10px] font-bold text-slate-400 align-top">
                            <span className="inline-block px-2.5 py-1 rounded-lg border bg-slate-900 border-slate-800 text-slate-300">
                              {item.masuk_list_force_success}
                            </span>
                          </td>
                          <td className="py-4 px-4 text-center align-top whitespace-nowrap">
                            <button onClick={() => copyMultiToClipboard(plainText, htmlText, idx)} className="bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-slate-700 transition">
                              {copiedMultiId === idx ? 'Tersalin!' : 'Copy'}
                            </button>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.VaMultipleView = VaMultipleView;