/**
 * Cache module — Lazy load polyfill / fade-in
 *
 * In 2026 every supported browser implements native loading="lazy". This file
 * is a tiny enhancement layer:
 *   - Adds a fade-in transition on natively-lazy images as they enter the
 *     viewport (cosmetic, no perf impact).
 *   - Polyfills loading="lazy" only on browsers that don't support it
 *     (IntersectionObserver-driven).
 *
 * Loaded via wp_enqueue_scripts only when lazy_load_images is on.
 *
 * @package BlaminhorEssentials
 */
(function () {
	'use strict';

	var supportsNative = ('loading' in HTMLImageElement.prototype);

	if (supportsNative) {
		// Cosmetic fade-in: nothing more.
		var imgs = document.querySelectorAll('img[loading="lazy"]');
		imgs.forEach(function (img) {
			if (img.complete) { return; }
			img.style.opacity = '0';
			img.style.transition = 'opacity .25s ease-in';
			img.addEventListener('load', function () { img.style.opacity = '1'; }, { once: true });
			img.addEventListener('error', function () { img.style.opacity = '1'; }, { once: true });
		});
		return;
	}

	// Polyfill path (older browsers — rare in 2026).
	if (!('IntersectionObserver' in window)) { return; }
	var io = new IntersectionObserver(function (entries) {
		entries.forEach(function (entry) {
			if (!entry.isIntersecting) { return; }
			var img = entry.target;
			if (img.dataset.src) { img.src = img.dataset.src; }
			if (img.dataset.srcset) { img.srcset = img.dataset.srcset; }
			img.removeAttribute('loading');
			io.unobserve(img);
		});
	}, { rootMargin: '200px 0px' });
	document.querySelectorAll('img[loading="lazy"]').forEach(function (img) { io.observe(img); });
})();
