/**
 * lazy-images.ts
 * Custom lazy-loading via IntersectionObserver for images
 * that use data-src / data-srcset fallback (legacy browsers or pre-rendered markup).
 * Native `loading="lazy"` is used for all new images via PHP;
 * this module handles any remaining cases.
 */

export function initLazyImages(): void {
	if ( ! ( 'IntersectionObserver' in window ) ) return;

	const images = document.querySelectorAll<HTMLImageElement>( 'img[data-src]' );
	if ( ! images.length ) return;

	const observer = new IntersectionObserver(
		( entries, obs ) => {
			entries.forEach( ( entry ) => {
				if ( ! entry.isIntersecting ) return;

				const img = entry.target as HTMLImageElement;

				if ( img.dataset.src ) {
					img.src = img.dataset.src;
					delete img.dataset.src;
				}

				if ( img.dataset.srcset ) {
					img.srcset = img.dataset.srcset;
					delete img.dataset.srcset;
				}

				img.classList.add( 'is-loaded' );
				obs.unobserve( img );
			} );
		},
		{ rootMargin: '200px 0px' }
	);

	images.forEach( ( img ) => observer.observe( img ) );
}
