<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue'

export interface KsDialogProps {
  visible: boolean
  title: string
  size?: 'sm' | 'md' | 'lg' | 'xl'
  closable?: boolean
  closeOnEscape?: boolean
  closeOnBackdrop?: boolean
  showHeader?: boolean
  showFooter?: boolean
}

const props = withDefaults(defineProps<KsDialogProps>(), {
  size: 'md',
  closable: true,
  closeOnEscape: true,
  closeOnBackdrop: true,
  showHeader: true,
  showFooter: true,
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
  open: []
  close: []
}>()

const dialogRef = ref<HTMLDivElement>()
const firstFocusableElement = ref<HTMLElement>()
const lastFocusableElement = ref<HTMLElement>()

const sizeClass = computed(() => {
  const sizes = {
    sm: 'max-w-96',
    md: 'max-w-2xl',
    lg: 'max-w-4xl',
    xl: 'max-w-6xl',
  }
  return sizes[props.size]
})

const dialogClass = computed(() => [
  'ks-dialog',
  `ks-dialog--${props.size}`,
  {
    'ks-dialog--visible': props.visible,
  },
])

const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && props.closeOnEscape) {
    event.preventDefault()
    handleClose()
  }

  if (event.key === 'Tab') {
    manageFocusTrap(event)
  }
}

const manageFocusTrap = (event: KeyboardEvent) => {
  if (!dialogRef.value) return

  const focusableElements = dialogRef.value.querySelectorAll(
    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
  )

  if (focusableElements.length === 0) return

  firstFocusableElement.value = focusableElements[0] as HTMLElement
  lastFocusableElement.value = focusableElements[focusableElements.length - 1] as HTMLElement

  if (event.shiftKey) {
    if (document.activeElement === firstFocusableElement.value) {
      event.preventDefault()
      lastFocusableElement.value?.focus()
    }
  } else {
    if (document.activeElement === lastFocusableElement.value) {
      event.preventDefault()
      firstFocusableElement.value?.focus()
    }
  }
}

const handleBackdropClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget && props.closeOnBackdrop) {
    handleClose()
  }
}

watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      document.body.style.overflow = 'hidden'
      emit('open')
      await nextTick()
      const focusElement = dialogRef.value?.querySelector('button, input, [tabindex="0"]') as HTMLElement
      focusElement?.focus()
    } else {
      document.body.style.overflow = ''
    }
  }
)
</script>

<template>
  <!-- Backdrop -->
  <Teleport to="body">
    <div
      v-if="visible"
      class="ks-dialog__backdrop"
      :aria-hidden="!visible"
      @click="handleBackdropClick"
    />
  </Teleport>

  <!-- Dialog -->
  <Teleport to="body">
    <div
      v-if="visible"
      ref="dialogRef"
      :class="dialogClass"
      role="dialog"
      aria-modal="true"
      :aria-labelledby="title ? 'dialog-title' : undefined"
      @keydown="handleKeydown"
    >
      <!-- Header -->
      <div v-if="showHeader" class="ks-dialog__header">
        <h2 id="dialog-title" class="ks-dialog__title">{{ title }}</h2>
        <button
          v-if="closable"
          type="button"
          class="ks-dialog__close"
          aria-label="Close dialog"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <!-- Content -->
      <div class="ks-dialog__content">
        <slot />
      </div>

      <!-- Footer -->
      <div v-if="showFooter && $slots.footer" class="ks-dialog__footer">
        <slot name="footer" />
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
/* Backdrop */
.ks-dialog__backdrop {
  position: fixed;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  animation: fadeIn var(--transition-normal);
  z-index: 999;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* Dialog container */
.ks-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  background-color: var(--color-background-primary);
  border-radius: var(--border-radius-lg);
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  z-index: 1000;
  animation: slideUp var(--transition-normal);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translate(-50%, -45%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

/* Size variants */
.ks-dialog--sm {
  max-width: 400px;
}

.ks-dialog--md {
  max-width: 600px;
}

.ks-dialog--lg {
  max-width: 900px;
}

.ks-dialog--xl {
  max-width: 1200px;
}

/* Header */
.ks-dialog__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--spacing-4);
  padding: var(--spacing-4);
  border-bottom: 1px solid var(--color-border-primary);
  flex-shrink: 0;
}

.ks-dialog__title {
  margin: 0;
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

/* Close button */
.ks-dialog__close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  border-radius: var(--border-radius-sm);
  transition: all var(--transition-normal);
  font-size: 1.25rem;
  line-height: 1;
}

.ks-dialog__close:hover {
  background-color: var(--color-background-secondary);
  color: var(--color-text-primary);
}

.ks-dialog__close:focus-visible {
  outline: 3px solid var(--color-primary-500);
  outline-offset: 2px;
}

/* Content */
.ks-dialog__content {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-4);
}

/* Scrollbar styling for content */
.ks-dialog__content::-webkit-scrollbar {
  width: 8px;
}

.ks-dialog__content::-webkit-scrollbar-track {
  background: var(--color-background-secondary);
}

.ks-dialog__content::-webkit-scrollbar-thumb {
  background: var(--color-border-primary);
  border-radius: 4px;
}

.ks-dialog__content::-webkit-scrollbar-thumb:hover {
  background: var(--color-border-secondary);
}

/* Footer */
.ks-dialog__footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-3);
  padding: var(--spacing-4);
  border-top: 1px solid var(--color-border-primary);
  flex-shrink: 0;
}

/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
  .ks-dialog,
  .ks-dialog__backdrop {
    animation: none;
  }
}

/* Mobile responsiveness */
@media (max-width: 640px) {
  .ks-dialog {
    width: 95%;
    max-height: 95vh;
    max-width: unset;
  }

  .ks-dialog__header {
    padding: var(--spacing-3);
  }

  .ks-dialog__content {
    padding: var(--spacing-3);
  }

  .ks-dialog__footer {
    padding: var(--spacing-3);
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
