import React, { useEffect, useState } from 'react';
import { Snackbar, Alert } from '@mui/material';
import { subscribeToast } from '../../utils/toastBus';

/**
 * Global snackbar host for copy/export/feedback errors (#97).
 */
const ToastHost = (): JSX.Element => {
  const [open, setOpen] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'error' | 'success' | 'info'>('info');

  useEffect(() => {
    return subscribeToast((nextMessage, nextSeverity) => {
      setMessage(nextMessage);
      setSeverity(nextSeverity);
      setOpen(true);
    });
  }, []);

  return (
    <Snackbar
      open={open}
      autoHideDuration={4000}
      onClose={() => setOpen(false)}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
    >
      <Alert
        onClose={() => setOpen(false)}
        severity={severity}
        variant="filled"
        sx={{ width: '100%' }}
      >
        {message}
      </Alert>
    </Snackbar>
  );
};

export default ToastHost;
