<template>
  <dialog ref="dialogRef" class="app-dialog" @close="unlockScroll(); $emit('close')">
    <form class="dialog-form" method="dialog">
      <header>
        <h2>{{ title }}</h2>
        <button type="button" aria-label="关闭" @click="closeDialog">×</button>
      </header>
      <div class="simple-dialog-body">
        <slot />
      </div>
      <footer>
        <slot name="footer">
          <span></span>
          <span></span>
          <button type="button" class="secondary" @click="closeDialog">关闭</button>
        </slot>
      </footer>
    </form>
  </dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { lockScroll, unlockScroll } from '../utils/scrollLock'

const props = defineProps({
  open: Boolean,
  title: {
    type: String,
    default: '',
  },
})

defineEmits(['close'])

const dialogRef = ref(null)

function closeDialog() {
  dialogRef.value?.close()
}

watch(
  () => props.open,
  (value) => {
    if (!dialogRef.value) return
    if (value && !dialogRef.value.open) {
      dialogRef.value.showModal()
      lockScroll()
    }
    if (!value && dialogRef.value.open) {
      dialogRef.value.close()
      unlockScroll()
    }
  },
)
</script>
