<template>
    <transition name="fade">
      <div v-if="isOpen" class="image-viewer-wrapper">
        <div v-if="!swiperContent.length" class="img-modale simple-viewer">
            <figure class="img-wrapper">
                <img :src="image.src" :alt="image.alt">
                <figcaption>{{ image.alt }}</figcaption>
            </figure>
          </div>
          <div v-else class="img-modale swiper-viewer">
            <div class="swiper-wrapper">
              <swiper-container
                :slidesPerView="1"
                :centeredSlides="true"
                :loop="true"
                :navigation="true"
                :pagination="true"
                :initialSlide="currentImgIndex"
                :injectStyles="[`
                  .swiper-button-next, .swiper-button-prev { 
                    color: white;
                    top: 50%;
                  }
                  .swiper-pagination-bullet:not(.swiper-pagination-bullet-active) {
                    background: white;
                    opacity: 0.8;
                  }
                `]"
              >
                <swiper-slide v-for="media in swiperContent">
                  <figure>
                    <img :src="media.src" :alt="media.alt" class="popup-img">
                    <figcaption>{{ media.alt }}</figcaption>
                  </figure>
                </swiper-slide>
              </swiper-container>
            </div>
          </div>
          <button @click="close" class="close-button">
              <div></div>
              <div></div>
          </button>
        </div>
    </transition>
</template>

<script setup>
import { ref, watch } from 'vue';
const props = defineProps({
  isOpen: Boolean,
  image: {
    type: Object,
    required: true,
  },
  swiperContent: {
    type: Array,
    required: true,
  }
});

const currentImgIndex = ref(0);

watch(
  () => props.isOpen,
  () => {
  if (props.isOpen && props.swiperContent.length) {
    for (let i = 0; i < props.swiperContent.length; i++) {
      const currentImgSrc = props.image.src;
      const truncatedSrc = currentImgSrc.substring(currentImgSrc.indexOf("/sites"));
      if (props.swiperContent[i].src === truncatedSrc) {
        currentImgIndex.value = i;
        break;     
      }
    }
  }
})

const emit = defineEmits(['close']);

const close = () => {
  emit('close');
};
</script>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>