<script setup lang="ts">
import { watch, ref } from 'vue'
import { useFocusTrap } from '../utils/focusTrap'

const props = defineProps<{ show: boolean }>()
const emit = defineEmits<{
  cancel: []
  discard: []
}>()

const { activate, deactivate } = useFocusTrap()
const dialogRef = ref<HTMLElement | null>(null)

watch(() => props.show, (val) => {
  if (val) {
    setTimeout(() => {
      if (dialogRef.value) activate(dialogRef.value, { onDeactivate: () => emit('cancel') })
    }, 50)
  } else {
    deactivate()
  }
})
</script>

<template>
  <Transition name="modal">
  <div
    v-if="show"
    class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center p-4 z-50"
    @click.self="$emit('cancel')"
  >
    <div ref="dialogRef" role="alertdialog" aria-modal="true" aria-labelledby="discard-title" aria-describedby="discard-desc" class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-xs p-6">
      <h2 id="discard-title" class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-2">Unsaved Changes</h2>
      <p id="discard-desc" class="text-[0.75rem] text-text-secondary mb-6">
        You have unsaved changes. Do you want to discard them?
      </p>
      <div class="flex justify-end gap-3">
        <button
          @click="$emit('cancel')"
          class="px-4 py-2 text-[0.8125rem] border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors duration-150"
        >
          Keep Editing
        </button>
        <button
          @click="$emit('discard')"
          class="px-4 py-2 text-[0.8125rem] border border-status-error text-status-error font-medium rounded-lg hover:bg-status-error/10 transition-colors duration-150"
        >
          Discard
        </button>
      </div>
    </div>
  </div>
  </Transition>
</template>
