( function () {
	'use strict';

	var PREVIEW_CLASS = 'is-rsm-rsf-animate-preview';

	function getEditorCanvas() {
		var iframe = document.querySelector( 'iframe[name="editor-canvas"]' );
		if ( iframe && iframe.contentDocument ) {
			return iframe.contentDocument;
		}

		return (
			document.querySelector( '.editor-styles-wrapper' ) ||
			document.querySelector( '.block-editor-writing-flow' ) ||
			document
		);
	}

	function resetPreviewState( root ) {
		root.querySelectorAll( '.rsm-rsf-animate' ).forEach( function ( el ) {
			el.classList.add( 'is-rsm-rsf-visible' );
			el.classList.remove( 'is-rsm-rsf-editor-preview' );
			el.style.transitionDuration = '';
			el.style.transitionDelay = '';
		} );

		root.querySelectorAll( '.rsm-rsf-stagger-host' ).forEach( function ( host ) {
			getStaggerChildren( host ).forEach( function ( child ) {
				child.classList.add( 'is-rsm-rsf-visible' );
				child.classList.remove( 'is-rsm-rsf-editor-preview' );
				child.style.transitionDuration = '';
				child.style.transitionDelay = '';
			} );
		} );
	}

	function getStaggerChildren( host ) {
		var inner = host.querySelector( ':scope > .wp-block-group__inner-container' );
		var container = inner || host;

		return container.querySelectorAll( ':scope > *' );
	}

	function enablePreviewState( root ) {
		root.querySelectorAll( '.rsm-rsf-animate' ).forEach( function ( el ) {
			el.classList.remove( 'is-rsm-rsf-visible' );
			el.classList.add( 'is-rsm-rsf-editor-preview' );
		} );

		root.querySelectorAll( '.rsm-rsf-stagger-host' ).forEach( function ( host ) {
			getStaggerChildren( host ).forEach( function ( child ) {
				child.classList.remove( 'is-rsm-rsf-visible' );
				child.classList.add( 'is-rsm-rsf-editor-preview' );
			} );
		} );

		if ( typeof window.rsmRsfInitAnimations === 'function' ) {
			window.rsmRsfInitAnimations( root );
		}
	}

	function syncPreview() {
		var root = getEditorCanvas();
		if ( document.body.classList.contains( PREVIEW_CLASS ) ) {
			enablePreviewState( root );
		} else {
			resetPreviewState( root );
		}
	}

	var observer = new MutationObserver( syncPreview );
	observer.observe( document.body, {
		attributes: true,
		attributeFilter: [ 'class' ],
	} );

	document.addEventListener( 'DOMContentLoaded', syncPreview );
	window.addEventListener( 'load', syncPreview );

	// Re-sync when editor canvas re-renders.
	var canvasObserver = new MutationObserver( function () {
		if ( document.body.classList.contains( PREVIEW_CLASS ) ) {
			syncPreview();
		}
	} );

	function watchCanvas() {
		var root = getEditorCanvas();
		if ( root && root !== document ) {
			canvasObserver.observe( root.body || root, {
				childList: true,
				subtree: true,
			} );
		}
	}

	watchCanvas();
	window.setInterval( watchCanvas, 2000 );
} )();
