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

let toastTimer = null;

export default function Toast({ message, onClose }) {
  const [visible, setVisible] = useState(!!message);

  useEffect(() => {
    if (!message) return undefined;
    setVisible(true);
    if (toastTimer) clearTimeout(toastTimer);
    toastTimer = setTimeout(() => {
      setVisible(false);
      onClose?.();
    }, 2500);
    return () => clearTimeout(toastTimer);
  }, [message, onClose]);

  if (!visible || !message) return null;
  return <div className="dt-toast">{message}</div>;
}

export function useToast() {
  const [message, setMessage] = useState('');
  const show = (msg) => setMessage(msg);
  const clear = () => setMessage('');
  return { message, show, clear };
}
