(function($) {
    'use strict';

    $(document).ready(function() {
        // Twitter username validation pattern (username only)
        const twitterUsernamePattern = /^[a-zA-Z][a-zA-Z0-9_]{3,14}$/;

        // Validate Twitter field on blur and input
        $(document).on('blur input', 'input[data-type="text"][name*="twitter"]', function() {
            const $input = $(this);
            let 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();

            // Remove @ symbol if user added it
            if (value.startsWith('@')) {
                value = value.substring(1);
                $input.val(value);
            }

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

            let isValid = twitterUsernamePattern.test(value);
            let errorMessage = 'Please enter a valid X (Twitter) username (4-15 characters, must start with a letter).';

            if (isValid) {
                $input.addClass('wpuf-valid');
            } else {
                $input.addClass('wpuf-error');
                $wrapper.append('<span class="wpuf-error-msg wpuf-twitter-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*="twitter"]').each(function() {
                const $input = $(this);
                let value = $input.val().trim();
                const isRequired = $input.data('required') === 'yes';

                // Remove @ symbol if present
                if (value.startsWith('@')) {
                    value = value.substring(1);
                    $input.val(value);
                }

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

                if (value) {
                    let isValid = twitterUsernamePattern.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);
