document.addEventListener("DOMContentLoaded", function () {

    // Handle form submissions for all forms with class 'ajax_form'
    document.querySelectorAll(".ajax_form").forEach(function (form) {
        form.addEventListener("submit", async function (event) {
            event.preventDefault(); // Prevent default form submission behavior

            const formData = new FormData(form); // Collect all form inputs
            const data = new URLSearchParams(formData); // Serialize form data
            const errorBlocks = form.querySelectorAll('.error'); // Select all error blocks
            const waitBlock = form.querySelector('.wait-block'); // Select the waiting block
            const successBlock = form.querySelector('.form-success'); // Select the success message block
            const errorBlock = form.querySelector('.form-error'); // Select the general form error block

            // Hide errors and show loading indicator
            errorBlocks.forEach(error => error.style.display = 'none'); // Hide all error messages
            if (waitBlock) waitBlock.style.display = 'block'; // Show wait indicator

            try {
                // Make an async request using fetch, to replace the old jQuery.ajax
                const response = await fetch(ajax_path, {
                    method: "POST", // Use POST method
                    body: data, // Send form data
                });

                const jsonResponse = await response.json(); // Parse JSON response
                waitBlock.style.display = 'none'; // Hide wait indicator

                if (jsonResponse.errors) {
                    // Display individual field errors, if any
                    Object.keys(jsonResponse.errors).forEach(function (key) {
                        const errorElement = form.querySelector(".error-" + key);
                        if (errorElement) {
                            errorElement.innerHTML = jsonResponse.errors[key];
                            errorElement.style.display = 'block'; // Show specific error
                        }
                    });
                } else {
                    // Display success message
                    if (successBlock) {
                        successBlock.innerHTML = jsonResponse.message;
                        successBlock.style.display = 'block'; // Show success block
                    }

                    // Clear all text inputs and textareas
                    form.querySelectorAll("input[type=text], textarea").forEach(function (input) {
                        input.value = ""; // Clear input value
                    });
                }
            } catch (error) {
                // Handle general error
                if (waitBlock) waitBlock.style.display = 'none'; // Hide wait indicator
                if (errorBlock) {
                    errorBlock.innerHTML = "There was an error submitting the form"; // Show form error message
                    errorBlock.style.display = 'block'; // Show error block
                }
            }
        });
    });

    // Example of additional functionality: scroll to a specific section after submission
    document.querySelectorAll('.scroll-to-section').forEach(function (button) {
        button.addEventListener('click', function (event) {
            event.preventDefault(); // Prevent default anchor behavior
            const targetSection = document.querySelector(this.getAttribute('href'));
            if (targetSection) {
                targetSection.scrollIntoView({ behavior: 'smooth' }); // Scroll smoothly to the section
            }
        });
    });

    // Example of enabling/disabling a submit button based on form input validity
    document.querySelectorAll('.form-validate').forEach(function (form) {
        const submitButton = form.querySelector('input[type=submit]');
        form.addEventListener('input', function () {
            const isValid = form.checkValidity(); // Check if the form is valid
            submitButton.disabled = !isValid; // Enable/disable the submit button
        });
    });

    // Example of live preview of text input (e.g., for a character counter)
    document.querySelectorAll('.live-preview').forEach(function (input) {
        input.addEventListener('input', function () {
            const previewTarget = document.querySelector(this.dataset.previewTarget);
            if (previewTarget) {
                previewTarget.textContent = this.value; // Update the preview element with the input value
            }
        });
    });
});
