// Function to populate the model select dropdown
function ai_app_onsite_get_model_list() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // Handle success response
                var response = JSON.parse(xhr.responseText);
                populateModelSelect(response);
            }
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_model_list');
}

function populateModelSelect(modelsGrouped) {
    const modelSelect = document.getElementById('model');
    modelSelect.innerHTML = '';

    const placeholder = document.createElement('option');
    placeholder.value = '';
    placeholder.textContent = 'Please select Model';
    modelSelect.appendChild(placeholder);

    Object.keys(modelsGrouped).forEach(category => {
        const optGroup = document.createElement('optgroup');
        optGroup.label = category;

        modelsGrouped[category].forEach(modelObj => {
            const option = document.createElement('option');
            option.value = modelObj.model;
            option.textContent = modelObj.model + ' – ' + modelObj.description;

            option.dataset.supportedParameters = JSON.stringify(modelObj.supported_parameters);
            option.dataset.apiEndpoint = modelObj.endpoint;
            option.dataset.description = modelObj.description;

            optGroup.appendChild(option);
        });

        modelSelect.appendChild(optGroup);
    });
}

//Start get model settings from db js
function ai_app_onsite_get_model_settings() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // Handle success response
                var response = JSON.parse(xhr.responseText);
                if (response.status === '404') {
                    var saveKpenapiKeyBtn = document.getElementById('save-openapi-key');
                    var apiDisableBtn     = document.getElementById("api-disable-btn");
                    var apiKeyMgtBtn      = document.getElementById("api-key-management");
                    var openaiKey         = document.getElementById('openai-key');
                    var openaiKeyHidden   = document.getElementById('openai-key-hidden');

                    populateModelSelect(response.models_list);

                    openaiKey.value = '';
                    openaiKeyHidden.value = '';

                    const engineDropdown = document.getElementById('model');
                    var dependentFieldsWrapper = document.getElementById('model-dependent-fields');

                    // Keep default placeholder selected
                    engineDropdown.value = '';

                    // Add Highlight Class
                    engineDropdown.classList.add('border-danger');

                    // Show Helper Text
                    document.getElementById('model-help-text').innerHTML = 'Please select a model to continue';

                    dependentFieldsWrapper.classList.add('blurred');

                    //hide the api key mgt button
                    apiKeyMgtBtn.style.display = 'none';


                    // Optional: Disable other fields until model selected
                    document.querySelectorAll('.model-dependent').forEach(function (el) {
                        el.disabled = true;
                    });

                    // Listen for change
                    engineDropdown.addEventListener('change', function () {
                        if (engineDropdown.value !== '') {
                            engineDropdown.classList.remove('border-danger');
                            document.getElementById('model-help-text').innerHTML = '';

                            // Enable fields
                            dependentFieldsWrapper.classList.remove('blurred');
                            document.querySelectorAll('#model-dependent-fields').forEach(function (el) {
                                el.disabled = false;
                            });

                            console.log('Model selected:', engineDropdown.value);

                            const modalElement = document.getElementById('apiinfoModal');
                            const modalInstance = new bootstrap.Modal(modalElement);
                            modalInstance.show()

                            apiKeyMgtBtn.style.display = 'block';


                            //saveKpenapiKeyBtn.disabled = true;
                            // apiDisableBtn.disabled = true;
                            // apiDisableBtn.checked = false;
                        }
                    });

                    return;
                } else {
                    document.getElementById('model').classList.remove('border-danger');
                    document.getElementById('model-help-text').innerHTML = '';
                    
                    document.getElementById('model-dependent-fields').classList.remove('blurred');
                    document.querySelectorAll('.model-dependent').forEach(function (el) {
                        el.disabled = false;
                    });
                    
                    document.getElementById("api-key-management").style.display = 'block';
                    
                    const apiDisableBtn = document.getElementById("api-disable-btn");
                    apiDisableBtn.disabled = false;
                    
                    // You can also re-enable save if needed
                    const saveKpenapiKeyBtn = document.getElementById('save-openapi-key');
                    saveKpenapiKeyBtn.removeAttribute('disabled'); // or saveKpenapiKeyBtn.disabled = false;
                }

                // Accessing the first object in the array
                var firstObject = response[0];

                var model       = firstObject.model;
                var max_tokens  = firstObject.max_tokens;
                var p_penalty   = firstObject.p_penalty;
                var f_penalty   = firstObject.f_penalty;
                var temperature = firstObject.temperature;
                var top_p       = firstObject.top_p;
                var openai_key  = firstObject.openai_key;
                var key_status  = firstObject.key_status;

                populateModelSelect(firstObject.models_list);

                if (key_status == 'false') {
                    document.getElementById('key-status').textContent = 'Disabled';
                    var element = document.getElementById('key-status');
                    element.textContent = 'Disabled';
                    element.style.color = 'red';
                    document.getElementById("api-disable-btn").checked = false;

                } else {
                    var element = document.getElementById('key-status');
                    element.textContent = 'Enabled';
                    element.style.color = 'Green';
                    document.getElementById("api-disable-btn").checked = true;

                }

                var openaiKey         = document.getElementById('openai-key');
                var openaiKeyHidden   = document.getElementById('openai-key-hidden');
                var saveKpenapiKeyBtn = document.getElementById('save-openapi-key');
                var apiDisableBtn     = document.getElementById("api-disable-btn");

                // Check if the value is null or empty
                if (!openai_key) {
                    openaiKey.value = '';
                    openaiKeyHidden.value = '';
                    
                    const modalElement = document.getElementById('apiinfoModal');
                    const modalInstance = new bootstrap.Modal(modalElement);
                    modalInstance.show();
                    //saveKpenapiKeyBtn.disabled = true;
                    apiDisableBtn.disabled = true;
                    apiDisableBtn.checked = false;

                } else {
                    openaiKey.value = maskAPIKey(openai_key);
                    openaiKeyHidden.value = openai_key;
                    var element = document.getElementById('text-switch');

                    if (key_status == 'false') {
                        element.textContent = 'Disabled';
                        element.style.color = 'Red';
                        apiDisableBtn.checked = false;

                    } else {
                        element.textContent = 'Enabled';
                        element.style.color = 'Green';
                        apiDisableBtn.checked = true;

                    }

                }

                // Collect error messages
                var errors = [];
                if (model === '' || model === 'Select') {
                    errors.push('Please select Model.');
                }

                // If there are errors, display them and return
                if (errors.length > 0) {
                    errors.forEach(function (error) {
                        // Find the corresponding error container and display the message
                        if (error === 'Please select Model.') {
                            document.getElementById('model-error').textContent = error;
                        }
                    });
                    return;
                }

                document.getElementById('model').value = model;
                document.getElementById('max-tokens').value = max_tokens;
                document.getElementById('temperature').value = temperature;
                document.getElementById('top-p').value = top_p;
                document.getElementById('f-penalty').value = f_penalty;
                document.getElementById('p-penalty').value = p_penalty;

                initializeFormChangeTracker();
            }

            document.getElementById('model').setAttribute('name', 'model');
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_model_settings');
}

