/**
 * Admin Videos Management Scripts
 *
 * @package Karate_Club_Manager
 * @since 1.0.27
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		// Media uploader for thumbnail
		var mediaUploader;

		$('#upload_thumbnail_button').on('click', function(e) {
			e.preventDefault();

			// If the media uploader exists, open it
			if (mediaUploader) {
				mediaUploader.open();
				return;
			}

			// Create the media uploader
			mediaUploader = wp.media({
				title: macmVideos.selectThumbnail,
				button: {
					text: macmVideos.useThumbnail
				},
				multiple: false
			});

			// When an image is selected
			mediaUploader.on('select', function() {
				var attachment = mediaUploader.state().get('selection').first().toJSON();

				// Set the thumbnail ID
				$('#thumbnail_id').val(attachment.id);

				// Display the thumbnail
				$('.kcm-thumbnail-preview img').attr('src', attachment.url);
				$('.kcm-thumbnail-preview').show();
				$('#remove_thumbnail_button').show();
			});

			// Open the uploader
			mediaUploader.open();
		});

		// Remove thumbnail
		$('#remove_thumbnail_button').on('click', function(e) {
			e.preventDefault();

			$('#thumbnail_id').val('');
			$('.kcm-thumbnail-preview img').attr('src', '');
			$('.kcm-thumbnail-preview').hide();
			$(this).hide();
		});

		// Delete video confirmation
		$('.kcm-delete-video').on('click', function(e) {
			if (!confirm(macmVideos.confirmDelete)) {
				e.preventDefault();
				return false;
			}
		});

		// Video URL preview (optional enhancement)
		$('#video_url').on('blur', function() {
			var url = $(this).val();
			var type = $('#video_type').val();

			// Could add URL validation here based on video type
			if (url && type === 'youtube') {
				// Check if it's a valid YouTube URL
				var youtubeRegex = /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\?\/]+)/;
				if (!youtubeRegex.test(url)) {
					// Could show a warning
				}
			} else if (url && type === 'vimeo') {
				// Check if it's a valid Vimeo URL
				var vimeoRegex = /vimeo\.com\/(\d+)/;
				if (!vimeoRegex.test(url)) {
				}
			}
		});

		// Form validation
		$('.kcm-video-form').on('submit', function(e) {
			var title = $('#title').val().trim();
			var videoUrl = $('#video_url').val().trim();

			if (!title) {
				alert('Please enter a video title.');
				$('#title').focus();
				e.preventDefault();
				return false;
			}

			if (!videoUrl) {
				alert('Please enter a video URL or embed code.');
				$('#video_url').focus();
				e.preventDefault();
				return false;
			}
		});
	});

})(jQuery);
