/**
 * Front-end behavior for the optional custom play overlay.
 */
( () => {
	const PLAY_CONTROL_SELECTOR = '[data-axb-video-play]';
	const PLAYER_SELECTOR = '.axcelersblocks-video--has-play-overlay';

	const addAutoplayParam = ( iframe ) => {
		const src = iframe.getAttribute( 'src' );

		if ( ! src ) {
			return;
		}

		try {
			const url = new URL( src, window.location.href );
			url.searchParams.set( 'autoplay', '1' );
			iframe.setAttribute( 'src', url.toString() );
		} catch ( error ) {
			const separator = src.includes( '?' ) ? '&' : '?';
			iframe.setAttribute( 'src', `${ src }${ separator }autoplay=1` );
		}
	};

	const bindVideoReset = ( player, video ) => {
		if ( video.dataset.axbPlayOverlayReady ) {
			return;
		}

		video.dataset.axbPlayOverlayReady = '1';
		video.addEventListener( 'ended', () => {
			if ( video.loop ) {
				return;
			}

			player.classList.remove( 'is-playing' );

			if ( player.dataset.axbShowControlsOnPlay === '1' ) {
				video.controls = false;
			}
		} );
	};

	const activatePlayer = ( control ) => {
		const player = control.closest( PLAYER_SELECTOR );

		if ( ! player ) {
			return;
		}

		const video = player.querySelector( 'video' );
		const iframe = player.querySelector( 'iframe' );

		player.classList.add( 'is-playing' );

		if ( video ) {
			bindVideoReset( player, video );

			if ( player.dataset.axbShowControlsOnPlay === '1' ) {
				video.controls = true;
			}

			const playPromise = video.play();

			if ( playPromise && typeof playPromise.catch === 'function' ) {
				playPromise.catch( () => {
					player.classList.remove( 'is-playing' );
				} );
			}

			return;
		}

		if ( iframe ) {
			addAutoplayParam( iframe );
		}
	};

	document.addEventListener( 'click', ( event ) => {
		if ( ! event.target || typeof event.target.closest !== 'function' ) {
			return;
		}

		const control = event.target.closest( PLAY_CONTROL_SELECTOR );

		if ( ! control ) {
			return;
		}

		event.preventDefault();
		event.stopPropagation();
		activatePlayer( control );
	} );

	document.addEventListener( 'keydown', ( event ) => {
		if ( event.key !== 'Enter' && event.key !== ' ' ) {
			return;
		}

		if ( ! event.target || typeof event.target.closest !== 'function' ) {
			return;
		}

		const control = event.target.closest( PLAY_CONTROL_SELECTOR );

		if ( ! control ) {
			return;
		}

		event.preventDefault();
		event.stopPropagation();
		activatePlayer( control );
	} );
} )();