function updateParameterFieldsVisibilityAndValues() {
    const modelSelect = document.getElementById('model');
    const selectedOption = modelSelect.options[modelSelect.selectedIndex];
    if (!selectedOption || !selectedOption.value) return;

    // --- Show/Hide Logic ---
    const supportedParams = JSON.parse(selectedOption.dataset.supportedParameters || '[]');
    const allFields = {
        temperature: document.getElementById('temperature').closest('.form-group'),
        top_p: document.getElementById('top-p').closest('.form-group'),
        f_penalty: document.getElementById('f-penalty').closest('.form-group'),
        p_penalty: document.getElementById('p-penalty').closest('.form-group'),
        max_tokens: document.getElementById('max-tokens').closest('.form-group')
    };

    Object.values(allFields).forEach(field => {
        if (field) field.style.display = 'none';
    });

    supportedParams.forEach(param => {
        switch (param) {
            case 'temperature':
                if (allFields.temperature) allFields.temperature.style.display = '';
                break;
            case 'top_p':
                if (allFields.top_p) allFields.top_p.style.display = '';
                break;
            case 'frequency_penalty':
                if (allFields.f_penalty) allFields.f_penalty.style.display = '';
                break;
            case 'presence_penalty':
                if (allFields.p_penalty) allFields.p_penalty.style.display = '';
                break;
            case 'max_tokens':
            case 'max_output_tokens':
                if (allFields.max_tokens) allFields.max_tokens.style.display = '';
                break;
        }
    });

    // --- Values from localStorage ---
    let savedSettings = localStorage.getItem('settings');
    if (savedSettings) {
        let settings = JSON.parse(savedSettings);
        if (modelSelect.value === settings.model) {
            document.getElementById('temperature').value = settings.temperature;
            document.getElementById('top-p').value = settings.top_p;
            document.getElementById('f-penalty').value = settings.f_penalty;
            document.getElementById('p-penalty').value = settings.p_penalty;
            document.getElementById('max-tokens').value = settings.max_tokens;
        } else {
            document.getElementById('temperature').value = '0.7';
            document.getElementById('top-p').value = '1';
            document.getElementById('f-penalty').value = '0';
            document.getElementById('p-penalty').value = '0';
            document.getElementById('max-tokens').value = '3000';
        }
    }
}

