<template>
  <div v-if="visiblePopups.length > 0" class="popup--container">
    <div
      v-for="(popup, index) in visiblePopups"
      :key="popup.id"
      class="popup--wrapper"
      :style="{
        top: popupPositions[index]?.top || popup.position_top + 'px',
        left: popupPositions[index]?.left || popup.position_left + 'px',
        width: popup.width + 'px',
        height: popup.type === 'image' ? 'auto' : popup.height + 'px'
      }"
    >
      <!-- 드래그 헤더 -->
      <div
        class="popup--header"
        @mousedown="startDrag($event, index)"
        @touchstart="startDrag($event, index)"
      >
        <span class="popup--title">{{ popup.title }}</span>
        <button
          class="popup--close"
          @click="closePopup(popup.id)"
          aria-label="팝업 닫기"
        >
          ✕
        </button>
      </div>

      <!-- 스크롤 가능한 콘텐츠 영역 -->
      <div class="popup--content">
        <!-- HTML 타입 팝업 -->
        <div v-if="popup.type === 'html'" class="popup--html" v-html="popup.content"></div>

        <!-- 이미지 타입 팝업 -->
        <div v-else-if="popup.type === 'image'" class="popup--image">
          <a
            v-if="popup.link_url"
            :href="popup.link_url"
            target="_blank"
            rel="noopener noreferrer"
          >
            <img :src="getImageUrl(popup.image_url)" :alt="popup.title" />
          </a>
          <img v-else :src="getImageUrl(popup.image_url)" :alt="popup.title" />
        </div>
      </div>

      <!-- 하단 고정 푸터 -->
      <div v-if="popup.cookie_setting !== 'none'" class="popup--footer">
        <label class="popup--checkbox">
          <input
            type="checkbox"
            @change="(e) => handleDontShowToday(e, popup.id, popup.cookie_setting)"
          />
          <span v-if="popup.cookie_setting === 'today'">오늘 하루 창 띄우지 않음</span>
          <span v-else-if="popup.cookie_setting === 'forever'">다시는 창을 띄우지 않음</span>
        </label>
      </div>
    </div>
  </div>
</template>

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

const API_BASE_URL = 'https://gojinaudi.mycafe24.com/api'
const visiblePopups = ref([])
const popupPositions = ref([])
const { getImageUrl } = useImage()

// 드래그 상태
const dragState = ref({
  isDragging: false,
  currentIndex: null,
  startX: 0,
  startY: 0,
  initialLeft: 0,
  initialTop: 0
})

// 쿠키 가져오기
const getCookie = (name) => {
  if (typeof document === 'undefined') return null
  const value = `; ${document.cookie}`
  const parts = value.split(`; ${name}=`)
  if (parts.length === 2) return parts.pop().split(';').shift()
  return null
}

// 쿠키 설정
const setCookie = (name, value, days) => {
  if (typeof document === 'undefined') return
  const date = new Date()
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
  const expires = `expires=${date.toUTCString()}`
  document.cookie = `${name}=${value};${expires};path=/`
}

// 팝업 데이터 가져오기
const fetchPopups = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/popup/active`)
    if (response.data.success && response.data.data) {
      // 쿠키 설정 필드 정규화 (cookie_setting 또는 cookie_type 지원)
      const popups = response.data.data.map(popup => ({
        ...popup,
        cookie_setting: popup.cookie_setting || popup.cookie_type || 'none'
      }))

      // 쿠키로 숨긴 팝업 필터링
      visiblePopups.value = popups.filter((popup) => {
        const cookieName = `popup_hide_${popup.id}`
        return !getCookie(cookieName)
      })

      // 초기 위치 설정
      popupPositions.value = visiblePopups.value.map(() => ({}))
    }
  } catch (error) {
    console.error('[Popup] Failed to fetch popups:', error)
  }
}

// 드래그 시작
const startDrag = (event, index) => {
  event.preventDefault()

  const e = event.touches ? event.touches[0] : event
  const popup = visiblePopups.value[index]

  dragState.value = {
    isDragging: true,
    currentIndex: index,
    startX: e.clientX,
    startY: e.clientY,
    initialLeft: parseInt(popupPositions.value[index]?.left || popup.position_left),
    initialTop: parseInt(popupPositions.value[index]?.top || popup.position_top)
  }

  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchmove', onDrag)
  document.addEventListener('touchend', stopDrag)
}

// 드래그 중
const onDrag = (event) => {
  if (!dragState.value.isDragging) return

  const e = event.touches ? event.touches[0] : event
  const deltaX = e.clientX - dragState.value.startX
  const deltaY = e.clientY - dragState.value.startY

  const newLeft = dragState.value.initialLeft + deltaX
  const newTop = dragState.value.initialTop + deltaY

  popupPositions.value[dragState.value.currentIndex] = {
    left: newLeft + 'px',
    top: newTop + 'px'
  }
}

// 드래그 종료
const stopDrag = () => {
  dragState.value.isDragging = false
  dragState.value.currentIndex = null

  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchmove', onDrag)
  document.removeEventListener('touchend', stopDrag)
}

// 팝업 닫기
const closePopup = (popupId) => {
  const index = visiblePopups.value.findIndex(p => p.id === popupId)
  if (index !== -1) {
    visiblePopups.value.splice(index, 1)
    popupPositions.value.splice(index, 1)
  }
}

// 오늘 하루 보지 않기
const handleDontShowToday = (event, popupId, cookieSetting) => {
  // 체크박스가 체크된 경우에만 실행
  if (!event.target.checked) return

  let days = 1 // 기본 1일
  if (cookieSetting === 'forever') days = 365 * 10 // 10년 (사실상 영구)
  else if (cookieSetting === 'today') days = 1

  const cookieName = `popup_hide_${popupId}`
  setCookie(cookieName, 'true', days)
  closePopup(popupId)
}

onMounted(() => {
  fetchPopups()
})

onUnmounted(() => {
  stopDrag()
})
</script>

<style scoped>
.popup--container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9999;
}

.popup--wrapper {
  position: absolute;
  pointer-events: auto;
  background: #1a1a1a;
  border: 1px solid #333;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.popup--header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(to bottom, #2a2a2a, #1f1f1f);
  border-bottom: 1px solid #333;
  cursor: move;
  user-select: none;
}

.popup--header:active {
  cursor: grabbing;
}

.popup--title {
  font-size: 14px;
  font-weight: 600;
  color: #ffffff;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.popup--close {
  width: 28px;
  height: 28px;
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  flex-shrink: 0;
  margin-left: 10px;
}

.popup--close:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
}

.popup--content {
  flex: 1;
  overflow: auto;
  background: #1a1a1a;
  min-height: 0;
}

.popup--html,
.popup--image {
  padding: 20px;
  color: #ffffff;
}

.popup--html {
  background: #1a1a1a;
}

.popup--html :deep(p),
.popup--html :deep(div),
.popup--html :deep(span) {
  color: #ffffff;
}

.popup--html :deep(a) {
  color: #4a9eff;
}

.popup--image {
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #0a0a0a;
}

.popup--image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.popup--footer {
  padding: 12px 20px;
  background: #222222;
  border-top: 1px solid #333;
  flex-shrink: 0;
}

.popup--checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
  color: #ffffff;
}

.popup--checkbox input[type='checkbox'] {
  cursor: pointer;
  accent-color: #4a9eff;
}

.popup--checkbox span {
  color: #e0e0e0;
}
</style>
