//video
document.addEventListener('DOMContentLoaded', function () {
	let videoBut = document.querySelector('.video__play');
	let video = document.querySelector('video');
	const orderForm = document.querySelector('.st-fast-checkout');
	let orderTimeout;
	let videoNotification = document.getElementById('videoNotification');
	let continueWatching = document.getElementById('continueWatching');
	let startFromBeginning = document.getElementById('startFromBeginning');
	let firstPlay = true;
	let userInteracted = false;
	let button = document.querySelector('.st-button');

	button.addEventListener('click', openForm);

	video.addEventListener('ended', openForm);
	function openForm() {
		 orderForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
	}

 
	// Проверяем LocalStorage
	if (firstPlay === false) {
		videoNotification.style.display = 'flex';
		videoBut.style.display = 'none';
	} else {
		videoNotification.style.display = 'none';
		videoBut.style.display = 'block';
	}
	let savedTime = parseFloat(localStorage.getItem('videoCurrentTime') || 0);
	if (savedTime > 0) {
		videoNotification.style.display = 'flex';
		videoBut.classList.add('play');
		firstPlay = false;
	}

	// Обработчики для кнопок уведомления
	continueWatching.addEventListener('click', function () {
		videoNotification.style.display = 'none';
		video.play();
		video.muted = false;
	});

	startFromBeginning.addEventListener('click', function () {
		videoNotification.style.display = 'none';
		// video.currentTime = 0;
		video.play();
		video.muted = false;
	});

	// Функция для сохранения текущего времени в LocalStorage
	function saveCurrentTime() {
		if (userInteracted) {
			localStorage.setItem('videoCurrentTime', video.currentTime);
			video.setAttribute('data-current-time', video.currentTime);
		}
	}

	video.addEventListener('timeupdate', saveCurrentTime);

	// Обработчики для кнопок продолжения и начала заново
	continueWatching.addEventListener('click', function () {
		if (savedTime) {
			video.currentTime = savedTime;
		}
		video.play();
		video.muted = false;
		videoNotification.style.display = 'none';
	});

	startFromBeginning.addEventListener('click', function () {
		video.currentTime = 0;
		video.play();
		video.muted = false;
		videoNotification.style.display = 'none';
	});

	// Обработчик для кнопки воспроизведения
	videoBut.addEventListener('click', function () {
		if (firstPlay) {
			video.play();
			video.muted = false;
			videoBut.classList.add('play');
			video.currentTime = 0;
			firstPlay = false;
			localStorage.setItem('videoStarted', 'true');
		} else {
			if (video.paused) {
				video.play();
				videoBut.classList.remove('pause');
				videoBut.classList.add('play');
			} else {
				video.pause();
				videoBut.classList.add('pause');
				videoBut.classList.remove('play');
			}
		}
		userInteracted = true;
	});

	// Устанавливаем начальное время для автопроигрывания
	if (savedTime && !videoNotification.style.display) {
		video.currentTime = savedTime;
	}
});