window.initMappingBuilder = function() {
    const rawGdrg = document.getElementById('rawGdrgData');
    const rawIcd = document.getElementById('rawIcdData');
    const rawMapping = document.getElementById('rawMappingData');
    
    if (!rawGdrg || !rawIcd || !rawMapping) return;

    const gdrgs = JSON.parse(rawGdrg.textContent);
    const icds = JSON.parse(rawIcd.textContent);
    const databaseMappings = JSON.parse(rawMapping.textContent);

    let selectedGdrg = null;
    let selectedIcds = new Set();
    let originalIcdsForSelectedGdrg = new Set(); 

    const gdrgList = document.getElementById('gdrgListContainer');
    const icdList = document.getElementById('icdListContainer');
    const gdrgSearch = document.getElementById('gdrgSearch');
    const icdSearch = document.getElementById('icdSearch');
    
    const targetGdrgInput = document.getElementById('targetGdrgInput');
    const hiddenIcdContainer = document.getElementById('hiddenIcdInputsContainer');
    const stagingText = document.getElementById('stagingTargetText');
    const submitBtn = document.getElementById('btnSubmitMapping');

    document.getElementById('gdrgCountBadge').textContent = gdrgs.length;
    document.getElementById('icdCountBadge').textContent = icds.length;

    renderGdrgs(gdrgs);

    // --- LEFT PANE (PROCEDURES/GDRG) ---
    function renderGdrgs(data) {
        gdrgList.innerHTML = '';
        data.forEach(item => {
            const div = document.createElement('div');
            const isSelected = selectedGdrg && selectedGdrg.code === item.code;
            div.className = `list-item gdrg-item ${isSelected ? 'selected' : ''}`;
            div.innerHTML = `
                <div style="width: 100%;">
                    <span class="gdrg-code">${item.code}</span>
                    <span style="font-size:12px; color:#64748b; font-weight:600; display:block; line-height:1.4;">${item.description}</span>
                </div>
            `;
            div.onclick = () => selectGdrg(item);
            gdrgList.appendChild(div);
        });
    }

    gdrgSearch.addEventListener('input', (e) => {
        const term = e.target.value.toLowerCase();
        const filtered = gdrgs.filter(g => 
            g.code.toLowerCase().includes(term) || 
            g.description.toLowerCase().includes(term)
        );
        renderGdrgs(filtered);
    });

    function selectGdrg(item) {
        selectedGdrg = item;
        targetGdrgInput.value = item.code;
        
        selectedIcds.clear();
        originalIcdsForSelectedGdrg.clear();
        icdSearch.value = '';
        
        // Find existing relations
        databaseMappings.forEach(map => {
            if(map.gdrg_code === item.code) {
                selectedIcds.add(map.icd10_code);
                originalIcdsForSelectedGdrg.add(map.icd10_code);
            }
        });

        renderGdrgs(gdrgs);

        // Unlock right pane and render intelligently
        icdList.style.pointerEvents = 'auto';
        icdList.style.opacity = '1';
        filterAndRenderIcds();
        updateStagingBar();
    }

    // --- RIGHT PANE (HIGH-PERFORMANCE ICD-10 SEARCH) ---
    function filterAndRenderIcds() {
        if (!selectedGdrg) return;
        const term = icdSearch.value.toLowerCase();
        
        let filtered = icds.filter(item => {
            const matchesSearch = item.code.toLowerCase().includes(term) || item.description.toLowerCase().includes(term);
            const isChecked = selectedIcds.has(item.code);
            return matchesSearch || isChecked;
        });

        // PREVENTS FREEZING: If no search term, only show already mapped + top 50
        if (term === '') {
            const preMapped = filtered.filter(item => originalIcdsForSelectedGdrg.has(item.code));
            const unMappedSample = filtered.filter(item => !originalIcdsForSelectedGdrg.has(item.code)).slice(0, 50);
            filtered = [...preMapped, ...unMappedSample];
        }

        icdList.innerHTML = '';
        const fragment = document.createDocumentFragment();

        filtered.forEach(item => {
            const isChecked = selectedIcds.has(item.code);
            const isOriginallyMapped = originalIcdsForSelectedGdrg.has(item.code);
            
            const div = document.createElement('div');
            div.className = `list-item icd-item ${isChecked ? 'selected' : ''}`;
            
            let statusBadge = isOriginallyMapped ? `<span class="badge-mapped">Mapped</span>` : '';

            div.innerHTML = `
                <input type="checkbox" class="custom-checkbox" value="${item.code}" ${isChecked ? 'checked' : ''}>
                <span class="icd-code">${item.code}</span>
                <span class="icd-desc">${item.description}</span>
                ${statusBadge}
            `;
            
            div.onclick = (e) => {
                if(e.target.type !== 'checkbox') {
                    const cb = div.querySelector('input');
                    cb.checked = !cb.checked;
                    toggleIcd(item.code, cb.checked, div);
                } else {
                    toggleIcd(item.code, e.target.checked, div);
                }
            };
            fragment.appendChild(div);
        });
        
        if (filtered.length === 0) {
            icdList.innerHTML = `<div style="text-align:center; padding: 40px; color:#64748b;">No ICD-10 results match.</div>`;
        } else {
            icdList.appendChild(fragment);
        }
    }

    icdSearch.addEventListener('input', filterAndRenderIcds);

    function toggleIcd(code, isChecked, rowElement) {
        if(isChecked) {
            selectedIcds.add(code);
            rowElement.classList.add('selected');
        } else {
            selectedIcds.delete(code);
            rowElement.classList.remove('selected');
        }
        updateStagingBar();
    }

    // --- STAGING BAR ---
    function updateStagingBar() {
        hiddenIcdContainer.innerHTML = '';
        selectedIcds.forEach(code => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'icd_codes[]';
            input.value = code;
            hiddenIcdContainer.appendChild(input);
        });

        const currentActiveCount = selectedIcds.size;
        if (selectedGdrg) {
            submitBtn.disabled = false;
            if (currentActiveCount > 0) {
                stagingText.innerHTML = `<i class="fa-solid fa-link" style="color:#10b981;"></i> Mapping <span class="badge-count" style="background:#10b981; color:#fff;">${currentActiveCount}</span> ICD-10 codes to <strong>${selectedGdrg.code}</strong>`;
            } else {
                stagingText.innerHTML = `<i class="fa-solid fa-circle-nodes" style="color:#ef4444;"></i> Unmapping all codes for <strong>${selectedGdrg.code}</strong>`;
            }
        } else {
            submitBtn.disabled = true;
            stagingText.innerHTML = `<i class="fa-solid fa-circle-exclamation" style="color:#ef4444;"></i> No Procedure Selected`;
        }
    }
};