/**
 * Animations
 * アニメーション機能
 */

/**
 * Intersection Observerを使用したフェードインアニメーション
 */
function initFadeInAnimations() {
	const elements = document.querySelectorAll( '.zenblocks-fade-in' );

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

	const observer = new IntersectionObserver(
		( entries ) => {
			entries.forEach( ( entry ) => {
				if ( entry.isIntersecting ) {
					entry.target.classList.add( 'is-visible' );
					observer.unobserve( entry.target );
				}
			} );
		},
		{
			threshold: 0.1,
			rootMargin: '0px 0px -50px 0px',
		}
	);

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

/**
 * スライドインアニメーション
 */
function initSlideInAnimations() {
	const elements = document.querySelectorAll( '.zenblocks-slide-in' );

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

	const observer = new IntersectionObserver(
		( entries ) => {
			entries.forEach( ( entry ) => {
				if ( entry.isIntersecting ) {
					entry.target.classList.add( 'is-visible' );
					observer.unobserve( entry.target );
				}
			} );
		},
		{
			threshold: 0.1,
			rootMargin: '0px 0px -50px 0px',
		}
	);

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

/**
 * パララックス効果
 */
function initParallaxEffect() {
	const elements = document.querySelectorAll( '.zenblocks-parallax' );

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

	let ticking = false;

	function updateParallax() {
		const scrolled = window.pageYOffset;

		elements.forEach( ( element ) => {
			const speed = element.dataset.parallaxSpeed || 0.5;
			const yPos = -( scrolled * speed );
			element.style.transform = `translate3d(0, ${ yPos }px, 0)`;
		} );

		ticking = false;
	}

	window.addEventListener( 'scroll', () => {
		if ( ! ticking ) {
			window.requestAnimationFrame( updateParallax );
			ticking = true;
		}
	} );

	// 初期位置を設定
	updateParallax();
}

// アニメーションの初期化
document.addEventListener( 'DOMContentLoaded', () => {
	initFadeInAnimations();
	initSlideInAnimations();
	initParallaxEffect();
} );

export { initFadeInAnimations, initSlideInAnimations, initParallaxEffect };
