jQuery(function($){

    $( document ).on( 'click', '.open-media-modal', function( event ) {
        
        var gallery_items_frame;
        const $el = $( this );

        var target_field = $el.attr('data-target-field');
        var target_id = $el.siblings('.'+target_field+'-id');
        var target_url = $el.siblings('.'+target_field+'-url');
        var image_preview = $el.siblings('.image-preview');
        var selected = target_id.val();
        var able_multiple = $el.attr('data-able-multiple');

        event.preventDefault();

        if ( gallery_items_frame ) {

            // Select the attachment when the frame opens
            gallery_items_frame.on( 'open', function() {
                var selection = gallery_items_frame.state().get( 'selection' );
                selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );
            });

            // Open the modal.
            gallery_items_frame.open();

            return;
        }

        // Create the media frame.
        gallery_items_frame = wp.media.frames.gallery_items = wp.media({
            // Set the title of the modal.
            title: 'Choose or upload media',
            button: {
                text: 'Select'
            },
            states: [
                new wp.media.controller.Library({
                    title: 'Choose or upload media',
                    filterable: 'all',
                    multiple: able_multiple
                })
            ]
        });

        // Select the attachment when the frame opens
        gallery_items_frame.on( 'open', function() {
            var selection = gallery_items_frame.state().get( 'selection' );
            selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );
        });

        gallery_items_frame.on( 'select', function() {
			// We set multiple to false so only get one image from the uploader
			attachment = gallery_items_frame.state().get('selection').first().toJSON();
			// Do something with attachment.id and/or attachment.url here
			target_url.val( attachment.url );
			target_id.val( attachment.id );
            // $el.find('.bi-image-alt').hide();
            image_preview.html('<img src="'+attachment.url+'" width="150px">');
            // $el.attr('data-id', attachment.id);
		});

        // Open the modal.
        gallery_items_frame.open();

    });

});