/**
 * Inspector-safe font size control (presets + custom unit).
 * Avoids WordPress FontSizePicker, whose in-panel unit/select UI overflows
 * scroll containers (admin / Gutenberg / frontend editors).
 */
import { __ } from '@wordpress/i18n';
import { DEFAULT_FONT_SIZES } from '../styleFieldDefaults';
import FlexibleUnitControl from './FlexibleUnitControl';
import SearchableSelect from './SearchableSelect';

const CUSTOM = '__custom__';

const FONT_SIZE_UNITS = [
	{ value: 'px', label: 'px', default: 16 },
	{ value: 'rem', label: 'rem', default: 1 },
	{ value: 'em', label: 'em', default: 1 },
];

/**
 * @param {Array<{ name?: string, size?: string|number, slug?: string }>} fontSizes
 * @return {Array<{ label: string, value: string }>}
 */
function buildOptions( fontSizes ) {
	const list = Array.isArray( fontSizes ) && fontSizes.length
		? fontSizes
		: DEFAULT_FONT_SIZES;
	return [
		{
			label: __( 'Default', 'joc-blockora-morph' ),
			value: '',
		},
		...list.map( ( fs ) => {
			const size = String( fs?.size ?? '' ).trim();
			const name = String( fs?.name || '' ).trim();
			return {
				label: name && size ? `${ name } (${ size })` : name || size,
				value: size,
			};
		} ),
		{
			label: __( 'Custom', 'joc-blockora-morph' ),
			value: CUSTOM,
		},
	];
}

/**
 * @param {object}   props
 * @param {string}   [props.label]
 * @param {string}   [props.help]
 * @param {string}   [props.className]
 * @param {string}   [props.value]
 * @param {Function} props.onChange
 * @param {Array}    [props.fontSizes]
 */
export default function FontSizeField( {
	label = __( 'Size', 'joc-blockora-morph' ),
	help,
	className = '',
	value = '',
	onChange,
	fontSizes,
} ) {
	const options = buildOptions( fontSizes );
	const valueStr = String( value || '' ).trim();
	const isPreset = options.some(
		( opt ) => opt.value && opt.value !== CUSTOM && opt.value === valueStr
	);
	const selectValue = ! valueStr ? '' : isPreset ? valueStr : CUSTOM;

	return (
		<div
			className={ [ 'bm-font-size-field', className ]
				.filter( Boolean )
				.join( ' ' ) }
		>
			<SearchableSelect
				label={ label }
				help={ help }
				value={ selectValue }
				options={ options }
				onChange={ ( next ) => {
					if ( next === CUSTOM ) {
						onChange(
							valueStr && ! isPreset ? valueStr : '16px'
						);
						return;
					}
					onChange( next || '' );
				} }
				searchableThreshold={ 99 }
			/>
			{ selectValue === CUSTOM ? (
				<FlexibleUnitControl
					label={ __( 'Custom size', 'joc-blockora-morph' ) }
					value={ valueStr }
					onChange={ ( next ) => onChange( next || '' ) }
					units={ FONT_SIZE_UNITS }
				/>
			) : null }
		</div>
	);
}
