<script setup lang="ts">
import { Splide } from '@splidejs/vue-splide'
import { useSplideArrow } from '#layers/composables/useSplideArrow'
import { getPaginationClass } from '#layers/utils/styleUtil'
import type { Splide as SplideType, ResponsiveOptions } from '@splidejs/splide'
import type { PageDataResourceGroups } from '#layers/types/api/pageData'

interface Props {
  autoplay?: boolean
  arrows?: boolean
  pagination?: boolean
  paginationData?: PageDataResourceGroups
}

const props = withDefaults(defineProps<Props>(), {
  autoplay: false,
  arrows: true,
  pagination: true,
})

const emit = defineEmits(['mounted', 'move', 'arrowClick'])

const splideRef = ref()
// Splide 화살표 로직을 위한 composable 사용
const { addArrowClickListeners } = useSplideArrow()

const options = computed((): ResponsiveOptions => {
  return {
    type: 'fade',
    rewind: true,
    perPage: 1,
    perMove: 1,
    speed: 500,
    updateOnMove: true,
    autoplay: props.autoplay,
    pauseOnHover: false,
    pauseOnFocus: false,
    arrows: props.arrows,
    pagination: props.pagination,
    classes: {
      arrows: 'splide-arrows type-full',
      arrow: 'splide-arrow',
      prev: 'arrow-prev',
      next: 'arrow-next',
      pagination: 'splide-pagination-bullets type-full',
      page: 'splide-pagination-bullet',
    },
  }
})

defineExpose({
  splide: computed(() => splideRef.value?.splide),
})

const handleSplideMounted = (splide: SplideType) => {
  emit('mounted', splide)

  // 화살표 버튼 클릭 이벤트 리스너 추가
  nextTick(() => {
    addArrowClickListeners(splide, (direction, targetIndex) => {
      emit('arrowClick', direction, targetIndex)
    })
  })
}

const handleMove = (
  splide: SplideType,
  newIndex: number,
  oldIndex: number,
  destIndex: number
) => {
  emit('move', splide, newIndex, oldIndex, destIndex)
}
</script>

<template>
  <Splide
    ref="splideRef"
    :options="options"
    class="h-full"
    :style="getPaginationClass(props.paginationData)"
    @splide:mounted="handleSplideMounted"
    @splide:move="handleMove"
  >
    <slot />
  </Splide>
</template>

<style scoped>
.splide:deep(.splide__track) {
  @apply h-full;
}
</style>
