<template>
  <section class="swiper--banner--wrapper2" :data-type="type" :data-fit="fit">
    <div class="swiper--banner--container">
      <div class="type--connection lincoln" :class="type" v-if="type == 'exterior'">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="30"
          height="30"
          viewBox="0 0 30 30"
          fill="none"
        >
          <path
            d="M15.1354 5H20.9482C21.5223 5 22.034 5.35992 22.2251 5.89813L25.1563 12.8077M25.1563 12.8077C26.1042 12.9423 28 13.6962 28 15.6346V16.8462M25.1563 12.8077H15.1354M25.1563 12.8077L27.7292 10.9231M28 16.8462V20.3462M28 16.8462L23.3958 18.5962M28 20.3462V23.8462C27.9097 24.5641 27.3229 26 25.6979 26C23.6674 26 23.396 25.3274 22.0431 22.503M28 20.3462C26.8663 21.4731 24.5199 22.1343 22.0431 22.503M22.0431 22.503C22.0426 22.502 22.0421 22.501 22.0417 22.5M22.0431 22.503C19.5496 22.8742 16.924 22.9489 15.2708 22.9038H14.7292C13.076 22.9489 10.4504 22.8742 7.9569 22.503M19.3333 22.5V19C19.3333 18.7026 19.0908 18.4615 18.7917 18.4615H11.2083C10.9092 18.4615 10.6667 18.7026 10.6667 19V22.5M14.8646 5H9.05184C8.4777 5 7.96596 5.35992 7.77488 5.89813L4.84375 12.8077M4.84375 12.8077C3.89583 12.9423 2 13.6962 2 15.6346V16.8462M4.84375 12.8077H14.8646M4.84375 12.8077L2.27083 10.9231M2 16.8462V20.3462M2 16.8462L6.60417 18.5962M2 20.3462V23.8462C2.09028 24.5641 2.67708 26 4.30208 26C6.33261 26 6.60398 25.3274 7.9569 22.503M2 20.3462C3.13367 21.4731 5.48012 22.1343 7.9569 22.503M7.9569 22.503C7.95738 22.502 7.95785 22.501 7.95833 22.5"
            stroke="white"
            stroke-width="2"
            stroke-linecap="round"
          /></svg
        >{{ type }}
      </div>
      <div class="type--connection lincoln" :class="type" v-else-if="type == 'interior'">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="30"
          height="30"
          viewBox="0 0 30 30"
          fill="none"
        >
          <path
            d="M2.30762 22.3072H13.8931M20.7409 22.3072H26.6922C27.2445 22.3072 27.6922 21.8595 27.6922 21.3072V18.0765M2.30762 3.8457C2.78804 3.8457 4.52124 3.8457 7.61071 3.8457C11.4725 3.8457 13.8931 6.92263 16.8791 9.61493C19.2679 11.7688 21.2214 12.3072 21.8995 12.3072C23.4442 12.3072 25.9288 12.5214 27.0908 14.9995M2.30762 6.92263H7.61071C8.12562 6.92263 9.46439 7.1534 10.7002 8.07647C11.7257 8.84247 13.8858 10.8974 15.3269 12.3072M2.30762 19.6149C4.84768 19.6149 10.1595 19.6149 11.0864 19.6149C12.05 19.6149 12.2121 19.0828 12.6838 18.4611M6.45216 13.8457L7.8038 11.9226M9.15544 9.99955L7.8038 11.9226M7.8038 11.9226L9.92781 13.4611M9.92781 13.4611C10.1853 13.0765 10.9319 12.3072 11.8587 12.3072C12.7856 12.3072 14.557 12.3072 15.3269 12.3072M9.92781 13.4611C9.30991 14.3842 9.67035 15.3842 9.92781 15.7688L12.6838 18.4611M15.3269 12.3072C15.6224 12.5963 15.8877 12.8583 16.1067 13.0765C16.3642 13.3329 16.8791 13.9995 16.8791 14.6149C16.8791 15.3842 16.8791 16.2288 15.7206 16.538C14.562 16.8472 13.7896 17.3072 13.0173 18.0765C12.8873 18.2059 12.7792 18.3353 12.6838 18.4611M27.6922 18.0765C27.6922 16.8049 27.464 15.7955 27.0908 14.9995M27.6922 18.0765H24.6345C23.124 18.0765 21.8995 16.852 21.8995 15.3414C21.8995 15.1526 22.0526 14.9995 22.2414 14.9995H27.0908"
            stroke="white"
            stroke-width="2"
            stroke-linecap="round"
          />
          <path
            d="M17.2653 20.2305C18.6364 20.2305 19.7408 21.3367 19.7408 22.6924C19.7406 24.0479 18.6362 25.1533 17.2653 25.1533C15.8943 25.1533 14.7899 24.0478 14.7897 22.6924C14.7897 21.3368 15.8942 20.2305 17.2653 20.2305Z"
            stroke="white"
            stroke-width="2"
            stroke-linecap="round"
          /></svg
        >{{ type }}
      </div>

      <!-- Pagination with Progress and Fractions -->
      <div class="swiper--pagination--wrapper">
        <div class="swiper-pagination" ref="paginationRef"></div>
        <div class="swiper--progressbar" ref="progressRef">
          <div class="swiper--progressbar-fill" :style="{ width: progressWidth }"></div>
        </div>
        <div class="swiper--fraction" ref="fractionRef">
          <span class="current">{{ currentSlide + 1 }}</span>
          <span class="separator">/</span>
          <span class="total">{{ slides.length }}</span>
        </div>
      </div>

      <!-- 70% 영역: 단일 배너 -->
      <div class="swiper--banner--section">
        <div class="swiper--container" ref="swiperContainer">
          <div class="swiper-wrapper">
            <div v-for="(slide, index) in slides" :key="index" class="swiper-slide">
              <div class="slide--image" v-if="slide.image">
                <img
                  :src="slide.image"
                  :alt="slide.alt || 'Banner Image'"
                  loading="lazy"
                />

                <!-- 확대 버튼 -->
                <button class="zoom--btn" @click="openLightbox(index)" aria-label="확대">
                  Image Details
                  <i>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="12"
                      height="12"
                      viewBox="0 0 12 12"
                      fill="none"
                    >
                      <path
                        d="M2.5 6H9.5"
                        stroke="white"
                        stroke-width="1.5"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                      <path
                        d="M6 2.5L9.5 6L6 9.5"
                        stroke="white"
                        stroke-width="1.5"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                    </svg>
                  </i>
                </button>
              </div>
              <div class="slide--image" v-if="slide.video">
                <video
                  autoplay
                  muted
                  loop
                  playsinline
                  :poster="slide.video"
                  controlslist="nodownload noplaybackrate"
                  disablepictureinpicture
                  preload="metadata"
                >
                  <source media="(min-width:320px)" :src="slide.video" type="video/mp4" />
                </video>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Lightbox -->
    <Transition name="lightbox-fade">
      <div v-if="isLightboxOpen" class="lightbox--overlay" @click.self="closeLightbox">
        <button class="lightbox--close" @click="closeLightbox" aria-label="닫기">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="32"
            height="32"
            viewBox="0 0 32 32"
            fill="none"
          >
            <path
              d="M24 8L8 24M8 8L24 24"
              stroke="white"
              stroke-width="2"
              stroke-linecap="round"
            />
          </svg>
        </button>

        <button class="lightbox--prev" @click="prevLightboxSlide" aria-label="이전">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="40"
            height="40"
            viewBox="0 0 40 40"
            fill="none"
          >
            <path
              d="M25 30L15 20L25 10"
              stroke="white"
              stroke-width="3"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </button>

        <div class="lightbox--content">
          <div class="lightbox--swiper" ref="lightboxSwiperContainer">
            <div class="swiper-wrapper">
              <div
                v-for="(slide, index) in slides"
                :key="`lightbox-${index}`"
                class="swiper-slide"
              >
                <img
                  v-if="slide.image"
                  :src="slide.image"
                  :alt="slide.alt || 'Banner Image'"
                />
              </div>
            </div>
          </div>

          <!-- Lightbox Pagination Info -->
          <div class="lightbox--info">
            <span class="lightbox--fraction">
              {{ lightboxCurrentSlide + 1 }} / {{ slides.length }}
            </span>
          </div>
        </div>

        <button class="lightbox--next" @click="nextLightboxSlide" aria-label="다음">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="40"
            height="40"
            viewBox="0 0 40 40"
            fill="none"
          >
            <path
              d="M15 30L25 20L15 10"
              stroke="white"
              stroke-width="3"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </button>
      </div>
    </Transition>
  </section>
