<script setup>
// Wraps PrimeVue Dialog; reusable modal overlay. Use default slot for content.
// Footer: #footer-left (left-aligned, e.g. checkbox), #footer-right (right-aligned actions). Show footer when either slot is used.
import { computed } from "vue";
import Dialog from "primevue/dialog";

const props = defineProps({
  visible: { type: Boolean, default: false }, // v-model
  title: { type: String, default: "" }, // header text
  width: { type: String, default: "30rem" }, // e.g. '30rem', '450px'
  modal: { type: Boolean, default: true },
  closable: { type: Boolean, default: true }, // show close button in header
  dismissableMask: { type: Boolean, default: false }, // close on backdrop click
  class: { type: [String, Object, Array], default: "" },
});

const emit = defineEmits(["update:visible", "show", "hide", "submit"]);

const modalStyle = computed(() => ({ width: props.width }));

function onContentKeydown(e) {
  if (e.key !== "Enter") return;
  if (e.target.closest("textarea")) return;
  // Let the browser submit the form once (avoids double fire with emit("submit")).
  if (e.target.closest("form")) return;
  e.preventDefault();
  emit("submit");
}
</script>

<template>
  <Dialog
    :visible="visible"
    :header="title"
    :style="modalStyle"
    :modal="modal"
    :closable="closable"
    :dismissable-mask="dismissableMask"
    :class="props['class']"
    v-bind="$attrs"
    @update:visible="emit('update:visible', $event)"
    @show="emit('show')"
    @hide="emit('hide')"
    @submit="emit('submit')"
  >
    <template v-if="$slots.header" #header><slot name="header" /></template>
    <div
      class="px-2 py-6 text-base text-surface-900 dark:text-surface-0"
      @keydown.enter="onContentKeydown"
    >
      <slot />
    </div>
    <template v-if="$slots['footer-left'] || $slots['footer-right']" #footer>
      <div class="flex items-center justify-between gap-4 w-full px-2">
        <div v-if="$slots['footer-left']" class="flex items-center gap-2">
          <slot name="footer-left" />
        </div>
        <div v-else />
        <div
          v-if="$slots['footer-right']"
          class="flex items-center justify-end gap-2"
        >
          <slot name="footer-right" />
        </div>
      </div>
    </template>
  </Dialog>
</template>
