/**
 * 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('.blynex-contact-form');
        
        forms.forEach(form => {
            // Set nonce value
            const nonceField = form.querySelector('.contact-form-nonce');
            if (nonceField && window.blynexContactForm) {
                nonceField.value = window.blynexContactForm.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', 'blynex_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.blynexContactForm?.submittingText || 'Sending...';

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

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

        // Submit form via AJAX
        fetch(ajaxUrl, {
            method: 'POST',
            body: postData,
            credentials: 'same-origin'
        })
        .then(response => {
            return response.text().then(text => {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    throw new Error('Server returned invalid JSON: ' + text.substring(0, 100));
                }
            });
        })
        .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.blynexContactForm?.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.blynexContactForm?.errorMessage || 'An error occurred. Please try again.';
                    errorMessage.style.display = 'flex';
                }
            }
        })
        .catch(error => {
            // Re-enable submit button
            submitButton.disabled = false;
            submitButton.classList.remove('submitting');
            submitButton.textContent = originalButtonText;

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