(function($) {
    'use strict';

    // LinkedIn username validation
    $(document).ready(function() {
        // LinkedIn username validation pattern (username only)
        const linkedinUsernamePattern = /^[a-zA-Z0-9\-]{3,100}$/;

        // Validate LinkedIn field on blur and input
        $(document).on('blur input', 'input[data-type="text"][name*="linkedin"]', 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 = linkedinUsernamePattern.test(value);
            let errorMessage = 'Please enter a valid LinkedIn username (e.g., john-doe). Use letters, numbers, and hyphens only.';

            if (isValid) {
                $input.addClass('wpuf-valid');
            } else {
                $input.addClass('wpuf-error');
                $wrapper.append('<span class="wpuf-error-msg wpuf-linkedin-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*="linkedin"]').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 = linkedinUsernamePattern.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);