(function($) {
    'use strict';

    // Instagram URL/username validation
    $(document).ready(function() {
        // Instagram username validation pattern
        const instagramUsernamePattern = /^[a-zA-Z0-9_\.]{1,30}$/;
        const instagramUrlPattern = /^(?:https?:\/\/)?(?:www\.)?(?:instagram\.com|instagr\.am)\/([A-Za-z0-9_\.]{1,30})\/?$/i;

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

            // Remove any existing error messages
            $input.removeClass('wpuf-error wpuf-valid');
            $input.parent().find('.wpuf-instagram-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 (instagramUsernamePattern.test(value) || instagramUrlPattern.test(value)) {
                    isValid = true;
                } else {
                    errorMessage = wpuf_frontend.i18n.instagramError || 'Please enter a valid Instagram username or URL';
                }
            } else {
                // Strict mode - only usernames
                if (instagramUsernamePattern.test(value)) {
                    isValid = true;
                } else {
                    errorMessage = wpuf_frontend.i18n.instagramUsernameError || 'Please enter a valid Instagram username (letters, numbers, periods and underscores only)';
                }
            }

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

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