/**
 * Twitter URL Field Frontend Validation
 */
(function ($) {
    "use strict";

    $(document).ready(function () {
        // Prevent default URL validation on Twitter fields
        $(document).on(
            "blur input",
            "input[data-username-validation]",
            function (e) {
                // Stop the event from bubbling up to prevent other URL validators
                e.stopImmediatePropagation();
            },
        );

        // Twitter URL field validation - support multiple possible field names and input types
        $(document).on(
            "blur",
            'input[name*="twitter"], input[name*="wpuf_social_twitter"], input[data-username-validation]',
            function (e) {
                var $field = $(this);
                var value = $field.val().trim();
                var $wrapper = $field.closest(".wpuf-fields");
                var $errorMsg = $wrapper.find(".wpuf-twitter-error");

                // Only validate if this is actually a Twitter field
                if (!isTwitterField($field)) {
                    return;
                }

                // Remove existing error messages (including general URL errors)
                $wrapper.find(".wpuf-error-msg").remove();
                $field.removeClass("wpuf-error");

                if (value === "") {
                    return; // Empty values are handled by required field validation
                }

                if (!validateTwitterField(value, $field)) {
                    $field.addClass("wpuf-error");
                    var errorMessage = getTwitterErrorMessage($field);
                    $wrapper.append(
                        '<span class="wpuf-error-msg wpuf-twitter-error">' +
                            errorMessage +
                            "</span>",
                    );
                }
            },
        );

        // Real-time validation as user types
        $(document).on(
            "input",
            'input[name*="twitter"], input[name*="wpuf_social_twitter"], input[data-username-validation]',
            function (e) {
                var $field = $(this);
                var value = $field.val().trim();
                var $wrapper = $field.closest(".wpuf-fields");
                var $errorMsg = $wrapper.find(".wpuf-twitter-error");

                // Only validate if this is actually a Twitter field
                if (!isTwitterField($field)) {
                    return;
                }

                // Remove all error messages
                $wrapper.find(".wpuf-error-msg").remove();
                $field.removeClass("wpuf-error");

                if (value !== "" && !validateTwitterField(value, $field)) {
                    $field.addClass("wpuf-error");
                    var errorMessage = getTwitterErrorMessage($field);
                    $wrapper.append(
                        '<span class="wpuf-error-msg wpuf-twitter-error">' +
                            errorMessage +
                            "</span>",
                    );
                }
            },
        );

        // Form submission validation
        $(document).on("submit", "form.wpuf-form-add", function (e) {
            var isValid = true;
            var $form = $(this);

            $form
                .find(
                    'input[name*="twitter"], input[name*="wpuf_social_twitter"], input[data-username-validation]',
                )
                .each(function () {
                    var $field = $(this);

                    // Only validate if this is actually a Twitter field
                    if (!isTwitterField($field)) {
                        return;
                    }

                    var value = $field.val().trim();
                    var $wrapper = $field.closest(".wpuf-fields");
                    var $errorMsg = $wrapper.find(".wpuf-twitter-error");

                    // Remove existing error messages (including general URL errors)
                    $wrapper.find(".wpuf-error-msg").remove();
                    $field.removeClass("wpuf-error");

                    if (value !== "" && !validateTwitterField(value, $field)) {
                        isValid = false;
                        $field.addClass("wpuf-error");
                        var errorMessage = getTwitterErrorMessage($field);
                        $wrapper.append(
                            '<span class="wpuf-error-msg wpuf-twitter-error">' +
                                errorMessage +
                                "</span>",
                        );
                    }
                });

            if (!isValid) {
                e.preventDefault();
                // Scroll to first error
                var $firstError = $form.find(".wpuf-error").first();
                if ($firstError.length) {
                    $("html, body").animate(
                        {
                            scrollTop: $firstError.offset().top - 100,
                        },
                        500,
                    );
                }
            }
        });
    });

    /**
     * Check if the field is actually a Twitter field
     *
     * @param {jQuery} $field
     * @returns {boolean}
     */
    function isTwitterField($field) {
        var fieldName = $field.attr("name") || "";
        var hasValidationAttr =
            $field.attr("data-username-validation") !== undefined;
        var isTwitterName =
            fieldName.includes("twitter") ||
            fieldName.includes("wpuf_social_twitter");

        return hasValidationAttr || isTwitterName;
    }

    /**
     * Get the appropriate error message based on validation type.
     *
     * @param {jQuery} $field
     * @returns {string}
     */
    function getTwitterErrorMessage($field) {
        var validationType =
            $field.data("username-validation") ||
            $field.attr("data-username-validation") ||
            "strict";

        if (validationType === "strict") {
            return "Please enter a valid X (Twitter) username (without @).";
        }
        return wpuf_frontend.error_message.twitter_url;
    }

    /**
     * Validate Twitter field input
     *
     * @param {string} value
     * @param {jQuery} $field
     * @returns {boolean}
     */
    function validateTwitterField(value, $field) {
        var validationType =
            $field.data("username-validation") ||
            $field.attr("data-username-validation") ||
            "strict";

        // Username pattern (with or without @, but for strict mode don't expect @ in input)
        var usernamePattern;
        if (validationType === "strict") {
            // For strict mode, validate without @ since user shouldn't type it (@ is shown as prefix)
            usernamePattern = /^[a-zA-Z0-9_]{1,15}$/;
        } else {
            // Allow both with and without @ for backwards compatibility in allow_full_url mode
            usernamePattern = /^@?[a-zA-Z0-9_]{1,15}$/;
        }

        // URL pattern (supports both twitter.com and x.com)
        var urlPattern =
            /^(https?:\/\/)?(www\.)?(twitter\.com|x\.com)\/[a-zA-Z0-9_]{1,15}\/?$/i;

        if (validationType === "strict") {
            return usernamePattern.test(value);
        }

        // For "allow_full_url" mode, accept both username and URL formats
        return usernamePattern.test(value) || urlPattern.test(value);
    }

    // Add error message if not already defined
    if (typeof wpuf_frontend === "undefined") {
        window.wpuf_frontend = {};
    }

    if (typeof wpuf_frontend.error_message === "undefined") {
        wpuf_frontend.error_message = {};
    }

    wpuf_frontend.error_message.twitter_url =
        "Please enter a valid X (Twitter) URL.";
    wpuf_frontend.error_message.twitter_username =
        "Please enter a valid X (Twitter) username (without @).";
})(jQuery);
