/**
 * Cache module — YouTube facade activator
 *
 * Replaces a clicked-on facade with the real iframe (autoplay enabled).
 * Click + keyboard (Enter / Space) trigger the swap.
 *
 * @package BlaminhorEssentials
 */
(function () {
	'use strict';

	function activate(node) {
		var src = node.getAttribute('data-src');
		var id = node.getAttribute('data-video-id');
		if (!src && !id) { return; }
		var url = src ? src : ('https://www.youtube-nocookie.com/embed/' + id);
		// Add autoplay so the click directly starts the video.
		var sep = url.indexOf('?') === -1 ? '?' : '&';
		url = url + sep + 'autoplay=1';

		var iframe = document.createElement('iframe');
		iframe.src = url;
		iframe.setAttribute('frameborder', '0');
		iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
		iframe.setAttribute('allowfullscreen', '');
		iframe.style.width = '100%';
		iframe.style.height = '100%';
		iframe.style.border = '0';
		iframe.title = node.getAttribute('aria-label') || 'YouTube video';

		node.innerHTML = '';
		node.appendChild(iframe);
		node.removeAttribute('role');
		node.removeAttribute('tabindex');
	}

	function onClick(e) {
		var node = e.target.closest('.be-yt-facade');
		if (!node) { return; }
		e.preventDefault();
		activate(node);
	}

	function onKey(e) {
		if (e.key !== 'Enter' && e.key !== ' ') { return; }
		var node = e.target.closest('.be-yt-facade');
		if (!node) { return; }
		e.preventDefault();
		activate(node);
	}

	document.addEventListener('click', onClick, false);
	document.addEventListener('keydown', onKey, false);
})();
