<script setup lang="ts">
withDefaults(
  defineProps<{
    open: boolean
    title: string
    eyebrow?: string
    confirmLabel?: string
    cancelLabel?: string
    tone?: 'primary' | 'danger'
    busy?: boolean
  }>(),
  {
    confirmLabel: 'Confirm',
    cancelLabel: 'Cancel',
    tone: 'primary',
    busy: false,
  },
)

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

onMounted(() => {
  const onKey = (e: KeyboardEvent) => {
    if (e.key === 'Escape') emit('close')
  }
  document.addEventListener('keydown', onKey)
  onBeforeUnmount(() => document.removeEventListener('keydown', onKey))
})
</script>

<template>
  <Teleport to="body">
    <div v-if="open" class="backdrop" @click="emit('close')">
      <div class="modal" @click.stop>
        <header>
          <div>
            <Eyebrow v-if="eyebrow">{{ eyebrow }}</Eyebrow>
            <h3>{{ title }}</h3>
          </div>
          <button class="close" @click="emit('close')">
            <UiIcon name="x" :size="18" />
          </button>
        </header>
        <div class="body">
          <slot />
        </div>
        <footer>
          <UiButton variant="ghost" @click="emit('close')">{{ cancelLabel }}</UiButton>
          <UiButton :variant="tone === 'danger' ? 'danger' : 'primary'" :disabled="busy" @click="emit('confirm')">
            {{ busy ? 'Working…' : confirmLabel }}
          </UiButton>
        </footer>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
  z-index: 80;
}

.modal {
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 10px;
  width: 100%;
  max-width: 480px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 24px 80px rgba(0, 0, 0, 0.4);
}

header {
  padding: 18px 24px;
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

h3 {
  margin: 4px 0 0 0;
  font-family: var(--font-display);
  font-weight: 600;
  font-size: 17px;
  letter-spacing: -0.015em;
}

.close {
  background: transparent;
  border: none;
  padding: 6px;
  border-radius: 4px;
  color: var(--text-dim);
  cursor: pointer;
}
.close:hover { background: var(--surface); }

.body {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
  font-size: 13px;
  line-height: 1.55;
  color: var(--text-dim);
}

footer {
  padding: 14px 24px;
  border-top: 1px solid var(--border);
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  background: var(--surface);
}
</style>
