jQuery(($) => {
    // By the time this runs, 'wp' and 'wp.media' are guaranteed to be loaded
    // because we set them as dependencies in the PHP file.

    // Initialise the WordPress color picker on the color swatch field.
    $('.psc-color-picker').wpColorPicker();

    // Handle 'Select Image' button click
    $(document).on('click', '.upload-image-button', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $inputField = $($button.data('target-input'));
        var $previewBox = $($button.data('target-preview'));

        // Create the media frame.
        var mediaFrame = wp.media({ // This is the line that was failing
            title: 'Select an Image',
            button: { text: 'Use this image' },
            multiple: false
        });

        // When an image is selected, run a callback.
        mediaFrame.on('select', function() {
            var attachment = mediaFrame.state().get('selection').first().toJSON();
            $inputField.val(attachment.id);
            var previewUrl = (attachment.sizes.thumbnail) ? attachment.sizes.thumbnail.url : attachment.url;
            $previewBox.html('<img src="' + previewUrl + '" />');
        });

        mediaFrame.open();
    });

    // Handle 'Remove Image' button click
    $(document).on('click', '.remove-image-button', function(e) {
        e.preventDefault();
        var $button = $(this);
        var $inputField = $($button.data('target-input'));
        var $previewBox = $($button.data('target-preview'));
        $inputField.val('');
        $previewBox.html('');
    });
});