// Helper: Levenshtein Distance
const getLevenshteinDistance = (a, b) => {
    if (a.length === 0) return b.length;
    if (b.length === 0) return a.length;

    const matrix = [];

    for (let i = 0; i <= b.length; i++) {
        matrix[i] = [i];
    }

    for (let j = 0; j <= a.length; j++) {
        matrix[0][j] = j;
    }

    for (let i = 1; i <= b.length; i++) {
        for (let j = 1; j <= a.length; j++) {
            if (b.charAt(i - 1) === a.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1];
            } else {
                matrix[i][j] = Math.min(
                    matrix[i - 1][j - 1] + 1,
                    matrix[i][j - 1] + 1,
                    matrix[i - 1][j] + 1
                );
            }
        }
    }
    return matrix[b.length][a.length];
};

// 1. Normalisasi Nama (Name Normalization)
const normalizeName = (str) => {
    if (!str) return "";
    let clean = str.toString().toLowerCase();

    // Remove content after comma (Titles often start after comma: "Name, S.Pd")
    if (clean.includes(',')) {
        clean = clean.split(',')[0];
    }

    // Replace common abbreviations/prefixes with standard forms
    clean = clean
        .replace(/\babd\b|\babd\./g, 'abdul')
        .replace(/\bmoh\b|\bmoh\./g, 'muhammad')
        .replace(/\bmuh\b|\bmuh\./g, 'muhammad')
        .replace(/^m\.\s/, 'muhammad ')
        .replace(/^m\s/, 'muhammad ');

    // Remove honorifics and academic titles found at start
    const prefixes = [
        'drs.', 'dra.', 'ir.', 'h.', 'hj.', 'kh.', 'kyai', 'ust.', 'ustdz.',
        'drs', 'dra', 'ir', 'h', 'hj', 'kh' // without dots
    ];
    
    // Check start of string
    for (const p of prefixes) {
        if (clean.startsWith(p + ' ')) {
            clean = clean.substring(p.length + 1);
        }
    }

    // Clean Punctuation: remove dots, quotes, etc.
    clean = clean.replace(/[^a-z0-9\s]/g, ' ');

    // Remove remaining academic titles that might not be after comma
    const titlesToRemove = [
        'spd', 'mpd', 'sag', 'mag', 'se', 'sh', 'mpsi', 'si', 'sthi', 'ba', 'skom', 'sos', 'mm', 'msi', 'hum'
    ];
    clean = clean.split(' ').filter(word => !titlesToRemove.includes(word)).join(' ');

    // Final Trim
    clean = clean.replace(/\s+/g, ' ').trim();

    return clean;
};

// 2. Logika Pencocokan & Skor (Match Logic & Scoring)
const calculateMatchScore = (str1, str2) => {
    const norm1 = normalizeName(str1);
    const norm2 = normalizeName(str2);

    if (!norm1 || !norm2) return 0;

    // A. Exact Normalized Match
    if (norm1 === norm2) return 100;

    let score = 0;
    const len1 = norm1.length;
    const len2 = norm2.length;
    const maxLen = Math.max(len1, len2);

    // B. Levenshtein Similarity (Base Weight: 30)
    // Distance 0-1 is very close.
    const dist = getLevenshteinDistance(norm1, norm2);
    const levSim = (maxLen - dist) / maxLen; // 0 to 1
    
    if (levSim >= 0.9) score += 30;
    else if (levSim >= 0.8) score += 20;
    else if (levSim >= 0.7) score += 10;

    // C. Partial Match / Substring (Base Weight: 30)
    // "a kholili" inside "a kholili al fahmi"
    if (norm1.includes(norm2) || norm2.includes(norm1)) {
        score += 30;
    } else {
        // Check word intersection overlap
        const words1 = norm1.split(' ');
        const words2 = norm2.split(' ');
        const commonWords = words1.filter(w => words2.includes(w));
        const overlapRatio = commonWords.length / Math.min(words1.length, words2.length);
        
        if (overlapRatio >= 0.8) score += 20; // High overlap
        else if (overlapRatio >= 0.5) score += 10;
    }

    // D. Same First + Last Name (Base Weight: 40)
    const words1 = norm1.split(' ');
    const words2 = norm2.split(' ');
    
    const first1 = words1[0];
    const last1 = words1[words1.length - 1];
    const first2 = words2[0];
    const last2 = words2[words2.length - 1];

    if (first1 === first2 && last1 === last2) {
        score += 40;
    } else {
        // E. Singkatan Nama Awal (Initial Match)
        // Check if one is an initial of the other: "a" vs "ahmad" (and last name matches)
        const firstIsInitial = (first1.length === 1 && first2.startsWith(first1)) || 
                               (first2.length === 1 && first1.startsWith(first2));
        
        if (firstIsInitial && last1 === last2) {
            score += 35; // Almost as good as full match
        } else if (first1 === first2) {
            // First name matches but last doesn't -> small boost
             score += 10;
        } else if (last1 === last2) {
            // Last name matches but first doesn't -> small boost
            score += 10;
        }
    }

    // Cap score at 100
    return Math.min(100, score);
};


