/* ai_app_get_the_Ai_response */	
function ai_app_onsite_get_the_ai_response() {
var aiappResultWrapper       = document.getElementById('ai-app-result-wrapper');
var aiappTestResponse        = document.getElementById('ai-app-result');
var aiappTestResponseMessage = document.getElementById('ai-app-result-message');
var aiappForm                = document.querySelector('#ai-app-openAi-app-form');
    //Show loader
    var loader = document.getElementById('loader');

    var xhr = new XMLHttpRequest();

    xhr.timeout = 200000;

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // Hide loader after 5 seconds
            setTimeout(function() {
                loader.style.display = 'none';
            }, 3000);
                if (xhr.status === 200) {
                    // Handle the response from the server
                    var response = JSON.parse(xhr.responseText);

                    if (response.success) {
                  
                        aiappTestResponse.innerHTML = response.data;
                        if(response.response_message){
                            aiappTestResponseMessage.innerHTML = response.response_message;
                        }
                        aiappTestResponseMessage.innerHTML =  '<span>'+response.response_message + '</span>';
                        document.getElementById('ai_response_id').value = response.response_id;

                    } else {
                        // Show error message if request fails
                        aiappTestResponse.innerHTML = '<span style="color: red;">Error: ' + response.data + '</span>';
                        document.getElementById('ai_response_id').style.display = 'none';
                    }
                } else {
                    // Show error message if request fails
                    aiappTestResponse.innerHTML = '<span style="color: red;">Error: Something Went Wrong</span>';
                    document.getElementById('ai_response_id').style.display = 'none';

                }
            
             aiappForm.style.display = 'none';
             aiappResultWrapper.style.display = 'block';

        }
    };

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

    if (!validateForm(aiappForm)) {
        return; // Exit if form validation fails
    }else{
           formData = validateForm(aiappForm);
           loader.style.display = 'flex';
        
        // If all required fields are filled, continue with form submission
        
        // Append action to form data
        formData.append('action', 'ai_app_onsite_openAi_api');
        
        // Send the form data
        xhr.send(formData);
    }
}

function refreshPage(){
    window.location.reload();
} 

function validateForm(aiappForm) {
    // Check if form exists
    if (!aiappForm) {
        console.error('Form not found.');
        return false; // Exit if form is not found
    }

    // Create a new FormData object to store form data
    var formData = new FormData();

    // Select all input, select, and textarea elements within the form
    var fields = aiappForm.querySelectorAll('input, select, textarea');
    
    // Flag to keep track of validation status
    var isValid = true;
    
    // Iterate over each field
    fields.forEach(function(field) {
        var errorParagraph = document.getElementById(field.id + '-error'); // Get the error paragraph for this field

        if (!errorParagraph) {
            // console.error('Error paragraph not found for field with ID:', field.id);
            return; // Exit the loop if error paragraph is not found
        }

        // Check if the field is required and its value is empty
        if (field.hasAttribute('required') && field.value.trim() === '') {
            var error = 'This field is required.';
            errorParagraph.textContent = error;
            isValid = false;
            field.classList.add('invalid');
        } else {
            field.classList.remove('invalid');
            errorParagraph.textContent = ''; // Clear error message
        }

        // Check Email validation
        if (field.type === 'email' && field.value.trim() !== '') {
            // Disallow multiple @, require valid domain and TLD
            const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

            if (!emailPattern.test(field.value.trim())) {
                const error = 'Please enter a valid email address.';
                errorParagraph.textContent = error;
                isValid = false;
                field.classList.add('invalid');
            } else {
                field.classList.remove('invalid');
                errorParagraph.textContent = '';
            }
        }

        // Append field's ID, name, and value to the formData object
        formData.append(field.name, field.value);

        // Listen for input/change event to remove error message when field value changes
        field.addEventListener('input', function() {
            if (field.value.trim() !== '') {
                errorParagraph.textContent = ''; // Clear error message if field is not empty
                field.classList.remove('invalid');
            }
        });
    });
    
    // If any required field is empty, show an alert and prevent form submission
    if (!isValid) {
        return false; // Form is invalid
    }

    return formData; // Return form data if form is valid
}

document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        event.preventDefault();
    }
});


document.querySelectorAll('a.open-new-tab').forEach(function (link) {
    link.setAttribute('target', '_blank');
    link.setAttribute('rel', 'noopener noreferrer');
});

const observer = new MutationObserver(function (mutationsList) {
    mutationsList.forEach(function (mutation) {
        mutation.addedNodes.forEach(function (node) {
            if (node.nodeType === 1) {
                if (node.matches('a.open-new-tab')) {
                    node.setAttribute('target', '_blank');
                    node.setAttribute('rel', 'noopener noreferrer');
                } else {
                    // Also check any child links inside
                    node.querySelectorAll('a.open-new-tab').forEach(function (link) {
                        link.setAttribute('target', '_blank');
                        link.setAttribute('rel', 'noopener noreferrer');
                    });
                }
            }
        });
    });
});

observer.observe(document.body, { childList: true, subtree: true });