(function ($) {
    const button = $('#kb-markdown-upload-theme-css');
    const input = $('#custom_theme_css_url');

    if (!button.length || !input.length || typeof wp === 'undefined' || !wp.media) {
        return;
    }

    button.on('click', function (event) {
        event.preventDefault();

        const frame = wp.media({
            title: 'Select theme.css',
            button: {
                text: 'Use this CSS file'
            },
            multiple: false,
            library: {
                type: ['text/css', 'text/plain']
            }
        });

        frame.on('select', function () {
            const attachment = frame.state().get('selection').first().toJSON();
            if (attachment && attachment.url) {
                input.val(attachment.url);
            }
        });

        frame.open();
    });
}(jQuery));
