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

export interface CountdownParts {
	days: number;
	hours: number;
	minutes: number;
	seconds: number;
}

const partsFor = ( targetMs: number ): CountdownParts => {
	let remaining = Math.max(
		0,
		Math.floor( ( targetMs - Date.now() ) / 1000 )
	);
	const days = Math.floor( remaining / 86400 );
	remaining %= 86400;
	const hours = Math.floor( remaining / 3600 );
	remaining %= 3600;
	const minutes = Math.floor( remaining / 60 );
	const seconds = remaining % 60;

	return { days, hours, minutes, seconds };
};

/**
 * Live countdown to a target timestamp, ticking once per second. Replaces the
 * static script's "Up next" interval.
 * @param targetMs
 */
export const useCountdown = ( targetMs: number ): CountdownParts => {
	const [ parts, setParts ] = useState< CountdownParts >( () =>
		partsFor( targetMs )
	);

	useEffect( () => {
		setParts( partsFor( targetMs ) );
		const id = setInterval( () => setParts( partsFor( targetMs ) ), 1000 );

		return () => clearInterval( id );
	}, [ targetMs ] );

	return parts;
};

/**
 * A small looping countdown (3 → 2 → 1 → 3 …) used by the "preparing your
 * recording" modal example.
 * @param from
 */
export const useLoopCountdown = ( from = 3 ): number => {
	const [ value, setValue ] = useState( from );

	useEffect( () => {
		const id = setInterval(
			() =>
				setValue( ( current ) =>
					current <= 1 ? from : current - 1
				),
			1000
		);

		return () => clearInterval( id );
	}, [ from ] );

	return value;
};
