/**
 * Breakpoint Indicator Initializer
 * エディタにブレークポイントインジケーターを追加
 */

import { createRoot, render } from '@wordpress/element';
import { subscribe, select } from '@wordpress/data';
import BreakpointIndicator from './breakpoint-indicator';

const CONTAINER_ID = 'zenblocks-breakpoint-indicator-container';

const initBreakpointIndicator = () => {
	const editorWrapper = document.querySelector( '.editor-styles-wrapper' );
	if ( ! editorWrapper ) {
		return;
	}

	let container = document.getElementById( CONTAINER_ID );
	if ( ! container ) {
		container = document.createElement( 'div' );
		container.id = CONTAINER_ID;
		editorWrapper.parentNode.insertBefore( container, editorWrapper );

		if ( createRoot ) {
			const root = createRoot( container );
			root.render( <BreakpointIndicator /> );
		} else {
			render( <BreakpointIndicator />, container );
		}
	}
};

let initialized = false;

subscribe( () => {
	if ( initialized ) {
		return;
	}

	const isSavingPost = select( 'core/editor' )?.isSavingPost?.();
	if ( isSavingPost === undefined ) {
		return;
	}

	setTimeout( () => {
		initBreakpointIndicator();
		initialized = true;
	}, 500 );
} );
