<script setup lang="ts">
import { ref, type Ref } from 'vue'
import AppButton from '@/components/common/AppButton.vue'

defineProps<{ id?: string }>()

const dialog: Ref<HTMLDialogElement | null> = ref(null)

function show(): Promise<string | undefined> {
  return new Promise((resolve) => {
    dialog.value?.showModal()
    dialog.value?.addEventListener(
      'close',
      () => {
        resolve(dialog.value?.returnValue)
      },
      { once: true },
    )
  })
}

function close(returnValue?: string) {
  dialog.value?.close(returnValue)
}

function isOpen(): boolean {
  return dialog.value?.open ?? false
}

defineExpose({ show, close, isOpen })
</script>
<template>
  <Teleport to="body">
    <dialog
      ref="dialog"
      class="app-modal-dialog"
      :id="id"
    >
      <slot></slot>

      <div class="app-modal-dialog-actions">
        <slot name="buttons">
          <AppButton
            button-style="secondary"
            @click="close()"
            >Close</AppButton
          >
        </slot>
      </div>
    </dialog>
  </Teleport>
</template>
<style lang="css">
.app-modal-dialog {
  background-color: var(--bg-lighter);
  color: inherit;
  border-radius: 1rem;
  border-width: 0;
  /* border: 3px solid var(--theme-secondary); */
  min-width: 300px;
  max-width: 500px;
  padding: 1rem;
}

.app-modal-dialog::backdrop {
  background-color: rgb(0 0 0 / 60%);
}

.app-modal-dialog-header {
  margin-top: 0;
}

.app-modal-dialog-actions {
  text-align: right;
  margin-top: 0.5rem;
}
</style>
