(function() {
    // Prevent modular namespace bleeding across runtime lifecycles
    window.initReferenceRangesModule = function() {
        const dropdown = document.getElementById('paramSelectDropdown');
        const form = document.getElementById('addReferenceRangeForm');
        const rightPanel = document.querySelector('.lis-panel-right');

        if (!dropdown) return;

        // Strip previous event hooks to prevent cross-fire loops during SPA state mutations
        dropdown.removeEventListener('change', window.handleParamDropdownChange);
        dropdown.addEventListener('change', window.handleParamDropdownChange);

        if (form) {
            form.removeEventListener('submit', window.handleRangeFormSubmit);
            form.addEventListener('submit', window.handleRangeFormSubmit);
        }

        if (rightPanel) {
            rightPanel.removeEventListener('click', window.handleTableActionClicks);
            rightPanel.addEventListener('click', window.handleTableActionClicks);
        }

        // Auto-run structural sync engine if direct deep link includes parameter state maps
        if (window.currentSelectedParamId && window.currentSelectedParamId > 0) {
            window.syncRangesUiMatrix(window.currentSelectedParamId);
        }
    };

    window.handleParamDropdownChange = function(e) {
        const paramId = parseInt(e.target.value) || 0;
        window.currentSelectedParamId = paramId;

        const leftFormBlock = document.getElementById('addNewRuleContainer');
        const hiddenIdInput = document.getElementById('hiddenParameterId');

        if (paramId <= 0) {
            if (leftFormBlock) leftFormBlock.style.display = 'none';
            document.getElementById('rangesTableContainer').innerHTML = `
                <div id="selectionPlaceholderNotice" style="text-align:center; padding:80px 20px; color:#94a3b8;">
                    <i class="fa-solid fa-hand-pointer" style="font-size:48px; margin-bottom:16px; color:#e2e8f0;"></i><br>
                    <span style="font-size: 15px; font-weight: 500;">Please select a parameter from the left panel to examine or construct range metrics.</span>
                </div>`;
            return;
        }

        if (hiddenIdInput) hiddenIdInput.value = paramId;
        if (leftFormBlock) leftFormBlock.style.display = 'block';

        window.syncRangesUiMatrix(paramId);
    };

    window.syncRangesUiMatrix = function(paramId) {
        const appRoot = window.rimaxAppRoot || '/rimax/application';
        const url = `${appRoot}/dripend/systemSetup/laboratory/fetchReferenceRanges.php?action=fetch&param_id=${paramId}`;

        fetch(url)
        .then(res => res.json())
        .then(res => {
            const container = document.getElementById('rangesTableContainer');
            const unitHeader = document.getElementById('volumetricUnitHeader');

            if (unitHeader && res.status === 'success') {
                unitHeader.textContent = `Normal Reference Range limits (${res.unit_of_measure})`;
            }

            if (res.status === 'success') {
                window.renderRangesTable(res.data);
            } else {
                if (container) {
                    container.innerHTML = `<div class="lis-alert lis-alert-error" style="display:flex;"><i class="fa-solid fa-circle-exclamation"></i> ${res.message}</div>`;
                }
            }
        })
        .catch(err => {
            console.error("UI Synchronization stream failure:", err);
        });
    };

    window.renderRangesTable = function(data) {
        const container = document.getElementById('rangesTableContainer');
        
        let html = `
            <table class="lis-table">
                <thead>
                    <tr>
                        <th width="30%">Gender / Age Context</th>
                        <th width="40%">Configured Ranges</th>
                        <th width="15%">Status</th>
                        <th width="15%" style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="rangesTableBody">`;

        if (!data || data.length === 0) {
            html += `
                <tr>
                    <td colspan="4" style="text-align:center; padding:40px; color:#94a3b8;">
                        <i class="fa-solid fa-ruler-horizontal" style="font-size:32px; margin-bottom:12px; color:#cbd5e1;"></i><br>
                        <span style="font-size:14px; font-weight:500;">No ranges defined for this parameter configuration.</span>
                    </td>
                </tr>`;
        } else {
            data.forEach(row => {
                const minVal = row.min_value !== null ? parseFloat(row.min_value) : '0';
                const maxVal = row.max_value !== null ? parseFloat(row.max_value) : '∞';
                const isActive = parseInt(row.is_active) === 1;

                let critBlock = '';
                if (row.critical_low !== null) critBlock += `Crit Low: &lt; ${parseFloat(row.critical_low)}<br>`;
                if (row.critical_high !== null) critBlock += `Crit High: &gt; ${parseFloat(row.critical_high)}`;

                html += `
                <tr data-row-id="${row.id}">
                    <td>
                        <span style="font-weight:700; color:#1e293b; display:block; margin-bottom:4px;">${window.escapeHtml(row.gender_target)}</span>
                        <span style="font-size:11px; color:#64748b;"><i class="fa-solid fa-clock"></i> ${row.min_age_years} to ${row.max_age_years} yrs</span>
                    </td>
                    <td>
                        <span style="background:#e0f2fe; color:#0369a1; padding:4px 10px; border-radius:6px; font-weight:700; font-size:12px; display:inline-block; margin-bottom:6px; border:1px solid #bae6fd;">
                            ${minVal} - ${maxVal}
                        </span>
                        <div style="font-size:11px; color:#b91c1c; line-height:1.5; font-weight:500;">${critBlock}</div>
                    </td>
                    <td>
                        <span class="lis-badge ${isActive ? 'bg-green' : 'bg-red'}">${isActive ? 'Active' : 'Inactive'}</span>
                    </td>
                    <td>
                        <div class="action-group">
                            <button type="button" class="btn-icon b-toggle btn-toggle-status-range" data-id="${row.id}" data-status="${row.is_active}" title="Toggle Visibility">
                                <i class="fa-solid ${isActive ? 'fa-ban' : 'fa-check'}"></i>
                            </button>
                            <button type="button" class="btn-icon b-delete btn-delete-range-rule" data-id="${row.id}" title="Drop Rule">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>`;
            });
        }

        html += `</tbody></table>`;
        if (container) container.innerHTML = html;
    };

    window.handleRangeFormSubmit = function(e) {
        e.preventDefault();
        const form = e.currentTarget;
        const submitBtn = document.getElementById('btnSaveRangeRule');
        const errAlert = document.getElementById('rangeGlobalErrorAlert');
        const successAlert = document.getElementById('rangeGlobalSuccessAlert');

        errAlert.style.display = 'none';
        successAlert.style.display = 'none';

        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';
        }

        const formData = new FormData(form);
        formData.append('action', 'add'); // Aligns smoothly with Backend Case Router

        const appRoot = window.rimaxAppRoot || '/rimax/application';

        fetch(`${appRoot}/dripend/systemSetup/laboratory/fetchReferenceRanges.php`, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                successAlert.innerHTML = `<i class="fa-solid fa-circle-check"></i> ${res.message}`;
                successAlert.style.display = 'flex';
                form.reset();
                
                // Keep context reference alive when clearing out metrics
                const hiddenInput = document.getElementById('hiddenParameterId');
                if (hiddenInput) hiddenInput.value = window.currentSelectedParamId;

                window.syncRangesUiMatrix(window.currentSelectedParamId);
                setTimeout(() => { successAlert.style.display = 'none'; }, 2000);
            } else {
                errAlert.innerHTML = `<i class="fa-solid fa-circle-exclamation"></i> ${res.message}`;
                errAlert.style.display = 'flex';
            }
        })
        .catch(err => {
            errAlert.innerHTML = `<i class="fa-solid fa-wifi"></i> Communication pipe error: ${err.message}`;
            errAlert.style.display = 'flex';
        })
        .finally(() => {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> Save Range Rule';
            }
        });
    };

    window.handleTableActionClicks = function(e) {
        const toggleBtn = e.target.closest('.btn-toggle-status-range');
        const deleteBtn = e.target.closest('.btn-delete-range-rule');
        const appRoot = window.rimaxAppRoot || '/rimax/application';

        if (toggleBtn) {
            const ruleId = toggleBtn.getAttribute('data-id');
            const status = toggleBtn.getAttribute('data-status');
            
            const params = new URLSearchParams();
            params.append('action', 'toggle');
            params.append('id', ruleId);
            params.append('current_status', status);

            fetch(`${appRoot}/dripend/systemSetup/laboratory/fetchReferenceRanges.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: params
            })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    window.syncRangesUiMatrix(window.currentSelectedParamId);
                } else {
                    alert(res.message);
                }
            })
            .catch(err => console.error("Toggle connection error:", err));
        }

        if (deleteBtn) {
            if (!confirm("Are you absolutely sure you want to delete this reference range rule?")) return;
            const ruleId = deleteBtn.getAttribute('data-id');

            const params = new URLSearchParams();
            params.append('action', 'delete');
            params.append('id', ruleId);

            fetch(`${appRoot}/dripend/systemSetup/laboratory/fetchReferenceRanges.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: params
            })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    window.syncRangesUiMatrix(window.currentSelectedParamId);
                } else {
                    alert(res.message);
                }
            })
            .catch(err => console.error("Delete connection error:", err));
        }
    };

    window.escapeHtml = function(text) {
        if (!text) return '';
        return text.toString().replace(/&/g, "&amp;")
                             .replace(/</g, "&lt;")
                             .replace(/>/g, "&gt;")
                             .replace(/"/g, "&quot;")
                             .replace(/'/g, "&#039;");
    };
})();