<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>
export default {
  name: 'KoleCarousel',
  props: {
    items: { type: Array, default: function () { return []; } },
    autoplay: { type: Boolean, default: true },
    interval: { type: Number, default: 3000 }
  },
  data: function () { return { index: 0, timer: null }; },
  methods: {
    go: function (i) {
      var len = this.items.length || 1;
      this.index = (i + len) % len;
      this.restart();
    },
    restart: function () {
      if (this.timer) clearInterval(this.timer);
      var self = this;
      if (this.autoplay && this.items.length > 1) {
        this.timer = setInterval(function () { self.go(self.index + 1); }, this.interval);
      }
    }
  },
  mounted: function () { this.restart(); },
  beforeDestroy: function () { if (this.timer) clearInterval(this.timer); }
};
</script>

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