<script setup lang="ts">
import { ref, computed, onMounted } from "vue";

const activeImage = ref(0);
const images = ref<Array<Element>>([]);

const offset = computed(() => `margin-left: -${activeImage.value * 100}%`);

const setActive = (index: number) => {
  activeImage.value = index;
};
const prev = () => {
  if (activeImage.value > 0) {
    activeImage.value -= 1;
  }
};
const next = () => {
  if (activeImage.value < images.value.length - 1) {
    activeImage.value += 1;
  }
};

onMounted(() => {
  const sel = ".gallery__viewport .figure";
  const elements = document.querySelectorAll(sel);
  const imageArray = Array.from(elements);
  images.value = imageArray;
});
</script>

<template>
  <div class="gallery">
    <div class="gallery__images">
      <a
        href="#"
        class="gallery__prev"
        @click.prevent="prev()"
        v-show="activeImage > 0"
      ></a>
      <a
        href="#"
        class="gallery__next"
        @click.prevent="next()"
        v-show="activeImage < images.length - 1"
      ></a>

      <div class="gallery__viewport" :style="offset">
        <slot></slot>
      </div>
    </div>

    <nav class="gallery__navigation">
      <ul>
        <li v-for="(image, idx) in images" :key="idx">
          <a
            href="#"
            :class="{ active: activeImage === idx }"
            @click.prevent="setActive(idx)"
          ></a>
        </li>
      </ul>
    </nav>
  </div>
</template>

<style lang="scss">
.gallery {
  &__prev,
  &__next {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);

    width: var(--gallery-size);
    height: var(--gallery-size);

    z-index: 1;

    border: {
      top: 0.125rem solid #fff;
      right: 0.125rem solid #fff;
    }
  }

  &__prev {
    left: var(--gallery-arrow-position);
    transform: rotate(-135deg);
  }

  &__next {
    right: var(--gallery-arrow-position);
    transform: rotate(45deg);
  }

  &__images {
    position: relative;
    overflow: hidden;
  }

  &__viewport {
    display: flex;
    flex-flow: row nowrap;
    align-items: center;

    width: 100%;
    height: 100%;

    transition: 0.3s all ease-in-out;
  }

  .figure {
    margin: 0;
    padding: var(--gallery-image-padding);
    flex: 1 0 100%;

    &__meta {
      text-align: center;

      p {
        margin: 0.5rem auto;
      }
    }
  }

  &__navigation {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;

    ul {
      flex: 0 1 auto;

      display: flex;
      flex-flow: row wrap;
      justify-content: center;

      list-style: none;
      margin: 1rem 0;
      padding: 0;
    }

    li {
      flex: 0 1 auto;
      padding: 0.375em;

      a {
        display: block;
        width: 0.5em;
        height: 0.5em;
        border-radius: 1em;
        background: rgba(#fff, 0.5);

        &.active {
          background: #fff;
        }
      }
    }
  }
}
</style>
