/**
 * BASE-THEME: Admin Theme Options
 * Media Library uploader com seleção múltipla
 */
(function($) {
	'use strict';

	$(document).ready(function() {
		var $imageList = $('#culturando-image-list');
		var $imageIdsInput = $('#culturando-image-ids');
		var $selectButton = $('#culturando-select-images');

		// Abre o Media Library
		$selectButton.on('click', function(e) {
			e.preventDefault();

			var frame = wp.media({
				title: baseThemeAdmin.title,
				button: {
					text: baseThemeAdmin.button
				},
				multiple: true,
				library: {
					type: 'image'
				}
			});

			frame.on('select', function() {
				var attachments = frame.state().get('selection').toArray();
				var currentIds = $imageIdsInput.val() ? $imageIdsInput.val().split(',').map(Number) : [];
				
				attachments.forEach(function(attachment) {
					var id = attachment.get('id');
					var url = attachment.get('sizes').thumbnail ? 
						attachment.get('sizes').thumbnail.url : 
						attachment.get('url');

					// Adiciona se ainda não existe
					if (currentIds.indexOf(id) === -1) {
						currentIds.push(id);
						addImageToPreview(id, url);
					}
				});

				$imageIdsInput.val(currentIds.join(','));
				updateEmptyMessage();
			});

			frame.open();
		});

		// Remove imagem individual
		$imageList.on('click', '.remove-image', function(e) {
			e.preventDefault();
			var $item = $(this).closest('.culturando-image-item');
			var idToRemove = parseInt($item.data('id'));

			var currentIds = $imageIdsInput.val() ? 
				$imageIdsInput.val().split(',').map(Number) : [];
			currentIds = currentIds.filter(function(id) {
				return id !== idToRemove;
			});

			$imageIdsInput.val(currentIds.join(','));
			$item.fadeOut(300, function() {
				$(this).remove();
				updateEmptyMessage();
			});
		});

		// Adiciona preview da imagem
		function addImageToPreview(id, url) {
			var $item = $('<div class="culturando-image-item" data-id="' + id + '">' +
				'<img src="' + url + '" alt="">' +
				'<button type="button" class="button remove-image" aria-label="Remover imagem">×</button>' +
			'</div>');
			
			$imageList.append($item);
		}

		// Atualiza mensagem de "nenhuma imagem"
		function updateEmptyMessage() {
			if ($imageList.find('.culturando-image-item').length === 0) {
				$imageList.html('<p class="description">' + baseThemeAdmin.noImages + '</p>');
			}
		}
	});
})(jQuery);