/**
 * Modern Social Login JavaScript
 * Handles interactions and loading states for the modern social login interface
 */
(function ($) {
    "use strict";

    $(document).ready(function () {
        // Add loading state when social login is clicked
        $(".wpuf-social-signin-btn").on("click", function (e) {
            var $this = $(this);

            // Prevent double-clicks
            if ($this.hasClass("wpuf-social-loading")) {
                e.preventDefault();
                return false;
            }

            // Add loading state
            $this.addClass("wpuf-social-loading");

            // Remove loading state after 5 seconds (failsafe)
            setTimeout(function () {
                $this.removeClass("wpuf-social-loading");
            }, 5000);
        });

        // Add keyboard navigation support
        $(".wpuf-social-signin-btn").on("keydown", function (e) {
            if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                $(this)[0].click();
            }
        });

        // Handle form ID propagation for dynamic forms
        function updateSocialLinksWithFormId() {
            var formId = "";

            // Try to get form ID from various sources
            var $formIdInput = $('input[name="form_id"]');
            if ($formIdInput.length) {
                formId = $formIdInput.val();
            } else {
                // Check for form ID in URL
                var urlParams = new URLSearchParams(window.location.search);
                formId = urlParams.get("form_id") || "";
            }

            if (formId) {
                $(".wpuf-social-signin-btn").each(function () {
                    var href = $(this).attr("href");
                    if (href && href.indexOf("form_id=") === -1) {
                        var separator = href.indexOf("?") > -1 ? "&" : "?";
                        $(this).attr(
                            "href",
                            href + separator + "form_id=" + formId,
                        );
                    }
                });
            }
        }

        // Update links initially
        updateSocialLinksWithFormId();

        // Update links when new forms are loaded (for AJAX forms)
        $(document).on("wpuf_form_loaded", updateSocialLinksWithFormId);

        // Handle dynamic content loading
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.addedNodes.length) {
                    updateSocialLinksWithFormId();
                }
            });
        });

        // Start observing
        observer.observe(document.body, {
            childList: true,
            subtree: true,
        });
    });
})(jQuery);
