/**
 * NodePalette — horizontal draggable/clickable action bar above the canvas,
 * grouped by module.
 */

import { __ } from '@wordpress/i18n';
import { toast } from '../../common/Toast';
import { actionIcon } from './utils/icons';
import { PALETTE_MIME } from './WorkflowCanvas';

const NodePalette = ( { actions, onAdd } ) => {
	const groups = {};
	( actions || [] ).forEach( ( a ) => {
		const mod = a.module || __( 'General', 'ai-marketing-expert' );
		( groups[ mod ] = groups[ mod ] || [] ).push( a );
	} );

	// AI modules first, then alphabetical.
	const moduleOrder = [ 'AI', __( 'General', 'ai-marketing-expert' ) ];
	const sortedGroups = Object.entries( groups ).sort( ( [ a ], [ b ] ) => {
		const idxA = moduleOrder.indexOf( a );
		const idxB = moduleOrder.indexOf( b );
		if ( idxA !== -1 && idxB !== -1 ) return idxA - idxB;
		if ( idxA !== -1 ) return -1;
		if ( idxB !== -1 ) return 1;
		return a.localeCompare( b );
	} );

	const handleClick = ( a ) => {
		if ( a.available === false ) {
			return;
		}
		onAdd( a.type );
	};

	return (
		<div className="aime-wf-palette">
			<div className="aime-wf-palette__intro">
				<h3 className="aime-wf-palette__title">{ __( 'Steps', 'ai-marketing-expert' ) }</h3>
				<p className="aime-wf-palette__hint">{ __( 'Drag onto the canvas or click to add.', 'ai-marketing-expert' ) }</p>
			</div>
			<div className="aime-wf-palette__groups">
				{ sortedGroups.map( ( [ mod, items ] ) => (
					<div key={ mod } className="aime-wf-palette__group">
						<div className="aime-wf-palette__group-label">{ mod }</div>
						<div className="aime-wf-palette__group-items">
							{ items.map( ( a ) => {
								const unavailable = a.available === false;
								return (
									<button
										key={ a.type }
										type="button"
										className={ `aime-wf-palette__item${ unavailable ? ' is-unavailable' : '' }` }
										title={
											unavailable
												? __( 'The module for this action is not active.', 'ai-marketing-expert' )
												: a.description || a.label
										}
										draggable={ ! unavailable }
										onDragStart={ ( e ) => {
											e.dataTransfer.setData( PALETTE_MIME, a.type );
											e.dataTransfer.effectAllowed = 'move';
										} }
										onClick={ () => handleClick( a ) }
									>
										<span className="aime-wf-palette__icon">{ actionIcon( a.type ) }</span>
										<span className="aime-wf-palette__label">{ a.label }</span>
									</button>
								);
							} ) }
						</div>
					</div>
				) ) }
			</div>
		</div>
	);
};

export default NodePalette;
