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

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

        // Facebook URL field validation - support multiple possible field names and input types
        $(document).on(
            "blur",
            'input[name*="facebook"], input[name*="wpuf_social_facebook"], 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-facebook-error");

                // Only validate if this is actually a Facebook field
                if (!isFacebookField($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 (!validateFacebookField(value, $field)) {
                    $field.addClass("wpuf-error");
                    var errorMessage = getFacebookErrorMessage($field);
                    $wrapper.append(
                        '<span class="wpuf-error-msg wpuf-facebook-error">' +
                            errorMessage +
                            "</span>",
                    );
                }
            },
        );

        // Real-time validation as user types
        $(document).on(
            "input",
            'input[name*="facebook"], input[name*="wpuf_social_facebook"], 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-facebook-error");

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

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

                if (value !== "" && !validateFacebookField(value, $field)) {
                    $field.addClass("wpuf-error");
                    var errorMessage = getFacebookErrorMessage($field);
                    $wrapper.append(
                        '<span class="wpuf-error-msg wpuf-facebook-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*="facebook"], input[name*="wpuf_social_facebook"], input[data-username-validation]',
                )
                .each(function () {
                    var $field = $(this);

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

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

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

                    if (value !== "" && !validateFacebookField(value, $field)) {
                        isValid = false;
                        $field.addClass("wpuf-error");
                        var errorMessage = getFacebookErrorMessage($field);
                        $wrapper.append(
                            '<span class="wpuf-error-msg wpuf-facebook-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 Facebook field
     *
     * @param {jQuery} $field
     * @returns {boolean}
     */
    function isFacebookField($field) {
        var fieldName = $field.attr("name") || "";
        var hasValidationAttr =
            $field.attr("data-username-validation") !== undefined;
        var isFacebookName =
            fieldName.includes("facebook") ||
            fieldName.includes("wpuf_social_facebook");

        return hasValidationAttr || isFacebookName;
    }

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

        if (validationType === "strict") {
            return "Please enter a valid Facebook username.";
        }
        return wpuf_frontend.error_message.facebook_url;
    }

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

        // Username pattern (Facebook allows letters, numbers, and dots)
        var usernamePattern = /^[a-zA-Z0-9\.]{1,50}$/;

        // URL pattern (supports both facebook.com and fb.com)
        var urlPattern =
            /^(https?:\/\/)?(www\.)?(facebook\.com|fb\.com)\/[a-zA-Z0-9\.]{1,50}\/?$/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.facebook_url =
        "Please enter a valid Facebook URL.";
    wpuf_frontend.error_message.facebook_username =
        "Please enter a valid Facebook username.";
})(jQuery);