<script setup lang="ts">
import { SplideSlide } from '@splidejs/vue-splide'
import {
  getComponentContainer,
  getComponentGroupAry,
  getComponentGroup,
  isTypeVideo,
} from '#layers/utils/dataUtil'
import { getMediaImgSrc, getMediaSrc } from '#layers/utils/youtubeUtil'
import type {
  PageDataTemplateComponents,
  PageDataTemplateComponentSet,
} from '#layers/types/api/pageData'

interface Props {
  components: PageDataTemplateComponents
  pageVerTmplSeq: number
}

const props = defineProps<Props>()

const { locale } = useI18n()
const { sendLog, useAnalyticsLogDataDirect } = useAnalytics()

const slideThumbnailRef = ref<any>(null)
const playingSlideIndex = ref<number | null>(null)

const backgroundData = computed(() =>
  getComponentGroup(props.components, 'background')
)
const mainTitleData = computed(() =>
  getComponentGroup(props.components, 'mainTitle')
)
const slideData = computed(() =>
  getComponentContainer(props.components, 'group_sets')
)
const paginationData = computed(() => {
  return getComponentGroupAry(props.components, 'pagination')
})

const getMediaComponent = (item: PageDataTemplateComponentSet) => {
  return getComponentGroup(item, 'media')
}

const getMediaImgSrcFromItem = (item: PageDataTemplateComponentSet) => {
  const mediaComponent = getMediaComponent(item)
  return mediaComponent ? getMediaImgSrc(mediaComponent) : ''
}

const getYouTubeEmbedUrlFromMedia = (item: PageDataTemplateComponentSet) => {
  const mediaComponent = getMediaComponent(item)
  if (!mediaComponent) return ''
  const mediaSrc = getMediaSrc(mediaComponent)
  return mediaSrc ? getYouTubeEmbedUrl(mediaSrc, true) : ''
}

const isPassVideo = (item: PageDataTemplateComponentSet, index: number) => {
  const mediaComponent = getMediaComponent(item)
  const isNotPlaying = index !== playingSlideIndex.value
  const isVideoType =
    mediaComponent && isTypeVideo(mediaComponent?.resource_type)

  return isVideoType && isNotPlaying
}

const handleVideoClick = (index: number) => {
  playingSlideIndex.value = index

  const group = getComponentGroup(props.components, 'videoPlay')
  const base = group?.tracking?.click_item || ''
  const next = base
    ? base.replace(/(^.*_)(\d+)$/, `$1${index}`) === base
      ? `${base}_${index}`
      : base.replace(/(^.*_)(\d+)$/, `$1${index}`)
    : `${index}`

  const sendingGroup = group
    ? { ...group, tracking: { ...group.tracking, click_item: next } }
    : group

  sendLog(
    locale.value,
    useAnalyticsLogDataDirect(
      (sendingGroup as any) || getComponentGroup(props.components, 'videoPlay'),
      props.pageVerTmplSeq
    )
  )
}

const stopVideo = () => {
  // 전환 시간 후 완전히 제거
  setTimeout(() => {
    playingSlideIndex.value = null
  }, 400)
}

const onArrowClick = (direction, targetIndex) => {
  const arrowGroupAry = getComponentGroupAry(props.components, 'arrow')
  const logTracking = arrowGroupAry?.[direction === 'prev' ? 0 : 1]
  sendLog(locale.value, useAnalyticsLogDataDirect(logTracking, 1))
}
</script>

<template>
  <section class="section-container min-h-[700px]">
    <WidgetsBackground v-if="backgroundData" :resources-data="backgroundData" />
    <div class="section-content">
      <WidgetsMainTitle
        v-if="mainTitleData"
        :resources-data="mainTitleData"
        class="title-md"
      />
      <BlocksSlideThumbnail
        ref="slideThumbnailRef"
        :slide-data="slideData"
        variant="media"
        :drag="false"
        class="mt-[24px] md:mt-[32px]"
        :pagination-data="paginationData"
        @move="stopVideo"
        @arrow-click="onArrowClick"
      >
        <SplideSlide
          v-for="(item, index) in slideData"
          :key="item.set_order || index"
          class="main-slide"
        >
          <img
            :src="getMediaImgSrcFromItem(item)"
            alt="main image"
            class="slide-image"
            :class="{
              'opacity-0': playingSlideIndex === index,
            }"
          />
          <AtomsButtonPlay
            v-if="isPassVideo(item, index)"
            class="btn-play"
            @click="handleVideoClick(index)"
          />
          <iframe
            v-if="playingSlideIndex === index"
            :src="getYouTubeEmbedUrlFromMedia(item)"
            class="video-iframe"
            frameborder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen
          />
        </SplideSlide>
      </BlocksSlideThumbnail>
    </div>
  </section>
</template>

<style scoped>
.thumbnail-carousel {
  @apply w-full md:max-w-[944px];
}
.thumbnail-carousel:deep(.main-splide) {
  @apply overflow-hidden rounded-lg border border-white/10 shadow-[0_4px_20px_0_rgba(0,0,0,0.5)];
}
.main-slide {
  @apply relative aspect-[16/9];
}
.slide-image {
  @apply transition-opacity duration-500 ease-in-out;
}
.btn-play {
  @apply absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2;
}
.video-iframe {
  @apply absolute top-0 left-0 w-full h-full object-cover;
}
</style>
