(function($) {
    // Check if we have the required data
    if (typeof formshieldCF7Data === 'undefined') {
        console.error('FormShield: CF7 data not found');
        return;
    }

    if (!formshieldCF7Data.protectedForms || !formshieldCF7Data.badge) {
        console.error('FormShield: Missing required data', formshieldCF7Data);
        return;
    }

    
    // Function to add badge to CF7 forms
    function addCF7Badge() {
        // Find all CF7 forms
        var $forms = $(".wpcf7-form");
        
        $forms.each(function() {
            var $form = $(this);
            var $container = $form.closest(".wpcf7");
            
            if (!$container.length) {
                console.warn('FormShield: Could not find .wpcf7 container for form', $form);
                return;
            }
            
            var formId = $container.attr("id") || "";
            
            // Extract form ID from container ID (e.g., wpcf7-f123-p4-o1 -> 123)
            var matches = formId.match(/wpcf7-f(\d+)/);
            if (!matches) {
                console.warn('FormShield: Could not extract CF7 ID from', formId);
                return;
            }
            
            var cf7Id = "cf7-" + matches[1];
            
            // Check if this form is protected
            var isProtected = formshieldCF7Data.protectedForms.indexOf(cf7Id) !== -1;
            
            // Only add badge if form is protected and doesn't already have one
            if (isProtected) {
                var $existingBadge = $container.find(".formshield-protected-badge");
                if ($existingBadge.length === 0) {
                    $container.append(formshieldCF7Data.badge);
                }
            }
        });
    }
    
    // Add badge when DOM is ready
    $(document).ready(function() {
        addCF7Badge();
    });
    
    // Add badge when forms are loaded via AJAX
    $(document).on("wpcf7mailsent wpcf7reset wpcf7invalid wpcf7valid", function(e) {
        setTimeout(addCF7Badge, 100);
    });
})(jQuery);
