/**
 * Shows a simple message dialog, with a 'close' button. It uses a pre-rendered
 * dialog element that's globally defined for the whole app.
 * @param msg The message to show.
 * @param alertType The type of alert. "info", "warning", "error"
 * @returns A promise that resolves when the alert is closed.
 */
export function showAlert(msg: string, alertType: string = 'info'): Promise<void> {
  const dialog = document.getElementById('alert-dialog') as HTMLDialogElement
  dialog.classList.remove('alert-dialog-error', 'alert-dialog-warning') // Clear old styling classes if they're present.
  if (alertType === 'warning') {
    dialog.classList.add('alert-dialog-warning')
  } else if (alertType === 'error') {
    dialog.classList.add('alert-dialog-error')
  }
  const messageBox = document.getElementById('alert-dialog-message') as HTMLParagraphElement
  const closeButton = document.getElementById('alert-dialog-close-button') as HTMLButtonElement
  closeButton.addEventListener('click', closeAlertDialog)
  messageBox.innerText = msg
  dialog.showModal()
  return new Promise((resolve) => {
    dialog.addEventListener('close', () => {
      closeButton.removeEventListener('click', closeAlertDialog)
      resolve()
    })
  })
}

function closeAlertDialog() {
  const dialog = document.getElementById('alert-dialog') as HTMLDialogElement
  dialog.close()
}
