(() => {
	if (
		!( 'IntersectionObserver' in window ) ||
		window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches
	) {
		return;
	}

	document.documentElement.classList.add( 'reveal-enabled' );

	const initializeReveal = () => {
		const revealItems = document.querySelectorAll(
			[
				'.wp-block-post-content .wp-block-group.is-style-section:not(.no-reveal)',
				'.wp-block-post-content .wp-block-group.is-style-section-divider:not(.no-reveal)',
				'.has-reveal:not(.no-reveal)',
			].join( ',' )
		);

		if ( ! revealItems.length ) {
			document.documentElement.classList.remove( 'reveal-enabled' );
			return;
		}

		revealItems.forEach( ( item ) => {
			item.classList.add( 'reveal-target' );
		} );

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

					entry.target.classList.add( 'is-visible' );
					observer.unobserve( entry.target );
				} );
			},
			{
				rootMargin: '0px 0px -5% 0px',
				threshold: 0.05,
			}
		);

		revealItems.forEach( ( item ) => {
			revealObserver.observe( item );
		} );
	};

	if ( 'loading' === document.readyState ) {
		document.addEventListener( 'DOMContentLoaded', initializeReveal, { once: true } );
	} else {
		initializeReveal();
	}
})();
