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

interface Props {
  autoplay?: boolean | string
  arrows?: boolean
  pagination?: boolean
  class?: string
}

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

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

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

const options = computed((): ResponsiveOptions => {
  return {
    type: 'fade',
    rewind: true,
    perPage: 1,
    perMove: 1,
    speed: 600,
    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)
  splide.refresh()

  // 화살표 버튼 클릭 이벤트 리스너 추가
  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)
}

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

<template>
  <Splide
    ref="splideRef"
    :options="options"
    class="h-full"
    @splide:mounted="handleSplideMounted"
    @splide:move="handleMove"
    @splide:moved="handleMoved"
  >
    <slot />
  </Splide>
</template>

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