/**
 * Accessible on/off switch.
 *
 * A locked switch renders unchecked, announces itself as unavailable and reports clicks
 * through onLockedClick instead of changing its value.
 *
 * @param {Object}   props
 * @param {string}   props.id            Input ID.
 * @param {string}   props.name          Input name.
 * @param {boolean}  props.checked       Checked state.
 * @param {Function} props.onChange      Receives the new boolean value.
 * @param {boolean}  props.locked        Pro feature without an active licence.
 * @param {Function} props.onLockedClick Called when a locked switch is clicked.
 * @param {boolean}  props.disabled      Not available in the current mode.
 * @param {string}   props.describedBy   ID of the description element.
 * @param {string}   props.className     'check2' gives the red "danger" variant (bulk edit).
 */
const Toggle = ( { id, name, checked, onChange, locked = false, onLockedClick, disabled = false, describedBy, className = '' } ) => {
	const variant = className.includes( 'check2' ) ? ' ssgsw-switch--danger' : '';

	return (
		<span className={ `ssgsw-switch${ variant }${ locked ? ' is-locked' : '' }` }>
			<input
				type="checkbox"
				role="switch"
				id={ id }
				name={ name }
				className="ssgsw-switch__input"
				checked={ ! locked && checked }
				disabled={ disabled }
				aria-disabled={ locked || undefined }
				aria-describedby={ describedBy }
				onChange={ ( event ) => {
					if ( locked ) {
						return;
					}
					onChange( event.target.checked );
				} }
				onClick={ ( event ) => {
					if ( locked ) {
						event.preventDefault();
						onLockedClick?.();
					}
				} }
			/>
			<span className="ssgsw-switch__track" aria-hidden="true">
				<span className="ssgsw-switch__thumb"></span>
			</span>
		</span>
	);
};

export default Toggle;
