window.currentMapPage = 1;
window.mapSearchTimeout = null;

window.debounceFetchMapping = function() {
    clearTimeout(window.mapSearchTimeout);
    window.mapSearchTimeout = setTimeout(() => {
        window.fetchMappingData(1);
    }, 400); 
};

window.fetchMappingData = function(page = 1) {
    window.currentMapPage = page;
    const container = document.getElementById('mappingAccordionContainer');
    if(!container) return;

    const search = document.getElementById('mapSearch') ? document.getElementById('mapSearch').value : '';
    const limit = document.getElementById('mapLimit') ? document.getElementById('mapLimit').value : 50;

    container.innerHTML = `<div style="text-align:center; padding: 40px; color:#64748b;"><i class="fa-solid fa-spinner fa-spin" style="font-size: 24px; margin-bottom:10px;"></i><br>Fetching Mappings...</div>`;

    fetch(`../../dripend/systemSetup/gdrg/fetch_gdrg_icd_mapping.php?page=${page}&limit=${limit}&search=${encodeURIComponent(search)}`)
        .then(async response => {
            const text = await response.text(); 
            try {
                const data = JSON.parse(text);
                if (data.error) {
                    container.innerHTML = `<div style="padding: 20px; color:#dc2626; background:#fef2f2; border:1px solid #fecaca; border-radius:12px;"><strong>Database Error:</strong><br>${data.error}</div>`;
                    return;
                }
                window.renderMappingData(data);
            } catch (e) {
                console.error("Parse Error:", e);
                container.innerHTML = `<div style="padding: 20px; color:#dc2626; background:#fef2f2; border:1px solid #fecaca; border-radius:12px;"><strong>Server Error:</strong><br><textarea style="width:100%; height:100px;">${text}</textarea></div>`;
            }
        })
        .catch(err => {
            console.error('Fetch Error:', err);
            container.innerHTML = `<div style="text-align:center; padding: 40px; color:#dc2626;"><i class="fa-solid fa-wifi" style="font-size: 24px; margin-bottom:10px;"></i><br>Network Error. Cannot reach the server.</div>`;
        });
};

window.renderMappingData = function(data) {
    const container = document.getElementById('mappingAccordionContainer');
    
    if (!data.records || data.records.length === 0) {
        container.innerHTML = `<div style="text-align:center; padding: 40px; color:#64748b; background:#fff; border:1px solid #e2e8f0; border-radius:12px;">No mappings found matching your criteria.</div>`;
        window.updateMapPagination(0, 0, 0, 0);
        return;
    }

    const grouped = data.records.reduce((acc, curr) => {
        const gdrgRaw = String(curr.gdrg_code).trim();
        const gdrgDesc = curr.gdrg_desc || 'Pending Update';
        const gdrgKey = `${gdrgRaw} - ${gdrgDesc}`;
        
        if (!acc[gdrgKey]) { acc[gdrgKey] = { code: gdrgRaw, items: [] }; }
        acc[gdrgKey].items.push(curr);
        return acc;
    }, {});

    container.innerHTML = ''; 
    let globalIndex = ((data.current_page - 1) * data.limit) + 1;

    Object.keys(grouped).forEach(gdrgKey => {
        const groupData = grouped[gdrgKey];
        const mappedItems = groupData.items;
        const safeId = 'acc-' + groupData.code.replace(/[^a-zA-Z0-9]/g, '');
        
        let tableRows = '';
        
        mappedItems.forEach(item => {
            const actionButtons = `
                <div class="actions-flex">
                    <button class="btn-action delete" title="Unlink ICD-10" onclick="if(confirm('Are you sure you want to remove ICD ${item.icd10_code} from GDRG ${item.gdrg_code}?')) { if(typeof loadContent === 'function') { loadContent('Delete Mapping', 'gdrg/deleteMapping.php?id=${item.id}', 'Mapping', 'facility', null, true); } }"><i class="fa-solid fa-link-slash"></i></button>
                </div>
            `;

            tableRows += `
                <tr>
                    <td style="width: 40px; font-weight:600; color:#94a3b8;">${globalIndex}</td>
                    <td style="width: 150px;"><span class="code-badge">${String(item.icd10_code).trim()}</span></td>
                    <td><span class="desc-text">${item.icd10_desc}</span></td>
                    <td style="text-align:right;">${actionButtons}</td>
                </tr>
            `;
            globalIndex++;
        });

        // Pure CSS Accordion
        const accordionHtml = `
            <div class="dept-accordion">
                <input type="checkbox" id="${safeId}" class="acc-toggle">
                <label class="accordion-header" for="${safeId}">
                    <div class="dept-title"><i class="fa-solid fa-layer-group"></i> ${gdrgKey}</div>
                    <div class="dept-meta">
                        <span class="meta-pill">Mapped ICD Codes: ${mappedItems.length}</span>
                        <i class="fa-solid fa-chevron-down chevron-icon"></i>
                    </div>
                </label>
                <div class="accordion-body">
                    <table class="inner-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>ICD-10 Code</th>
                                <th>ICD-10 Description</th>
                                <th style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>${tableRows}</tbody>
                    </table>
                </div>
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', accordionHtml);
    });

    window.updateMapPagination(data.total_records, data.total_pages, window.currentMapPage, data.limit);
};

window.updateMapPagination = function(totalRecords, totalPages, current, limit) {
    const prevBtn = document.getElementById('mapPrev');
    const nextBtn = document.getElementById('mapNext');
    const pageInfo = document.getElementById('mapPageInfo');

    if(prevBtn) prevBtn.disabled = current <= 1;
    if(nextBtn) nextBtn.disabled = current >= totalPages || totalPages === 0;

    if(pageInfo) {
        if (totalRecords === 0) {
            pageInfo.textContent = `Showing 0 entries`;
        } else {
            const start = ((current - 1) * limit) + 1;
            const end = Math.min(current * limit, totalRecords);
            pageInfo.textContent = `Showing ${start} to ${end} of ${totalRecords} entries (Page ${current} of ${totalPages})`;
        }
    }
};

window.changeMapPage = function(direction) {
    window.fetchMappingData(window.currentMapPage + direction);
};