( function ( wp ) {
	'use strict';

	if ( ! wp || ! wp.hooks || ! wp.blockEditor || ! wp.element || ! wp.components ) {
		return;
	}
	if ( typeof newsai_vars === 'undefined' || ! newsai_vars.ai_active ) {
		return;
	}
	if ( newsai_vars.features && newsai_vars.features.floating_ai_menu === false ) {
		return;
	}

	var el = wp.element.createElement;
	var Fragment = wp.element.Fragment;
	var BlockControls = wp.blockEditor.BlockControls;
	var __ = wp.i18n.__;
	var ToolbarGroup = wp.components.ToolbarGroup;
	var ToolbarDropdownMenu = wp.components.ToolbarDropdownMenu;

	if ( ! BlockControls || ! ToolbarDropdownMenu ) {
		return;
	}

	var TEXT_BLOCKS = {
		'core/paragraph': true,
		'core/heading': true,
		'core/list-item': true,
		'core/quote': true,
		'core/pullquote': true,
		'core/preformatted': true,
		'core/verse': true,
		'core/table-cell': true,
	};

	function runAction( action ) {
		if ( typeof window.nrosAiFloatRunEdit !== 'function' ) {
			return;
		}
		window.nrosAiFloatRunEdit( action );
	}

	function buildControls() {
		return [
			{
				title: __( 'Rewrite', 'newsroom-ai-assistant' ),
				onClick: function () { runAction( 'rewrite' ); },
			},
			{
				title: __( 'Shorten', 'newsroom-ai-assistant' ),
				onClick: function () { runAction( 'shorten' ); },
			},
			{
				title: __( 'Expand', 'newsroom-ai-assistant' ),
				onClick: function () { runAction( 'expand' ); },
			},
			{
				title: __( 'Simplify', 'newsroom-ai-assistant' ),
				onClick: function () { runAction( 'simplify' ); },
			},
		];
	}

	function NewsroomAIBlockControls( props ) {
		if ( ! props.blockName || ! TEXT_BLOCKS[ props.blockName ] ) {
			return null;
		}
		return el(
			BlockControls,
			{ group: 'other' },
			el(
				ToolbarGroup,
				null,
				el( ToolbarDropdownMenu, {
					icon: 'admin-site-alt3',
					label: __( 'Newsroom AI', 'newsroom-ai-assistant' ),
					controls: buildControls(),
					toggleProps: {
						onMouseDown: function () {
							if ( typeof window.nrosAiFloatCaptureSelection === 'function' ) {
								window.nrosAiFloatCaptureSelection();
							}
						},
						onClick: function () {
							if ( typeof window.nrosAiFloatCaptureSelection === 'function' ) {
								window.nrosAiFloatCaptureSelection();
							}
						},
					},
				} )
			)
		);
	}

	wp.hooks.addFilter(
		'editor.BlockEdit',
		'newsroom-os/ai-block-toolbar',
		function ( BlockEdit ) {
			return function ( props ) {
				return el(
					Fragment,
					null,
					el( BlockEdit, props ),
					el( NewsroomAIBlockControls, { blockName: props.name } )
				);
			};
		}
	);
}( window.wp ) );
