/**
 * Taxonomy Image JS
 * 
 * Handles the media uploader functionality for device categories
 */
(function($) {
    'use strict';

    // When the DOM is ready
    $(document).ready(function() {
        let file_frame;

        // Handle the upload image button click
        $(document).on('click', '.trs-upload-image', function(e) {
            e.preventDefault();

            const button = $(this);
            const container = button.closest('.trs-category-image-container');
            const imageIdInput = container.find('.trs-category-image-id');
            const previewContainer = container.find('.trs-category-image-preview');
            const removeButton = container.find('.trs-remove-image');

            // If the media frame already exists, reopen it
            if (file_frame) {
                file_frame.open();
                return;
            }

            // Create a new media frame
            file_frame = wp.media({
                title: trs_l10n?.upload_image_title || 'Select or Upload an Image',
                button: {
                    text: trs_l10n?.use_this_image || 'Use this image'
                },
                multiple: false // Set to true for multiple file selection
            });

            // When an image is selected in the media frame...
            file_frame.on('select', function() {
                // Get media attachment details from the frame state
                const attachment = file_frame.state().get('selection').first().toJSON();

                // Set the image ID in the hidden field
                imageIdInput.val(attachment.id);

                // Create an image element and add it to the preview container
                previewContainer.html('<img src="' + (attachment.sizes?.thumbnail?.url || attachment.url) + '" alt="" style="max-width:100px;height:auto;">');

                // Show the remove button
                removeButton.show();
            });

            // Finally, open the modal
            file_frame.open();
        });

        // Handle the remove image button click
        $(document).on('click', '.trs-remove-image', function(e) {
            e.preventDefault();

            const button = $(this);
            const container = button.closest('.trs-category-image-container');
            const imageIdInput = container.find('.trs-category-image-id');
            const previewContainer = container.find('.trs-category-image-preview');

            // Clear the image ID input
            imageIdInput.val('');

            // Clear the preview
            previewContainer.html('');

            // Hide the remove button
            button.hide();
        });
    });

})(jQuery);
