'use client';

import { useState, useRef, useEffect } from 'react';
import { useLatest } from 'use-a-hook';

export default function GreetingPreview() {
  const [name, setName] = useState('Ada');
  const [message, setMessage] = useState('');
  const latestName = useLatest(name);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);
  function preview() {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setMessage(`Hello, ${latestName.current}!`), 1000);
  }
  return (
    <section>
      <input
        aria-label="Recipient"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <button onClick={preview}>Preview in one second</button>
      <p>{message}</p>
    </section>
  );
}
