<script setup lang="ts">
import type { Swiper  as SwiperClass} from 'swiper';

interface ISwiperData {
  id: number,
  url: string,
}

interface ISwiperProps {
  list: ISwiperData[]
  reverseDirection?: boolean,
}

withDefaults(defineProps<ISwiperProps>(), {
  reverseDirection: () => false
})

let swiperInstance: SwiperClass;
let timer: null | NodeJS.Timeout = null;

const onSwiper = (swiper: SwiperClass) => {
  swiperInstance = swiper;
}

const listenerScreenSize = () => {
  swiperInstance.autoplay.stop();
  clearTimeout(Number(timer));
  timer = setTimeout(() => {
    swiperInstance.autoplay.start();
  }, 2000);
}

onMounted(() => {
  if (process.client) {
    window.addEventListener('resize', listenerScreenSize);
  }
})

onUnmounted(() => {
  if (process.client) {
    window.removeEventListener('resize', listenerScreenSize);
  }
})
</script>

<template>
  <Swiper 
    class="swiper-no-swiping"
    @swiper="onSwiper"
    :modules="[SwiperAutoplay]"
    :slides-per-view="1"
    :loop="true"
    :speed="2000"
    :observer="true"
    :observeParents="true"
    :resizeObserver="true"
    :autoplay="{
      delay: 3000,
      disableOnInteraction: false,
      reverseDirection,
    }"
  >
    <SwiperSlide v-for="slide in list" :key="slide.id" >
      <div class="swiper-item" :style="{ background: 'url(' + slide.url + ')', backgroundSize: 'cover' }"></div>
    </SwiperSlide>
  </Swiper>
</template>

<style scoped lang="scss">
.swiper, .swiper-item {
  height: 100%;
}
</style>