jQuery(document).ready(function ($) {
    var mediaUploader;

    $('#upload_bg_image_button').on('click', function (e) {
        e.preventDefault();

        // If already opened, reopen
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }

        // Initialize uploader
        mediaUploader = wp.media.frames.file_frame = wp.media({
            title: 'Select Background Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        mediaUploader.on('select', function () {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#ucm_bg_image').val(attachment.url);
            $('#ucm_bg_image_id').val(attachment.id);
            $('#bg_image_preview').html(
                '<img src="' + attachment.url + '" style="max-width:300px; height:auto;" />'
            );
        });

        mediaUploader.open();
    });

    // logo upload
    $('#upload_logo_button').on('click', function (e) {
        e.preventDefault();
        let mediaUploader = wp.media({
            title: 'Select Company Logo',
            button: { text: 'Use this logo' },
            multiple: false
        });
        mediaUploader.on('select', function () {
            let attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#ucm_logo_url').val(attachment.url);
            $('#ucm_logo_id').val(attachment.id);
            $('#logo_preview').html('<img src="' + attachment.url + '" style="max-width:150px; height:auto;" />');
        });
        mediaUploader.open();
    });

});