export function showAlert(message: string): Promise<void> {
  getText().innerText = message
  getOkButton().style.display = 'none'
  getCancelButton().style.display = 'none'
  getCloseButton().style.display = ''
  return new Promise((resolve) => {
    const modal = getModal()
    modal.showModal()
    modal.addEventListener(
      'close',
      () => {
        resolve()
      },
      { once: true },
    )
  })
}

export function showConfirm(message: string): Promise<boolean> {
  getText().innerText = message
  getOkButton().style.display = ''
  getCancelButton().style.display = ''
  getCloseButton().style.display = 'none'
  return new Promise((resolve) => {
    const modal = getModal()
    modal.showModal()
    modal.addEventListener('close', () => resolve(modal.returnValue === 'ok'), { once: true })
  })
}

function getModal(): HTMLDialogElement {
  return document.getElementById('global-alert-modal') as HTMLDialogElement
}

function getText(): HTMLParagraphElement {
  return document.getElementById('global-alert-modal-text') as HTMLParagraphElement
}

function getOkButton(): HTMLButtonElement {
  return document.getElementById('global-alert-modal-ok-button') as HTMLButtonElement
}

function getCancelButton(): HTMLButtonElement {
  return document.getElementById('global-alert-modal-cancel-button') as HTMLButtonElement
}

function getCloseButton(): HTMLButtonElement {
  return document.getElementById('global-alert-modal-close-button') as HTMLButtonElement
}
