<template>
  <ClientOnly>
    <Teleport to="body">
      <div
        class="modal--dim"
        :class="{ active: modelValue }"
        @click.self="handleBackdrop"
      >
        <div class="alert--wrap" :class="[{ center, active: modelValue }]">
          <div
            v-if="iconType"
            :class="['error--ico', `error--ico--${iconType}`]"
          >{{ iconText }}</div>

          <div v-if="title" class="modal--tit">
            <h2>{{ title }}</h2>
          </div>

          <div v-if="message" class="modal--cont">
            <p v-html="formattedMessage"></p>
          </div>

          <div class="modal--btn">
            <button
              v-if="type === 'confirm'"
              type="button"
              class="cancel"
              @click="handleCancel"
            >{{ cancelText }}</button>
            <button type="button" @click="handleConfirm">{{ confirmText }}</button>
          </div>
        </div>
      </div>
    </Teleport>
  </ClientOnly>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  // 'alert'(확인만) | 'confirm'(취소/확인)
  type: { type: String, default: 'alert' },
  // 'error' | 'success' | 'info' | null
  iconType: { type: String, default: null },
  title: { type: String, default: '' },
  message: { type: String, default: '' },
  confirmText: { type: String, default: '확인' },
  cancelText: { type: String, default: '취소' },
  center: { type: Boolean, default: true },
  // 백드롭 클릭으로 닫기 허용 여부
  closeOnBackdrop: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'confirm', 'cancel'])

const iconText = computed(() => {
  if (props.iconType === 'error') return '!'
  if (props.iconType === 'success') return '✓'
  if (props.iconType === 'info') return 'i'
  return ''
})

const formattedMessage = computed(() =>
  (props.message || '').replace(/\n/g, '<br />')
)

const close = () => emit('update:modelValue', false)

const handleConfirm = () => {
  emit('confirm')
  close()
}

const handleCancel = () => {
  emit('cancel')
  close()
}

const handleBackdrop = () => {
  if (props.closeOnBackdrop) close()
}
</script>
