jQuery(document).ready(function($){
    // Debug logging for DOM elements
    console.log('easyaibloggen-update.js loaded');
    
    // Handle preferred keyword saving
    $('#easyaibloggen-save-preferred-keyword').on('click', function() {
        var button = $(this);
        var input = $('#easyaibloggen-preferred-keyword');
        var statusDiv = $('#easyaibloggen-keyword-save-status');
        var keyword = input.val().trim();
        var postId = button.data('postid');
        
        if (!keyword) {
            statusDiv.html('<span style="color: #dc3232;">Please enter a keyword</span>');
            return;
        }
        
        // Disable button and show loading state
        button.prop('disabled', true);
        statusDiv.html('<span style="color: #007cba;">Saving...</span>');
        
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: {
                action: 'easyaibloggen_save_preferred_keyword',
                nonce: easyaibloggenUpdate.preferredKeywordNonce,
                post_id: postId,
                keyword: keyword
            },
            success: function(response) {
                if (response.success) {
                    statusDiv.html('<span style="color: #46b450;">Keyword saved successfully!</span>');
                    // Update button text
                    button.text('Update Keyword');
                } else {
                    statusDiv.html('<span style="color: #dc3232;">Error: ' + (response.data || 'Unknown error') + '</span>');
                }
            },
            error: function() {
                statusDiv.html('<span style="color: #dc3232;">Error saving keyword. Please try again.</span>');
            },
            complete: function() {
                button.prop('disabled', false);
            }
        });
    });
    
    // Debug logging for social elements
    console.log('Social previews container exists:', $('#easyaibloggen-social-previews').length > 0);
    console.log('Social buttons exist:', $('.easyaibloggen-social-button').length > 0);
    
    // Define the function inside jQuery scope
    function ensureSocialPreviewsContainer() {
        // Check if container already exists
        if ($('#easyaibloggen-social-previews').length > 0) {
            return $('#easyaibloggen-social-previews');
        }
        
        console.log('Social previews container not found, trying to create it');
        
        // Try to find the metabox container
        var possibleContainers = [
            // Try the inside of the metabox that contains the social buttons
            $('.easyaibloggen-social-button').closest('.postbox').find('> .inside'),
            
            // Try the parent metabox itself
            $('.easyaibloggen-social-button').first().closest('.postbox'),
            
            // Try just the direct parent of the buttons
            $('.easyaibloggen-social-button').first().parent(),
        ];
        
        var containerFound = false;
        
        // Try each possible container
        $.each(possibleContainers, function(i, container) {
            if (container && container.length > 0) {
                console.log('Found a suitable container, appending social previews container');
                containerFound = true;
                
                // Create and append the container
                var container = $('<div id="easyaibloggen-social-previews" style="margin-top: 20px; border-top: 1px solid #ddd; padding-top: 20px;"></div>');
                $(possibleContainers[i]).append(container);
                
                return false; // Break the loop
            }
        });
        
        if (containerFound) {
            return $('#easyaibloggen-social-previews');
        }
        
        console.error('Could not find a suitable container for social previews');
        return null;
    }
    
    // Add a function to check if the boost button is visible
    function checkBoostButtonVisibility() {
        setTimeout(function() {
            var boostButtons = $('.social-boost-btn');
            console.log('Found ' + boostButtons.length + ' boost buttons in the DOM');
            
            if (boostButtons.length > 0) {
                // Check if the buttons are visible
                var visibleButtons = boostButtons.filter(function() {
                    var $this = $(this);
                    return $this.is(':visible') && $this.css('display') !== 'none' && $this.css('visibility') !== 'hidden';
                });
                
                console.log('Visible boost buttons: ' + visibleButtons.length);
                
                // For each button, log its CSS properties
                boostButtons.each(function(index) {
                    var $btn = $(this);
                    console.log('Button ' + index + ':');
                    console.log('- Display: ' + $btn.css('display'));
                    console.log('- Visibility: ' + $btn.css('visibility'));
                    console.log('- Opacity: ' + $btn.css('opacity'));
                    console.log('- Height: ' + $btn.css('height'));
                    console.log('- Is in viewport: ' + isElementInViewport($btn[0]));
                    console.log('- HTML: ' + $btn.prop('outerHTML').substring(0, 100) + '...');
                    
                    // Add a red border to help identify it visually
                    $btn.css('border', '3px solid red');
                });
            }
        }, 1000); // Check after 1 second
    }

    // Helper function to check if element is in viewport
    function isElementInViewport(el) {
        var rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
    
    // Ensure the social previews container exists
    var $previewsContainer = ensureSocialPreviewsContainer();
    console.log('Social previews container ready:', $previewsContainer !== null);
    
    // Social Media Promotion functionality
    $(document).on('click', '.easyaibloggen-social-button', function(e){
        e.preventDefault();
        var platform = $(this).data('platform');
        var postId = $(this).data('postid');
        var buttonText = $(this).text();
        
        // Disable all social buttons and show loading
        $('.easyaibloggen-social-button').prop('disabled', true);
        $(this).text('Generating...');
        
        // Clear previous previews if generating all or when showing single platform
        if (platform === 'all') {
            $('#easyaibloggen-social-previews').empty();
        } else {
            // Only remove the specific platform card if it exists
            $('#easyaibloggen-social-' + platform).remove();
        }
        
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: {
                action: 'easyaibloggen_generate_social_promotion',
                nonce: easyaibloggenUpdate.nonce,
                post_id: postId,
                platform: platform
            },
            success: function(response) {
                // Re-enable buttons
                $('.easyaibloggen-social-button').prop('disabled', false);
                $('.easyaibloggen-social-button.twitter').text('Twitter/X');
                $('.easyaibloggen-social-button.facebook').text('Facebook');
                $('.easyaibloggen-social-button.linkedin').text('LinkedIn');
                $('.easyaibloggen-social-button.instagram').text('Instagram');
                $('.easyaibloggen-social-button.all').text('Generate All');
                
                console.log('Social content response:', response); // Add logging
                
                // Ensure we have a container for the previews
                var $previewsContainer = ensureSocialPreviewsContainer();
                if (!$previewsContainer) {
                    console.error('Could not find or create social previews container');
                    alert('Error: Could not display social media content');
                    return;
                }
                
                if (response.success) {
                    if (platform === 'all') {
                        // Handle all platforms response
                        var platforms = ['twitter', 'facebook', 'linkedin', 'instagram'];
                        platforms.forEach(function(p) {
                            if (response.data[p]) {
                                // Directly add the social content to the preview area
                                $previewsContainer.append(
                                    '<div id="easyaibloggen-social-' + p + '" class="easyaibloggen-social-card" style="margin-top: 15px; padding: 12px; border: 1px solid ' + 
                                    {
                                        'twitter': '#1DA1F2',
                                        'facebook': '#4267B2',
                                        'linkedin': '#0077B5',
                                        'instagram': '#C13584'
                                    }[p] + 
                                    '; border-radius: 4px;">' +
                                    '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                                    '<span class="dashicons dashicons-' + 
                                    {
                                        'twitter': 'twitter',
                                        'facebook': 'facebook',
                                        'linkedin': 'linkedin',
                                        'instagram': 'instagram'
                                    }[p] + 
                                    '" style="color: ' + 
                                    {
                                        'twitter': '#1DA1F2',
                                        'facebook': '#4267B2',
                                        'linkedin': '#0077B5',
                                        'instagram': '#C13584'
                                    }[p] + 
                                    '; margin-right: 8px;"></span>' +
                                    '<strong>' + 
                                    {
                                        'twitter': 'Twitter/X',
                                        'facebook': 'Facebook',
                                        'linkedin': 'LinkedIn',
                                        'instagram': 'Instagram'
                                    }[p] + 
                                    '</strong></div>' +
                                    '<textarea id="easyaibloggen-social-textarea-' + p + '" class="easyaibloggen-social-textarea" data-platform="' + p + '" style="width: 100%; min-height: 120px;">' + response.data[p].content + '</textarea>' +
                                    '<div class="easyaibloggen-char-count" style="font-size: 0.9em; margin-top: 5px;">' + response.data[p].character_count + ' characters</div>' +
                                    '<div style="margin-top: 10px; margin-bottom: 5px;">' +
                                    '<button type="button" class="button social-boost-btn" style="background-color: #5d9cec; color: white; border-color: #4a89dc; margin-right: 5px;" data-platform="' + p + '" data-textarea-id="easyaibloggen-social-textarea-' + p + '"><span class="dashicons dashicons-chart-line" style="margin-top: 3px; margin-right: 5px;"></span> Boost Engagement</button>' +
                                    '<div style="color: #666; font-style: italic; margin-top: 5px; font-size: 0.85em;"><small>⚠️ Optimizes for clicks & shares. May appear promotional.</small></div>' +
                                    '</div>' +
                                    '<button class="button easyaibloggen-copy-social" style="margin-top: 10px;"><span class="dashicons dashicons-clipboard" style="margin-top: 3px;"></span> Copy to Clipboard</button>' +
                                    '</div>'
                                );
                                console.log('Added card for platform ' + p + ' to container');
                            }
                        });
                    } else {
                        // Handle single platform response - direct HTML insertion
                        $previewsContainer.append(
                            '<div id="easyaibloggen-social-' + platform + '" class="easyaibloggen-social-card" style="margin-top: 15px; padding: 12px; border: 1px solid ' + 
                            {
                                'twitter': '#1DA1F2',
                                'facebook': '#4267B2',
                                'linkedin': '#0077B5',
                                'instagram': '#C13584'
                            }[platform] + 
                            '; border-radius: 4px;">' +
                            '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                            '<span class="dashicons dashicons-' + 
                            {
                                'twitter': 'twitter',
                                'facebook': 'facebook',
                                'linkedin': 'linkedin',
                                'instagram': 'instagram'
                            }[platform] + 
                            '" style="color: ' + 
                            {
                                'twitter': '#1DA1F2',
                                'facebook': '#4267B2',
                                'linkedin': '#0077B5',
                                'instagram': '#C13584'
                            }[platform] + 
                            '; margin-right: 8px;"></span>' +
                            '<strong>' + 
                            {
                                'twitter': 'Twitter/X',
                                'facebook': 'Facebook',
                                'linkedin': 'LinkedIn',
                                'instagram': 'Instagram'
                            }[platform] + 
                            '</strong></div>' +
                            '<textarea id="easyaibloggen-social-textarea-' + platform + '" class="easyaibloggen-social-textarea" data-platform="' + platform + '" style="width: 100%; min-height: 120px;">' + response.data.content + '</textarea>' +
                            '<div class="easyaibloggen-char-count" style="font-size: 0.9em; margin-top: 5px;">' + response.data.character_count + ' characters</div>' +
                            '<div style="margin-top: 10px; margin-bottom: 5px;">' +
                            '<button type="button" class="button social-boost-btn" style="background-color: #5d9cec; color: white; border-color: #4a89dc; margin-right: 5px;" data-platform="' + platform + '" data-textarea-id="easyaibloggen-social-textarea-' + platform + '"><span class="dashicons dashicons-chart-line" style="margin-top: 3px; margin-right: 5px;"></span> Boost Engagement</button>' +
                            '<div style="color: #666; font-style: italic; margin-top: 5px; font-size: 0.85em;"><small>⚠️ Optimizes for clicks & shares. May appear promotional.</small></div>' +
                            '</div>' +
                            '<button class="button easyaibloggen-copy-social" style="margin-top: 10px;"><span class="dashicons dashicons-clipboard" style="margin-top: 3px;"></span> Copy to Clipboard</button>' +
                            '</div>'
                        );
                        console.log('Added card for platform ' + platform + ' to container');
                    }
                } else {
                    alert('Error: ' + (response.data || 'Something went wrong'));
                }
            },
            error: function() {
                // Re-enable buttons
                $('.easyaibloggen-social-button').prop('disabled', false);
                $('.easyaibloggen-social-button.twitter').text('Twitter/X');
                $('.easyaibloggen-social-button.facebook').text('Facebook');
                $('.easyaibloggen-social-button.linkedin').text('LinkedIn');
                $('.easyaibloggen-social-button.instagram').text('Instagram');
                $('.easyaibloggen-social-button.all').text('Generate All');
                
                alert('Error: Could not connect to the server');
            }
        });
    });
    
    // Handle copying to clipboard
    $(document).on('click', '.easyaibloggen-copy-social', function(e) {
        e.preventDefault();
        var textArea = $(this).closest('.easyaibloggen-social-card').find('textarea');
        textArea.select();
        document.execCommand('copy');
        
        // Temporarily change button text
        var originalText = $(this).text();
        $(this).text('Copied!');
        
        var button = $(this);
        setTimeout(function() {
            button.text(originalText);
        }, 2000);
    });
    
    // Handle editing the social content with character counting for Twitter
    $(document).on('input', '.easyaibloggen-social-textarea', function() {
        var platform = $(this).data('platform');
        var charCount = $(this).val().length;
        
        // Update character count
        var countElement = $(this).closest('.easyaibloggen-social-card').find('.easyaibloggen-char-count');
        countElement.text(charCount + ' characters');
        
        // Add warning for Twitter if over character limit
        if (platform === 'twitter' && charCount > 280) {
            countElement.css('color', 'red');
            countElement.html('<strong>' + charCount + ' characters</strong> - <span style="color: #ff0000;">Exceeds Twitter\'s 280 character limit! Please shorten your message.</span>');
            
            // Disable copy button if over limit
            $(this).closest('.easyaibloggen-social-card').find('.easyaibloggen-copy-social').prop('disabled', true);
        } else if (platform === 'twitter' && charCount > 260) {
            countElement.css('color', '#ff9900'); // Warning color
            countElement.html('<strong>' + charCount + ' characters</strong> - <span style="color: #ff9900;">Warning: Approaching Twitter\'s limit. Leave room for the URL.</span>');
            $(this).closest('.easyaibloggen-social-card').find('.easyaibloggen-copy-social').prop('disabled', false);
        } else {
            countElement.css('color', '');
            $(this).closest('.easyaibloggen-social-card').find('.easyaibloggen-copy-social').prop('disabled', false);
        }
    });
    
    // Single, clean handler for the Engagement Boost button
    $(document).on('click', '.social-boost-btn', function(e) {
        e.preventDefault(); // Prevent link from navigating
        var button = $(this);
        var platform = button.data('platform');
        var textareaId = button.data('textarea-id');
        var textarea = $('#' + textareaId);
        var content = textarea.val();
        
        console.log('Boost button clicked for: ' + platform + ', textarea: ' + textareaId);
        
        // Show loading indicator
        button.html('<span class="dashicons dashicons-update" style="animation: spin 2s linear infinite; margin-top: 3px;"></span> Boosting...');
        
        // Send AJAX request
        $.ajax({
            url: easyaibloggenUpdate.ajaxurl,
            type: 'POST',
            data: {
                action: 'easyaibloggen_engagement_boost',
                platform: platform,
                content: content,
                nonce: easyaibloggenUpdate.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Replace original content with engagement-optimized version
                    textarea.val(response.data.content);
                    
                    // Show success message
                    $('<div style="background-color: #e7f7e3; border-left: 4px solid #46b450; padding: 10px; margin: 10px 0; font-size: 0.9em;">Engagement elements added! This optimizes for more clicks and shares.</div>')
                        .insertAfter(textarea)
                        .delay(5000)
                        .fadeOut(function() { $(this).remove(); });
                } else {
                    // Show error message
                    $('<div style="background-color: #ffe5e5; border-left: 4px solid #dc3232; padding: 10px; margin: 10px 0; font-size: 0.9em;">Failed to optimize content. Please try again.</div>')
                        .insertAfter(textarea)
                        .delay(5000)
                        .fadeOut(function() { $(this).remove(); });
                }
            },
            error: function(xhr, status, error) {
                // Show error message
                $('<div style="background-color: #ffe5e5; border-left: 4px solid #dc3232; padding: 10px; margin: 10px 0; font-size: 0.9em;">Server error. Please try again later.</div>')
                    .insertAfter(textarea)
                    .delay(5000)
                    .fadeOut(function() { $(this).remove(); });
                console.log('AJAX error: ' + error);
            },
            complete: function() {
                // Reset button
                button.html('<span class="dashicons dashicons-chart-line" style="margin-top: 3px; margin-right: 5px;"></span> Boost Engagement');
            }
        });
    });

    // Format Conversion functionality
    $(document).on('click', '.easyaibloggen-convert-format-btn', function(e){
        e.preventDefault();
        var currentPostId = $(this).data('postid');
        var selectedFormat = $('#easyaibloggen-format-style').val();
        
        console.log("Convert format:", selectedFormat, "Post ID:", currentPostId);
        $('#easyaibloggen-update-preview').html('<p>Generating format preview...</p>');
        
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: {
                action: 'easyaibloggen_convert_format',
                nonce: easyaibloggenUpdate.nonce,
                post_id: currentPostId,
                format: selectedFormat,
                preview: 1
            },
            success: function(response){
                console.log("Format preview response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').html('<p>Preview of ' + selectedFormat + ' format:</p><div>' + response.data.preview + '</div>');
                    
                    // Create an apply button specifically for the format conversion
                    var applyButton = $('<button id="easyaibloggen-apply-format" class="button button-primary" style="margin-top:10px;">Apply Format Changes</button>');
                    $('#easyaibloggen-update-preview').append(applyButton);
                } else {
                    $('#easyaibloggen-update-preview').html('<p>Error: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').html('<p>AJAX error: ' + textStatus + '</p>');
                console.log("AJAX error in format preview:", textStatus);
            }
        });
    });
    
    // Handle the dynamically created Apply Format button
    $(document).on('click', '#easyaibloggen-apply-format', function(e){
        e.preventDefault();
        var postId = $('.easyaibloggen-convert-format-btn').data('postid');
        var format = $('#easyaibloggen-format-style').val();
        applyFormatChanges(postId, format);
    });
    
    function applyFormatChanges(postId, format) {
        $('#easyaibloggen-update-preview').append('<p>Applying format changes...</p>');
        
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: {
                action: 'easyaibloggen_convert_format',
                nonce: easyaibloggenUpdate.nonce,
                post_id: postId,
                format: format,
                from_preview: 1 // Use the saved preview data instead of generating new content
            },
            success: function(response){
                console.log("Format apply response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').append('<p>Format changes applied successfully. <a href="' + window.location.href + '">Refresh</a> to see the updated post.</p>');
                } else {
                    $('#easyaibloggen-update-preview').append('<p>Error applying format changes: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').append('<p>AJAX error applying format changes: ' + textStatus + '</p>');
                console.log("AJAX error in format apply:", textStatus);
            }
        });
    }
    
    // Handle the Update buttons
    $(document).on('click', '.easyaibloggen-update-btn', function(e){
        e.preventDefault();
        var currentUpdateType = $(this).data('update-type');
        var currentPostId = $(this).data('postid');
        console.log("Preview update:", currentUpdateType, "Post ID:", currentPostId);
        var extraData = {};
        if(currentUpdateType === 'image'){
            extraData.image_style = $('#easyaibloggen-meta-image-style').val();
        }
        $('#easyaibloggen-update-preview').html('<p>Loading preview...</p>');
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: $.extend({
                action: 'easyaibloggen_update_' + currentUpdateType,
                nonce: easyaibloggenUpdate.nonce,
                post_id: currentPostId,
                preview: 1
            }, extraData),
            success: function(response){
                console.log("Preview response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').html('<p>Preview:</p><div>' + response.data.preview + '</div>');
                    $('#easyaibloggen-apply-changes')
                        .data('update-type', currentUpdateType)
                        .data('postid', currentPostId)
                        .show();
                } else {
                    $('#easyaibloggen-update-preview').html('<p>Error: ' + response.data + '</p>');
                    $('#easyaibloggen-apply-changes').hide();
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').html('<p>AJAX error: ' + textStatus + '</p>');
                console.log("AJAX error in preview:", textStatus);
                $('#easyaibloggen-apply-changes').hide();
            }
        });
    });
    
    // Handle the Apply Changes button
    $(document).on('click', '#easyaibloggen-apply-changes', function(e){
        e.preventDefault();
        var currentUpdateType = $(this).data('update-type');
        var currentPostId = $(this).data('postid');
        if(!currentUpdateType || !currentPostId){
            alert("No update to apply.");
            return;
        }
        console.log("Applying update:", currentUpdateType, "Post ID:", currentPostId);
        $('#easyaibloggen-update-preview').append('<p>Applying changes...</p>');
        var extraData = {};
        if(currentUpdateType === 'image'){
            extraData.image_style = $('#easyaibloggen-meta-image-style').val();
        }
        $.ajax({
            type: 'POST',
            url: easyaibloggenUpdate.ajaxurl,
            data: $.extend({
                action: 'easyaibloggen_update_' + currentUpdateType,
                nonce: easyaibloggenUpdate.nonce,
                post_id: currentPostId
            }, extraData),
            success: function(response){
                console.log("Apply response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').append('<p>Update applied successfully.</p>');
                } else {
                    $('#easyaibloggen-update-preview').append('<p>Error applying update: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').append('<p>AJAX error applying update: ' + textStatus + '</p>');
                console.log("AJAX error in apply:", textStatus);
            }
        });
    });

    // Add click handler for plain text boost link
    $(document).on('click', '.plain-text-boost', function(e) {
        e.preventDefault();
        var $this = $(this);
        var platform = $this.data('platform');
        var textareaId = $this.data('textarea-id');
        
        // Find the corresponding button and trigger its click handler
        $('.social-boost-btn[data-platform="' + platform + '"][data-textarea-id="' + textareaId + '"]').trigger('click');
    });

    // Add a new click handler for the basic boost button
    $(document).on('click', '.easyaibloggen-basic-boost-btn', function(e) {
        console.log('Basic boost button clicked');
        var $this = $(this);
        var platform = $this.data('platform');
        var textareaId = $this.data('textarea-id');
        
        // Trigger the same functionality as the original boost button
        $('.social-boost-btn[data-platform="' + platform + '"][data-textarea-id="' + textareaId + '"]').trigger('click');
        
        // If the original button is missing, perform the boost directly
        if ($('.social-boost-btn[data-platform="' + platform + '"][data-textarea-id="' + textareaId + '"]').length === 0) {
            var textarea = $('#' + textareaId);
            var content = textarea.val();
            
            $this.text('Boosting...');
            
            // Send AJAX request
            $.ajax({
                url: easyaibloggenUpdate.ajaxurl,
                type: 'POST',
                data: {
                    action: 'easyaibloggen_engagement_boost',
                    platform: platform,
                    content: content,
                    nonce: easyaibloggenUpdate.nonce
                },
                success: function(response) {
                    if (response.success) {
                        textarea.val(response.data.content);
                        
                        $('<div style="background-color: #e7f7e3; border-left: 4px solid #46b450; padding: 10px; margin: 10px 0; font-size: 0.9em;">Engagement elements added! This optimizes for more clicks and shares.</div>')
                            .insertAfter(textarea)
                            .delay(5000)
                            .fadeOut(function() { $(this).remove(); });
                    } else {
                        $('<div style="background-color: #ffe5e5; border-left: 4px solid #dc3232; padding: 10px; margin: 10px 0; font-size: 0.9em;">Failed to optimize content. Please try again.</div>')
                            .insertAfter(textarea)
                            .delay(5000)
                            .fadeOut(function() { $(this).remove(); });
                    }
                },
                error: function(xhr, status, error) {
                    $('<div style="background-color: #ffe5e5; border-left: 4px solid #dc3232; padding: 10px; margin: 10px 0; font-size: 0.9em;">Server error. Please try again later.</div>')
                        .insertAfter(textarea)
                        .delay(5000)
                        .fadeOut(function() { $(this).remove(); });
                    console.log('AJAX error: ' + error);
                },
                complete: function() {
                    $this.text('💫 Boost Engagement (Basic)');
                }
            });
        }
    });

    // Emergency fix for missing boost buttons
    console.log('Setting up emergency boost button inserter');
    var buttonCheckInterval = setInterval(function() {
        var socialTextareas = $('.easyaibloggen-social-textarea');
        console.log('Found ' + socialTextareas.length + ' social textareas');
        
        if (socialTextareas.length > 0) {
            socialTextareas.each(function() {
                var $textarea = $(this);
                var $card = $textarea.closest('.easyaibloggen-social-card');
                var platform = $textarea.data('platform');
                var textareaId = $textarea.attr('id');
                
                // Only add button if it doesn't exist already
                if ($card.find('.social-boost-btn').length === 0) {
                    console.log('Adding boost button after textarea: ' + textareaId);
                    
                    // Get the character count div
                    var $charCount = $card.find('.easyaibloggen-char-count');
                    
                    // Create button HTML
                    var $boostButton = $(
                        '<div style="margin: 10px 0;">' +
                        '<button type="button" class="button social-boost-btn" style="background-color: #5d9cec; color: white; border-color: #4a89dc; margin-right: 5px;" data-platform="' + platform + '" data-textarea-id="' + textareaId + '">' +
                        '<span class="dashicons dashicons-chart-line" style="margin-top: 3px; margin-right: 5px;"></span> Boost Engagement' +
                        '</button>' +
                        '<div style="color: #666; font-style: italic; margin-top: 5px; font-size: 0.85em;"><small>⚠️ Optimizes for clicks & shares. May appear promotional.</small></div>' +
                        '</div>'
                    );
                    
                    // Insert after character count
                    $boostButton.insertAfter($charCount);
                }
            });
        }
    }, 1000); // Check every 1 second
    
    // Stop checking after 30 seconds
    setTimeout(function() {
        console.log('Stopping emergency boost button inserter');
        clearInterval(buttonCheckInterval);
    }, 30000);
}); 