jQuery(document).ready(function($) {
    jQuery('#upload_image_button').click(function() {
        var popupUploader = wp.media({
            title: 'Choose Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        popupUploader.on('select', function() {
            var attachment = popupUploader.state().get('selection').first().toJSON();
            
            jQuery('#popup_image_url').val(attachment.id);
            jQuery('.preview-img img').attr('src', attachment.url);
            jQuery('.preview-img img').removeAttr('srcset');

            // Use AJAX to get the image HTML
            jQuery.ajax({
                url: admin_ajax_object.ajax_url, // WordPress AJAX URL
                type: 'POST',
                data: {
                    action: 'get_image_html', // Custom action
                    attachment_id: attachment.id,
                    nonce: admin_ajax_object.nonce
                },
                success: function(response) {
                    if (jQuery('.preview-img').data('media-id') <= 0) {
                        jQuery('.preview-img').html(response); // Insert the image HTML
                        jQuery('.preview-img').data('media-id', attachment.id); // Store the media ID
                    }
                }
            });
            
        });

        popupUploader.open();
    });
});