document.addEventListener('DOMContentLoaded', function() {
    const KEY = 'player_vol';
    const vids = document.querySelectorAll('.video-player-placeholder');
    vids.forEach(v => {
        const desired = Number(localStorage.getItem(KEY) ?? 0.5);
        const apply = () => v.volume = Math.max(0, Math.min(1, desired));
        if (v.readyState >= 1) apply(); else v.addEventListener('loadedmetadata', apply, { once:true });
        v.addEventListener('volumechange', () => localStorage.setItem(KEY, v.volume.toString()));
    });
    const v = document.getElementById('player');
	const btnPlay = document.getElementById('btnPlay');
	const btnPause = document.getElementById('btnPause');
	if (!v) {
		console.warn('Video element #player tidak ditemukan');
		return;
	}
	const showPlay = () => {
		btnPlay.classList.remove('hidden');
		btnPause.classList.add('hidden');
	};
	const showPause = () => {
		btnPause.classList.remove('hidden');
		btnPlay.classList.add('hidden');
	};
	const syncButtons = () => (v.paused ? showPlay() : showPause());
	syncButtons();
	v.addEventListener('loadedmetadata', syncButtons);
	v.addEventListener('play', syncButtons);
	v.addEventListener('pause', syncButtons);
	v.addEventListener('ended', syncButtons);
	btnPlay.addEventListener('click', (e) => {
		e.preventDefault();
		v.play().catch(err => console.debug('Play ditolak:', err));
	});
	btnPause.addEventListener('click', (e) => {
		e.preventDefault();
		v.pause();
	});
	[btnPlay, btnPause].forEach(a => {
		a.setAttribute('role', 'button');
		a.setAttribute('tabindex', '0');
		a.addEventListener('keydown', e => {
			if (e.key === 'Enter' || e.key === ' ') a.click();
		});
	});
	
    const autoplaySwitch = document.getElementById('autoplay-switch');
    const players = document.querySelectorAll('.video-player-element');
	if(customPlayer) {
        function postMessageToPlayer(iframeElement, command) {
            const message = { cmd: command }; 
            if (iframeElement.contentWindow) {
                iframeElement.contentWindow.postMessage(message, '*');
            }
        }
        function attemptAutoplay() {
            players.forEach(player => {
                postMessageToPlayer(player, 'play');
                console.info("Perintah Autoplay dikirim ke iframe melalui Post Message.");
            });
        }
        players.forEach(iframe => {
            iframe.addEventListener('load', () => {
                attemptAutoplay(); 
            }, { once: true });
        });
	} else {
    	function attemptAutoplay() {
    		players.forEach(player => {
    			player.muted = false;
    			const playPromise = player.play(); 
    
    			if (playPromise !== undefined) {
    				playPromise.catch(error => {
    
    					console.warn("Autoplay (unmuted) diblokir oleh browser:", error);
    
    					player.muted = true;
    					player.play();
    				});
    			}
    		});
    	}
	}
	const storageKey = 'autonext_enabled';
	const autonextSwitch = document.getElementById('autonext-switch');
	if (autonextSwitch) {
		const savedState = localStorage.getItem(storageKey);
		autonextSwitch.checked = (savedState === 'true');
		autonextSwitch.addEventListener('change', function() {
			localStorage.setItem(storageKey, this.checked);
			console.log('Status Auto Next disimpan:', this.checked);
		});
	}
	function goToNextEpisode() {
		const isAutoplayOn = localStorage.getItem(storageKey) === 'true';

		if (isAutoplayOn && typeof nextUrl !== 'undefined' && nextUrl) {
			console.log('Autoplay aktif. Memutar selanjutnya: ' + nextUrl);
			window.location.href = nextUrl;
		} else {
			console.log('Video selesai, autoplay non-aktif atau ini episode terakhir.');
		}
	}
	if (typeof players !== 'undefined') {
		players.forEach(player => {
			player.addEventListener('ended', goToNextEpisode);
		});
	} else {
		console.warn('Variabel "players" tidak ditemukan. Event "ended" tidak akan berfungsi.');
	}
	autoplaySwitch.addEventListener('change', function() {
		if (this.checked) {
			localStorage.setItem('autoplay_enabled', 'true');
			attemptAutoplay();
		} else {
			localStorage.setItem('autoplay_enabled', 'false');
		}
	});
	const isAutoplayOn = localStorage.getItem('autoplay_enabled') === 'true';
	if (isAutoplayOn) {
		autoplaySwitch.checked = true;
	}
	if (isAutoplayOn) {
		attemptAutoplay();
	}
	const lightButton = document.querySelector('#light-mode');
	const playerContainer = document.querySelector('#player');
	const overlay = document.getElementById('light-overlay');
	function toggleLights() {
		overlay.classList.toggle('active');
		playerContainer.classList.toggle('lights-off');
	}
	if (lightButton) {
		lightButton.addEventListener('click', function(e) {
			e.preventDefault(); 
			lightButton.classList.toggle('active');
			toggleLights();
		});
	}
	if (overlay) {
		overlay.addEventListener('click', function() {

			overlay.classList.remove('active');
			lightButton.classList.remove('active');
			playerContainer.classList.remove('lights-off');
		});
	}
});