/**
 * Frontend Training Videos Scripts
 *
 * @package Karate_Club_Manager
 * @since 1.0.27
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		// Video modal elements
		var $modal = $('#kcm-video-modal');
		var $modalPlayer = $modal.find('.kcm-video-modal-player');
		var $modalClose = $modal.find('.kcm-video-modal-close');
		var $modalOverlay = $modal.find('.kcm-video-modal-overlay');

		// Open video modal
		$('.kcm-video-thumbnail').on('click', function() {
			var $thumbnail = $(this);
			var videoUrl = $thumbnail.data('video-url');
			var videoType = $thumbnail.data('video-type');

			if (!videoUrl) {
				return;
			}

			// Generate embed code
			var embedCode = generateEmbedCode(videoUrl, videoType);

			if (embedCode) {
				// Insert embed code
				$modalPlayer.html(embedCode);

				// Show modal
				$modal.fadeIn(300);

				// Prevent body scroll
				$('body').css('overflow', 'hidden');
			}
		});

		// Close modal
		function closeModal() {
			$modal.fadeOut(300, function() {
				// Clear player
				$modalPlayer.html('');

				// Restore body scroll
				$('body').css('overflow', '');
			});
		}

		$modalClose.on('click', closeModal);
		$modalOverlay.on('click', closeModal);

		// Close on ESC key
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape' && $modal.is(':visible')) {
				closeModal();
			}
		});

		/**
		 * Generate embed code based on video type
		 */
		function generateEmbedCode(url, type) {
			var embedCode = '';

			switch (type) {
				case 'youtube':
					var youtubeId = extractYoutubeId(url);
					if (youtubeId) {
						embedCode = '<iframe width="100%" height="100%" src="https://www.youtube.com/embed/' + youtubeId + '?autoplay=1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
					}
					break;

				case 'vimeo':
					var vimeoId = extractVimeoId(url);
					if (vimeoId) {
						embedCode = '<iframe src="https://player.vimeo.com/video/' + vimeoId + '?autoplay=1" width="100%" height="100%" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
					}
					break;

				case 'direct':
					embedCode = '<video width="100%" height="100%" controls autoplay><source src="' + escapeHtml(url) + '" type="video/mp4">Your browser does not support the video tag.</video>';
					break;

				case 'embed':
					// Custom embed code - sanitize but allow iframe
					embedCode = url; // Already sanitized on backend
					break;
			}

			return embedCode;
		}

		/**
		 * Extract YouTube video ID from URL
		 */
		function extractYoutubeId(url) {
			var patterns = [
				/youtube\.com\/watch\?v=([^&]+)/,
				/youtube\.com\/embed\/([^?]+)/,
				/youtu\.be\/([^?]+)/
			];

			for (var i = 0; i < patterns.length; i++) {
				var match = url.match(patterns[i]);
				if (match) {
					return match[1];
				}
			}

			return null;
		}

		/**
		 * Extract Vimeo video ID from URL
		 */
		function extractVimeoId(url) {
			var match = url.match(/vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|)(\d+)(?:$|\/|\?)/);
			if (match) {
				return match[1];
			}
			return null;
		}

		/**
		 * Escape HTML for security
		 */
		function escapeHtml(text) {
			var map = {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			};
			return text.replace(/[&<>"']/g, function(m) { return map[m]; });
		}

		/**
		 * Video filtering functionality
		 */
		var $filterBeltLevel = $('#filter-belt-level');
		var $filterCategory = $('#filter-category');
		var $filterDifficulty = $('#filter-difficulty');
		var $filterInstructor = $('#filter-instructor');
		var $clearFilters = $('#clear-filters');
		var $videoCards = $('.kcm-video-card');

		// Filter videos
		function filterVideos() {
			var beltLevel = $filterBeltLevel.val();
			var category = $filterCategory.val();
			var difficulty = $filterDifficulty.val();
			var instructorId = $filterInstructor.val();

			var visibleCount = 0;

			$videoCards.each(function() {
				var $card = $(this);
				var show = true;

				// Check belt level
				if (beltLevel && $card.data('belt-level') !== beltLevel) {
					show = false;
				}

				// Check category
				if (category && $card.data('category') !== category) {
					show = false;
				}

				// Check difficulty
				if (difficulty && $card.data('difficulty') !== difficulty) {
					show = false;
				}

				// Check instructor
				if (instructorId && $card.data('instructor-id') != instructorId) {
					show = false;
				}

				if (show) {
					$card.fadeIn(300);
					visibleCount++;
				} else {
					$card.fadeOut(300);
				}
			});

			// Show/hide no results message
			showNoResultsMessage(visibleCount);
		}

		// Show no results message if no videos match filters
		function showNoResultsMessage(count) {
			var $grid = $('.kcm-videos-grid');
			var $noResults = $grid.find('.kcm-no-results');

			if (count === 0) {
				if ($noResults.length === 0) {
					$grid.append('<div class="kcm-no-results"><p>No videos match the selected filters.</p></div>');
				} else {
					$noResults.show();
				}
			} else {
				$noResults.hide();
			}
		}

		// Bind filter events
		$filterBeltLevel.on('change', filterVideos);
		$filterCategory.on('change', filterVideos);
		$filterDifficulty.on('change', filterVideos);
		$filterInstructor.on('change', filterVideos);

		// Clear all filters
		$clearFilters.on('click', function() {
			$filterBeltLevel.val('');
			$filterCategory.val('');
			$filterDifficulty.val('');
			$filterInstructor.val('');

			$videoCards.fadeIn(300);
			$('.kcm-no-results').hide();
		});
	});

})(jQuery);
