import { BaseControl, ColorPalette } from '@wordpress/components';
import { PALETTE_SLOTS } from '../utils/field-defs';

export default function PaletteColorSelect( { label, value, onChange, help, slots } ) {
	const allowed = slots || PALETTE_SLOTS;
	const slotLabels = window?.wuppiSettingsBoot?.paletteSlots || {};
	const slotColors = window?.wuppiSettingsBoot?.paletteColors || {};

	const colors = allowed
		.filter( ( slug ) => slotColors[ slug ] )
		.map( ( slug ) => ( {
			slug,
			name: slotLabels[ slug ] || slug,
			color: slotColors[ slug ],
		} ) );

	const currentHex = slotColors[ value ] || undefined;

	const handleChange = ( hex ) => {
		if ( ! hex ) return;
		const found = colors.find( ( c ) => c.color === hex );
		if ( found ) onChange( found.slug );
	};

	return (
		<BaseControl label={ label } help={ help } __nextHasNoMarginBottom>
			<ColorPalette
				colors={ colors }
				value={ currentHex }
				onChange={ handleChange }
				disableCustomColors
				clearable={ false }
			/>
		</BaseControl>
	);
}
