import {Controller} from '@hotwired/stimulus';

/*
* The following line makes this controller "lazy": it won't be downloaded until needed
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
*/
/* stimulusFetch: 'lazy' */
export default class extends Controller {
  static targets = ['alert', 'icon', 'message']

  connect() {
    window.addEventListener('alert:show', this.showAlert.bind(this));
  }

  // ...
  showAlert(event) {
    const detail = event.detail;
    const message = detail.message;
    const level = detail.level;

    let alertClass = "";
    let iconClass = "";
    switch (level) {
      case 'success':
        alertClass = "bg-green-500";
        iconClass = "fa-circle-check";
        break;
      case 'warning':
        alertClass = "bg-yellow-500";
        iconClass = "fa-circle-exclamation";
        break;
      case 'error':
        alertClass = "bg-red-500";
        iconClass = "fa-circle-xmark";
        break;
      case 'info':
      default:
        alertClass = "bg-blue-500";
        iconClass = "fa-circle-info";
        break;
    }

    this.messageTarget.innerHTML = message;
    this.alertTarget.classList.add(alertClass);
    this.iconTarget.classList.add(iconClass);
    this.alertTarget.style.display = "block";

    setTimeout(() => {
      this.alertTarget.style.opacity = 0;

      setTimeout(() => {
        this.alertTarget.style.display = 'none';
        this.alertTarget.classList.remove(alertClass);
        this.alertTarget.style.opacity = 1;
        this.iconTarget.classList.remove(iconClass);
        this.messageTarget.innerHTML = message;
      }, 1000);
    }, 3000);
  }
}
