import { useState, useEffect, useCallback } from 'react';

// Simple seconds countdown. `start(n)` (re)starts it at n seconds; it ticks down to 0.
export default function useCountdown(initial = 0) {
  const [seconds, setSeconds] = useState(initial);

  useEffect(() => {
    if (seconds <= 0) return undefined;
    const t = setTimeout(() => setSeconds((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [seconds]);

  const start = useCallback((n) => setSeconds(n), []);
  return [seconds, start];
}
