/**
 * WP Agentic Writer - Block Toolbar Chat Mention
 *
 * Adds "@chat" button to block toolbar to insert the block mention into chat input.
 *
 * @package WP_Agentic_Writer
 */

( function ( wp ) {
	const { BlockControls } = wp.blockEditor;
	const { ToolbarButton, ToolbarGroup } = wp.components;
	const { createHigherOrderComponent } = wp.compose;
	const { useSelect } = wp.data;
	const { addFilter } = wp.hooks;
	const { __ } = wp.i18n;

	const buildMentionToken = ( block, allBlocks ) => {
		if ( ! block ) {
			return '@this';
		}

		if ( block.name === 'core/list-item' ) {
			let listIndex = 0;

			for ( const parent of allBlocks ) {
				if ( parent.name !== 'core/list' ) {
					continue;
				}

				listIndex += 1;
				const innerItems = Array.isArray( parent.innerBlocks ) ? parent.innerBlocks : [];
				const itemIndex = innerItems.findIndex( ( item ) => item.clientId === block.clientId );
				if ( itemIndex !== -1 ) {
					return `@list-${ listIndex }.list-item-${ itemIndex }`;
				}
			}
		}

		if ( ! block.name || ! block.name.startsWith( 'core/' ) ) {
			return '@this';
		}

		const typeName = block.name.replace( 'core/', '' );
		let count = 0;

		for ( const entry of allBlocks ) {
			if ( ! entry.name || ! entry.name.startsWith( 'core/' ) ) {
				continue;
			}

			if ( entry.name.replace( 'core/', '' ) === typeName ) {
				count += 1;
			}

			if ( entry.clientId === block.clientId ) {
				break;
			}
		}

		return `@${ typeName }-${ count }`;
	};

	const withChatMentionToolbar = createHigherOrderComponent( ( BlockEdit ) => {
		return ( props ) => {
			const { clientId } = props;
			const block = useSelect(
				( select ) => select( 'core/block-editor' ).getBlock( clientId ),
				[ clientId ]
			);
			const allBlocks = useSelect(
				( select ) => select( 'core/block-editor' ).getBlocks(),
				[]
			);
			const mentionToken = buildMentionToken( block, allBlocks );

			const sendToChat = () => {
				window.dispatchEvent(
					new CustomEvent( 'wpaw:insert-mention', {
						detail: {
							token: `${ mentionToken } `,
							blockId: block?.clientId || clientId,
						},
					} )
				);
			};

			return wp.element.createElement(
				wp.element.Fragment,
				null,
				wp.element.createElement( BlockEdit, props ),
				wp.element.createElement(
					BlockControls,
					null,
					wp.element.createElement(
						ToolbarGroup,
						null,
						wp.element.createElement( ToolbarButton, {
							icon: 'format-chat',
							label: __( 'Send to chat', 'wp-agentic-writer' ),
							onClick: sendToChat,
							children: '@chat',
						} )
					)
				)
			);
		};
	}, 'withChatMentionToolbar' );

	addFilter(
		'editor.BlockEdit',
		'wp-agentic-writer/block-chat-mention',
		withChatMentionToolbar
	);
} )( window.wp );
