/**
 * Minimal Content Widgets block registration for the Gutenberg editor.
 *
 * Waits for blocks-editor.js before registering preview-only blocks. If the full
 * bundle never loads, registers ServerSideRender fallbacks so markup stays visible.
 */
( function ( wp ) {
	if ( ! wp || ! wp.blocks || ! wp.element ) {
		return;
	}

	var config =
		window.rsmsparkContentWidgetsBlocks ||
		{};
	var blocks = config.blocks || [];
	var schemas =
		window.rsmsparkContentWidgetsBlockAttributes ||
		{};
	var createElement = wp.element.createElement;
	var registerBlockType = wp.blocks.registerBlockType;
	var getBlockType = wp.blocks.getBlockType;
	var ServerSideRender =
		wp.serverSideRender ||
		( wp.components && wp.components.ServerSideRender );

	var bootstrapRegistered = false;

	function registerOne( block ) {
		if ( ! block || ! block.name || getBlockType( block.name ) ) {
			return;
		}

		var settings = {
			apiVersion: 3,
			title: block.title || block.name,
			description: block.description || '',
			category: block.category || 'rsm-spark',
			icon: block.icon || 'screenoptions',
			keywords: block.keywords || [],
			supports: block.supports || { html: false },
			attributes: schemas[ block.name ] || {},
			save: function () {
				return null;
			},
			edit: function ( props ) {
				if ( ! ServerSideRender ) {
					return createElement(
						'p',
						null,
						block.title || block.name
					);
				}

				return createElement( ServerSideRender, {
					block: block.name,
					attributes: props.attributes,
					httpMethod: 'POST',
				} );
			},
		};

		registerBlockType( block.name, settings );

		if (
			block.legacy_name &&
			block.legacy_name !== block.name &&
			! getBlockType( block.legacy_name )
		) {
			var legacySupports = Object.assign( {}, settings.supports || {} );
			if ( ! config.experimentalBlocks ) {
				legacySupports.inserter = false;
			}
			registerBlockType(
				block.legacy_name,
				Object.assign( {}, settings, {
					attributes: schemas[ block.legacy_name ] || settings.attributes,
					supports: legacySupports,
				} )
			);
		}
	}

	function registerBootstrapBlocks() {
		if ( bootstrapRegistered || window.rsmCwBlocksEditorReady ) {
			return;
		}
		bootstrapRegistered = true;
		blocks.forEach( registerOne );
	}

	function fullEditorScriptTag() {
		return document.querySelector(
			'script[src*="content-widgets/assets/js/blocks-editor.js"]'
		);
	}

	function fullEditorReady() {
		return !! window.rsmCwBlocksEditorReady;
	}

	function waitForFullEditor( callback, maxMs ) {
		var started = Date.now();

		( function tick() {
			if ( fullEditorReady() ) {
				callback( true );
				return;
			}

			if ( Date.now() - started >= maxMs ) {
				callback( fullEditorReady() );
				return;
			}

			setTimeout( tick, 50 );
		} )();
	}

	function injectFullEditor( callback ) {
		var url = config.scriptUrl || '';
		if ( ! url || fullEditorScriptTag() ) {
			waitForFullEditor( callback, 8000 );
			return;
		}

		var script = document.createElement( 'script' );
		script.src =
			url +
			( url.indexOf( '?' ) > -1 ? '&' : '?' ) +
			'rsmcw_fallback=1';
		script.async = false;
		script.onload = function () {
			waitForFullEditor( callback, 3000 );
		};
		script.onerror = function () {
			callback( false );
		};
		document.head.appendChild( script );
	}

	function boot() {
		// Let WordPress print queued footer scripts (blocks-editor.js) first.
		setTimeout( function () {
			if ( fullEditorReady() ) {
				return;
			}

			if ( fullEditorScriptTag() ) {
				waitForFullEditor( function ( ready ) {
					if ( ! ready ) {
						registerBootstrapBlocks();
					}
				}, 30000 );
				return;
			}

			injectFullEditor( function ( ready ) {
				if ( ! ready ) {
					registerBootstrapBlocks();
				}
			} );
		}, 0 );
	}

	boot();
} )( window.wp );
