// Contact Form Submission Script

const form = document.getElementById("contact-form");
const resetButton = form.querySelector('button[type="reset"]');

// Add a div for non-blocking messages
const messageDiv = document.createElement('div');
messageDiv.id = 'form-message';
messageDiv.style.display = 'none';
messageDiv.style.padding = '10px';
messageDiv.style.marginTop = '10px';
messageDiv.style.border = '1px solid';
form.parentNode.insertBefore(messageDiv, form);


// Utility: Show a message to the user
function showMessage(text, isError = false) {
    messageDiv.textContent = text;
    messageDiv.style.display = 'block';
    if (isError) {
        messageDiv.style.backgroundColor = '#f8d7da';
        messageDiv.style.borderColor = '#f5c6cb';
        messageDiv.style.color = '#721c24';
    } else {
        messageDiv.style.backgroundColor = '#d4edda';
        messageDiv.style.borderColor = '#c3e6cb';
        messageDiv.style.color = '#155724';
    }
}

// Utility: Show error for specific input
function showError(inputId, message) {
    const input = document.getElementById(inputId);
    const errorSpan = document.getElementById(`${inputId}-error`);
    if (input) input.classList.add("error");
    if (errorSpan) errorSpan.textContent = message;
}

// Utility: Clear all errors and messages
function clearErrors() {
    document.querySelectorAll(".error-message").forEach(span => span.textContent = "");
    document.querySelectorAll("input, textarea").forEach(input => input.classList.remove("error"));
    messageDiv.style.display = 'none';
    messageDiv.textContent = '';
}

form.addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent actual form submission

    clearErrors(); // Clear previous errors

    const honeypotField = document.getElementById("url").value.trim();
    if (honeypotField.length > 0) {
        console.warn("Honeypot field was filled. Blocking submission.");
        return;
    }

    const firstName = document.getElementById("first-name").value.trim();
    const lastName = document.getElementById("last-name").value.trim();
    const organization = document.getElementById("organization").value.trim();
    const email = document.getElementById("email").value.trim();
    const phone = document.getElementById("phone").value.trim();
    const contactMethod = document.querySelector('input[name="contact-method"]:checked')?.value;
    const message = document.getElementById("message").value.trim();

    let hasErrors = false;

    if (!firstName) {
        showError("first-name", "Please enter your first name.");
        hasErrors = true;
    } else if (firstName.length < 2) {
        showError("first-name", "First name must be at least 2 characters.");
        hasErrors = true;
    }

    if (!lastName) {
        showError("last-name", "Please enter your last name.");
        hasErrors = true;
    } else if (lastName.length < 2) {
        showError("last-name", "Last name must be at least 2 characters.");
        hasErrors = true;
    }
    
    // Organization (optional)
    if (organization.length > 0 && organization.length < 2) {
        showError("organization", "Organization name must be at least 2 characters.");
        hasErrors = true;
    }

    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(email)) {
        showError("email", "Please enter a valid email address.");
        hasErrors = true;
    }

    const phonePattern = /^(\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4})$/;
    if (!phonePattern.test(phone)) {
        showError("phone", "Phone number must be in the format 123-456-7890.");
        hasErrors = true;
    }

    if (message.length < 10) {
        showError("message", "Message must be at least 10 characters long.");
        hasErrors = true;
    }
    
    const hCaptchaResponse = hcaptcha.getResponse();
    // Check for hCaptcha token
    if (!hCaptchaResponse) {
        showMessage("Please complete the CAPTCHA.", true);
        hasErrors = true;
    }

    if (!hasErrors) {
        // Package the form data, including the hCaptcha token
        const formData = {
            firstName: firstName,
            lastName: lastName,
            organization: organization,
            email: email,
            phone: phone,
            contactMethod: contactMethod,
            message: message,
            url: honeypotField,
            hCaptchaResponse: hCaptchaResponse,
        };

        // Send the data to the backend using fetch()
        fetch('/api/submit-form', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Network response was not ok.');
        })
        .then(data => {
            console.log('Success:', data);
            showMessage('Form submitted successfully!', false);
            form.reset();
            hcaptcha.reset();
        })
        .catch((error) => {
            console.error('Error:', error);
            showMessage('An error occurred during submission. Please try again.', true);
        });
    }
});

form.addEventListener("reset", function (event) {
    const confirmed = window.confirm("Are you sure you want to clear the form?");
    if (!confirmed) {
        event.preventDefault();
        return;
    }
    clearErrors();
});