jQuery(document).ready(function($) {
    $('#upload-category-image-button').on('click', function(e) {
        e.preventDefault();
        
        var imageFrame;
        
        if (imageFrame) {
            imageFrame.open();
            return;
        }

        imageFrame = wp.media({
            title: 'Select or Upload Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        imageFrame.on('select', function() {
            var attachment = imageFrame.state().get('selection').first().toJSON();
            $('#category-image').val(attachment.url);
            $('#category-image-preview').html('<img src="' + attachment.url + '" style="max-width:100%;" />');
        });

        imageFrame.open();
    });
});