/**
 * Picks one Random Image variant in the browser so full-page HTML cache does not freeze the selection.
 *
 * @package DiviSupreme
 */
( function () {
	'use strict';

	/**
	 * @param {Element} root Element with [data-dsm-random-image-hydrate].
	 * @return {void}
	 */
	function pickAndInject( root ) {
		var slot = root.querySelector( '.dsm-random-image__slot' );
		var templates = root.querySelectorAll( 'template.dsm-random-image__tpl' );
		if ( ! slot || ! templates.length ) {
			return;
		}
		var i = Math.floor( Math.random() * templates.length );
		var frag = templates[ i ].content.cloneNode( true );
		slot.appendChild( frag );
	}

	function init() {
		document
			.querySelectorAll( '[data-dsm-random-image-hydrate="1"]' )
			.forEach( pickAndInject );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
