(function() {
    window.initAddLabParameter = function() {
        const form = document.getElementById('addLabParameterForm');
        const selector = document.getElementById('result_type');
        
        if (!form || !selector) return;

        selector.removeEventListener('change', window.handleResultTypePanelToggling);
        selector.addEventListener('change', window.handleResultTypePanelToggling);

        form.removeEventListener('submit', window.submitLabParameterViaAjax);
        form.addEventListener('submit', window.submitLabParameterViaAjax);

        window.handleResultTypePanelToggling();
    };

    window.handleResultTypePanelToggling = function() {
        const currentType = document.getElementById('result_type').value;
        const numericPanel = document.getElementById('numeric_ranges_panel');
        const optionsPanel = document.getElementById('options_panel');
        const unitInput = document.getElementById('unit_of_measure');

        if (!numericPanel || !optionsPanel || !unitInput) return;

        document.getElementById('addParamErrorAlert').style.display = 'none';

        if (currentType === 'Numeric') {
            numericPanel.style.display = 'block';
            optionsPanel.style.display = 'none';
            unitInput.disabled = false;
            unitInput.style.backgroundColor = '#f8fafc';
        } else if (currentType === 'Options') {
            numericPanel.style.display = 'none';
            optionsPanel.style.display = 'block';
            unitInput.value = ''; 
            unitInput.disabled = true;
            unitInput.style.backgroundColor = '#e2e8f0';
        } else {
            numericPanel.style.display = 'none';
            optionsPanel.style.display = 'none';
            unitInput.disabled = false;
            unitInput.style.backgroundColor = '#f8fafc';
        }
    };

    window.submitLabParameterViaAjax = function(event) {
        event.preventDefault();

        const form = event.currentTarget;
        
        // NO HARD CODING: Pull target URL directly from the form tag.
        const actionUrl = form.getAttribute('action'); 
        if (!actionUrl) {
            console.error('Configuration Error: Form requires a valid action endpoint.');
            return;
        }

        const submitBtn = document.getElementById('btnSubmitLabParam');
        const errorAlert = document.getElementById('addParamErrorAlert');
        const successAlert = document.getElementById('addParamSuccessAlert');

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

        const paramNameInput = document.getElementById('parameter_name');
        if (!paramNameInput || paramNameInput.value.trim() === '') {
            errorAlert.innerHTML = '<i class="fa-solid fa-circle-exclamation"></i> Parameter Name is required.';
            errorAlert.style.display = 'flex';
            paramNameInput.focus();
            return;
        }

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

        const formData = new FormData(form);
        
        fetch(actionUrl, {
            method: 'POST',
            body: formData
        })
        .then(res => {
            if (!res.ok) throw new Error('System encountered HTTP networking anomaly code: ' + res.status);
            return 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();
                
                setTimeout(() => {
                    if (typeof loadContent === 'function') {
                        loadContent('Laboratory Settings', 'laboratory/labSetup.php', 'Laboratory', 'system_setup', null, true);
                    } else {
                        window.location.reload();
                    }
                }, 1200);
            } else {
                errorAlert.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> ' + res.message;
                errorAlert.style.display = 'flex';
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> Save Parameter';
                }
            }
        })
        .catch(err => {
            errorAlert.innerHTML = '<i class="fa-solid fa-wifi"></i> Connection failed: ' + err.message;
            errorAlert.style.display = 'flex';
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> Save Parameter';
            }
        });
    };
})();