/**
 * @file
 * Overriding core's message functions to add icon and a remove button to each message.
 */

((Drupal) => {
  /**
   * Overrides message theme function.
   *
   * @param {object} message
   *   The message object.
   * @param {string} message.text
   *   The message text.
   * @param {object} options
   *   The message context.
   * @param {string} options.type
   *   The message type.
   * @param {string} options.id
   *   ID of the message, for reference.
   *
   * @return {HTMLElement}
   *   A DOM Node.
   */
  Drupal.theme.message = ({ text }, { type, id }) => {
    const messagesTypes = Drupal.Message.getMessageTypeLabels();
    const messageWrapper = document.createElement('div');
    const kernType = type === 'error' ? 'danger' : (type === 'status' ? 'success' : type);

    messageWrapper.setAttribute(
      'class',
      `messages-list__item messages messages--${type} kern-alert kern-alert--${kernType}`,
    );
    messageWrapper.setAttribute('data-drupal-selector', 'messages');
    messageWrapper.setAttribute(
      'role',
      type === 'error' || type === 'warning' ? 'alert' : 'status',
    );
    messageWrapper.setAttribute('aria-labelledby', `${id}-title`);
    messageWrapper.setAttribute('data-drupal-message-id', id);
    messageWrapper.setAttribute('data-drupal-message-type', type);


    messageWrapper.innerHTML = `
    <div class="messages__container" data-drupal-selector="messages-container">
      <div class="kern-alert__header messages__header">
        <span class="kern-icon kern-icon--${kernType}" aria-hidden="true"></span>
        <span class="kern-title">${messagesTypes[type]}</span>
      </div>
      <div class="kern-alert__body messages__content">
        <div class="kern-body">
            ${text}
        </div>
      </div>
    </div>
    `;

    return messageWrapper;
  };
})(Drupal);
