<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--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="popup.link_target || '_blank'"
            :rel="popup.link_target === '_self' ? '' : 'noopener noreferrer'"
          >
            <img :src="popup.image_url" :alt="popup.title" />
          </a>
          <img v-else :src="popup.image_url" :alt="popup.title" />
        </div>
      </div>

      <!-- 하단 고정 푸터 -->
      <div class="popup--footer" :class="{ solo: popup.cookie_setting == 'none' }">
        <label class="popup--checkbox" v-if="popup.cookie_setting !== 'none'">
          <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>
        <button
          class="popup--close"
          @click.stop="closePopup(popup.id)"
          @mousedown.stop
          @touchstart.stop
          @touchend.stop="closePopup(popup.id)"
          aria-label="팝업 닫기"
        >
          닫기
        </button>
      </div>
    </div>
  </div>
</template>

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

  const props = defineProps({
    site: {
      type: String,
      required: true,
      validator: (value) => ["ford", "lincoln"].includes(value),
    },
  });

  const config = useRuntimeConfig();
  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 apiUrl = `${config.public.apiBase}/api/popup/active?site=${props.site}`;
      const response = await axios.get(apiUrl);

      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",
        }));

        // 1차 필터: 기간(시작/종료 시각 포함) 재검증 — 백엔드 버그/캐시 대비 안전장치
        const now = new Date();
        const inPeriod = popups.filter((popup) => {
          if (!popup.start_date || !popup.end_date) return false;
          const start = new Date(
            `${popup.start_date}T${popup.start_time || "00:00:00"}`
          );
          const end = new Date(
            `${popup.end_date}T${popup.end_time || "23:59:59"}`
          );
          const active = now >= start && now <= end;
          if (!active) {
            console.log(
              `[Popup] ID ${popup.id} "${popup.title}" - 기간 외 노출 차단`,
              { now, start, end }
            );
          }
          return active;
        });

        // 2차 필터: 쿠키로 숨긴 팝업 제외
        visiblePopups.value = inPeriod.filter((popup) => {
          const cookieName = `popup_hide_${popup.id}`;
          const isHidden = getCookie(cookieName);
          console.log(
            `[Popup] ID ${popup.id} "${popup.title}" - Hidden by cookie:`,
            !!isHidden
          );
          return !isHidden;
        });

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

  // 드래그 시작
  const startDrag = (event, index) => {
    // 1024px 이하에서는 드래그 비활성화
    if (window.innerWidth <= 1024) return;

    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);
  };

  // 팝업 닫기 (모바일에서 연속 닫힘 방지)
  let lastCloseTime = 0;
  const closePopup = (popupId) => {
    const now = Date.now();
    // 300ms 이내 연속 닫기 시도 무시 (터치 이벤트 중복 방지)
    if (now - lastCloseTime < 300) return;
    lastCloseTime = now;

    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(() => {
    console.log("[Popup] Component mounted, starting to fetch popups...");
    fetchPopups();
  });

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

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

  .popup--wrapper {
    position: absolute;
    pointer-events: auto;
    background: #fff;
    /* 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-width: calc(100% - 40px);
    max-height: 90vh;
  }
  @media (max-width: 1024px) {
    .popup--wrapper {
      left: 20px !important;
    }
  }

  .lincoln .popup--header {
    background-color: #db784d;
  }

  .popup--header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background-color: #076fed;
    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 {
    height: 28px;
    background: rgba(255, 255, 255, 0.1);
    color: #000;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    flex-shrink: 0;
    margin-left: 10px;
    padding: 0 20px;
  }

  .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: #fff;
    min-height: 0;
  }

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

  .popup--html {
    background: #fff;
  }

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

  .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;
    border-top: 1px solid #333;
    flex-shrink: 0;
    color: #000;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .popup--footer.solo {
    justify-content: flex-end;
  }

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

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

  .lincoln .popup--checkbox input[type="checkbox"] {
    accent-color: #db784d;
  }

  .popup--checkbox span {
    color: #444;
  }

  @media (max-width: 768px) {
    .popup--wrapper {
      left: 50% !important;
      transform: translateX(-50%);
      max-width: calc(100% - 40px);
    }
  }
</style>
