/**
 * Password Fields Frontend Validation
 * Handles password requirements validation and password matching
 */
(function($) {
    'use strict';

    var WPUF_PasswordFields = {

        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            var self = this;

            // Handle password requirements validation
            $(document).on('keyup input blur', 'input[data-type="password"]', function() {
                self.checkPasswordRequirements($(this));
            });

            // Handle password matching validation
            $(document).on('keyup input blur', 'input[data-type="password"], input[data-type="confirm_password"]', function() {
                self.checkPasswordMatch($(this));
            });
        },

        /**
         * Check password requirements and update indicators
         */
        checkPasswordRequirements: function($passField) {
            var password = $passField.val();
            var $requirementsList = $passField.closest('.wpuf-fields').find('.wpuf-password-requirements');

            if (!$requirementsList.length) {
                return;
            }

            // Clear previous errors
            if (typeof WP_User_Frontend !== 'undefined' && WP_User_Frontend.removeErrors) {
                WP_User_Frontend.removeErrors($passField.closest('li'));
            }

            // Reset requirements indicators
            this.updateRequirementsList($requirementsList, password);

            if (!password) {
                return;
            }

            // Check uppercase
            if ($passField.data('require-uppercase') === 'yes') {
                if (/[A-Z]/.test(password)) {
                    $requirementsList.find('[data-requirement="uppercase"] .wpuf-req-icon')
                        .text('✓')
                        .removeClass('wpuf-req-unmet')
                        .addClass('wpuf-req-met');
                }
            }

            // Check lowercase
            if ($passField.data('require-lowercase') === 'yes') {
                if (/[a-z]/.test(password)) {
                    $requirementsList.find('[data-requirement="lowercase"] .wpuf-req-icon')
                        .text('✓')
                        .removeClass('wpuf-req-unmet')
                        .addClass('wpuf-req-met');
                }
            }

            // Check number
            if ($passField.data('require-number') === 'yes') {
                if (/[0-9]/.test(password)) {
                    $requirementsList.find('[data-requirement="number"] .wpuf-req-icon')
                        .text('✓')
                        .removeClass('wpuf-req-unmet')
                        .addClass('wpuf-req-met');
                }
            }

            // Check special character
            if ($passField.data('require-special-char') === 'yes') {
                if (/[^A-Za-z0-9]/.test(password)) {
                    $requirementsList.find('[data-requirement="special"] .wpuf-req-icon')
                        .text('✓')
                        .removeClass('wpuf-req-unmet')
                        .addClass('wpuf-req-met');
                }
            }

            // Check common passwords
            if ($passField.data('disallow-common-passwords') === 'yes') {
                var isValid = true;

                // First check for repeated patterns (handled via regex)
                if (this.hasRepeatedPatterns(password)) {
                    isValid = false;
                } else {
                    // Check against common passwords list from wp_localize_script
                    var commonPasswords = (typeof wpufPasswordFields !== 'undefined' && wpufPasswordFields.commonPasswords)
                        ? wpufPasswordFields.commonPasswords
                        : [];

                    if (commonPasswords.length > 0) {
                        var passwordLower = password.toLowerCase();
                        var isCommon = commonPasswords.some(function(common) {
                            return common.toLowerCase() === passwordLower;
                        });

                        if (isCommon) {
                            isValid = false;
                        }
                    }
                }

                if (isValid) {
                    $requirementsList.find('[data-requirement="common"] .wpuf-req-icon')
                        .text('✓')
                        .removeClass('wpuf-req-unmet')
                        .addClass('wpuf-req-met');
                }
            }
        },

        /**
         * Update requirements list indicators
         */
        updateRequirementsList: function($list, password) {
            if (!$list.length) {
                return;
            }

            // Always reset indicators, even when password is empty
            $list.find('.wpuf-password-req-item').each(function() {
                var $item = $(this);
                $item.find('.wpuf-req-icon')
                    .text('✗')
                    .removeClass('wpuf-req-met')
                    .addClass('wpuf-req-unmet');
            });
        },

        /**
         * Check if password contains repeated patterns
         *
         * Detects common weak patterns such as:
         * - Same character repeated 3+ times (e.g., "aaa", "111", "tttt")
         * - Repeated sequences of 2+ characters (e.g., "121212", "paspas", "abcabc")
         *
         * @param {string} password Password to check
         * @return {boolean} True if password contains repeated patterns, false otherwise
         */
        hasRepeatedPatterns: function(password) {
            if (!password || password.length < 3) {
                return false;
            }

            // Check for same character repeated 3+ times (e.g., "aaa", "111", "tttt")
            if (/(.)\1{2,}/.test(password)) {
                return true;
            }

            // Check if entire password is a repeated sequence (e.g., "121212", "paspas", "abcabc")
            if (/^(.{2,})\1+$/.test(password)) {
                return true;
            }

            return false;
        },

        /**
         * Check if passwords match
         */
        checkPasswordMatch: function($field) {
            var $passField, $passField2, $passwordMatchMessage;
            var fieldId = $field.attr('id');

            if (!fieldId) {
                return;
            }

            // Determine which field we're working with and find its pair
            var baseId;

            if ($field.data('type') === 'password') {
                $passField = $field;
                // Find the confirm password field by replacing _1 with _2 in the ID
                baseId = fieldId.replace('_1', '');
                $passField2 = $('#' + baseId + '_2');
            } else if ($field.data('type') === 'confirm_password') {
                $passField2 = $field;
                // Find the password field by replacing _2 with _1 in the ID
                baseId = fieldId.replace('_2', '');
                $passField = $('#' + baseId + '_1');
            } else {
                return;
            }

            if (!$passField || !$passField.length || !$passField2 || !$passField2.length) {
                return;
            }

            // Find the password match message element within the same form context
            // First try to find it by ID pattern, then fall back to searching in the same container
            var $container = $field.closest('form, .wpuf-form, .wpuf-form-wrap');
            $passwordMatchMessage = $container.find('.wpuf-password-match-message');

            // If not found, try to extract form ID from field ID and search by ID
            if (!$passwordMatchMessage.length) {
                // Extract form ID: field ID format is {name}_{form_id}_{1|2}
                // Try to match the pattern by finding the last number before _1 or _2
                var match = fieldId.match(/_(\d+)_[12]$/);
                if (match && match[1]) {
                    $passwordMatchMessage = $('#wpuf-password-match_' + match[1]);
                }
            }

            if (!$passwordMatchMessage || !$passwordMatchMessage.length) {
                return;
            }

            var password1 = $passField.val();
            var password2 = $passField2.val();

            if (!password2) {
                $passwordMatchMessage.hide();
                return;
            }

            var messages = typeof wpufPasswordFields !== 'undefined' ? wpufPasswordFields : {
                matched: 'Password Matched',
                mismatch: 'Password doesn\'t match'
            };

            if (password1 === password2) {
                $passwordMatchMessage
                    .text(messages.matched)
                    .removeClass('wpuf-password-mismatch')
                    .addClass('wpuf-password-matched')
                    .show();
            } else {
                $passwordMatchMessage
                    .text(messages.mismatch)
                    .removeClass('wpuf-password-matched')
                    .addClass('wpuf-password-mismatch')
                    .show();
            }
        }
    };

    // Initialize on document ready
    // Note: bindEvents() uses delegated handlers on $(document), so a single init() is sufficient.
    // No need to re-init on wpuf-form-loaded as delegated handlers automatically cover dynamically added elements.
    $(document).ready(function() {
        WPUF_PasswordFields.init();
    });

})(jQuery);

