/*!
 * HotPocket by BTHLabs (https://hotpocket.app/)
 * Copyright 2025-present BTHLabs <contact@bthlabs.pl> (https://bthlabs.pl/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
((HotPocket, bootstrap) => {
  const LEVEL_TO_BOOTSTRAP_CLASS = {
    'debug': 'alert-secondary',
    'info': 'alert-info',
    'success': 'alert-success',
    'warning': 'alert-warning',
    'error': 'alert-danger',
  };

  class HotPocketUIMessagesPlugin {
    constructor (app) {
      this.containerElement = null;
      this.templateElement = null;
    }
    onLoad = (event) => {
      this.containerElement = document.querySelector('.ui-messages');
      this.templateElement = document.querySelector('#Messages-Alert');

      for (let element of this.containerElement.querySelectorAll('.alert')) {
        element.classList.add('alert-dismissible');
        element.classList.add('fade');
        element.classList.add('show');

        new bootstrap.Alert(element);
      }

      document.addEventListener('HotPocket:UI:Messages:addMessage', this.onAddMessage);
    };
    onAddMessage = (event) => {
      const alertContentElement = this.templateElement.content.cloneNode(true);

      const alertElement = alertContentElement.querySelector('.alert');
      alertElement.classList.add(LEVEL_TO_BOOTSTRAP_CLASS[event.detail.level] || 'alert-secondary');
      if (event.detail.extra_tags) {
        alertElement.classList.add(event.detail.extra_tags);
      }
      alertElement.querySelector('.ui-alert-message').innerHTML = event.detail.message;
      new bootstrap.Alert(alertElement);

      this.containerElement.appendChild(alertContentElement);
    };
  }

  HotPocket.addPlugin('UI.Messages', (app) => {
    return new HotPocketUIMessagesPlugin(app);
  });
})(window.HotPocket, window.bootstrap);
