jQuery(function ($) {

    let $btn = $('#upload_logo_button');

    if ($btn.length && typeof wp !== 'undefined' && wp.media) {

        let frame;
        const title = $btn.data('title') || 'Select or Upload Logo';
        const button = $btn.data('button') || 'Use this logo';

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

            if (frame) {
                frame.open();
                return;
            }

            frame = wp.media({
                title: title,
                button: {text: button},
                multiple: false
            });

            frame.on('select', function () {
                const attachment = frame.state().get('selection').first().toJSON();
                $('#sapsfwc-logo-url').val(attachment.url);
            });

            frame.open();

        });

    }

    let $reset = $('#sapsfwc-reset-button');

    if ($reset.length) {

        $reset.on('click', function (e) {
            const msg = $reset.data('confirm') || 'Are you sure?';
            if (!window.confirm(msg)) e.preventDefault();
        });

    }

});