/*
 * Sanitized Number Input Component
 */

import { useState, useEffect } from '@wordpress/element';

const DecimalNumberInput = ( { value, onChange, min = 0, max = 1, step = 0.1, className = '', style = {} } ) => {
	const [ inputValue, setInputValue ] = useState( value );

	// Sync local state with the prop value when it changes
	useEffect( () => {
		setInputValue( value );
	}, [ value ] );

	const handleInputChange = ( e ) => {
		let inputValue = e.target.value;

		// Remove leading zeros but preserve single '0' before decimal point
		inputValue = inputValue.replace( /^(-?)0+(?!\.|$)/, '$1' );

		// Parse to float
		let parsedValue = parseFloat( inputValue );

		// If not a valid number, set to 0
		if ( isNaN( parsedValue ) ) {
			parsedValue = 0;
		}

		// Clamp the value between min and max
		parsedValue = Math.min( Math.max( parsedValue, min ), max );

		// Update the input field to reflect the corrected value
		e.target.value = parsedValue;

		// Update local state
		setInputValue( parsedValue );

		// Call the onChange callback
		onChange( parsedValue );
	};

	return (
		<input
			type = "number"
			value = { inputValue }
			onChange = { handleInputChange }
			min = { min }
			max = { max }
			step = { step }
			className = { className }
			style = { style }
		/>
	);
};

export default DecimalNumberInput;
