/**
 * Contact Form Frontend Script
 * Handles form submission via AJAX
 */

(function() {
    'use strict';

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initContactForms);
    } else {
        initContactForms();
    }

    function initContactForms() {
        const forms = document.querySelectorAll('.cryzel-contact-form');
        
        forms.forEach(form => {
            // Set nonce value
            const nonceField = form.querySelector('.contact-form-nonce');
            if (nonceField && window.cryzelContactForm) {
                nonceField.value = window.cryzelContactForm.nonce;
            }

            // Handle form submission
            form.addEventListener('submit', handleFormSubmit);
        });
    }

    function handleFormSubmit(e) {
        e.preventDefault();

        const form = e.target;
        const submitButton = form.querySelector('.submit-button');
        const successMessage = form.querySelector('.success-message');
        const errorMessage = form.querySelector('.error-message');

        // Get form data
        const formData = new FormData(form);
        
        // Add recipient email from data attribute
        const recipientEmail = form.getAttribute('data-recipient');
        if (recipientEmail) {
            formData.append('recipientEmail', recipientEmail);
        }

        // Rename fields to match backend expectations
        const name = formData.get('contact_name');
        const email = formData.get('contact_email');
        const phone = formData.get('contact_phone');
        const subject = formData.get('contact_subject');
        const message = formData.get('contact_message');
        const website = formData.get('contact_website');

        // Create new FormData with correct field names
        const postData = new FormData();
        postData.append('action', 'cryzel_contact_form_submit');
        postData.append('nonce', formData.get('nonce'));
        postData.append('name', name);
        postData.append('email', email);
        if (phone) postData.append('phone', phone);
        if (subject) postData.append('subject', subject);
        postData.append('message', message);
        if (website) postData.append('website', website);
        if (recipientEmail) postData.append('recipientEmail', recipientEmail);

        // Disable submit button and show loading state
        submitButton.disabled = true;
        submitButton.classList.add('submitting');
        const originalButtonText = submitButton.textContent;
        submitButton.textContent = window.cryzelContactForm?.submittingText || 'Sending...';

        // Hide previous messages
        if (successMessage) successMessage.style.display = 'none';
        if (errorMessage) errorMessage.style.display = 'none';

        // Get AJAX URL
        const ajaxUrl = window.cryzelContactForm?.ajaxUrl || '/wp-admin/admin-ajax.php';

        // Submit form via AJAX
        fetch(ajaxUrl, {
            method: 'POST',
            body: postData,
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            // Re-enable submit button
            submitButton.disabled = false;
            submitButton.classList.remove('submitting');
            submitButton.textContent = originalButtonText;

            if (data.success) {
                // Show success message
                if (successMessage) {
                    successMessage.textContent = data.data.message || window.cryzelContactForm?.successMessage || 'Message sent successfully!';
                    successMessage.style.display = 'flex';
                }
                
                // Reset form
                form.reset();

                // Hide success message after 5 seconds
                setTimeout(() => {
                    if (successMessage) successMessage.style.display = 'none';
                }, 5000);
            } else {
                // Show error message
                if (errorMessage) {
                    errorMessage.textContent = data.data?.message || window.cryzelContactForm?.errorMessage || 'An error occurred. Please try again.';
                    errorMessage.style.display = 'flex';
                }
            }
        })
        .catch(error => {
            console.error('Form submission error:', error);
            
            // Re-enable submit button
            submitButton.disabled = false;
            submitButton.classList.remove('submitting');
            submitButton.textContent = originalButtonText;

            // Show error message
            if (errorMessage) {
                errorMessage.textContent = window.cryzelContactForm?.errorMessage || 'An error occurred. Please try again.';
                errorMessage.style.display = 'flex';
            }
        });
    }
})();
