/**
 * WP Agentic Writer - Image Block Toolbar Button
 *
 * Adds "Generate AI Image" button to image blocks with data-agent-image-id attribute.
 *
 * @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;

	/**
	 * Add "Generate AI Image" toolbar button to image blocks with data-agent-image-id.
	 */
	const withImageGenerateToolbar = createHigherOrderComponent((BlockEdit) => {
		return (props) => {
			const { clientId } = props;
			const block = useSelect(
				(select) => select('core/block-editor').getBlock(clientId),
				[clientId]
			);

			// Only add button to core/image blocks
			if (!block || block.name !== 'core/image') {
				return wp.element.createElement(BlockEdit, props);
			}

			// Check for agent image ID in multiple locations
			const getAgentImageId = () => {
				// Method 1: Direct attribute
				if (block.attributes['data-agent-image-id']) {
					return block.attributes['data-agent-image-id'];
				}
				
				// Method 2: Check className for pattern wpaw-agent-img-*
				const className = block.attributes.className || '';
				const classMatch = className.match(/wpaw-agent-img-([^\s]+)/);
				if (classMatch) {
					return classMatch[1];
				}
				
				// Method 3: Check innerHTML for data-agent-image-id
				const innerHTML = block.attributes.innerHTML || '';
				const htmlMatch = innerHTML.match(/data-agent-image-id=["']([^"']+)["']/);
				if (htmlMatch) {
					return htmlMatch[1];
				}
				
				// Method 4: Check if placeholder (no url but has alt)
				if (!block.attributes.url && block.attributes.alt && block.attributes.alt.includes('[Image:')) {
					return 'placeholder_' + clientId;
				}
				
				return null;
			};
			
			const agentImageId = getAgentImageId();

			const openImageModal = () => {
				// Dispatch custom event to open image generation modal
				window.dispatchEvent(
					new CustomEvent('wpaw:open-image-modal', {
						detail: {
							agentImageId: agentImageId || null,
							blockId: 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-image',
							label: __('Generate AI Image', 'wp-agentic-writer'),
							onClick: openImageModal,
							className: 'wpaw-generate-image-btn',
						})
					)
				)
			);
		};
	}, 'withImageGenerateToolbar');

	// Apply the filter to add toolbar button
	addFilter(
		'editor.BlockEdit',
		'wp-agentic-writer/image-generate-toolbar',
		withImageGenerateToolbar
	);
})(window.wp);
