import { enqueueSnackbar, closeSnackbar } from 'notistack';

import { setSnackbarId } from '../../store/reducers/toastSlice';
import { store, dispatch } from 'store';

export const GlobalToast = (message, color = 'default', vertical = 'top') => {
  const id = enqueueSnackbar(message, {
    variant: color,
    anchorOrigin: { vertical, horizontal: 'right' },
    autoHideDuration: null,
    action: (snackbarId) => (
      <button onClick={() => closeSnackbar(snackbarId)} style={{ background: 'none', border: 'none', cursor: 'pointer' }}>
        ❌
      </button>
    )
  });

  // Save snackbarId globally
  dispatch(setSnackbarId(id));

  return id;
};

// GLOBAL close function
export const closeGlobalToast = () => {
  const id = store.getState().toastSlice.snackbarId;
  if (id) {
    closeSnackbar(id);
  }
};
