jQuery(document).ready(function($) {
    // Check if we're on the right page and have the right elements
    if (!$('#upload-image-button').length) {
        return;
    }

    // Create the media frame once
    let mediaUploader;
    
    // Handle the upload button click
    $('#upload-image-button').on('click', function(e) {
        e.preventDefault();
        
        // If the user isn't pro or higher, don't do anything
        if ($(this).prop('disabled')) {
            return;
        }
        
        // If the uploader object has already been created, reopen it
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        
        // Create the media uploader
        mediaUploader = wp.media({
            title: 'Sélectionner une image pour le chatbot',
            button: {
                text: 'Utiliser cette image'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });
        
        // When an image is selected
        mediaUploader.on('select', function() {
            const attachment = mediaUploader.state().get('selection').first().toJSON();
            
            // Update the form fields
            $('#botami_bot_image_url').val(attachment.url);
            $('#botami_bot_image_id').val(attachment.id);
            
            // Update the preview image
            $('#preview').attr('src', attachment.url).removeClass('hidden');
            
            // Update the custom logo element
            $('.logo-template:last-child img').attr('src', attachment.url);
            $('.logo-template:last-child').attr('data-logo', attachment.url);
            
            // Deselect all logo templates
            $('.logo-template').removeClass('border-blue-500 bg-blue-50');
            
            // Select the custom logo template
            $('.logo-template:last-child').addClass('border-blue-500 bg-blue-50');
            
            // Show a success message
            showMessage('Image sélectionnée avec succès', 'success');
        });
        
        // Open the uploader dialog
        mediaUploader.open();
    });
    
    // Helper function to show messages
    function showMessage(message, type = 'error') {
        const messageElement = $('#error-message');
        
        if (type === 'success') {
            messageElement.removeClass('text-red-500').addClass('text-green-500');
        } else {
            messageElement.removeClass('text-green-500').addClass('text-red-500');
        }
        
        messageElement.text(message).removeClass('hidden');
        
        // Hide the message after 3 seconds
        setTimeout(function() {
            messageElement.addClass('hidden');
        }, 3000);
    }
    
    // Ensure logo template selection updates the hidden input
    $('.logo-template').on('click', function() {
        // Clear media library selection ID when using predefined logos
        if (!$(this).is(':last-child')) {
            $('#botami_bot_image_id').val('');
        }
    });
});