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

export interface ToastController {
	message: string;
	visible: boolean;
	showToast: ( message: string ) => void;
}

/**
 * React owner of the toast text and `show` state. Replaces the static script's
 * global `toast()` helper and its 1400ms auto-hide timer.
 */
export const useToast = (): ToastController => {
	const [ message, setMessage ] = useState( '' );
	const [ visible, setVisible ] = useState( false );
	const timer = useRef< ReturnType< typeof setTimeout > | null >( null );

	const showToast = useCallback( ( next: string ) => {
		setMessage( next );
		setVisible( true );

		if ( timer.current ) {
			clearTimeout( timer.current );
		}

		timer.current = setTimeout( () => setVisible( false ), 1400 );
	}, [] );

	return { message, visible, showToast };
};
