<template>
  <div class="kole-carousel">
    <div class="kole-carousel-track" :style="{ transform: `translateX(-${index * 100}%)` }">
      <div class="kole-carousel-slide" v-for="(s, i) in items" :key="i" :style="{ background: s.color }">{{ s.text }}</div>
    </div>
    <button class="kole-carousel-arrow prev" @click="go(index - 1)">‹</button>
    <button class="kole-carousel-arrow next" @click="go(index + 1)">›</button>
    <div class="kole-carousel-dots">
      <span class="kole-carousel-dot" v-for="(s, i) in items" :key="i"
            :class="{ 'is-active': i === index }" @click="go(i)"></span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
const props = defineProps({
  items: { type: Array, default: () => [] },
  autoplay: { type: Boolean, default: true },
  interval: { type: Number, default: 3000 }
});
const index = ref(0);
let timer = null;
function go(i) {
  const len = props.items.length || 1;
  index.value = (i + len) % len;
  restart();
}
function restart() {
  if (timer) clearInterval(timer);
  if (props.autoplay && props.items.length > 1) {
    timer = setInterval(() => go(index.value + 1), props.interval);
  }
}
onMounted(restart);
onBeforeUnmount(() => { if (timer) clearInterval(timer); });
</script>

<style src="./Carousel.css"></style>
