const { useState, useEffect } = React;
const { encodeBase64, formatDateTime, formatCleanAmount } = window;

function VaSingleView() {
  const [data, setData] = useState([]);
  const [mutationsData, setMutationsData] = useState([]); 
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('ALL');
  const [viewMode, setViewMode] = useState('text'); 
  const [activeSubTab, setActiveSubTab] = useState('REKON'); 
  const [copiedId, setCopiedId] = useState(null);
  const [copiedAll, setCopiedAll] = useState(false);

  const [tagsForceAll, setTagsForceAll] = useState([]);
  const [inputForceAll, setInputForceAll] = useState('');
  const [tagsForceList, setTagsForceList] = useState([]);
  const [inputForceList, setInputForceList] = useState('');
  const [tagsRefundAll, setTagsRefundAll] = useState([]);
  const [inputRefundAll, setInputRefundAll] = useState('');

  const fetchData = async () => {
    setLoading(true); setError(null);
    try {
      const response = await fetch('/api/va-single');
      const contentType = response.headers.get("content-type");
      if (!contentType || !contentType.includes("application/json")) {
        setData([]); setMutationsData([]); throw new Error("Waktu tunggu habis (Timeout) atau Server memori penuh.");
      }
      const result = await response.json();
      if (response.ok && result.success) {
        const sortedData = (result.data || []).sort((a, b) => new Date(a.tx_date) - new Date(b.tx_date));
        setData(sortedData); setMutationsData(result.mutations || []);
      } else { throw new Error(result.message || 'Gagal memuat data'); }
    } catch (err) { setError(err.message); } finally { setLoading(false); }
  };

  useEffect(() => { fetchData(); }, []);

  const getMetabaseLinks = (va, username) => {
    const v = va || ''; const u = username || '';
    const 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 q2 = `{"dataset_query":{"type":"query","query":{"source-table":320,"filter":["and",["=",["field",4019,null],"${v}"]]},"database":3},"display":"table","visualization_settings":{},"original_card_id":null}`;
    const q3 = `{"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 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}`;
    return { 
      url1: "https://metabase.danarapay.com/question#" + encodeBase64(q1), 
      url2: "https://metabase.danarapay.com/question#" + encodeBase64(q2), 
      url3: "https://metabase.danarapay.com/question#" + encodeBase64(q3), 
      url4: "https://metabase.danarapay.com/question#" + encodeBase64(q4) 
    };
  };

  const filterLabelMap = { 'ALL': 'Semua', '1X': 'Masuk 1x', 'MULTI': 'Masuk >1x', 'REVERSAL': 'Dana Reversal', 'FORCE_SUCCESS': 'Force Success', 'NOT_FORCE_SUCCESS': 'Tidak Force Success' };

  const formatItemText = (item, index, links) => {
    const tabLabel = filterLabelMap[filterStatus] || 'Semua';
    const mainText = `VA Single Use\n\n${tabLabel}\n\nno: ${index + 1}\nva : ${item.va || '-'}\npartner tx id : ${item.partner_tx_id || '-'}\ntx date : ${formatDateTime(item.tx_date)}\namount : ${formatCleanAmount(item.amount)}\nusername : ${item.username || '-'}\nstatus akun : ${item.status_akun || '-'}\nstatus va_history : ${item.status_va_history || '-'}\nstatus b2x_va_tx_history : ${item.status_b2x_va_tx_history || '-'}\nstatus b2x_balance_adjustment_requests : ${item.status_b2x_balance_adjustment_requests || '-'}\ndana masuk mutasi: ${item.dana_masuk_mutasi || '-'}\nmasuk list force success: ${item.masuk_list_force_success || '-'}`;
    return mainText + `\n\n${item.va || '-'} | va_history | b2x_va_tx_history | b2x_balance_adjustment_requests | b2x_users`;
  };

  const formatItemHTML = (item, index, links) => {
    const tabLabel = filterLabelMap[filterStatus] || 'Semua';
    const mainText = `VA Single Use<br><br>${tabLabel}<br><br>no: ${index + 1}<br>va : ${item.va || '-'}<br>partner tx id : ${item.partner_tx_id || '-'}<br>tx date : ${formatDateTime(item.tx_date)}<br>amount : ${formatCleanAmount(item.amount)}<br>username : ${item.username || '-'}<br>status akun : ${item.status_akun || '-'}<br>status va_history : ${item.status_va_history || '-'}<br>status b2x_va_tx_history : ${item.status_b2x_va_tx_history || '-'}<br>status b2x_balance_adjustment_requests : ${item.status_b2x_balance_adjustment_requests || '-'}<br>dana masuk mutasi: ${item.dana_masuk_mutasi || '-'}<br>masuk list force success: ${item.masuk_list_force_success || '-'}`;
    return mainText + `<br><br>${item.va || '-'} | <a href="${links.url1}">va_history</a> | <a href="${links.url2}">b2x_va_tx_history</a> | <a href="${links.url3}">b2x_balance_adjustment_requests</a> | <a href="${links.url4}">b2x_users</a>`;
  };

  const isReversalCheck = (text) => text && String(text).startsWith('DANA REVERSAL');
  const is1xCheck = (text) => text && String(text).includes('(1x)');
  const isMultiCheck = (text) => text && String(text).includes('x)') && !is1xCheck(text) && !isReversalCheck(text);

  const totalTrx = data.length;
  const count1x = data.filter(d => is1xCheck(d.dana_masuk_mutasi)).length;
  const countMulti = data.filter(d => isMultiCheck(d.dana_masuk_mutasi)).length;
  const countReversal = data.filter(d => isReversalCheck(d.dana_masuk_mutasi)).length;

  const filteredData = data.filter((item, idx) => {
    const query = searchTerm.toLowerCase().trim();
    const mutasiText = String(item.dana_masuk_mutasi || '');
    const forceSuccessText = String(item.masuk_list_force_success || '');
    let matchesSearch = false;

    if (query === 'masuk list force success') matchesSearch = forceSuccessText === 'MASUK LIST FORCE SUCCESS';
    else if (query === 'tidak masuk list force success') matchesSearch = forceSuccessText === 'TIDAK MASUK LIST FORCE SUCCESS';
    else if (query === 'sudah ada dana masuk (1x) dan tidak reversal') matchesSearch = mutasiText === 'SUDAH ADA DANA MASUK (1x) DAN TIDAK REVERSAL';
    else if (query === 'tidak ditemukan di mutasi') matchesSearch = mutasiText === 'TIDAK DITEMUKAN DI MUTASI';
    else {
      const cleanValues = [ item.va, item.partner_tx_id, formatDateTime(item.tx_date), formatCleanAmount(item.amount), item.username, item.status_akun, item.status_va_history, item.status_b2x_va_tx_history, item.status_b2x_balance_adjustment_requests, mutasiText, forceSuccessText].join(' | ').toLowerCase();
      matchesSearch = query.includes(':') ? formatItemText(item, idx, getMetabaseLinks(item.va, item.username)).toLowerCase().includes(query) : cleanValues.includes(query);
    }

    if (filterStatus === '1X') return matchesSearch && is1xCheck(mutasiText);
    if (filterStatus === 'MULTI') return matchesSearch && isMultiCheck(mutasiText);
    if (filterStatus === 'REVERSAL') return matchesSearch && isReversalCheck(mutasiText);
    if (filterStatus === 'FORCE_SUCCESS') return matchesSearch && forceSuccessText.includes('MASUK LIST') && !forceSuccessText.includes('TIDAK');
    if (filterStatus === 'NOT_FORCE_SUCCESS') return matchesSearch && forceSuccessText.includes('TIDAK MASUK LIST');
    return matchesSearch;
  });

  const filteredMutations = 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;
  }).filter(row => {
    const query = searchTerm.toLowerCase().trim();
    if (!query) return true;
    return Object.values(row).map(v => v !== null ? String(v).toLowerCase() : '').join(' | ').includes(query);
  });

  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 filterByTags = (baseList, tags) => {
    if (tags.length === 0) return baseList;
    return baseList.filter(item => {
      const rowString = Object.values(item).map(v => String(v || '').toLowerCase()).join(' ');
      return tags.some(tag => rowString.includes(tag.toLowerCase()));
    });
  };

  const deduplicateById = (items) => {
    const seen = new Set();
    return items.filter(item => {
      const key = item.id; 
      if (!key || seen.has(key)) return false;
      seen.add(key);
      return true;
    });
  };

  const baseForceAll = deduplicateById(data.filter(d => {
    const isWaiting = d.status_va_history === "WAITING_PAYMENT" || String(d.status_va_history || '').toUpperCase() === "EXPIRED";
    const noSystem = d.status_b2x_va_tx_history === "BELUM TERCATAT";
    const noRefund = String(d.status_b2x_balance_adjustment_requests || '').includes("BELUM TERCATAT");
    const adaDana = is1xCheck(d.dana_masuk_mutasi) || isMultiCheck(d.dana_masuk_mutasi);
    return isWaiting && noSystem && noRefund && adaDana;
  }));
  const filteredForceAllData = filterByTags(baseForceAll, tagsForceAll);

  const baseForceList = deduplicateById(data.filter(d => {
    const isWaiting = d.status_va_history === "WAITING_PAYMENT" || String(d.status_va_history || '').toUpperCase() === "EXPIRED";
    const noSystem = d.status_b2x_va_tx_history === "BELUM TERCATAT";
    const noRefund = String(d.status_b2x_balance_adjustment_requests || '').includes("BELUM TERCATAT");
    const adaDana = is1xCheck(d.dana_masuk_mutasi) || isMultiCheck(d.dana_masuk_mutasi);
    const inList = String(d.masuk_list_force_success || '') === "MASUK LIST FORCE SUCCESS";
    return isWaiting && noSystem && noRefund && adaDana && inList;
  }));
  const filteredForceListData = filterByTags(baseForceList, tagsForceList);

  const baseRefundAll = deduplicateById(data.filter(d => {
    const isComplete = d.status_va_history === "COMPLETE";
    const isWaiting = d.status_va_history === "WAITING_PAYMENT" || String(d.status_va_history || '').toUpperCase() === "EXPIRED";
    const masukSatu = is1xCheck(d.dana_masuk_mutasi);
    const masukMulti = isMultiCheck(d.dana_masuk_mutasi);
    return (isComplete && masukMulti) || (isWaiting && (masukSatu || masukMulti));
  }));
  const filteredRefundAllData = filterByTags(baseRefundAll, tagsRefundAll);

  const downloadFilteredExcel = (type, items) => {
    if (items.length === 0) { alert("Tidak ada data untuk diunduh!"); return; }
    let wsData = [];
    const today = new Date().toISOString().split('T')[0];
    const fileName = `Automate_${type}_${today}.xlsx`;

    if (type === "FORCE_ALL" || type === "FORCE_LIST") {
      wsData.push(["va_history_id", "va_number", "amount"]);
      items.forEach(d => { wsData.push([d.id || d.va_history_id || '', d.va || '', Number(d.amount) || 0]); });
    } else if (type === "REFUND_ALL") {
      wsData.push(["Transaction ID*", "Username*", "Transfer Amount*", "Admin Fee", "Tax", "Transaction Type*", "Adjustment Type*", "Description"]); 
      items.forEach(d => { wsData.push(['', d.username || '', Number(d.amount) || 0, 0, 0, 'IN', 'IN_VA', `Refund VA ${d.va || ''}`]); });
    }
    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, fileName);
  };

  const copyToClipboard = 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]);
      setCopiedId(id); setTimeout(() => setCopiedId(null), 2000);
    } catch (err) { navigator.clipboard.writeText(plainText).then(() => { setCopiedId(id); setTimeout(() => setCopiedId(null), 2000); }); }
  };

  const copyAllFiltered = async () => {
    const plainTextArr = []; const htmlTextArr = [];
    filteredData.forEach((item, idx) => {
      const links = getMetabaseLinks(item.va, item.username);
      plainTextArr.push(formatItemText(item, idx, links)); htmlTextArr.push(formatItemHTML(item, idx, links));
    });
    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]);
      setCopiedAll(true); setTimeout(() => setCopiedAll(false), 2000);
    } catch (err) { navigator.clipboard.writeText(fullPlainText).then(() => { setCopiedAll(true); setTimeout(() => setCopiedAll(false), 2000); }); }
  };

  return (
    <div className="w-full space-y-6 pb-12">
      {/* Header */}
      <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-blue-500/10 text-blue-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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" /></svg>
            </span>
            <h1 className="text-xl md:text-2xl font-extrabold text-white tracking-tight">VA Single Use</h1>
          </div>
          <p className="text-xs md:text-sm text-slate-400 mt-1 pl-11">Monitoring rekonsiliasi otomatis transaksi Virtual Account sekali pakai</p>
        </div>
        <div className="flex flex-col space-y-2 items-end">
          <div className="flex items-center space-x-2">
            {activeSubTab === 'REKON' && (
              <button onClick={copyAllFiltered} 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>{copiedAll ? '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="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-cardbg p-5 rounded-2xl border border-slate-700/60 shadow-md">
          <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">Total Transaksi</p>
          <p className="text-2xl font-black text-white mt-2">{loading ? '-' : totalTrx}</p>
        </div>
        <div className="bg-cardbg p-5 rounded-2xl border border-slate-700/60 shadow-md">
          <p className="text-xs font-semibold uppercase tracking-wider text-emerald-400">Masuk 1x (Normal)</p>
          <p className="text-2xl font-black text-emerald-400 mt-2">{loading ? '-' : count1x}</p>
        </div>
        <div className="bg-cardbg p-5 rounded-2xl border border-slate-700/60 shadow-md">
          <p className="text-xs font-semibold uppercase tracking-wider text-amber-400">Masuk &gt;1x (Multi)</p>
          <p className="text-2xl font-black text-amber-400 mt-2">{loading ? '-' : countMulti}</p>
        </div>
        <div className="bg-cardbg p-5 rounded-2xl border border-slate-700/60 shadow-md">
          <p className="text-xs font-semibold uppercase tracking-wider text-rose-400">Dana Reversal</p>
          <p className="text-2xl font-black text-rose-400 mt-2">{loading ? '-' : countReversal}</p>
        </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-primary 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</span>
        </button>
        <button onClick={() => setActiveSubTab('MUTASI')} 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' ? '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-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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
          <span>Automate Data Download</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-primary 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">Memproses data dari MySQL & GSheets...</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 === 'AUTOMATE' ? (
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 items-start">
          
          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-lg flex flex-col h-[600px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-cyan-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="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>
                Auto Force Success All
              </h3>
              <button onClick={() => downloadFilteredExcel('FORCE_ALL', filteredForceAllData)} className="p-1.5 bg-slate-800 hover:bg-slate-700 text-cyan-400 rounded-lg border border-slate-700 transition" title="Download Excel"><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></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>
                {tagsForceAll.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, tagsForceAll, setTagsForceAll)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik lalu Enter" value={inputForceAll} onChange={(e) => setInputForceAll(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsForceAll, setTagsForceAll, inputForceAll, setInputForceAll)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[100px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto">
              {filteredForceAllData.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs font-bold uppercase tracking-widest mt-10">TIDAK ADA DATA</div>
              ) : (
                <table className="w-full text-left text-[10px] 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">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">
                    {filteredForceAllData.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">{d.id || d.va_history_id || '-'}</td>
                        <td className="p-3 border-r border-slate-800">{d.va || '-'}</td>
                        <td className="p-3">{formatCleanAmount(d.amount)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
          
          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-lg flex flex-col h-[600px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-amber-500 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="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>
                Auto Force Success Masuk List
              </h3>
              <button onClick={() => downloadFilteredExcel('FORCE_LIST', filteredForceListData)} className="p-1.5 bg-slate-800 hover:bg-slate-700 text-amber-500 rounded-lg border border-slate-700 transition" title="Download Excel"><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></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>
                {tagsForceList.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, tagsForceList, setTagsForceList)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik lalu Enter" value={inputForceList} onChange={(e) => setInputForceList(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsForceList, setTagsForceList, inputForceList, setInputForceList)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[100px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto">
              {filteredForceListData.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs font-bold uppercase tracking-widest mt-10">TIDAK ADA DATA</div>
              ) : (
                <table className="w-full text-left text-[10px] 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">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">
                    {filteredForceListData.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">{d.id || d.va_history_id || '-'}</td>
                        <td className="p-3 border-r border-slate-800">{d.va || '-'}</td>
                        <td className="p-3">{formatCleanAmount(d.amount)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>

          <div className="bg-[#0b1329] border border-slate-800 rounded-xl overflow-hidden shadow-lg flex flex-col h-[600px]">
            <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
              <h3 className="text-emerald-500 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 All
              </h3>
              <button onClick={() => downloadFilteredExcel('REFUND_ALL', filteredRefundAllData)} className="p-1.5 bg-slate-800 hover:bg-slate-700 text-emerald-500 rounded-lg border border-slate-700 transition" title="Download Excel"><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></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>
                {tagsRefundAll.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, tagsRefundAll, setTagsRefundAll)} className="ml-1 text-slate-400 hover:text-rose-400">&times;</button>
                  </span>
                ))}
                <input type="text" placeholder="Ketik lalu Enter" value={inputRefundAll} onChange={(e) => setInputRefundAll(e.target.value)} onKeyDown={(e) => handleTagKeyDown(e, tagsRefundAll, setTagsRefundAll, inputRefundAll, setInputRefundAll)} className="bg-transparent text-xs text-white focus:outline-none flex-1 min-w-[100px] py-1" />
              </div>
            </div>
            <div className="flex-1 overflow-auto">
              {filteredRefundAllData.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs font-bold uppercase tracking-widest mt-10">TIDAK ADA DATA</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">
                    {filteredRefundAllData.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">{d.username || '-'}</td>
                        <td className="p-3 border-r border-slate-800">{formatCleanAmount(d.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">Refund VA {d.va || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      ) : activeSubTab === 'REKON' ? (
        <>
          <div className="flex flex-col md:flex-row gap-4 bg-cardbg/50 p-4 rounded-2xl border border-slate-700/60 items-center justify-between mb-4">
            <div className="relative flex-1 w-full">
              <svg className="absolute left-3.5 top-3.5 h-4 w-4 text-slate-400" 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>
              <input type="text" placeholder="Ketik kata kunci apa saja untuk memfilter data di bawah..." className="w-full bg-slate-900/80 border border-slate-700 text-white pl-10 pr-4 py-2.5 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary transition" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
            </div>
            <div className="flex items-center space-x-3 w-full md:w-auto justify-between md:justify-end">
              <div className="flex items-center space-x-1.5 overflow-x-auto pb-2 md:pb-0">
                {[{ id: 'ALL', label: 'Semua' }, { id: '1X', label: 'Masuk 1x' }, { id: 'MULTI', label: 'Masuk >1x' }, { id: 'REVERSAL', label: 'Dana Reversal' }, { id: 'FORCE_SUCCESS', label: 'Force Success' }, { id: 'NOT_FORCE_SUCCESS', label: 'Tidak Force Success' }].map((tab) => (
                  <button key={tab.id} onClick={() => setFilterStatus(tab.id)} className={`px-3 py-2 rounded-xl text-xs font-bold transition whitespace-nowrap ${filterStatus === tab.id ? 'bg-primary text-white shadow-md shadow-blue-500/20' : 'bg-slate-800 text-slate-400 hover:bg-slate-700 hover:text-white'}`}>
                    {tab.label}
                  </button>
                ))}
              </div>
              <div className="bg-slate-900 p-1 rounded-xl border border-slate-700 flex items-center space-x-1 hidden md:flex">
                <button onClick={() => setViewMode('text')} className={`p-1.5 rounded-lg text-xs font-semibold transition ${viewMode === 'text' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}>
                  <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h16M4 18h7"></path></svg>
                </button>
                <button onClick={() => setViewMode('table')} className={`p-1.5 rounded-lg text-xs font-semibold transition ${viewMode === 'table' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}>
                  <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>
                </button>
              </div>
            </div>
          </div>

          {filteredData.length === 0 ? (
            <div className="p-16 bg-cardbg rounded-2xl border border-slate-700/60 text-center text-slate-400"><p className="text-base font-bold text-slate-300 mb-1">Data Tidak Ditemukan</p><p className="text-xs text-slate-500">Tidak ada transaksi yang sesuai.</p></div>
          ) : viewMode === 'text' ? (
            <div className="space-y-4">
              {filteredData.map((item, idx) => {
                const links = getMetabaseLinks(item.va, item.username);
                const plainText = formatItemText(item, idx, links);
                const htmlText = formatItemHTML(item, idx, links);
                const isCopied = copiedId === item.no;
                const formattedDate = formatDateTime(item.tx_date);
                const cleanAmt = formatCleanAmount(item.amount);
                const mainString = `VA Single Use\n\n${filterLabelMap[filterStatus] || 'Semua'}\n\nno: ${idx + 1}\nva : ${item.va || '-'}\npartner tx id : ${item.partner_tx_id || '-'}\ntx date : ${formattedDate}\namount : ${cleanAmt}\nusername : ${item.username || '-'}\nstatus akun : ${item.status_akun || '-'}\nstatus va_history : ${item.status_va_history || '-'}\nstatus b2x_va_tx_history : ${item.status_b2x_va_tx_history || '-'}\nstatus b2x_balance_adjustment_requests : ${item.status_b2x_balance_adjustment_requests || '-'}\ndana masuk mutasi: ${item.dana_masuk_mutasi || '-'}\nmasuk list force success: ${item.masuk_list_force_success || '-'}`;

                return (
                  <div key={item.no} className="bg-[#0b1329] border-l-4 border-emerald-500 border-y border-r border-slate-800/80 rounded-xl p-5 shadow-lg relative group transition hover:border-blue-500">
                    <button onClick={() => copyToClipboard(plainText, htmlText, item.no)} className="absolute top-4 right-4 bg-slate-800/90 hover:bg-slate-700 text-slate-300 hover:text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center space-x-1.5 border border-slate-700 transition">
                      <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                      <span>{isCopied ? 'Tersalin!' : 'Copy'}</span>
                    </button>
                    <pre className="font-mono text-xs md:text-sm text-slate-200 whitespace-pre-wrap leading-relaxed mb-4">{mainString}</pre>
                    <div className="font-mono text-xs md:text-sm text-slate-300">
                      <span className="font-bold text-white">{item.va || '-'}</span> 
                      <span className="mx-2 text-slate-600">|</span> 
                      <a href={links.url1} target="_blank" rel="noopener noreferrer" className="text-blue-400 hover:text-blue-300 underline underline-offset-2">va_history</a>
                      <span className="mx-2 text-slate-600">|</span> 
                      <a href={links.url2} target="_blank" rel="noopener noreferrer" className="text-blue-400 hover:text-blue-300 underline underline-offset-2">b2x_va_tx_history</a>
                      <span className="mx-2 text-slate-600">|</span> 
                      <a href={links.url3} target="_blank" rel="noopener noreferrer" className="text-blue-400 hover:text-blue-300 underline underline-offset-2">b2x_balance_adjustment_requests</a>
                      <span className="mx-2 text-slate-600">|</span> 
                      <a href={links.url4} target="_blank" rel="noopener noreferrer" className="text-blue-400 hover:text-blue-300 underline underline-offset-2">b2x_users</a>
                    </div>
                  </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">INFORMASI VA & TX</th>
                      <th className="py-4 px-4">NOMINAL</th>
                      <th className="py-4 px-4">INFORMASI USER</th>
                      <th className="py-4 px-4">STATUS SISTEM & REFUND</th>
                      <th className="py-4 px-4">DANA MASUK MUTASI</th>
                      <th className="py-4 px-4">LIST FORCE SUCCESS</th>
                      <th className="py-4 px-4 text-center">AKSI</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800/60">
                    {filteredData.map((item, idx) => {
                      const mutasiText = item.dana_masuk_mutasi || '';
                      const forceSuccessText = item.masuk_list_force_success || '';
                      const is1x = is1xCheck(mutasiText);
                      const isMulti = isMultiCheck(mutasiText);
                      const isReversal = isReversalCheck(mutasiText);

                      const sysOk = item.status_b2x_va_tx_history && item.status_b2x_va_tx_history.includes('SUDAH');
                      const refundOk = item.status_b2x_balance_adjustment_requests && item.status_b2x_balance_adjustment_requests.includes('SUDAH');
                      const isForceInList = forceSuccessText.includes('MASUK LIST') && !forceSuccessText.includes('TIDAK');
                      const formattedDate = formatDateTime(item.tx_date);
                      const cleanAmt = formatCleanAmount(item.amount);
                      const links = getMetabaseLinks(item.va, item.username);
                      const plainText = formatItemText(item, idx, links);
                      const htmlText = formatItemHTML(item, idx, links);

                      return (
                        <tr key={item.no} className="hover:bg-slate-800/40 transition">
                          <td className="py-4 px-4 text-center font-mono text-slate-500 font-bold">{idx + 1}</td>
                          <td className="py-4 px-4 whitespace-nowrap">
                            <div className="font-extrabold text-white text-sm tracking-wide">{item.va}</div>
                            <div className="text-[11px] text-slate-400 font-mono mt-0.5">Partner TX ID: <span className="text-slate-300">{item.partner_tx_id || '-'}</span></div>
                            <div className="text-[11px] text-slate-500 font-mono">TX Date: <span className="text-slate-400">{formattedDate}</span></div>
                          </td>
                          <td className="py-4 px-4 font-bold text-emerald-400 whitespace-nowrap text-sm align-top pt-4">
                            Rp {Number(cleanAmt).toLocaleString('id-ID')}
                          </td>
                          <td className="py-4 px-4 whitespace-nowrap">
                            <div className="font-semibold text-slate-200">{item.username || '-'}</div>
                            <div className="text-[11px] text-slate-400 mt-0.5">Akun: <span className="text-slate-300 font-medium">{item.status_akun || '-'}</span></div>
                            <div className="text-[11px] text-slate-400 mt-0.5">VA Hist: <span className="text-slate-300 font-medium">{item.status_va_history || '-'}</span></div>
                          </td>
                          <td className="py-4 px-4 whitespace-nowrap space-y-1">
                            <div><span className={`text-[11px] font-semibold px-2 py-0.5 rounded ${sysOk ? 'bg-blue-500/10 text-blue-400 border border-blue-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700'}`}>System: {item.status_b2x_va_tx_history}</span></div>
                            <div><span className={`text-[11px] font-semibold px-2 py-0.5 rounded ${refundOk ? 'bg-indigo-500/10 text-indigo-400 border border-indigo-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700'}`}>Refund: {item.status_b2x_balance_adjustment_requests}</span></div>
                          </td>
                          <td className="py-4 px-4 whitespace-nowrap">
                            <span className={`inline-flex items-center px-3 py-1.5 rounded-full text-xs font-bold ${is1x ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : isMulti ? 'bg-amber-500/10 text-amber-400 border border-amber-500/30' : isReversal ? 'bg-rose-500/10 text-rose-400 border border-rose-500/30' : 'bg-slate-800 text-slate-400 border border-slate-700'}`}>
                              {item.dana_masuk_mutasi}
                            </span>
                          </td>
                          <td className="py-4 px-4 whitespace-nowrap">
                             <span className={`text-[11px] font-bold px-2.5 py-1 rounded-lg border ${isForceInList ? 'bg-purple-500/10 text-purple-400 border-purple-500/20' : 'bg-slate-800/80 text-slate-400 border-slate-700'}`}>
                              {forceSuccessText.replace('LIST FORCE SUCCESS', '').trim() || 'TIDAK MASUK'}
                            </span>
                          </td>
                          <td className="py-4 px-4 text-center whitespace-nowrap">
                            <button onClick={() => copyToClipboard(plainText, htmlText, item.no)} 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">
                              {copiedId === item.no ? 'Tersalin!' : 'Copy'}
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      ) : (
        <>
          <div className="flex flex-col md:flex-row gap-4 bg-cardbg/50 p-4 rounded-2xl border border-slate-700/60 items-center justify-between mb-4">
            <div className="relative flex-1 w-full">
              <svg className="absolute left-3.5 top-3.5 h-4 w-4 text-slate-400" 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>
              <input type="text" placeholder="Ketik kata kunci apa saja untuk memfilter data di bawah..." className="w-full bg-slate-900/80 border border-slate-700 text-white pl-10 pr-4 py-2.5 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary transition" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
            </div>
          </div>
          
          {filteredMutations.length === 0 ? (
            <div className="p-16 bg-cardbg rounded-2xl border border-slate-700/60 text-center text-slate-400">
              <p className="text-base font-bold text-slate-300 mb-1">Raw Mutasi Kosong</p>
              <p className="text-xs text-slate-500">Tidak ada baris mutasi bank yang terpilih atau cocok.</p>
            </div>
          ) : (
            <div className="bg-cardbg rounded-2xl border border-slate-700/60 overflow-hidden shadow-2xl">
              <div className="overflow-x-auto max-h-[600px]">
                <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-700/80 sticky top-0 z-10">
                    <tr>
                      <th className="py-3 px-4 border-r border-slate-700">#</th>
                      {Object.keys(filteredMutations[0] || {}).map(key => (
                        <th key={key} className="py-3 px-4 border-r border-slate-700">{key.replace(/_/g, ' ')}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800/60 font-mono">
                    {filteredMutations.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>
  );
}

window.VaSingleView = VaSingleView;