jQuery(document).ready(function($){
    

    const sunset_media_upload = (button_class, input_class) => {
        'use strict';
        jQuery('body').on('click', button_class, function () {
            let button_id = '#' + jQuery(this).attr('id');
            let display_field = jQuery(this).closest('.menu-item-actions').find(input_class);
            let display_preview = jQuery(this).closest('.menu-item-actions').find('img');
            let display_del = jQuery(this).closest('.menu-item-actions').find('a.delete');
            let _custom_media = true;
    
            wp.media.editor.send.attachment = function (props, attachment) {
    
                if (_custom_media) {
                    if (typeof display_field !== 'undefined') {
                        switch (props.size) {
                            case 'full':
                                display_field.val(attachment.sizes.full.url);
                                display_field.trigger('change');
                                break;
                            case 'medium':
                                display_field.val(attachment.sizes.medium.url);
                                display_field.trigger('change');
                                break;
                            case 'thumbnail':
                                display_field.val(attachment.sizes.thumbnail.url);
                                display_field.trigger('change');
                                break;
                            default:
                                display_field.val(attachment.url);
                                display_field.trigger('change');
                        }
                    }
                    display_preview.attr("src", display_field.val());
                    display_preview.show();
                    display_del.show();
                    _custom_media = false;
                } else {
                    return wp.media.editor.send.attachment(button_id, [props, attachment]);
                }
            };
            wp.media.editor.open(button_class);
            window.send_to_editor = function (html) {
                
            };
            return false;
        });
    }

    sunset_media_upload(".sunset-upload-menu-image-button", 'input.sunset-menu-image-url');

    // Handle deletion of menu item's image
    jQuery('body').on('click', '.sunset-delete-menu-image-button', function (e) {
        e.preventDefault();
        $(this).closest('.menu-item-actions').find('input:hidden').val('');
        $(this).closest('.menu-item-actions').find('input:hidden').trigger('change');
        $(this).closest('.menu-item-actions').find('img').attr('src', '');
        $(this).closest('.menu-item-actions').find('img').hide();
        $(this).hide();
    });
});