/* NaveenCodes Image Optimizer — LQIP blur-placeholder fade-in */
( function () {
	'use strict';

	function initLQIP() {
		var imgs = document.querySelectorAll( 'img.nc-lqip[data-nc-lqip]' );
		if ( ! imgs.length ) return;

		imgs.forEach( function ( img ) {
			var lqip = img.getAttribute( 'data-nc-lqip' );
			if ( ! lqip ) return;

			/* Show blurred LQIP as background while the real src loads */
			img.style.backgroundImage    = 'url(' + lqip + ')';
			img.style.backgroundSize     = 'cover';
			img.style.backgroundPosition = 'center';
			img.style.backgroundRepeat   = 'no-repeat';

			function reveal() {
				/* Fade out the background once real image is ready */
				img.classList.add( 'nc-lqip-loaded' );
				/* Short delay so the CSS transition fires cleanly */
				setTimeout( function () {
					img.style.backgroundImage = 'none';
				}, 450 );
			}

			if ( img.complete && img.naturalWidth > 0 ) {
				reveal();
			} else {
				img.addEventListener( 'load', reveal, { once: true } );
				img.addEventListener( 'error', reveal, { once: true } );
			}
		} );
	}

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