/**
 * Sponsors admin - Media Library integration for logo selection
 *
 * @package Chess_Podium
 */
(function() {
    'use strict';

    var btn = document.getElementById('cp_sponsor_select_media');
    var input = document.getElementById('sponsor_logo');

    if (!btn || !input) {
        return;
    }

    if (typeof wp === 'undefined' || !wp.media) {
        console.warn('Chess Podium Sponsors: wp.media not available. Ensure wp_enqueue_media() is called.');
        return;
    }

    btn.addEventListener('click', function(e) {
        e.preventDefault();
        var frame = wp.media({
            title: window.chessPodiumSponsorsAdmin && window.chessPodiumSponsorsAdmin.selectTitle
                ? window.chessPodiumSponsorsAdmin.selectTitle
                : 'Select sponsor logo',
            library: { type: 'image' },
            multiple: false,
            button: {
                text: window.chessPodiumSponsorsAdmin && window.chessPodiumSponsorsAdmin.useImageText
                    ? window.chessPodiumSponsorsAdmin.useImageText
                    : 'Use image'
            }
        });
        frame.on('select', function() {
            var selection = frame.state().get('selection');
            var attachment = selection ? selection.first() : null;
            if (attachment) {
                var att = attachment.toJSON();
                if (att && att.url) {
                    input.value = att.url;
                }
            }
        });
        frame.open();
    });
})();
