document.addEventListener('DOMContentLoaded', () => {
	let videoFrame, galleryFrame;

	// ---------- VIDEO UPLOAD ----------
	const uploadVideoButtons = document.querySelectorAll('.sp-smart-upload-video-btn');
	uploadVideoButtons.forEach((button) => {
		button.addEventListener('click', (e) => {
			e.preventDefault();

			if (!videoFrame) {
				videoFrame = wp.media({
					title: 'Select or Upload Video',
					button: { text: 'Use this video' },
					library: { type: 'video' },
					multiple: false,
				});

				videoFrame.on('select', () => {
					const attachment = videoFrame.state().get('selection').first().toJSON();
					const input = document.querySelector('#sp_video_url');
					if (input) input.value = attachment.url;
				});
			}

			videoFrame.open();
		});
	});

	// ---------- GALLERY UPLOAD ----------
	const uploadButton = document.querySelector('.sp-upload-gallery');
	const clearButton = document.querySelector('.sp-clear-gallery');
	const preview = document.querySelector('.sp-gallery-preview');
	const input = document.querySelector('#sp_gallery_ids');

	if (!uploadButton || !input || !preview) return;

	uploadButton.addEventListener('click', (e) => {
		e.preventDefault();

		if (!galleryFrame) {
			galleryFrame = wp.media({
				title: 'Select or Upload Images',
				button: { text: 'Use these images' },
				library: { type: 'image' },
				multiple: true,
			});

			galleryFrame.on('select', () => {
				const attachments = galleryFrame.state().get('selection').toJSON();

				const ids = attachments.map((a) => a.id);
				const urls = attachments.map((a) => a.sizes?.thumbnail?.url || a.url);

				// Update hidden input
				input.value = ids.join(',');

				// Clear and rebuild preview
				preview.innerHTML = '';
				urls.forEach((url, i) => {
					const wrapper = document.createElement('div');
					wrapper.className = 'sp-gallery-preview-images';

					const img = document.createElement('img');
					img.src = url;
					img.dataset.image_id = ids[i];

					const removeBtn = document.createElement('span');
					removeBtn.className = 'sp-gallery-remove-img';
					removeBtn.dataset.image_id = ids[i];
					removeBtn.textContent = '×';

					wrapper.append(img, removeBtn);
					preview.appendChild(wrapper);
				});
			});
		}

		galleryFrame.open();

		// Preselect previously selected images
		const existingIds = input.value ? input.value.split(',').map(Number) : [];
		const selection = galleryFrame?.state()?.get('selection');

		if (existingIds.length) {
			existingIds.forEach((id) => {
				const attachment = wp.media.attachment(id);
				if (attachment) {
					attachment.fetch();
					selection.add(attachment);
				}
			});
		}
	});

	// ---------- REMOVE IMAGE ----------
	preview.addEventListener('click', (e) => {
		const target = e.target.closest('.sp-gallery-remove-img');
		if (!target) return;

		const id = target.dataset.image_id;
		if (!id) return;

		// Optional: confirm before deleting
		// if (!confirm('Remove this image?')) return;

		// Remove from DOM
		const wrapper = target.closest('.sp-gallery-preview-images');
		if (wrapper) wrapper.remove();

		// Update hidden input
		const remainingIds = Array.from(
			preview.querySelectorAll('img[data-image_id]')
		).map((img) => img.dataset.image_id);

		input.value = remainingIds.join(',');
	});

	// ---------- CLEAR GALLERY BUTTON ----------
	if (clearButton) {
		clearButton.addEventListener('click', (e) => {
			e.preventDefault();
			preview.innerHTML = '';
			input.value = '';
		});
	}
});

// ---------- jQuery UI SORTABLE FUNCTIONALITY ----------
jQuery(document).ready(function($) {
    // 1. Initialize Sortable
    $(".sp-gallery-preview").sortable({
        items: '.sp-gallery-preview-images', // The items to sort.
        cursor: 'move',
		containment: '.sp-gallery-metabox',
        opacity: 0.7,
        placeholder: 'sp-gallery-sortable-placeholder', // Optional CSS class for the gap.
        update: function(event, ui) {
            updateGalleryIDs();
        }
    });

    // 2. Function to update the hidden input field.
    function updateGalleryIDs() {
        var ids = [];
        
        // Loop through each image and grab the ID from the data attribute.
        $('.sp-gallery-preview-images img').each(function() {
            var id = $(this).data('image_id');
            if (id) {
                ids.push(id);
            }
        });

        // Join the array into a comma-separated string and update the hidden input.
        $('#sp_gallery_ids').val(ids.join(','));
    }
});
