/**
 * Author Widget Admin — Media Uploader
 *
 * Handles avatar image upload and removal in the widget admin form.
 * Uses the WordPress Media Library (wp.media).
 *
 * @package Blog_Over
 * @since 1.4.0
 */
(function ($) {
    'use strict';

    /**
     * Bind media uploader events.
     * Uses event delegation so dynamically added widgets also work.
     */
    function bindEvents() {
        // Upload button
        $(document).on('click', '.blog-over-upload-avatar', function (e) {
            e.preventDefault();

            var $button = $(this);
            var $target = $($button.data('target'));
            var $preview = $($button.data('preview'));

            var frame = wp.media({
                title: 'Select Author Avatar',
                button: { text: 'Use This Image' },
                multiple: false,
                library: { type: 'image' }
            });

            frame.on('select', function () {
                var attachment = frame.state().get('selection').first().toJSON();
                // Use medium size if available, otherwise full
                var url = attachment.sizes && attachment.sizes.medium
                    ? attachment.sizes.medium.url
                    : attachment.url;

                $target.val(url).trigger('change');
                $preview.find('img').attr('src', url);
                $preview.show();
                $button.siblings('.blog-over-remove-avatar').show();
            });

            frame.open();
        });

        // Remove button
        $(document).on('click', '.blog-over-remove-avatar', function (e) {
            e.preventDefault();

            var $button = $(this);
            var $target = $($button.data('target'));
            var $preview = $($button.data('preview'));

            $target.val('').trigger('change');
            $preview.hide().find('img').attr('src', '');
            $button.hide();
        });
    }

    $(document).ready(function () {
        bindEvents();
    });

})(jQuery);
