/**
 * Lazy Load
 * 遅延読み込み機能
 */

/**
 * 画像の遅延読み込み
 */
function initLazyLoadImages() {
	const images = document.querySelectorAll(
		'img[data-src], img[loading="lazy"]'
	);

	if ( images.length === 0 ) {
		return;
	}

	const imageObserver = new IntersectionObserver(
		( entries ) => {
			entries.forEach( ( entry ) => {
				if ( entry.isIntersecting ) {
					const img = entry.target;

					// data-src属性がある場合
					if ( img.dataset.src ) {
						img.src = img.dataset.src;
						delete img.dataset.src;
					}

					// data-srcset属性がある場合
					if ( img.dataset.srcset ) {
						img.srcset = img.dataset.srcset;
						delete img.dataset.srcset;
					}

					img.classList.add( 'is-loaded' );
					imageObserver.unobserve( img );
				}
			} );
		},
		{
			rootMargin: '50px 0px',
			threshold: 0.01,
		}
	);

	images.forEach( ( img ) => {
		imageObserver.observe( img );
	} );
}

/**
 * iframeの遅延読み込み
 */
function initLazyLoadIframes() {
	const iframes = document.querySelectorAll( 'iframe[data-src]' );

	if ( iframes.length === 0 ) {
		return;
	}

	const iframeObserver = new IntersectionObserver(
		( entries ) => {
			entries.forEach( ( entry ) => {
				if ( entry.isIntersecting ) {
					const iframe = entry.target;
					iframe.src = iframe.dataset.src;
					delete iframe.dataset.src;
					iframe.classList.add( 'is-loaded' );
					iframeObserver.unobserve( iframe );
				}
			} );
		},
		{
			rootMargin: '100px 0px',
			threshold: 0.01,
		}
	);

	iframes.forEach( ( iframe ) => {
		iframeObserver.observe( iframe );
	} );
}

/**
 * 背景画像の遅延読み込み
 */
function initLazyLoadBackgrounds() {
	const elements = document.querySelectorAll( '[data-bg-src]' );

	if ( elements.length === 0 ) {
		return;
	}

	const bgObserver = new IntersectionObserver(
		( entries ) => {
			entries.forEach( ( entry ) => {
				if ( entry.isIntersecting ) {
					const element = entry.target;
					element.style.backgroundImage = `url('${ element.dataset.bgSrc }')`;
					delete element.dataset.bgSrc;
					element.classList.add( 'is-loaded' );
					bgObserver.unobserve( element );
				}
			} );
		},
		{
			rootMargin: '100px 0px',
			threshold: 0.01,
		}
	);

	elements.forEach( ( element ) => {
		bgObserver.observe( element );
	} );
}

// 遅延読み込みの初期化
document.addEventListener( 'DOMContentLoaded', () => {
	// ブラウザがネイティブのloading="lazy"をサポートしていない場合のみ実行
	if ( ! ( 'loading' in HTMLImageElement.prototype ) ) {
		initLazyLoadImages();
	}

	initLazyLoadIframes();
	initLazyLoadBackgrounds();

} );

export { initLazyLoadImages, initLazyLoadIframes, initLazyLoadBackgrounds };