function initializeFormChangeTracker() {
    const appModalSettingsformTracker = trackFormChanges('#ai_app_onsite_reset_modal-setting');
    window.FormChangeRegistry.register('app_modal_settings', appModalSettingsformTracker, 'model-settings');

    document.getElementById('save_ai_app_modal_settings_data').addEventListener('click', function () {
        appModalSettingsformTracker.reset(); 
    });
}

//Start save model settings JS
function ai_app_onsite_save_model_settings() {
    // Clear all previous error messages
    document.querySelectorAll('.fields-error').forEach(function (error) {
        error.textContent = '';
    });

    // Show loader
    document.getElementById("loader").style.display = 'flex';

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var messageContainer = document.getElementById('model-settings-msg-container');
            // Hide loader after 5 seconds
            setTimeout(function () {
                document.getElementById("loader").style.display = 'none';

                if (xhr.status === 200) {
                    // Handle the response from the server
                    var response = JSON.parse(xhr.responseText);

                    let temperatureSettings = {
                        temperature: response.data.data.temperature,
                        top_p: response.data.data.top_p,
                        f_penalty: response.data.data.f_penalty,
                        p_penalty: response.data.data.p_penalty,
                        max_tokens: response.data.data.max_tokens,
                        model: response.data.data.model
                    };
                    localStorage.setItem('settings', JSON.stringify(temperatureSettings));


                    if (response.data.status) {
                        // Show success message
                        messageContainer.innerHTML = '<span style="color: green;"> ' + response.data.message + '</span>';
                    } else {
                        // Show error message if request fails
                        messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                    }
                } else {
                    // Show error message if request fails
                    messageContainer.innerHTML = '<span style="color: red;">Error: Failed to save data</span>';
                }
                // Hide message after 3 seconds
                setTimeout(function () {
                    messageContainer.innerHTML = '';
                }, 3000);
            }, 2000);
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);

    var formData = new FormData();

    // Gather form data api-key
    formData.append('action', 'ai_app_onsite_save_model_settings');
    formData.append('model', document.getElementById("model") ? document.getElementById("model").value : "");
    formData.append('max-tokens', document.getElementById("max-tokens") ? document.getElementById("max-tokens").value : "");
    formData.append('temperature', document.getElementById("temperature") ? document.getElementById("temperature").value : "");
    formData.append('top-p', document.getElementById("top-p") ? document.getElementById("top-p").value : "");
    formData.append('f-penalty', document.getElementById('f-penalty').value ? document.getElementById('f-penalty').value : "");
    formData.append('p-penalty', document.getElementById('p-penalty').value ? document.getElementById('p-penalty').value : "");

    // Include nonce field value
    formData.append('ai_app_onsite_model_settings_nonce_field', document.getElementById("ai_app_onsite_model_settings_nonce_field").value);

    xhr.send(formData);
}

