(function($) {
    'use strict';

    // LinkedIn URL/username validation
    $(document).ready(function() {
        // LinkedIn username validation pattern
        const linkedinUsernamePattern = /^[a-zA-Z0-9\-]{3,100}$/;
        const linkedinUrlPattern = /^(?:https?:\/\/)?(?:www\.)?(?:linkedin\.com)\/(?:in|company)\/([A-Za-z0-9\-]{3,100})\/?$/i;

        // 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 validationType = $input.data('username-validation') || 'strict';

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

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

            let isValid = false;
            let errorMessage = '';

            if (validationType === 'allow_full_url') {
                // Allow both usernames and full URLs
                if (linkedinUsernamePattern.test(value) || linkedinUrlPattern.test(value)) {
                    isValid = true;
                } else {
                    errorMessage = wpuf_frontend.i18n.linkedinError || 'Please enter a valid LinkedIn username (e.g., john-doe) or URL';
                }
            } else {
                // Strict mode - only usernames
                if (linkedinUsernamePattern.test(value)) {
                    isValid = true;
                } else {
                    errorMessage = wpuf_frontend.i18n.linkedinUsernameError || 'Please enter a valid LinkedIn username (e.g., john-doe)';
                }
            }

            if (isValid) {
                $input.addClass('wpuf-valid');
            } else {
                $input.addClass('wpuf-error');
                $('<span class="wpuf-linkedin-error wpuf-help">' + errorMessage + '</span>').insertAfter($input.parent());
            }
        });

        // 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 validationType = $input.data('username-validation') || 'strict';
                const isRequired = $input.data('required') === 'yes';

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

                if (value) {
                    let isValid = false;

                    if (validationType === 'allow_full_url') {
                        isValid = linkedinUsernamePattern.test(value) || linkedinUrlPattern.test(value);
                    } else {
                        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);
                }
            }
        });

        // Clean up username on paste
        $(document).on('paste', 'input[data-type="text"][name*="linkedin"]', function(e) {
            const $input = $(this);
            
            setTimeout(function() {
                let value = $input.val();
                
                // Extract username from full URL if pasted
                const urlMatch = value.match(linkedinUrlPattern);
                if (urlMatch && urlMatch[1]) {
                    $input.val(urlMatch[1]);
                }
            }, 100);
        });
    });
})(jQuery);