/**
 * Guard Dog Password Policy JavaScript
 *
 * Enhances WordPress password strength meter with policy requirements.
 *
 * @package GuardDog
 * @since 1.9.0
 */

(function($) {
    'use strict';

    // Wait for WordPress password strength meter to be available
    $(document).ready(function() {
        // Check if policy settings are available
        var policy = typeof guardDogPasswordPolicy !== 'undefined' ? guardDogPasswordPolicy : {
            minLength: 12,
            requireUppercase: true,
            requireLowercase: true,
            requireNumbers: true,
            requireSpecial: true,
            blockUsername: true,
            blockEmail: true,
            ajaxUrl: '',
            nonce: ''
        };

        // Find password fields - #pass1 is only on password-setting forms (registration, reset, profile)
        // The login form doesn't have #pass1, so if we find it, we're on a password-setting page
        var $pass1 = $('#pass1').first();
        var $pass2 = $('#pass2').first();
        
        // If #pass1 doesn't exist, we might be on a different form - check for other password fields
        // but exclude the login form which has #user_pass (authentication, not password setting)
        if ($pass1.length === 0) {
            // Check if we're on login form - if so, don't show requirements
            if ($('#loginform').length > 0 && $('#registerform').length === 0 && $('#resetpassform').length === 0) {
                return; // Don't enhance login form
            }
            // Try other password field selectors for custom forms
            $pass1 = $('#user_pass, #password, input[type="password"][name*="pass1"]').first();
            if ($pass2.length === 0) {
                $pass2 = $('input[type="password"][name*="pass2"]').first();
            }
        }
        
        if ($pass1.length === 0) {
            return;
        }

        // Expired password reset form handling
        var $resetForm = $('#resetpasswordform');
        if ($resetForm.length > 0) {
            var $resetPass1 = $resetForm.find('#pass1');
            var $resetPass2 = $resetForm.find('#pass2');
            var $checklist = $('.guard-dog-password-checklist');

            function updateResetFormRequirements() {
                var password = $resetPass1.val();
                var confirm = $resetPass2.val();
                var resetPolicy = window.guardDogPasswordPolicy || {};

                // Check length
                var lengthMet = password.length >= (resetPolicy.minLength || 12);
                updateResetRequirement('length', lengthMet);

                // Check uppercase
                if (resetPolicy.requireUppercase !== false) {
                    updateResetRequirement('uppercase', /[A-Z]/.test(password));
                }

                // Check lowercase
                if (resetPolicy.requireLowercase !== false) {
                    updateResetRequirement('lowercase', /[a-z]/.test(password));
                }

                // Check numbers
                if (resetPolicy.requireNumbers !== false) {
                    updateResetRequirement('number', /[0-9]/.test(password));
                }

                // Check special characters
                if (resetPolicy.requireSpecial !== false) {
                    updateResetRequirement('special', /[^A-Za-z0-9]/.test(password));
                }

                // Check passwords match
                var matchMet = password.length > 0 && password === confirm;
                updateResetRequirement('match', matchMet);
            }

            function updateResetRequirement(requirement, isMet) {
                var $item = $checklist.find('[data-requirement="' + requirement + '"]');
                if (isMet) {
                    $item.addClass('met');
                } else {
                    $item.removeClass('met');
                }
            }

            // Bind to input events
            $resetPass1.on('input keyup', updateResetFormRequirements);
            $resetPass2.on('input keyup', updateResetFormRequirements);

            // Initial check
            updateResetFormRequirements();
        }

        // Store original check function if it exists
        var originalCheck = typeof pwsL10n !== 'undefined' ? null : null;

        /**
         * Update requirement display
         */
        function updateRequirementDisplay(requirements) {
            // Find or create requirement indicator - place it after pass2 field
            var $indicator = $('#guard-dog-password-requirements');
            if ($indicator.length === 0) {
                // Try to find the pass2 field's parent paragraph and insert after it
                if ($pass2.length > 0) {
                    var $pass2Parent = $pass2.closest('p');
                    if ($pass2Parent.length > 0) {
                        $indicator = $('<div id="guard-dog-password-requirements" class="guard-dog-password-requirements"></div>');
                        $pass2Parent.after($indicator);
                    } else {
                        $indicator = $('<div id="guard-dog-password-requirements" class="guard-dog-password-requirements"></div>');
                        $pass2.after($indicator);
                    }
                } else {
                    // Fallback to pass1 if pass2 doesn't exist
                    var $pass1Parent = $pass1.closest('p');
                    if ($pass1Parent.length > 0) {
                        $indicator = $('<div id="guard-dog-password-requirements" class="guard-dog-password-requirements"></div>');
                        $pass1Parent.after($indicator);
                    } else {
                        $indicator = $('<div id="guard-dog-password-requirements" class="guard-dog-password-requirements"></div>');
                        $pass1.after($indicator);
                    }
                }
            }

            // Always show the indicator
            $indicator.show();

            var html = '<strong>' + (typeof pwsL10n !== 'undefined' && pwsL10n.requirements ? pwsL10n.requirements : 'Password Requirements:') + '</strong>';
            html += '<ul class="password-requirements-list">';
            
            html += '<li class="' + (requirements.length ? 'met' : 'unmet') + '">';
            html += 'At least ' + policy.minLength + ' characters';
            html += '</li>';

            if (policy.requireUppercase) {
                html += '<li class="' + (requirements.uppercase ? 'met' : 'unmet') + '">';
                html += 'One uppercase letter (A-Z)';
                html += '</li>';
            }

            if (policy.requireLowercase) {
                html += '<li class="' + (requirements.lowercase ? 'met' : 'unmet') + '">';
                html += 'One lowercase letter (a-z)';
                html += '</li>';
            }

            if (policy.requireNumbers) {
                html += '<li class="' + (requirements.numbers ? 'met' : 'unmet') + '">';
                html += 'One number (0-9)';
                html += '</li>';
            }

            if (policy.requireSpecial) {
                html += '<li class="' + (requirements.special ? 'met' : 'unmet') + '">';
                html += 'One special character (!@#$%^&* etc.)';
                html += '</li>';
            }

            html += '</ul>';
            $indicator.html(html);
        }

        /**
         * Validate password in real-time
         */
        function validatePassword(password) {
            password = password || '';
            
            // Check each requirement
            var requirements = {
                length: password.length >= policy.minLength,
                uppercase: !policy.requireUppercase || /[A-Z]/.test(password),
                lowercase: !policy.requireLowercase || /[a-z]/.test(password),
                numbers: !policy.requireNumbers || /[0-9]/.test(password),
                special: !policy.requireSpecial || /[^A-Za-z0-9]/.test(password),
            };

            // Always update UI with requirement status
            updateRequirementDisplay(requirements);

            // Also do server-side validation via AJAX if password has content
            if (password.length > 0 && typeof $.ajax !== 'undefined') {
                $.ajax({
                    url: policy.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_validate_password',
                        password: password,
                        nonce: policy.nonce,
                    },
                    success: function(response) {
                        if (!response.success && response.data && response.data.errors) {
                            // Show server-side validation errors
                            console.log('Password validation errors:', response.data.errors);
                        }
                    }
                });
            }
        }

        /**
         * Check if password meets all requirements
         */
        function checkPasswordRequirements(password) {
            var requirements = {
                length: password.length >= policy.minLength,
                uppercase: !policy.requireUppercase || /[A-Z]/.test(password),
                lowercase: !policy.requireLowercase || /[a-z]/.test(password),
                numbers: !policy.requireNumbers || /[0-9]/.test(password),
                special: !policy.requireSpecial || /[^A-Za-z0-9]/.test(password),
            };

            return Object.values(requirements).every(function(met) {
                return met === true;
            });
        }

        // Show requirements initially (empty password)
        updateRequirementDisplay({
            length: false,
            uppercase: false,
            lowercase: false,
            numbers: false,
            special: false
        });

        // Function to check and update password requirements
        function checkAndUpdatePassword() {
            var password = $pass1.val();
            validatePassword(password);
            
            // Also check if passwords match
            if ($pass2.length > 0) {
                checkPasswordMatch();
            }
        }

        // Enhance password strength meter - only on pass1
        $pass1.on('input keyup paste', function() {
            checkAndUpdatePassword();
        });

        // Listen for WordPress password generation event
        // WordPress triggers 'pwupdate' event when password is generated
        $pass1.on('pwupdate', function() {
            // Small delay to ensure value is set
            setTimeout(function() {
                checkAndUpdatePassword();
            }, 50);
        });

        // Also listen for focus event in case password was generated but pwupdate didn't fire
        $pass1.on('focus', function() {
            // Check if password was just generated (has value but requirements weren't updated)
            var password = $(this).val();
            if (password.length > 0) {
                checkAndUpdatePassword();
            }
        });

        // Check password match on pass2 changes
        if ($pass2.length > 0) {
            $pass2.on('input keyup paste', function() {
                checkPasswordMatch();
            });
        }

        /**
         * Check if passwords match and display message
         */
        function checkPasswordMatch() {
            var password1 = $pass1.val();
            var password2 = $pass2.val();
            
            var $matchIndicator = $('#guard-dog-password-match');
            if ($matchIndicator.length === 0) {
                // Insert after password requirements
                var $requirements = $('#guard-dog-password-requirements');
                if ($requirements.length > 0) {
                    $matchIndicator = $('<div id="guard-dog-password-match" class="guard-dog-password-match"></div>');
                    $requirements.after($matchIndicator);
                } else {
                    // Fallback: insert after pass2
                    if ($pass2.length > 0) {
                        var $pass2Parent = $pass2.closest('p');
                        if ($pass2Parent.length > 0) {
                            $matchIndicator = $('<div id="guard-dog-password-match" class="guard-dog-password-match"></div>');
                            $pass2Parent.after($matchIndicator);
                        }
                    }
                }
            }
            
            // Only show message if both fields have content
            if (password1.length > 0 && password2.length > 0) {
                if (password1 === password2) {
                    $matchIndicator.removeClass('mismatch').addClass('match').html('<span class="match-icon">✓</span> Passwords match').show();
                } else {
                    $matchIndicator.removeClass('match').addClass('mismatch').html('<span class="mismatch-icon">✗</span> Passwords do not match').show();
                }
            } else {
                $matchIndicator.hide();
            }
        }

        // Prevent form submission if password doesn't meet requirements
        $('form').on('submit', function(e) {
            var password = $pass1.val();
            if (password.length > 0) {
                var isValid = checkPasswordRequirements(password);
                if (!isValid) {
                    e.preventDefault();
                    alert('Please ensure your password meets all requirements.');
                    return false;
                }
                
                // Also check if passwords match
                if ($pass2.length > 0) {
                    var password2 = $pass2.val();
                    if (password !== password2) {
                        e.preventDefault();
                        alert('Passwords do not match. Please ensure both password fields match.');
                        return false;
                    }
                }
            }
        });
    });

})(jQuery);

