/**
 * HVAC Community Events: Login Form JavaScript
 * 
 * Enhanced login form functionality following WordPress best practices.
 * 
 * @version 2.0.0
 */

jQuery(document).ready(function($) {
    'use strict';

    /**
     * Password Show/Hide Toggle
     */
    const HVACPasswordToggle = {
        init: function() {
            $('.hvac-password-toggle').on('click', this.togglePassword);
            
            // Handle keyboard accessibility
            $('.hvac-password-toggle').on('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    $(this).click();
                }
            });
        },

        togglePassword: function() {
            const $button = $(this);
            const $input = $button.siblings('.hvac-password-input');
            const $icon = $button.find('.hvac-password-toggle-icon');
            
            const isVisible = $input.attr('type') === 'text';
            
            if (isVisible) {
                // Hide password
                $input.attr('type', 'password');
                $icon.text('👁️');
                $button.attr('aria-label', hvacLogin.showPassword);
                $button.attr('aria-pressed', 'false');
            } else {
                // Show password
                $input.attr('type', 'text');
                $icon.text('🙈');
                $button.attr('aria-label', hvacLogin.hidePassword);
                $button.attr('aria-pressed', 'true');
            }
            
            // Keep focus on the input field
            $input.focus();
        }
    };

    /**
     * Form Validation
     */
    const HVACLoginValidation = {
        init: function() {
            $('#hvac_community_loginform').on('submit', this.validateForm);
            
            // Real-time validation feedback
            $('.hvac-login-form-input').on('blur', this.validateField);
            $('.hvac-login-form-input').on('input', this.clearFieldError);
        },

        validateForm: function(e) {
            const $form = $(this);
            let isValid = true;
            
            // Clear previous errors
            $form.find('.hvac-field-error').remove();
            $form.find('.hvac-login-form-input').removeClass('hvac-input-error');
            
            // Validate username/email
            const $username = $form.find('#user_login');
            if (!$username.val().trim()) {
                HVACLoginValidation.showFieldError($username, hvacLogin.usernameRequired);
                isValid = false;
            }
            
            // Validate password
            const $password = $form.find('#user_pass');
            if (!$password.val()) {
                HVACLoginValidation.showFieldError($password, hvacLogin.passwordRequired);
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
                return false;
            }
            
            // Show loading state
            HVACLoginLoading.show();
        },

        validateField: function() {
            const $field = $(this);
            const value = $field.val().trim();
            
            HVACLoginValidation.clearFieldError($field);
            
            if ($field.attr('id') === 'user_login' && !value) {
                HVACLoginValidation.showFieldError($field, hvacLogin.usernameRequired);
            } else if ($field.attr('id') === 'user_pass' && !value) {
                HVACLoginValidation.showFieldError($field, hvacLogin.passwordRequired);
            }
        },

        clearFieldError: function() {
            const $field = $(this);
            HVACLoginValidation.clearFieldError($field);
        },

        showFieldError: function($field, message) {
            $field.addClass('hvac-input-error');
            const $error = $('<div class="hvac-field-error">' + message + '</div>');
            $field.closest('.hvac-login-form-group').append($error);
        },

        clearFieldError: function($field) {
            $field.removeClass('hvac-input-error');
            $field.closest('.hvac-login-form-group').find('.hvac-field-error').remove();
        }
    };

    /**
     * Loading States
     */
    const HVACLoginLoading = {
        show: function() {
            const $button = $('#wp-submit');
            const $text = $button.find('.hvac-login-submit-text');
            const $spinner = $button.find('.hvac-login-spinner');
            
            $button.prop('disabled', true);
            $text.text(hvacLogin.loggingIn);
            $spinner.show();
        },

        hide: function() {
            const $button = $('#wp-submit');
            const $text = $button.find('.hvac-login-submit-text');
            const $spinner = $button.find('.hvac-login-spinner');
            
            $button.prop('disabled', false);
            $text.text(hvacLogin.logIn);
            $spinner.hide();
        }
    };

    /**
     * Enhanced User Experience
     */
    const HVACLoginUX = {
        init: function() {
            // Auto-focus first empty field
            this.autoFocus();
            
            // Add smooth scrolling to errors
            this.setupErrorScrolling();
            
            // Handle form submission with better UX
            this.enhanceFormSubmission();
        },

        autoFocus: function() {
            const $username = $('#user_login');
            const $password = $('#user_pass');
            
            if (!$username.val()) {
                $username.focus();
            } else if (!$password.val()) {
                $password.focus();
            }
        },

        setupErrorScrolling: function() {
            // Scroll to first error after form submission
            $('#hvac_community_loginform').on('submit', function() {
                setTimeout(function() {
                    const $firstError = $('.hvac-field-error').first();
                    if ($firstError.length) {
                        $('html, body').animate({
                            scrollTop: $firstError.offset().top - 100
                        }, 300);
                    }
                }, 50);
            });
        },

        enhanceFormSubmission: function() {
            // Prevent double submission
            $('#hvac_community_loginform').on('submit', function() {
                const $form = $(this);
                if ($form.data('submitting')) {
                    return false;
                }
                $form.data('submitting', true);
                
                // Reset after 10 seconds as fallback
                setTimeout(function() {
                    $form.removeData('submitting');
                    HVACLoginLoading.hide();
                }, 10000);
            });
        }
    };

    // Initialize all components
    if ($('#hvac_community_loginform').length) {
        HVACPasswordToggle.init();
        HVACLoginValidation.init();
        HVACLoginUX.init();
    }
});