function DuplicateMerger({ year }) {
    const { addToast } = window.ToastSystem.useToast();
    const [duplicates, setDuplicates] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [processing, setProcessing] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [threshold, setThreshold] = React.useState(70); // User suggestion: > 70 is match

    const fetchAndAnalyze = async () => {
        setLoading(true);
        setError(null);
        try {
            const client = window.SupabaseUtils.getClient();
            const { data, error } = await client
                .from('employees')
                .select('*')
                .eq('tahun', year); // Filter year
            
            if (error) throw error;

            const groups = [];
            const processedIds = new Set();
            
            // Sort by name length to prioritize longer/fuller names as group headers
            const sortedData = [...data].sort((a, b) => (b.nama || '').length - (a.nama || '').length);

            sortedData.forEach(emp => {
                if (!emp.nama || processedIds.has(emp.id)) return;
                if (emp.is_verified_unique) return;

                const currentGroup = [emp];
                processedIds.add(emp.id);

                sortedData.forEach(candidate => {
                    if (candidate.id === emp.id || processedIds.has(candidate.id)) return;
                    if (candidate.is_verified_unique) return;

                    // Calculate Score
                    const score = calculateMatchScore(emp.nama, candidate.nama);
                    
                    if (score >= threshold) {
                        currentGroup.push({ ...candidate, _matchScore: score });
                        processedIds.add(candidate.id);
                    }
                });

                if (currentGroup.length > 1) {
                    // Sort inside group: 
                    // 1. Has NIK
                    // 2. Active status
                    // 3. Name length
                    currentGroup.sort((a, b) => {
                        if (a.nik && !b.nik) return -1;
                        if (!a.nik && b.nik) return 1;
                        return 0; 
                    });

                    groups.push({
                        name: currentGroup[0].nama,
                        records: currentGroup,
                        selectedMasterId: currentGroup[0].id
                    });
                }
            });

            setDuplicates(groups);

        } catch (err) {
            console.error("Duplicate Check Error:", err);
            setError(window.SupabaseUtils.formatError(err));
        } finally {
            setLoading(false);
        }
    };

    React.useEffect(() => {
        fetchAndAnalyze();
    }, [threshold, year]); 

    const handleSelectMaster = (groupIndex, masterId) => {
        const newDuplicates = [...duplicates];
        newDuplicates[groupIndex].selectedMasterId = masterId;
        setDuplicates(newDuplicates);
    };

    const handleMarkAsDifferent = async (groupIndex) => {
        const group = duplicates[groupIndex];
        const result = await Swal.fire({
            title: "Tandai Berbeda?",
            text: "Data dalam grup ini akan ditandai sebagai orang berbeda dan tidak akan muncul lagi di sini.",
            icon: "question",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Ya, Tandai!",
            cancelButtonText: "Batal"
        });

        if (!result.isConfirmed) return;

        setProcessing(true);
        try {
            const client = window.SupabaseUtils.getClient();
            const ids = group.records.map(r => r.id);
            const { error } = await client.from('employees').update({ is_verified_unique: true }).in('id', ids);
            if (error) throw error;

            setDuplicates(prev => prev.filter((_, i) => i !== groupIndex));
            addToast('Berhasil ditandai sebagai orang berbeda', 'success');
        } catch (err) {
            addToast('Gagal menandai data: ' + window.SupabaseUtils.formatError(err), 'error');
        } finally {
            setProcessing(false);
        }
    };

    const handleRemoveItem = (groupIndex, itemId) => {
        const newDuplicates = [...duplicates];
        const group = newDuplicates[groupIndex];
        group.records = group.records.filter(r => r.id !== itemId);
        if (group.records.length < 2) {
            newDuplicates.splice(groupIndex, 1);
        } else if (group.selectedMasterId === itemId) {
            group.selectedMasterId = group.records[0].id;
        }
        setDuplicates(newDuplicates);
    };

    const handleDeleteRecord = async (groupIndex, itemId) => {
        const result = await Swal.fire({
            title: "Hapus Data Permanen?",
            text: "Data ini akan dihapus permanen dari database!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d33",
            cancelButtonColor: "#3085d6",
            confirmButtonText: "Ya, Hapus!",
            cancelButtonText: "Batal"
        });

        if (!result.isConfirmed) return;
        setProcessing(true);

        try {
            const client = window.SupabaseUtils.getClient();
            const { error } = await client.from('employees').delete().eq('id', itemId);
            if (error) throw error;

            // Remove from local list using existing logic
            handleRemoveItem(groupIndex, itemId);
            addToast('Data berhasil dihapus dari database', 'success');
        } catch (err) {
            addToast('Gagal menghapus: ' + window.SupabaseUtils.formatError(err), 'error');
        } finally {
            setProcessing(false);
        }
    };

    const handleMerge = async (groupIndex) => {
        const group = duplicates[groupIndex];
        const master = group.records.find(r => r.id === group.selectedMasterId);
        const secondaries = group.records.filter(r => r.id !== group.selectedMasterId);
        
        if (!master || secondaries.length === 0) return;

        const result = await Swal.fire({
            title: "Gabungkan Data?",
            html: `Gabungkan <b>${secondaries.length} data</b> ke dalam <b>"${master.nama}"</b>?`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#0f766e",
            cancelButtonColor: "#d33",
            confirmButtonText: "Ya, Gabungkan!",
            cancelButtonText: "Batal"
        });

        if (!result.isConfirmed) return;

        setProcessing(true);
        try {
            const client = window.SupabaseUtils.getClient();
            let allLocations = new Set();
            if (master.lembaga) master.lembaga.split(',').forEach(l => allLocations.add(l.trim()));
            if (master.satminkal) allLocations.add(master.satminkal.trim()); 
            let newNik = master.nik;

            secondaries.forEach(sec => {
                if (sec.satminkal) allLocations.add(sec.satminkal.trim());
                if (sec.lembaga) sec.lembaga.split(',').forEach(l => allLocations.add(l.trim()));
                if (!newNik && sec.nik) newNik = sec.nik;
            });

            if (master.satminkal) allLocations.delete(master.satminkal.trim());
            const mergedLembagaStr = Array.from(allLocations).filter(Boolean).join(', ');

            const { error: updateError } = await client.from('employees').update({
                lembaga: mergedLembagaStr,
                nik: newNik,
                is_verified_unique: true
            }).eq('id', master.id);
            if (updateError) throw updateError;

            const { error: deleteError } = await client.from('employees').delete().in('id', secondaries.map(s => s.id));
            if (deleteError) throw deleteError;

            addToast('Penggabungan berhasil!', 'success');
            setDuplicates(prev => prev.filter((_, i) => i !== groupIndex));
        } catch (err) {
            addToast('Gagal menggabungkan: ' + window.SupabaseUtils.formatError(err), 'error');
        } finally {
            setProcessing(false);
        }
    };

    return (
        <div className="p-4 md:p-8" data-name="duplicate-merger" data-file="components/DuplicateMerger.js">
            <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center mb-6 gap-4">
                <div>
                    <h2 className="text-xl md:text-2xl font-bold text-gray-800 flex items-center gap-2">
                        <div className="icon-git-merge text-orange-600"></div>
                        Smart Duplicate Check
                    </h2>
                    <p className="text-gray-500 text-sm mt-1">
                        Menggunakan algoritma <b>Fuzzy Matching</b> untuk mendeteksi variasi nama.
                    </p>
                </div>

                <div className="flex flex-wrap items-center gap-2 w-full lg:w-auto">
                    <button 
                        onClick={fetchAndAnalyze} 
                        disabled={loading}
                        className="bg-white h-[46px] w-[46px] flex-shrink-0 flex items-center justify-center rounded-lg shadow-sm border border-gray-200 text-gray-600 hover:text-orange-600 hover:border-orange-200 transition-all disabled:opacity-50"
                        title="Segarkan Analisis"
                    >
                        <div className={`icon-refresh-cw text-lg ${loading ? 'animate-spin' : ''}`}></div>
                    </button>

                    <div className="bg-white p-2 md:p-3 rounded-lg shadow-sm border border-gray-200 flex items-center gap-2 flex-1 lg:flex-none justify-between lg:justify-start">
                        <label className="text-sm font-medium text-gray-700 whitespace-nowrap">
                            Threshold:
                        </label>
                        <div className="relative flex-1 lg:flex-none">
                            <select 
                                value={threshold}
                                onChange={(e) => setThreshold(Number(e.target.value))}
                                className="w-full lg:w-auto appearance-none bg-orange-50 border border-orange-200 text-orange-800 text-sm font-bold py-1.5 pl-3 pr-8 rounded focus:outline-none focus:ring-2 focus:ring-orange-500 cursor-pointer"
                            >
                                <option value={80}>80 (Ketat)</option>
                                <option value={70}>70 (Rekomendasi)</option>
                                <option value={60}>60 (Longgar)</option>
                                <option value={50}>50 (Sangat Longgar)</option>
                                <option value={40}>40 (Ekstrem)</option>
                                <option value={30}>30 (Semua Kemungkinan)</option>
                            </select>
                            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-orange-800">
                                <div className="icon-chevron-down text-xs"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {loading ? (
                <div className="flex flex-col justify-center items-center py-20 bg-gray-50 rounded-lg border border-dashed border-gray-300">
                    <div className="animate-spin w-10 h-10 border-4 border-orange-500 border-t-transparent rounded-full mb-4"></div>
                    <span className="text-gray-600 font-medium">Menganalisis kemiripan nama...</span>
                    <span className="text-gray-400 text-sm mt-1">Normalisasi • Levenshtein • Substring Match</span>
                </div>
            ) : duplicates.length === 0 ? (
                <div className="bg-green-50 border border-green-200 rounded-lg p-12 text-center animate-fade-in">
                    <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
                        <div className="icon-circle-check text-4xl text-green-600"></div>
                    </div>
                    <h3 className="text-xl font-bold text-green-800 mb-2">Tidak Ditemukan Duplikasi</h3>
                    <p className="text-green-600 max-w-lg mx-auto">
                        Hebat! Data pegawai terlihat bersih dengan skor minimal <strong>{threshold}</strong>.
                    </p>
                </div>
            ) : (
                <div className="space-y-6 animate-fade-in">
                    <div className="bg-blue-50 border-l-4 border-blue-400 p-4 mb-4 text-sm text-blue-800 flex items-start gap-3">
                        <div className="icon-info text-xl mt-0.5"></div>
                        <div>
                            <p className="font-bold">Ditemukan {duplicates.length} grup potensi duplikasi.</p>
                            <p className="opacity-90 mt-1">
                                Sistem menghitung skor (0-100) berdasarkan kesamaan karakter, kata awal/akhir, dan substring.
                            </p>
                        </div>
                    </div>

                    {duplicates.map((group, idx) => (
                        <div key={idx} className="bg-white rounded-lg shadow-md border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow">
                            <div className="bg-gray-50 px-4 py-3 border-b border-gray-200 flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
                                <div className="flex flex-col sm:flex-row sm:items-center gap-2 w-full md:w-auto">
                                    <div className="flex items-center gap-2">
                                        <span className="bg-orange-100 text-orange-700 w-6 h-6 flex-shrink-0 flex items-center justify-center rounded-full text-xs font-bold">{idx + 1}</span>
                                        <span className="text-xs font-normal bg-gray-200 px-2 py-0.5 rounded text-gray-600 whitespace-nowrap">
                                            Basis
                                        </span>
                                    </div>
                                    <h3 className="font-mono text-lg font-bold text-teal-700 break-all sm:break-normal">
                                        "{normalizeName(group.name)}"
                                    </h3>
                                </div>
                                
                                <div className="flex gap-2 w-full md:w-auto justify-end">
                                    <button 
                                        onClick={() => handleMarkAsDifferent(idx)}
                                        disabled={processing}
                                        className="flex-1 md:flex-none justify-center bg-white border border-gray-300 text-gray-700 text-xs px-3 py-2 rounded flex items-center gap-1 hover:bg-gray-100 transition-colors"
                                    >
                                        <div className="icon-user-check text-sm"></div>
                                        Beda Orang
                                    </button>
                                    <button 
                                        onClick={() => handleMerge(idx)}
                                        disabled={processing}
                                        className="flex-1 md:flex-none justify-center bg-teal-600 hover:bg-teal-700 text-white text-xs px-3 py-2 rounded flex items-center gap-1 transition-colors disabled:opacity-50 shadow-sm"
                                    >
                                        <div className="icon-git-merge text-sm"></div>
                                        Gabungkan ({group.records.length})
                                    </button>
                                </div>
                            </div>
                            
                            {/* Desktop Table View */}
                            <div className="hidden md:block overflow-x-auto">
                                <table className="w-full text-sm text-left">
                                    <thead className="text-gray-500 border-b border-gray-100 bg-white">
                                        <tr>
                                            <th className="px-4 py-2 w-16 text-center bg-gray-50">Master</th>
                                            <th className="px-4 py-2">Nama Terdata</th>
                                            <th className="px-4 py-2">Info Tambahan</th>
                                            <th className="px-4 py-2">Satminkal</th>
                                            <th className="px-4 py-2 text-center">Skor</th>
                                            <th className="px-4 py-2 w-10"></th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {group.records.map(rec => {
                                            const isMaster = group.selectedMasterId === rec.id;
                                            const score = rec._matchScore !== undefined 
                                                ? rec._matchScore 
                                                : calculateMatchScore(rec.nama, group.name);
                                            
                                            return (
                                                <tr key={rec.id} className={`transition-colors ${isMaster ? 'bg-teal-50/50' : 'hover:bg-gray-50'}`}>
                                                    <td className="px-4 py-3 text-center">
                                                        <input 
                                                            type="radio" 
                                                            name={`master-${idx}`}
                                                            checked={isMaster}
                                                            onChange={() => handleSelectMaster(idx, rec.id)}
                                                            className="w-4 h-4 text-teal-600 focus:ring-teal-500 border-gray-300 cursor-pointer"
                                                        />
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <div className="font-bold text-gray-900">{rec.nama}</div>
                                                        <div className="text-xs text-gray-400 font-mono flex gap-2">
                                                            <span>Norm: {normalizeName(rec.nama)}</span>
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3">
                                                         <div className="flex flex-col gap-1">
                                                            <span className="text-xs text-gray-500">
                                                                NIK: {rec.nik ? <span className="text-gray-700 font-medium">{rec.nik}</span> : <span className="text-red-300 italic">Kosong</span>}
                                                            </span>
                                                            {rec.jabatan && (
                                                                <span className="text-xs text-gray-600 font-medium flex items-center gap-1" title={rec.jabatan}>
                                                                    <div className="icon-briefcase text-[10px]"></div>
                                                                    <span className="truncate max-w-[150px]">{rec.jabatan}</span>
                                                                </span>
                                                            )}
                                                            <span className={`text-[10px] w-fit px-1.5 py-0.5 rounded font-bold uppercase tracking-wide ${rec.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                                                {rec.is_active ? 'Aktif' : 'Non-Aktif'}
                                                            </span>
                                                         </div>
                                                    </td>
                                                    <td className="px-4 py-3 text-gray-600">
                                                        <div className="flex flex-col">
                                                            {rec.satminkal ? (
                                                                <span className="font-medium">{rec.satminkal}</span>
                                                            ) : (
                                                                <span className="text-gray-400 italic font-light">Non-Satminkal (Induk Kosong)</span>
                                                            )}
                                                            {rec.lembaga && (
                                                                <span className="text-xs text-orange-500 mt-0.5 flex items-center gap-1">
                                                                    <div className="icon-plus-circle text-[10px]"></div>
                                                                    {rec.lembaga}
                                                                </span>
                                                            )}
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3 text-center">
                                                        {rec.nama === group.name ? (
                                                            <span className="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded">Ref</span>
                                                        ) : (
                                                            <span className={`text-xs font-bold px-2 py-0.5 rounded ${
                                                                score >= 90 ? 'bg-green-100 text-green-700' :
                                                                score >= 70 ? 'bg-blue-100 text-blue-700' :
                                                                'bg-yellow-100 text-yellow-700'
                                                            }`}>
                                                                {Math.round(score)}
                                                            </span>
                                                        )}
                                                    </td>
                                                    <td className="px-4 py-3 text-right">
                                                        <div className="flex justify-end gap-1">
                                                            {group.records.length > 2 && (
                                                                <button 
                                                                    onClick={() => handleDeleteRecord(idx, rec.id)}
                                                                    className="text-red-400 hover:text-red-600 transition-colors p-1 hover:bg-red-50 rounded"
                                                                    title="Hapus Permanen dari Database"
                                                                >
                                                                    <div className="icon-trash text-lg"></div>
                                                                </button>
                                                            )}
                                                            <button 
                                                                onClick={() => handleRemoveItem(idx, rec.id)}
                                                                className="text-gray-300 hover:text-gray-500 transition-colors p-1 hover:bg-gray-100 rounded"
                                                                title="Keluarkan dari grup ini (Abaikan)"
                                                            >
                                                                <div className="icon-x-circle text-lg"></div>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>

                            {/* Mobile Card View */}
                            <div className="md:hidden divide-y divide-gray-100">
                                {group.records.map(rec => {
                                    const isMaster = group.selectedMasterId === rec.id;
                                    const score = rec._matchScore !== undefined 
                                        ? rec._matchScore 
                                        : calculateMatchScore(rec.nama, group.name);
                                    
                                    return (
                                        <div key={rec.id} className={`p-4 ${isMaster ? 'bg-teal-50/50' : ''}`}>
                                            <div className="flex justify-between items-start mb-3">
                                                <div className="flex items-center gap-3">
                                                    <input 
                                                        type="radio" 
                                                        name={`master-mobile-${idx}`}
                                                        checked={isMaster}
                                                        onChange={() => handleSelectMaster(idx, rec.id)}
                                                        className="w-5 h-5 text-teal-600 focus:ring-teal-500 border-gray-300"
                                                    />
                                                    <span className={`text-[10px] font-bold px-2 py-0.5 rounded ${
                                                        score >= 90 ? 'bg-green-100 text-green-700' :
                                                        score >= 70 ? 'bg-blue-100 text-blue-700' :
                                                        'bg-yellow-100 text-yellow-700'
                                                    }`}>
                                                        Skor: {Math.round(score)}
                                                    </span>
                                                </div>
                                                
                                                <div className="flex gap-2">
                                                    {group.records.length > 2 && (
                                                        <button 
                                                            onClick={() => handleDeleteRecord(idx, rec.id)}
                                                            className="text-red-400 hover:text-red-600 bg-white border border-red-100 p-1.5 rounded shadow-sm"
                                                            title="Hapus"
                                                        >
                                                            <div className="icon-trash text-base"></div>
                                                        </button>
                                                    )}
                                                    <button 
                                                        onClick={() => handleRemoveItem(idx, rec.id)}
                                                        className="text-gray-400 hover:text-gray-600 bg-white border border-gray-100 p-1.5 rounded shadow-sm"
                                                        title="Abaikan"
                                                    >
                                                        <div className="icon-x-circle text-base"></div>
                                                    </button>
                                                </div>
                                            </div>

                                            <div className="mb-2">
                                                <div className="font-bold text-gray-800 text-sm">{rec.nama}</div>
                                                <div className="text-xs text-gray-500 font-mono mt-0.5">Norm: {normalizeName(rec.nama)}</div>
                                            </div>

                                            <div className="grid grid-cols-2 gap-2 text-xs mb-2">
                                                <div>
                                                    <span className="text-gray-400 block text-[10px] uppercase">NIK</span>
                                                    <span className="font-mono text-gray-700">{rec.nik || '-'}</span>
                                                </div>
                                                <div>
                                                    <span className="text-gray-400 block text-[10px] uppercase">Jabatan</span>
                                                    <span className="text-gray-700 truncate block">{rec.jabatan || '-'}</span>
                                                </div>
                                            </div>

                                            <div className="bg-gray-50 p-2 rounded text-xs mb-2">
                                                <div className="font-medium text-gray-800">
                                                    {rec.satminkal || <span className="text-gray-400 italic">Non-Satminkal</span>}
                                                </div>
                                                {rec.lembaga && (
                                                    <div className="text-orange-600 mt-0.5 flex items-center gap-1">
                                                        <div className="icon-plus-circle text-[10px]"></div>
                                                        {rec.lembaga}
                                                    </div>
                                                )}
                                            </div>

                                            <span className={`inline-block text-[10px] px-2 py-0.5 rounded font-bold uppercase ${rec.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                                {rec.is_active ? 'Aktif' : 'Non-Aktif'}
                                            </span>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}