const notificationsList = [];

window.notificationMsg = function(message, type) {
  let container = document.querySelector('.js-notifications');

  if (!container) {
    container = document.createElement('div');
    container.classList.add('notifications', 'js-notifications');
    document.body.insertBefore(container, document.body.childNodes[0]);
  }

  const notification = document.createElement('div');
  notification.classList.add(
    'notification',
    'flex',
    'flex-row',
    'flex-nowrap',
    'top-xs',
    'hidden-overflow',
    'rel',
    'padding-small',
    'bottom-margin-small',
    'rounded-x-small',
    'shadow-large',
    'text-break-word',
    `background-${type}`,
    `text-${type}`
  );

  notification.dataset.displayTime = setTimeout(() => {
    container.removeChild(notification);

    const notificationIndex = notificationsList.indexOf(notification);
    notificationsList.splice(notificationIndex, 1);
  }, 5000);

  const notificationIcon = document.createElement('i');
  const notificationIconClasses = {
    success: 'fa-check-circle',
    info: 'fa-info-circle',
    warning: 'fa-exclamation-circle',
    error: 'fa-times-circle',
  };
  notificationIcon.classList.add('text-medium', 'padding-small', 'fas', notificationIconClasses[type]);

  const notificationClose = document.createElement('button');
  notificationClose.type = 'button';
  notificationClose.classList.add('btn-default', 'btn-small-square', `btn-${type}`);
  const notificationCloseIcon = document.createElement('i');
  notificationCloseIcon.classList.add('fas', 'fa-times');
  notificationClose.appendChild(notificationCloseIcon);

  notificationClose.addEventListener('click', () => {
    clearTimeout(notification.dataset.displayTime);
    container.removeChild(notification);

    const notificationIndex = notificationsList.indexOf(notification);
    notificationsList.splice(notificationIndex, 1);
  });

  const notificationMessage = document.createElement('span');
  notificationMessage.classList.add('flex-1', 'text-small', 'padding-small');
  notificationMessage.innerHTML = message;

  notification.appendChild(notificationIcon);
  notification.appendChild(notificationMessage);
  notification.appendChild(notificationClose);

  container.insertBefore(notification, container.childNodes[0]);

  notificationsList.push(notification);
  if (notificationsList.length > 3) {
    clearTimeout(notificationsList[0].dataset.displayTime);
    container.removeChild(notificationsList[0]);
    notificationsList.splice(0, 1);
  }
};
