document.addEventListener('DOMContentLoaded', function () {
    // FIXED: Endpoints configured directly for accurate relative execution paths
    const API = {
        FETCH: 'fetchMapLabDepartments.php',
        UPDATE: 'processAddMapLabDepartments.php'
    };

    const elements = {
        searchInput: document.getElementById('lisTestSearch'),
        tableBody: document.querySelector('#lisRoutingTable tbody'),
        mappingForm: document.getElementById('lisMappingForm'),
        alertContainer: document.getElementById('lisAlertContainer'),
        liveBoard: document.getElementById('lisLiveBoard'),
        submitBtn: document.getElementById('lisSubmitBtn')
    };

    let subDepartments = [];
    let services = [];

    function escapeHtml(str) {
        if (!str) return '';
        const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
        return String(str).replace(/[&<>"']/g, m => map[m]);
    }

    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `lis-alert lis-alert-${type}`;
        const icon = type === 'success' ? 'fa-check-circle' : 'fa-triangle-exclamation';
        alertDiv.innerHTML = `<i class="fa-solid ${icon}"></i> <span>${escapeHtml(message)}</span>`;
        
        elements.alertContainer.appendChild(alertDiv);
        setTimeout(() => alertDiv.remove(), 4000);
    }

    // Dynamic Retrieval Engine
    async function loadMatrixData() {
        try {
            const response = await fetch(API.FETCH);
            if (!response.ok) throw new Error('API communication error.');
            
            const res = await response.json();
            if (!res.success) throw new Error(res.message);

            subDepartments = res.data.sub_departments;
            services = res.data.services;
            
            renderLeftTable(services);
            renderRightBoard();
        } catch (err) {
            console.error(err);
            showAlert('error', 'Initialization Failed: ' + err.message);
            elements.tableBody.innerHTML = `<tr><td colspan="2" style="text-align:center; padding:20px; color:#ef4444;">Could not sync dashboard data layers.</td></tr>`;
        }
    }

    // Render Left Form Elements
    function renderLeftTable(servicesList) {
        if (servicesList.length === 0) {
            elements.tableBody.innerHTML = `<tr><td colspan="2" style="text-align:center; padding:20px;">No operational records found.</td></tr>`;
            return;
        }

        elements.tableBody.innerHTML = servicesList.map(service => {
            const options = subDepartments.map(dept => `
                <option value="${dept.id}" ${service.lab_sub_dept_id == dept.id ? 'selected' : ''}>
                    ${escapeHtml(dept.sub_dept_name)}
                </option>
            `).join('');

            return `
                <tr class="lis-test-row">
                    <td><strong>${escapeHtml(service.service_name)}</strong></td>
                    <td>
                        <select name="sub_dept_mapping[${service.service_id}]" class="lis-select">
                            <option value="0">-- Unassigned / Hold --</option>
                            ${options}
                        </select>
                    </td>
                </tr>
            `;
        }).join('');
    }

    // Render Right Verified Display Panels
    function renderRightBoard() {
        if (!elements.liveBoard) return;

        // Create Unassigned Bench Card First
        const unassignedList = services.filter(s => !s.lab_sub_dept_id || s.lab_sub_dept_id == 0);
        let boardHtml = `
            <div class="lis-board-card" style="border-left: 4px solid #64748b; background: #fff;">
                <div class="lis-board-card-header">
                    <span><i class="fa-solid fa-circle-question" style="color:#64748b;"></i> Unassigned Pool</span>
                    <span class="lis-board-count" style="background:#f1f5f9;">${unassignedList.length}</span>
                </div>
                <div class="lis-board-card-body">
                    ${unassignedList.length > 0 
                        ? unassignedList.map(s => `<div class="lis-board-item" style="border-color:#cbd5e1;"><i class="fa-solid fa-xs fa-circle" style="color:#94a3b8;"></i> ${escapeHtml(s.service_name)}</div>`).join('')
                        : '<div class="lis-board-empty">All diagnostics successfully allocated.</div>'}
                </div>
            </div>
        `;

        // Render Cards for Active Sub-Departments
        boardHtml += subDepartments.map(dept => {
            const assigned = services.filter(s => s.lab_sub_dept_id == dept.id);
            return `
                <div class="lis-board-card" style="border-left: 4px solid #1e40af;">
                    <div class="lis-board-card-header">
                        <span><i class="fa-solid fa-flask-vial" style="color:#1e40af;"></i> ${escapeHtml(dept.sub_dept_name)}</span>
                        <span class="lis-board-count" style="background:#eff6ff; color:#1e40af;">${assigned.length}</span>
                    </div>
                    <div class="lis-board-card-body">
                        ${assigned.length > 0 
                            ? assigned.map(s => `<div class="lis-board-item"><i class="fa-solid fa-vial" style="color:#b91c1c; font-size:10px;"></i> ${escapeHtml(s.service_name)}</div>`).join('')
                            : '<div class="lis-board-empty">No investigations mapped to this workstation bench.</div>'}
                    </div>
                </div>
            `;
        }).join('');

        elements.liveBoard.innerHTML = boardHtml;
    }

    // Real-Time Query Filter
    elements.searchInput?.addEventListener('input', (e) => {
        const filter = e.target.value.toLowerCase();
        document.querySelectorAll('.lis-test-row').forEach(row => {
            const text = row.querySelector('strong').textContent.toLowerCase();
            row.style.display = text.includes(filter) ? "" : "none";
        });
    });

    // Form Processing Transmission
    elements.mappingForm?.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const origBtnText = elements.submitBtn.innerHTML;
        elements.submitBtn.disabled = true;
        elements.submitBtn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i> Synchronizing...`;

        try {
            const response = await fetch(API.UPDATE, {
                method: 'POST',
                body: new FormData(elements.mappingForm)
            });
            
            const res = await response.json();
            if (!res.success) throw new Error(res.message);

            showAlert('success', res.message);
            await loadMatrixData(); // Dynamic double-column interface reload
        } catch (err) {
            showAlert('error', err.message || 'Transmission failed.');
        } finally {
            elements.submitBtn.disabled = false;
            elements.submitBtn.innerHTML = origBtnText;
        }
    });

    loadMatrixData();
});