<script setup lang="ts">
import { onBeforeUnmount, onMounted, watch } from "vue";

const props = withDefaults(defineProps<{ open: boolean; title: string; description?: string; wide?: boolean; closeOnBackdrop?: boolean }>(), {
  description: "",
  wide: false,
  closeOnBackdrop: true
});

const emit = defineEmits<{ close: [] }>();

function close(): void {
  emit("close");
}

function onKeydown(event: KeyboardEvent): void {
  if (event.key === "Escape" && props.open) close();
}

watch(() => props.open, (open) => {
  document.body.classList.toggle("dialog-open", open);
});

onMounted(() => window.addEventListener("keydown", onKeydown));
onBeforeUnmount(() => {
  window.removeEventListener("keydown", onKeydown);
  document.body.classList.remove("dialog-open");
});
</script>

<template>
  <Teleport to="body">
    <div v-if="open" class="workbench-dialog-backdrop" role="presentation" @click.self="closeOnBackdrop ? close() : undefined">
      <section class="workbench-dialog" :class="{ wide }" role="dialog" aria-modal="true" :aria-label="title">
        <header>
          <div class="dialog-title-stack">
            <h2>{{ title }}</h2>
            <p v-if="description">{{ description }}</p>
          </div>
          <button type="button" class="dialog-close" aria-label="关闭" @click="close">x</button>
        </header>
        <slot />
        <footer v-if="$slots.footer" class="dialog-footer">
          <slot name="footer" />
        </footer>
      </section>
    </div>
  </Teleport>
</template>
