/**
 * WordPress dependencies
 */
import { render } from '@safe-wordpress/element';

/**
 * External dependencies
 */
import type { ExperimentId, AlternativeId } from '@nab/types';

/**
 * Internal dependencies
 */
import { hideAlternativeSidebars, hideAllSidebarsBut } from './utils';
import { DuplicateControlWidgetsButton } from './duplicate-control-widgets-button';

type Settings = {
	readonly sidebars: ReadonlyArray< string >;
	readonly experiment: ExperimentId;
	readonly alternative: AlternativeId;
};

export function initControlEdition(): void {
	hideAlternativeSidebars();
}

export function initAlternativeEdition( settings: Settings ): void {
	hideAllSidebarsBut( settings.sidebars );
	addMainButton( settings );
}

// HACK. Add “Dupliacte Widgets” button.
function addMainButton( settings: Settings ) {
	const add = ( actions: Element ) => {
		const child = actions.children[ 0 ];
		if ( ! child ) {
			return;
		}

		const holder = document.createElement( 'div' );
		actions.insertBefore( holder, child );
		render(
			<DuplicateControlWidgetsButton
				experiment={ settings.experiment }
				alternative={ settings.alternative }
			/>,
			holder
		);
	};

	let i = 0;
	const check = (): void => {
		const actions = document.querySelector(
			'.edit-widgets-header__actions'
		);
		if ( ! actions?.children?.length && i < 40 ) {
			setTimeout( check, ++i * 250 );
			return;
		}
		if ( actions ) {
			add( actions );
		}
	};
	check();
}
