/**
 * Cache module — Delay-JS runtime
 *
 * Pairs with PHP-side Cache_Js_Optimizer::transform_to_delay(). Scripts that
 * carry `type="text/be-delayed"` and `data-be-src="..."` are NOT executed by
 * the browser. On first user interaction we re-emit them as standard
 * <script src=...> tags so they execute then.
 *
 * Why first-interaction (not DOMContentLoaded): we want analytics/marketing
 * scripts to never block the LCP/INP measurement. The trade-off: events that
 * fire only at page-load will not be recorded for non-interacting visitors —
 * the safelist exists precisely to opt back in.
 *
 * @package BlaminhorEssentials
 */
(function () {
	'use strict';

	var loaded = false;
	var events = ['mouseover', 'click', 'touchstart', 'keydown', 'wheel', 'scroll'];

	function loadAll() {
		if (loaded) { return; }
		loaded = true;
		events.forEach(function (e) {
			window.removeEventListener(e, loadAll, { passive: true });
		});

		var nodes = document.querySelectorAll('script[type="text/be-delayed"]');
		nodes.forEach(function (node) {
			var src = node.getAttribute('data-be-src');
			if (!src) { return; }
			// Replace with a fresh <script> so the browser fetches + executes.
			var fresh = document.createElement('script');
			// Copy original attributes (id, defer, async, etc.) except our own.
			for (var i = 0; i < node.attributes.length; i++) {
				var a = node.attributes[i];
				if (a.name === 'type' || a.name === 'data-be-src') { continue; }
				fresh.setAttribute(a.name, a.value);
			}
			fresh.src = src;
			// Insert before the placeholder so execution order is preserved.
			node.parentNode.insertBefore(fresh, node);
			node.parentNode.removeChild(node);
		});
	}

	events.forEach(function (e) {
		window.addEventListener(e, loadAll, { passive: true, once: false });
	});

	// Safety net: trigger the load after 10s even if no interaction happened,
	// so server-rendered conversion pixels still fire on idle tabs.
	setTimeout(loadAll, 10000);
})();