// Function to update the input value
function updateApiKeyInput() {
    const input = document.getElementById("openai-key");
    const value = input.value;

    // Check if the entered value has more than 6 characters
    if (value.length > 6) {
        // Get the first two characters
        const prefix = value.substring(0, 2);

        // Get the last four characters
        const suffix = value.substring(value.length - 4);

        // Create the masked value
        const maskedValue = prefix + "*".repeat(value.length - 6) + suffix;

        // Update the input value
        input.value = maskedValue;
    }
}

// Function to send the original API key to the server
function save_openapi_key() {
    // Clear all previous error messages
    document.querySelectorAll('.fields-error').forEach(function (error) {
        error.textContent = '';
    });

    // Get form fields
    var openaiKeyError = document.getElementById('openai-key').value.trim();
    var openaiKeyHidden = document.getElementById('openai-key-hidden').value.trim();

    // Collect error messages
    var errors = [];
    if (openaiKeyError === '' || openaiKeyHidden === '') {
        errors.push('API key is required.');
    }

    // If there are errors, display them and return
    if (errors.length > 0) {
        errors.forEach(function (error) {
            // Find the corresponding error container and display the message
            if (error === 'API key is required.') {
                document.getElementById('openai-key-error').textContent = error;
            }
        });
        return;
    }


    document.getElementById("loader").style.display = 'flex';

    var messageContainer = document.getElementById('modal-message-container');

    // Get the API key value from the input field
    const api_Key = document.getElementById("openai-key-hidden") ? document.getElementById("openai-key-hidden").value : "";
    const api_status = document.getElementById("api-disable-btn") ? document.getElementById("api-disable-btn").checked : "";
    const api_nonce = document.getElementById("ai_app_onsite_model_settings_nonce_field") ? document.getElementById("ai_app_onsite_model_settings_nonce_field").value : "";
    const engineDropdown = document.getElementById('model');

    // Send the API key to the server using an AJAX request
    fetch(myPluginAjax.ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded', // Set the content type
        },
        body: new URLSearchParams({

            action       : 'ai_app_onsite_save_openai_key',           // Action for the server-side function
            api_key      : api_Key,
            api_status   : api_status,
            api_Key_nonce: api_nonce,
            engine_model : engineDropdown.value,

        })
    })
        .then(response => {
            setTimeout(function () {
                document.getElementById("loader").style.display = 'none';

                if (!response.ok) {
                    throw new Error('Failed to save API key');
                }
                messageContainer.innerHTML =
                    '<span style="color: green;"> API key saved successfully!</span>';
            }, 2000);

            // Hide message after 3 seconds
            setTimeout(function () {
                var modal = document.getElementById('apiinfoModal');
                // Close the modal
                jQuery(modal).modal('hide');
                messageContainer.innerHTML = '';
            }, 3000);
        })
        .catch(error => {
            console.error('Error:', error.message);
            messageContainer.innerHTML = '<span style="color: red;">Failed to save API key!</span>';
            // Hide loader if there's an error
            document.getElementById("loader").style.display = 'none';
        });
}

document.addEventListener('DOMContentLoaded', function () {
    const maskToggle = document.getElementById('maskToggle');
    const openaiKeyInput = document.getElementById('openai-key');
    const openaiKeyHidden = document.getElementById('openai-key-hidden');

    if (maskToggle && openaiKeyInput && openaiKeyHidden) {
        // Initial check to hide maskToggle text if no value is present in openaiKeyHidden
        updateMaskToggleVisibility();

        // Add event listener for maskToggle click
        maskToggle.addEventListener('click', function () {
            if (maskToggle.textContent.trim() === 'Show Key') {
                // Show the full API key
                openaiKeyInput.value = openaiKeyHidden.value;
                maskToggle.textContent = 'Hide Key';
            } else {
                // Mask the API key
                openaiKeyInput.value = maskAPIKey(openaiKeyHidden.value);
                maskToggle.textContent = 'Show Key';
            }
        });

        // Function to update the visibility of maskToggle text
        function updateMaskToggleVisibility() {
            if (!openaiKeyHidden.value.trim()) {
                maskToggle.textContent = ''; // Hide text if no value is present
            } else {
                maskToggle.textContent = 'Show Key'; // Default text when value exists
            }
        }

        // Observe changes to the value of openaiKeyHidden
        const observer = new MutationObserver(updateMaskToggleVisibility);
        observer.observe(openaiKeyHidden, { attributes: true, attributeFilter: ['value'] });
    }

    // Helper function to mask the API key
    function maskAPIKey(input) {
        var maxLength = 40;
        var len = input.length;
        if (len <= 6) return input;
        var maskedPart = input.slice(0, 2) + '*'.repeat(Math.min(len - 6, maxLength - 6)) + input.slice(len - 4);
        return maskedPart.slice(0, maxLength);
    }
});

