/**
 * Video Background Manager
 * Handles play/pause of background videos based on viewport visibility
 * for performance optimization and accessibility
 */

export const videoBackground = () => {
	const videos = document.querySelectorAll('.js-cover-video');

	if (videos.length === 0) return;

	// Intersection Observer options
	const observerOptions = {
		root: null, // viewport
		rootMargin: '0px',
		threshold: 0.25 // Video must be at least 25% visible
	};

	/**
	 * Handle video play/pause based on visibility
	 */
	const handleVideoVisibility = (entries) => {
		entries.forEach(entry => {
			const video = entry.target;

			if (entry.isIntersecting) {
				// Video is in viewport - play it
				if (video.paused) {
					video.play().catch(error => {
						// Handle autoplay restrictions
						console.warn('Video autoplay failed:', error);
					});
				}
			} else {
				// Video is out of viewport - pause it
				if (!video.paused) {
					video.pause();
				}
			}
		});
	};

	// Create Intersection Observer
	const observer = new IntersectionObserver(handleVideoVisibility, observerOptions);

	// Observe all video elements
	videos.forEach(video => {
		// Set up video attributes for better performance
		video.setAttribute('preload', 'metadata');
		video.setAttribute('playsinline', '');

		// Reduce quality on slower connections
		if ('connection' in navigator && navigator.connection) {
			const connection = navigator.connection;
			if (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g') {
				// On slow connections, don't autoplay
				video.removeAttribute('autoplay');
				video.pause();
			}
		}

		// Handle video load errors
		video.addEventListener('error', (e) => {
			console.error('Video failed to load:', e);
			// Hide video on error to show fallback image
			video.style.display = 'none';
		});

		// Start observing
		observer.observe(video);
	});

	// Pause all videos when page is hidden (tab switching, minimize)
	document.addEventListener('visibilitychange', () => {
		if (document.hidden) {
			videos.forEach(video => {
				if (!video.paused) {
					video.pause();
					video.dataset.wasPlaying = 'true';
				}
			});
		} else {
			// Resume videos that were playing when page becomes visible again
			videos.forEach(video => {
				if (video.dataset.wasPlaying === 'true') {
					video.play().catch(error => {
						console.warn('Video resume failed:', error);
					});
					delete video.dataset.wasPlaying;
				}
			});
		}
	});

	// Pause videos on reduced motion preference
	if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
		videos.forEach(video => {
			video.pause();
			video.removeAttribute('autoplay');
		});
	}

	// Clean up on page unload
	window.addEventListener('beforeunload', () => {
		videos.forEach(video => {
			video.pause();
			video.src = '';
			video.load();
		});
	});
};
