/**
 * Product Video Module - Frontend Script
 *
 * @package OM_Product_Page_Essentials
 */

(function($) {
	'use strict';

	var OMPPEProductVideo = {
		/**
		 * Initialize product video functionality.
		 */
		init: function() {
			var self = this;

			// Mark video thumbnails in gallery
			self.markVideoThumbnails();

			// Handle video autoplay based on data attribute
			self.handleAutoplay();

			// Handle video in lightbox (if using WooCommerce photoswipe)
			$(document).on('wc-product-gallery-after-init', function(event, gallery) {
				self.markVideoThumbnails();
			});
		},

		/**
		 * Mark video thumbnails with play icon overlay.
		 */
		markVideoThumbnails: function() {
			$('.woocommerce-product-gallery__image[data-video]').each(function(index) {
				var $slide = $(this);
				var $thumbNav = $slide.closest('.woocommerce-product-gallery').find('.flex-control-thumbs, .woocommerce-product-gallery__thumbnails');

				if ($thumbNav.length) {
					$thumbNav.find('li, .woocommerce-product-gallery__thumbnail').eq(index).addClass('om-ppe-video-thumb');
				}
			});
		},

		/**
		 * Handle video autoplay setting.
		 */
		handleAutoplay: function() {
			$('.om-ppe-product-video[data-autoplay="true"] video').each(function() {
				var $video = $(this);

				// Try to autoplay when visible
				if (typeof IntersectionObserver !== 'undefined') {
					var observer = new IntersectionObserver(function(entries) {
						entries.forEach(function(entry) {
							if (entry.isIntersecting) {
								entry.target.play().catch(function() {
									// Autoplay was prevented, that's okay
								});
							} else {
								entry.target.pause();
							}
						});
					}, { threshold: 0.5 });

					observer.observe(this);
				} else {
					// Fallback: just try to autoplay
					$video[0].play().catch(function() {});
				}
			});
		}
	};

	// Initialize on document ready
	$(document).ready(function() {
		OMPPEProductVideo.init();
	});

	// Expose globally for theme integration
	window.OMPPEProductVideo = OMPPEProductVideo;

})(jQuery);