document.addEventListener('DOMContentLoaded', function () {
    const copyButton = document.querySelector('.copy-api-key');
    if (copyButton) {
        copyButton.addEventListener('click', ai_app_onsite_copy_openapi_key);
    }
});

function ai_app_onsite_copy_openapi_key() {
    var openai_key = document.getElementById('openai-key');
    var openaiKeyHidden = document.getElementById('openai-key-hidden');
    var copyIcon = document.querySelector('.copy-api-key .assets-copy-icon');
    const maskToggle = document.getElementById('maskToggle');
    if (!openai_key || !openaiKeyHidden || !copyIcon) {
        console.error('Required elements not found: openai-key, openai-key-hidden, or copy-icon');
        return;
    }

    // Temporarily set the visible input field to the full API key
    openai_key.value = openaiKeyHidden.value;

    try {
        // Select the text field
        openai_key.select();
        openai_key.setSelectionRange(0, openai_key.value.length); // For mobile devices

        // Copy the text inside the text field
        if (document.execCommand('copy')) {

            // Change the icon color by adding a class
            copyIcon.classList.add('icon-success');

            // Remove the class after 2 seconds
            setTimeout(() => {
                copyIcon.classList.remove('icon-success');
            }, 2000);
        } else {
            console.error('Failed to copy API key to clipboard.');
        }
    } catch (err) {
        console.error('Error copying API key:', err);
    }
    maskToggle.textContent = 'Hide Key';
    // Restore the masked API key in the visible input field
    openai_key.value = maskAPIKey(openaiKeyHidden.value);
    maskToggle.textContent = 'Show Key';

    // Deselect the input field
    openai_key.blur();
}

function ai_app_onsite_clear_openapi_Key_field() {
    document.getElementById('openai-key').value = "";
    document.getElementById("openai-key-hidden").value = "";

    const apiDisableBtn = document.getElementById('api-disable-btn');
    const apiDisableTxt = document.getElementById('text-switch');

    const keyStatus = document.getElementById('key-status');

    keyStatus.textContent = 'Disabled';
    keyStatus.style.color = 'red';

    apiDisableTxt.textContent = 'Disabled';
    apiDisableTxt.style.color = 'red';

    apiDisableBtn.checked = false;
}

function ai_app_onsite_disable_openapi_key() {
    const api_status = document.getElementById("api-disable-btn").checked;
    const api_Key = document.getElementById("openai-key");

     api_Key.disabled = !!api_status;

}

