<script setup>
import { useId, onMounted, ref } from 'vue'

defineProps({
  title: { type: String, default: '' },
  wide: { type: Boolean, default: false },
})

const emit = defineEmits(['close'])

const uid = useId()
const cardRef = ref(null)

onMounted(() => {
  cardRef.value?.focus()
})
</script>

<template>
  <Teleport to="body">
    <div
      class="modal-overlay"
      data-testid="modal-overlay"
      @click.self="emit('close')"
      @keydown.esc="emit('close')"
    >
      <div
        ref="cardRef"
        class="modal-card"
        :class="{ 'modal-wide': wide }"
        data-testid="modal-card"
        role="dialog"
        aria-modal="true"
        :aria-labelledby="title ? `modal-title-${uid}` : undefined"
        tabindex="-1"
      >
        <div v-if="title" class="modal-header">
          <h3 :id="`modal-title-${uid}`" data-testid="modal-title">{{ title }}</h3>
          <button
            class="modal-close-btn"
            data-testid="modal-close"
            :aria-label="$t('modal.close')"
            @click="emit('close')"
          >
            <i class="bi bi-x-lg"></i>
          </button>
        </div>
        <div class="modal-body">
          <slot />
        </div>
      </div>
    </div>
  </Teleport>
</template>

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

.modal-card {
  background: var(--bg-color1);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  width: 100%;
  max-width: 480px;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  outline: none;
}

.modal-wide {
  max-width: 600px;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
  font-size: 17px;
  font-weight: 600;
  margin: 0;
}

.modal-close-btn {
  background: none;
  border: none;
  color: var(--front-color1);
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  line-height: 1;
  opacity: 0.7;
}

.modal-close-btn:hover {
  opacity: 1;
}

.modal-body {
  padding: 20px;
}
</style>
