import { useEffect, useState, useCallback } from 'react';
import styles from './Toast.module.css';

let showToastFn: ((msg: string) => void) | null = null;

export function showToast(msg: string) {
  showToastFn?.(msg);
}

export function Toast() {
  const [visible, setVisible] = useState(false);
  const [message, setMessage] = useState('');

  const show = useCallback((msg: string) => {
    setMessage(msg);
    setVisible(true);
    setTimeout(() => setVisible(false), 2000);
  }, []);

  useEffect(() => {
    showToastFn = show;
    return () => { showToastFn = null; };
  }, [show]);

  return (
    <div className={`${styles.toast} ${visible ? styles.show : ''}`}>
      <span className={styles.icon}>!</span>
      {message}
    </div>
  );
}