function ai_app_onsite_get_openapi_data() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // Handle success response
                var response = JSON.parse(xhr.responseText);

                // Accessing the first object in the array
                var firstObject = response[0];

                // Accessing properties of the first object
                var openai_key = firstObject.openai_key;
                var key_status = firstObject.key_status;

                if (key_status == 'false') {
                    document.getElementById('key-status').textContent = 'DISABLED';
                    document.getElementById("api-disable-btn").checked = false;
                    document.getElementsByClassName('text-switch')[0].textContent = 'DISABLED';
                    document.getElementsByClassName('text-switch')[0].style.color = 'red';
                } else {
                    document.getElementById('key-status').textContent = 'ENABLED';
                    document.getElementsByClassName('text-switch')[0].textContent = 'ENABLED';
                    document.getElementsByClassName('text-switch')[0].style.color = 'green';
                    document.getElementById("api-disable-btn").checked = true;
                }

                var errors = [];
                if (openai_key === '') {
                    errors.push('Please set OpenAI Key.');
                }

                // If there are errors, display them and return
                if (errors.length > 0) {
                    errors.forEach(function (error) {
                        if (error === 'Please set OpenAI Key.') {
                            document.getElementById('manage-key-error').textContent = error;
                        }
                    });
                    return;
                }

                document.getElementById('openai-key').value = maskAPIKey(openai_key);
                document.getElementById('openai-key-hidden').value = openai_key;
            } else {
                // Handle error response
                alert('Error occurred: ' + xhr.responseText);
            }
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_openapi_data');
}

function maskAPIKey(input) {
    var maxLength = 40;
    var len = input.length;
    if (len <= 6) return input;
    var maskedPart = input.slice(0, 2) + '*'.repeat(Math.min(len - 6, maxLength - 6)) + input.slice(len - 4);
    return maskedPart.slice(0, maxLength);
}

// Add event listener for input changes
var openaiKeychange = document.getElementById('openai-key')
if (openaiKeychange) {
    openaiKeychange.onchange = handleInputChange;
}

// Function to initialize the modal with original API key value
function handleInputChange() {
    const inputElement = document.getElementById('openai-key');
    const openaiKeyHidden = document.getElementById('openai-key-hidden');
    const openaiKeyError = document.getElementById('openai-key-error');
    const apiDisableText = document.getElementById('text-switch');
    const keyStatus = document.getElementById('key-status');
    const apiDisableBtn = document.getElementById('api-disable-btn');

    if (inputElement.value) {
        // Clear error message
        openaiKeyError.textContent = '';

        // Update hidden input and mask the visible input
        openaiKeyHidden.value = inputElement.value;
        inputElement.value = maskAPIKey(inputElement.value);

        // Update status text and color
        const statusText = 'Enabled';
        const statusColor = 'green';
        apiDisableText.textContent = statusText;
        apiDisableText.style.color = statusColor;
        keyStatus.textContent = statusText;
        keyStatus.style.color = statusColor;
        apiDisableBtn.checked = true;
    }
}

document.getElementById('api-disable-btn').addEventListener('change', function () {
    if (this.checked == true) {
        var switchText = document.getElementsByClassName('text-switch')[0];
        switchText.textContent = 'ENABLED';
        switchText.style.color = 'Green';
        var element = document.getElementById('key-status');
        element.textContent = 'ENABLED';
        element.style.color = 'Green';
    } else {

        var switchText = document.getElementsByClassName('text-switch')[0];
        switchText.textContent = 'DISABLED';
        switchText.style.color = 'Red';
        var element = document.getElementById('key-status');
        element.textContent = 'DISABLED';
        element.style.color = 'Red';
    }
})

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('model').addEventListener('change', updateParameterFieldsVisibilityAndValues);
});

document.addEventListener('DOMContentLoaded', function () {
    const hiddenKeyInput = document.getElementById('openai-key-hidden');
    const removeKeyButton = document.getElementById('key-remove-btn');

    if (hiddenKeyInput && removeKeyButton) {
        // Initial check when the page loads
        updateRemoveButtonVisibility();

        // Periodically check if the value of the hidden input changes dynamically
        const observer = new MutationObserver(updateRemoveButtonVisibility);
        observer.observe(hiddenKeyInput, { attributes: true, attributeFilter: ['value'] });

        // Function to update the visibility of the remove button
        function updateRemoveButtonVisibility() {
            if (!hiddenKeyInput.value.trim()) {
                removeKeyButton.style.display = 'none';
            } else {
                removeKeyButton.style.display = 'flex';
            }
        }
    }

    const modalElement = document.getElementById('apiinfoModal');
    modalElement.addEventListener('hidden.bs.modal', function () {
        // Remove lingering backdrop
        document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
      
        // Remove modal-open class and inline styles
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
    }, { once: true });
});
