// VALIDATE THE EMAIL FORMAT
function validateEmail() {
    const emailInput = document.getElementById("emailAddressInput");
    const emailError = document.getElementById("emailError");

    emailInput.addEventListener("input", function () {
        const email = emailInput.value.trim();
        const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

        if (!emailPattern.test(email)) {
            emailError.textContent = "Please enter a valid email address.";
        } else {
            // Check email availability on the server
            fetch("/check-email-availability/?email=" + email)
                .then((response) => response.json())
                .then((data) => {
                    if (data.exists) {
                        // Email already exists
                        emailError.textContent = "A user with this email already exists.";
                    } else {
                        // Email is unique
                        emailError.textContent = "";
                    }
                })
                .catch((error) => {
                    console.error("Error checking email availability:", error);
                });
        }
    });
}



// VALIDATE THE PASSWORD STRENGTH AND PASSWORD CONFIRMATION
function validatePasswords() {
    const password1Input = document.querySelector('input[name="password1"]');
    const password2Input = document.querySelector('input[name="password2"]');
    const passwordMatchingError = document.getElementById('passwordError');

    const password1 = password1Input.value;
    const password2 = password2Input.value;

    // Password strength requirements
    const isLengthValid = password1.length >= 8;

    // Clear all error messages
    passwordMatchingError.textContent = '';
    passwordMatchingError.style.display = 'none';

    if (password1 && password2) {
        // Check for password match
        if (password1 === password2) {
            let errorMessage = '';

            // Check for password strength
            if (!isLengthValid) {
                errorMessage += '- At least 8 characters\n';
                errorMessage += '<br>'
            }

            if (errorMessage) {
                passwordMatchingError.innerHTML = errorMessage;
                passwordMatchingError.style.display = 'block';
            }
        } else {
            // Passwords do not match
            passwordMatchingError.textContent = 'Passwords do not match';
            passwordMatchingError.style.display = 'block';
        }
    }
}


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

    // Add event listeners to both password inputs to trigger validation
    const password1Input = document.querySelector('input[name="password1"]');
    const password2Input = document.querySelector('input[name="password2"]');

    password1Input.addEventListener('input', validatePasswords);
    password2Input.addEventListener('input', validatePasswords);


    // PREVENT THE FORM FROM SUBMITTING IF THE VALIDATIONS FAILS
    const myForm = document.getElementById("registerForm");

    myForm.addEventListener("submit", function (event) {
        const emailError = document.getElementById("emailError");
        const passwordMatchingError = document.getElementById('passwordError');
        const message = document.getElementById("register-error-message");

        const emailValid = emailError.textContent === "";
        const passwordValid = passwordMatchingError.textContent === "";

        if (!emailValid || !passwordValid) {
            event.preventDefault();
            message.classList.add("show-message");
            setTimeout(function () {
                message.classList.add("hide-message");
            }, 3000);
        }
    });
});

