jQuery(document).ready(function($) {
    var currentImageData = null;

    $('#diyseo_generate_featured_image').on('click', function() {
        generateImage();
    });

    $('#diyseo_regenerate_image').on('click', function() {
        generateImage();
    });

    function generateImage() {
        var prompt = $('#diyseo_image_prompt').val();
        if (!prompt) {
            alert('Please enter a prompt for the image.');
            return;
        }

        var data = {
            action: 'diyseo_generate_featured_image',
            prompt: prompt,
            nonce: diyseoFeaturedImageParams.generateNonce
        };

        $('#diyseo_featured_image_loading').show();
        $('#diyseo_preview_actions').hide();
        showImageLoading();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
    $('#diyseo_featured_image_loading').hide();
    hideImageLoading();
    if (response.success && response.data.url && response.data.id) {
        currentImageData = response.data;
        $('#diyseo_featured_image_preview').html(
            '<div style="text-align: center;">' +
            '<img src="' + currentImageData.url + '" style="max-width:100%; margin-bottom: 10px;">' +
            '</div>'
        );

        // Remove any existing notifications first
        $('.diyseo-notification').remove();

        // Add the notification
        var notification = $('<div>', {
            class: 'diyseo-notification',
            text: 'Image saved to media library!'
        }).appendTo('body');

        // Show notification with a slight delay
        requestAnimationFrame(function() {
            notification.addClass('show');
        });

        // Remove notification after animation
        setTimeout(function() {
            notification.removeClass('show');
            setTimeout(function() {
                notification.remove();
            }, 300);
        }, 2000);

        console.log('Image generated and saved successfully:', currentImageData);
        $('#diyseo_regenerate_image').show();
    } else {
        console.error('Failed to generate image:', response.data);
        alert('Failed to generate image: ' + (response.data || 'Unknown error'));
    }
},
            error: function(xhr, status, error) {
                $('#diyseo_featured_image_loading').hide();
                hideImageLoading();
                console.error('AJAX error:', status, error, xhr.responseText);
                var message = 'An error occurred while generating the image. Please try again.';
                if (xhr.responseJSON && xhr.responseJSON.data) {
                    message = xhr.responseJSON.data;
                }
                alert(message);
            }
        });
    }

function showImageLoading() {
    const container = document.getElementById('imageLoadingContainer');
    const messages = [
        { main: 'Summoning the SEO gods…', sub: 'This image better rank' },
        { main: 'Compressing some creativity...', sub: 'Optimized for humans and bots' },
        { main: 'Painting backlinks into the pixels…', sub: 'Just kidding (kind of)' },
        { main: 'Running image through something..', sub: 'Enhancing clickability' },
        { main: 'Embedding E-E-A-T signals...', sub: 'Experience, Expertise, and… coffee' },
        { main: 'Keyword-stuffing the pixels (Just kidding)', sub: 'Still looks natural' },
        { main: 'Writing alt text in binary…', sub: '01001110 for Nice' },
        { main: 'Doing artsy things with AI', sub: 'Please don’t bounce' },
        { main: 'Running core web vitals on the image', sub: 'LCP: Looking Cool Probably' }
    ];

    container.style.display = 'flex';
    let messageIndex = 0;

    const messageInterval = setInterval(() => {
        if (messageIndex < messages.length) {
            document.getElementById('imageLoadingMessage').textContent = messages[messageIndex].main;
            document.getElementById('imageLoadingSubMessage').textContent = messages[messageIndex].sub;
            messageIndex++;
        } else {
            messageIndex = 0;
        }
    
    }, 3000);

    container.dataset.intervalId = messageInterval;
}

    function hideImageLoading() {
        const container = document.getElementById('imageLoadingContainer');
        if (container.dataset.intervalId) {
            clearInterval(parseInt(container.dataset.intervalId));
        }
        container.style.display = 'none';
    }
});