(function($) {
    'use strict';

    $(document).ready(function() {
        // Facebook username validation pattern (username only)
        const facebookUsernamePattern = /^[a-zA-Z0-9\.]{5,50}$/;

        // Validate Facebook field on blur and input
        $(document).on('blur input', 'input[data-type="text"][name*="facebook"]', function() {
            const $input = $(this);
            const value = $input.val().trim();
            const $wrapper = $input.closest('.wpuf-fields');

            // Remove any existing error messages
            $input.removeClass('wpuf-error wpuf-valid');
            $wrapper.find('.wpuf-error-msg').remove();

            if (!value) {
                return; // Empty is valid (handled by required field validation)
            }

            let isValid = facebookUsernamePattern.test(value);
            let errorMessage = 'Please enter a valid Facebook username (5-50 characters: letters, numbers, and dots only).';

            if (isValid) {
                $input.addClass('wpuf-valid');
            } else {
                $input.addClass('wpuf-error');
                $wrapper.append('<span class="wpuf-error-msg wpuf-facebook-error">' + errorMessage + '</span>');
            }
        });

        // Handle form submission
        $(document).on('submit', '.wpuf-form-add, .wpuf-profile-form', function(e) {
            let hasError = false;

            $(this).find('input[data-type="text"][name*="facebook"]').each(function() {
                const $input = $(this);
                const value = $input.val().trim();
                const isRequired = $input.data('required') === 'yes';

                if (!value && !isRequired) {
                    return; // Skip validation for empty non-required fields
                }

                if (value) {
                    let isValid = facebookUsernamePattern.test(value);

                    if (!isValid) {
                        hasError = true;
                        $input.trigger('blur'); // Trigger blur to show error
                    }
                }
            });

            if (hasError) {
                e.preventDefault();
                // Scroll to first error
                const $firstError = $('.wpuf-error:first');
                if ($firstError.length) {
                    $('html, body').animate({
                        scrollTop: $firstError.offset().top - 100
                    }, 500);
                }
            }
        });
    });
})(jQuery);