</template>

<script setup>
  import { Swiper } from "swiper";
  import { Navigation, Pagination, Autoplay, EffectFade } from "swiper/modules";
  import "swiper/css";
  import "swiper/css/navigation";
  import "swiper/css/pagination";
  import "swiper/css/effect-fade";

  const { getMediaUrl } = useImage();

  // Props 정의
  const props = defineProps({
    slides: {
      type: Array,
      default: () => [],
    },
    height: {
      type: String,
      default: "60%",
    },
    title: {
      type: String,
      default: "",
    },
    subtitle: {
      type: String,
      default: "",
    },
    smalldesc: {
      type: String,
      default: "",
    },
    cautiondesc: {
      type: String,
      default: "",
    },
    morelink: {
      type: String,
      default: "",
    },
    morelinktitle: {
      type: String,
      default: "자세히 보기",
    },
    morelinktarget: {
      type: String,
      default: "_self",
    },
    notice: {
      type: String,
      default: "",
    },
    autoplay: {
      type: [Boolean, Object],
      default: () => ({ delay: 5000 }),
    },
    loop: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: "", // 'horz' , 'vert'
      validator: (value) => ["exterior", "interior"].includes(value),
    },
    fit: {
      type: String,
      default: "cover",
      validator: (value) => ["cover", "contain"].includes(value),
    },
  });

  // Refs
  const swiperContainer = ref(null);
  const lightboxSwiperContainer = ref(null);
  const paginationRef = ref(null);
  const progressRef = ref(null);
  const fractionRef = ref(null);
  const prevRef = ref(null);
  const nextRef = ref(null);
  const textSlider = ref(null);
  let swiperInstance = null;
  let lightboxSwiperInstance = null;

  // 현재 슬라이드 인덱스
  const currentSlide = ref(0);
  const lightboxCurrentSlide = ref(0);
  const progressWidth = ref("0%");

  // 라이트박스 상태
  const isLightboxOpen = ref(false);

  // 슬라이드별 텍스트 반환 함수들
  const getSlideTitle = (index) => {
    return props.slides[index]?.title || props.title;
  };

  const getSlideSubtitle = (index) => {
    return props.slides[index]?.subtitle || props.subtitle;
  };

  const getSlideSmalldesc = (index) => {
    return props.slides[index]?.smalldesc || props.smalldesc;
  };

  const getSlideMorelink = (index) => {
    return props.slides[index]?.morelink || props.morelink;
  };

  const getSlideMorelinktitle = (index) => {
    return props.slides[index]?.morelinktitle || props.morelinktitle;
  };

  const getSlideTarget = (index) => {
    return props.slides[index]?.morelinktarget || props.morelinktarget;
  };

  const getSlideCautiondesc = (index) => {
    return props.slides[index]?.cautiondesc || props.cautiondesc;
  };

  // Progress bar 업데이트 함수
  const updateProgress = () => {
    const progress = ((currentSlide.value + 1) / props.slides.length) * 100;
    progressWidth.value = `${progress}%`;
  };

  // 라이트박스 열기
  const openLightbox = (index) => {
    isLightboxOpen.value = true;
    document.body.style.overflow = "hidden";
    document.querySelector(".g-layout").classList.add("active");

    nextTick(() => {
      initLightboxSwiper(index);
    });
  };

  // 라이트박스 닫기
  const closeLightbox = () => {
    isLightboxOpen.value = false;
    document.body.style.overflow = "";
    document.querySelector(".g-layout").classList.remove("active");

    if (lightboxSwiperInstance) {
      lightboxSwiperInstance.destroy(true, true);
      lightboxSwiperInstance = null;
    }
  };

  // 라이트박스 Swiper 초기화
  const initLightboxSwiper = (initialIndex = 0) => {
    if (!lightboxSwiperContainer.value) return;

    lightboxSwiperInstance = new Swiper(lightboxSwiperContainer.value, {
      modules: [Navigation],
      slidesPerView: 1,
      spaceBetween: 0,
      initialSlide: initialIndex,
      loop: false,
      keyboard: {
        enabled: true,
      },
      on: {
        slideChange: function () {
          lightboxCurrentSlide.value = this.activeIndex;

          // 메인 스와이퍼도 동일한 인덱스로 이동
          if (swiperInstance && !swiperInstance.destroyed) {
            swiperInstance.slideToLoop(this.activeIndex, 0);
          }
        },
        init: function () {
          lightboxCurrentSlide.value = this.activeIndex;
        },
      },
    });
  };

  // 라이트박스 이전 슬라이드
  const prevLightboxSlide = () => {
    if (lightboxSwiperInstance) {
      lightboxSwiperInstance.slidePrev();
    }
  };

  // 라이트박스 다음 슬라이드
  const nextLightboxSlide = () => {
    if (lightboxSwiperInstance) {
      lightboxSwiperInstance.slideNext();
    }
  };

  // ESC 키로 라이트박스 닫기
  const handleKeydown = (e) => {
    if (e.key === "Escape" && isLightboxOpen.value) {
      closeLightbox();
    }
  };

  onMounted(() => {
    // 키보드 이벤트 리스너 추가
    window.addEventListener("keydown", handleKeydown);
    // Swiper 인스턴스 초기화
    swiperInstance = new Swiper(swiperContainer.value, {
      modules: [Navigation, Pagination, Autoplay],
      slidesPerView: 1,
      spaceBetween: 0,
      loop: props.loop,
      autoplay: props.autoplay
        ? {
            delay:
              typeof props.autoplay === "object" ? props.autoplay.delay || 5000 : 5000,
            disableOnInteraction: false,
            pauseOnMouseEnter: true,
          }
        : false,
      navigation: {
        nextEl: nextRef.value,
        prevEl: prevRef.value,
      },
      pagination: {
        el: paginationRef.value,
        clickable: true,
        type: "bullets",
        // renderBullet: function (index, className) {
        //   return '<span class="' + className + '">' + (index + 1) + "</span>";
        // },
      },
      effect: "fade",
      fadeEffect: {
        crossFade: true,
      },
      speed: 800,
      // 슬라이드 변경 이벤트
      on: {
        slideChange: function () {
          if (this && this.realIndex !== undefined) {
            currentSlide.value = this.realIndex;
          }
          // Progress bar 업데이트
          updateProgress();

          // 모든 비디오 일시정지
          const allVideos = this.el.querySelectorAll("video");
          allVideos.forEach((video) => {
            video.pause();
            video.currentTime = 0;
          });
          // 현재 슬라이드의 비디오 재생
          const currentSlideEl = this.slides[this.activeIndex];
          if (currentSlideEl) {
            const video = currentSlideEl.querySelector("video");
            if (video) {
              video.play().catch((err) => console.log("Video play failed:", err));
            }
          }
        },
        init: function () {
          if (this && this.realIndex !== undefined) {
            currentSlide.value = this.realIndex;
          }

          // 초기 Progress bar 업데이트 - nextTick으로 지연
          nextTick(() => {
            updateProgress();
          });

          // 초기 슬라이드의 비디오 재생
          const currentSlideEl = this.slides[this.activeIndex];
          if (currentSlideEl) {
            const video = currentSlideEl.querySelector("video");
            if (video) {
              video.play().catch((err) => console.log("Video play failed:", err));
            }
          }
        },
      },
    });
  });

  onUnmounted(() => {
    // 키보드 이벤트 리스너 제거
    window.removeEventListener("keydown", handleKeydown);

    // Swiper 인스턴스 정리
    if (swiperInstance) {
      swiperInstance.destroy(true, true);
    }
    if (lightboxSwiperInstance) {
      lightboxSwiperInstance.destroy(true, true);
    }

    // body overflow 복원
    document.body.style.overflow = "";
  });
</script>
