/**
 * Contact Form JavaScript
 * Handles contact form validation and submission
 */

(function($) {
    'use strict';
    
    $(document).ready(function() {
        const contactForm = {
            init: function() {
                this.bindEvents();
                this.initValidation();
            },
            
            bindEvents: function() {
                $('#contactForm').on('submit', this.handleSubmit.bind(this));
                $('.modern-input, .modern-textarea').on('blur', this.validateField.bind(this));
                $('.modern-input, .modern-textarea').on('input', this.clearValidation.bind(this));
                
                // Character count for message field
                $('#message').on('input', this.updateCharacterCount.bind(this));
            },
            
            initValidation: function() {
                // Add validation rules
                this.rules = {
                    name: {
                        required: true,
                        minlength: 2,
                        maxlength: 50,
                        pattern: /^[A-Za-z\s]+$/
                    },
                    email: {
                        required: true,
                        email: true
                    },
                    phone: {
                        required: false,
                        pattern: /^[\+]?[0-9\s\-\(\)]{10,20}$/
                    },
                    inquiry_type: {
                        required: true
                    },
                    subject: {
                        required: false,
                        minlength: 5,
                        maxlength: 100,
                        pattern: /^[A-Za-z0-9\s\-\.]+$/
                    },
                    message: {
                        required: true,
                        minlength: 10,
                        maxlength: 1000
                    }
                };
            },
            
            validateField: function(e) {
                const field = $(e.target);
                const fieldName = field.attr('name');
                const value = field.val().trim();
                const rules = this.rules[fieldName];
                
                if (!rules) return;
                
                let isValid = true;
                let errorMessage = '';
                
                // Required validation
                if (rules.required && !value) {
                    isValid = false;
                    errorMessage = nihongo_ajax.fill_required_fields || 'This field is required.';
                }
                
                // Length validation
                if (isValid && value) {
                    if (rules.minlength && value.length < rules.minlength) {
                        isValid = false;
                        errorMessage = nihongo_ajax.min_length_error || `Minimum ${rules.minlength} characters required.`;
                    }
                    
                    if (rules.maxlength && value.length > rules.maxlength) {
                        isValid = false;
                        errorMessage = nihongo_ajax.max_length_error || `Maximum ${rules.maxlength} characters allowed.`;
                    }
                }
                
                // Pattern validation
                if (isValid && value && rules.pattern && !rules.pattern.test(value)) {
                    isValid = false;
                    errorMessage = nihongo_ajax.invalid_format || 'Invalid format.';
                }
                
                // Email validation
                if (isValid && value && rules.email && !this.isValidEmail(value)) {
                    isValid = false;
                    errorMessage = nihongo_ajax.invalid_email || 'Please enter a valid email address.';
                }
                
                this.showFieldValidation(field, isValid, errorMessage);
            },
            
            clearValidation: function(e) {
                const field = $(e.target);
                this.showFieldValidation(field, true, '');
            },
            
            showFieldValidation: function(field, isValid, errorMessage) {
                const validationElement = field.siblings('.validation-message');
                
                if (isValid) {
                    field.removeClass('error');
                    validationElement.text('').hide();
                } else {
                    field.addClass('error');
                    validationElement.text(errorMessage).show();
                }
            },
            
            isValidEmail: function(email) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                return emailRegex.test(email);
            },
            
            updateCharacterCount: function(e) {
                const field = $(e.target);
                const count = field.val().length;
                const maxLength = this.rules.message.maxlength;
                
                const counter = field.siblings('.character-count');
                counter.find('#messageCount').text(count);
                
                if (count > maxLength * 0.9) {
                    counter.addClass('warning');
                } else {
                    counter.removeClass('warning');
                }
            },
            
            handleSubmit: function(e) {
                e.preventDefault();
                
                const form = $(e.target);
                const submitBtn = form.find('#submitBtn');
                
                // Validate all fields
                let isFormValid = true;
                form.find('.modern-input, .modern-textarea, .modern-select').each((index, field) => {
                    this.validateField({ target: field });
                    if ($(field).hasClass('error')) {
                        isFormValid = false;
                    }
                });
                
                if (!isFormValid) {
                    this.showFormError('Please correct the errors above.');
                    return;
                }
                
                // Show loading state
                this.setLoadingState(submitBtn, true);
                
                // Submit form via AJAX
                $.ajax({
                    url: nihongo_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'nihongo_contact_form',
                        nonce: nihongo_ajax.nonce,
                        name: form.find('#name').val(),
                        email: form.find('#email').val(),
                        phone: form.find('#phone').val(),
                        inquiry_type: form.find('#inquiry_type').val(),
                        subject: form.find('#subject').val(),
                        message: form.find('#message').val()
                    },
                    success: (response) => {
                        if (response.success) {
                            this.showFormSuccess(response.data.message);
                            form[0].reset();
                        } else {
                            this.showFormError(response.data.message);
                        }
                    },
                    error: () => {
                        this.showFormError('An error occurred. Please try again.');
                    },
                    complete: () => {
                        this.setLoadingState(submitBtn, false);
                    }
                });
            },
            
            setLoadingState: function(button, isLoading) {
                if (isLoading) {
                    button.addClass('loading');
                    button.prop('disabled', true);
                } else {
                    button.removeClass('loading');
                    button.prop('disabled', false);
                }
            },
            
            showFormSuccess: function(message) {
                this.showAlert('success', message);
            },
            
            showFormError: function(message) {
                this.showAlert('error', message);
            },
            
            showAlert: function(type, message) {
                const alertClass = type === 'success' ? 'modern-alert-success' : 'modern-alert-error';
                const icon = type === 'success' ? '✅' : '⚠️';
                
                const alert = $(`
                    <div class="modern-alert ${alertClass}">
                        <div class="alert-icon">${icon}</div>
                        <div class="alert-content">
                            <h4>${type === 'success' ? 'Success' : 'Error'}</h4>
                            <p>${message}</p>
                        </div>
                    </div>
                `);
                
                $('.modern-form-container').prepend(alert);
                
                // Auto-hide after 5 seconds
                setTimeout(() => {
                    alert.fadeOut();
                }, 5000);
            }
        };
        
        // Initialize contact form
        contactForm.init();
    });
    
})(jQuery);
