/**
 * EdGEL alert component.
 */

import { html } from 'lit'
import Alert from 'bootstrap/js/src/alert.js'
import EventHandler from 'bootstrap/js/src/dom/event-handler.js'
import { EdGELElement } from '../base.js'

const EVENT_CLOSED = 'closed.bs.alert'

export class EdGELAlert extends EdGELElement {
  static properties = {
    colour: { type: String },
    dismiss: { type: Boolean }
  }

  constructor() {
    super()

    this.colour = 'dark'
    this.dismiss = false
  }

  _dismissAlert() {
    const div = this.shadowRoot.querySelector('.show')
    // The closed event will not bubble because it is fired after the element has been
    // removed from the DOM, so we relay it here.
    EventHandler.one(div, EVENT_CLOSED, () => {
      EventHandler.trigger(this, EVENT_CLOSED)
    })

    const data = Alert.getOrCreateInstance(div)
    data.close(div)
  }

  render() {
    let closeButton
    let classes = `alert alert-${this.colour}`

    if (this.dismiss) {
      classes = `${classes} alert-dismissible fade show`
      closeButton = html`
        <button type="button" class="btn-close" aria-label="Close" @click=${this._dismissAlert}></button>
      `
    }

    return html`
      <div class=${classes} role="alert">
        <slot></slot>
        ${closeButton}
      </div>
    `
  }
}
