<script setup lang="ts">
import { ref } from 'vue'

const dialog = ref<HTMLDialogElement>()
const result = ref(false)

function onCancelClicked() {
  result.value = false
  dialog.value?.close('false')
}

function onConfirmClicked() {
  result.value = true
  dialog.value?.close('true')
}

async function show(): Promise<boolean> {
  dialog.value?.showModal()
  return new Promise((resolve) => {
    dialog.value?.addEventListener('close', () => {
      if (dialog.value?.returnValue === 'true') {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}

defineExpose({
  show,
})
</script>
<template>
  <dialog ref="dialog" method="dialog">
    <form>
      <slot></slot>

      <div class="button-bar align-right">
        <button @click.prevent="onConfirmClicked">Confirm</button>
        <button @click.prevent="onCancelClicked">Cancel</button>
      </div>
    </form>
  </dialog>
</template>
