/**
 * Shared spacing control: preset dropdown + custom unit input.
 * Used by StyleField (block styles) and ElementToolbar (per-element spacing).
 */
import { BaseControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { SPACING_PRESETS, SPACING_UNITS } from '../styleFieldDefaults';
import FlexibleUnitControl from './FlexibleUnitControl';
import SearchableSelect from './SearchableSelect';
/**
 * Preset select + FlexibleUnitControl row (no outer label).
 *
 * @param {object}   props
 * @param {string}   [props.value]
 * @param {Function} props.onChange
 * @param {string}   [props.label] Accessible label for the preset select
 */
export function SpacingInputRow( { value = '', onChange, label } ) {
	const presetMatch = SPACING_PRESETS.find( ( p ) => p.size === value );
	const presetValue = presetMatch ? presetMatch.slug : value ? 'custom' : '';

	const presetOptions = [
		{
			label: value
				? __( 'Custom', 'joc-blockora-morph' )
				: __( 'Select size', 'joc-blockora-morph' ),
			value: value && ! presetMatch ? 'custom' : '',
		},
		...SPACING_PRESETS.map( ( p ) => ( {
			label: `${ p.name } (${ p.size })`,
			value: p.slug,
		} ) ),
	];

	return (
		<div className="bm-style-field__spacing-row">
			<div className="bm-style-field__spacing-col bm-style-field__spacing-col--preset">
				<SearchableSelect
					label={ label || __( 'Preset', 'joc-blockora-morph' ) }
					hideLabelFromVision
					value={ presetValue }
					options={ presetOptions }
					onChange={ ( slug ) => {
						if ( ! slug || slug === 'custom' ) {
							return;
						}
						const preset = SPACING_PRESETS.find( ( p ) => p.slug === slug );
						if ( preset ) {
							onChange( preset.size );
						}
					} }
				/>
			</div>
			<div className="bm-style-field__spacing-col bm-style-field__spacing-col--unit">
				<FlexibleUnitControl
					label={ __( 'Custom', 'joc-blockora-morph' ) }
					hideLabelFromVision
					value={ value || '' }
					onChange={ ( next ) => onChange( next || '' ) }
					units={ SPACING_UNITS }
				/>
			</div>
		</div>
	);
}

/**
 * Labeled spacing field (BaseControl + SpacingInputRow).
 *
 * @param {object}   props
 * @param {string}   props.label
 * @param {string}   [props.value]
 * @param {Function} props.onChange
 * @param {string}   [props.className]
 * @param {string}   [props.id]
 * @param {string}   [props.help]
 */
export default function SpacingControl( {
	label,
	value = '',
	onChange,
	className = '',
	id,
	help,
} ) {
	return (
		<BaseControl
			id={ id }
			label={ label }
			help={ help }
			className={ [ 'bm-style-field', 'bm-style-field--spacing', className ]
				.filter( Boolean )
				.join( ' ' ) }
		>
			<SpacingInputRow value={ value } onChange={ onChange } label={ label } />
		</BaseControl>
	);
}
