(function($) {
    'use strict';

    // Instagram username validation
    $(document).ready(function() {
        // Instagram username validation pattern (username only)
        const instagramUsernamePattern = /^[a-zA-Z0-9_\.]{1,30}$/;

        // Validate Instagram field on blur and input
        $(document).on('blur input', 'input[data-type="text"][name*="instagram"]', 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 = instagramUsernamePattern.test(value);
            let errorMessage = 'Please enter a valid Instagram username (letters, numbers, periods and underscores only).';

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