<template>
  <Transition>
    <div v-if="isEtapeValid">
      <div class="content-wrapper">
        <header>
          <div class="cover">
            <img :src="etape.vignette.url" :alt="etape.vignette.alt">
          </div>
          <div class="cartouche" :style="{ backgroundColor: etape.couleur }">
            <p>Étape n°{{etape.etape_number}}</p>
            <p>Du {{etape.dates.start.d}} {{etape.dates.start.m}} au {{ etape.dates.end.d }} {{ etape.dates.end.m }} {{ etape.dates.end.y }}</p>
          </div>
          <div class="brand-pattern" :style="{ backgroundColor: etape.couleur }">
            <div class="pattern"></div>
          </div>
          <div class="locality">
            <div class="top-triangle"></div>
            <div class="locality-title">
              <h1>{{etape.title}} <em>({{ etape.adresse.postal_code }})</em></h1>
            </div>
          </div>
        </header>
        <main>
          <div v-if="etape.sensibleMap" id="sensible-map">
            <figure>
              <vue-image-zoomer
                :regular="etape.sensibleMap.url"
                :zoom="etape.sensibleMap.url"
                :zoom-amount="3.5"
                alt="Carte sensible du territoire"
                hover-message="Survolez pour zoomer dans la carte"
              />
              <figcaption class="caption">{{ etape.sensibleMap.alt }}</figcaption>
            </figure>
          </div>
          <div v-for="partie in etape.parties" class="partie" @click="handleImageClick">

            <div v-if="Object.keys(partie.chiffresCles).length" class="chiffres-cles">
              <h3>
                <div class="underline" :style="{ backgroundColor: etape.couleur }"></div>
                <p>Chiffres clés</p>
              </h3>
              <div>
                <div v-for="chiffre in partie.chiffresCles">
                  <div v-html="chiffre.split('<br />')[0]" class="chiffre" :style="{ borderLeft: `solid 10px ${etape.couleur}` }"></div>
                  <p v-html="chiffre.split('<br />')[1]" class="chiffre-caption" :style="{ borderLeft: `solid 10px ${etape.couleur}` }"></p>
                </div>
              </div>
            </div>
            <div class="partie-title">
              <h3>
                <div class="underline" :style="{ backgroundColor: etape.couleur }"></div>
                <p v-html="partie.title"></p>
              </h3>
            </div>
            <div v-html="partie.text" v-alt class="partie-content"></div>
            <swiper-container
              v-if="partie.diaporama.length"
              class="diaporama"
              :slidesPerView="1.5"
              :centeredSlides="true"
              :loop="true"
              :navigation="true"
              :pagination="true"
              :injectStyles="[`.swiper-button-next, .swiper-button-prev { z-index: 11; }`]"
            >
              <swiper-slide v-for="image in partie.diaporama" style="width: 100%">
                <figure>
                  <img :src="image.url" :alt="image.alt">
                  <figcaption class="caption">{{ image.alt }}</figcaption>
                </figure>
              </swiper-slide>
            </swiper-container>
            <div v-if="partie.videos.length" class="videos">
              <iframe v-for="video in partie.videos" :src="video" frameborder="0" width="100%" style="aspect-ratio: 16 / 9;"></iframe>
            </div>
          </div>

          <div class="brand-pattern pattern-bottom" :style="{ backgroundColor: etape.couleur }">
            <div class="pattern"></div>
          </div>

          <div v-if="etape.previous || etape.next" class="related-etape-links">
            <div v-if="etape.previous" class="card previous" @click="store.fetchEtapeData(etape.previous.nid)">
              <div class="icon">
                <div :style="{ backgroundColor: etape.previous.couleur }"></div>
                <div :style="{ backgroundColor: etape.previous.couleur }"></div>
                <div :style="{ backgroundColor: etape.previous.couleur }"></div>
              </div>
              <div class="card-content">
                <div class="infos">
                  <div class="titre">{{ etape.previous.title }} <span>({{ etape.previous.postalCode }})</span></div>
                  <div class="date">Du {{ etape.previous.dates.start.d }} {{ etape.previous.dates.start.m }}<br>au {{ etape.previous.dates.end.d }} {{ etape.previous.dates.end.m }} {{ etape.previous.dates.end.y }}</div>
                </div>
                <div class="vignette">
                  <img :src="etape.previous.vignette.url" :alt="etape.previous.vignette.alt">
                </div>
              </div>
            </div>
            <div v-if="etape.next" class="card next" @click="store.fetchEtapeData(etape.next.nid)">
              <div class="icon">
                <div :style="{ backgroundColor: etape.next.couleur }"></div>
                <div :style="{ backgroundColor: etape.next.couleur }"></div>
                <div :style="{ backgroundColor: etape.next.couleur }"></div>
              </div>
              <div class="card-content">
                <div class="infos">
                  <div class="titre">{{ etape.next.title }} <span>({{ etape.next.postalCode }})</span></div>
                  <div class="date">Du {{ etape.next.dates.start.d }} {{ etape.next.dates.start.m }}<br>au {{ etape.next.dates.end.d }} {{ etape.next.dates.end.m }} {{ etape.next.dates.end.y }}</div>
                </div>
                <div class="vignette">
                  <img :src="etape.next.vignette.url" :alt="etape.next.vignette.alt">
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>

  <!--     
      <div v-if="loading">Loading...</div>
      <div v-if="error">{{ error }}</div>
      {{etape.adresse.locality}}
   -->
    
<!--       <div><pre>{{href}}</pre></div>
  
      
      <div><pre><b>GEOFIELD</b>{{etape.geofield}}</pre></div>
      <div><pre><b>VIGNETTE</b>{{etape.vignette}}</pre></div>
      <div><pre><b>GALERIES</b>{{etape.galeries}}</pre></div>
      <div><pre><b>PARTIES</b>{{etape.parties}}</pre></div>
      <div><pre><b>SAISON</b>{{etape.saison}}</pre></div>
      <div><pre><b>THEMATIQUES</b>{{etape.thematiques}}</pre></div>
 -->  
    </div>
  </Transition>

  <ImageModale :isOpen="isModaleOpen" :image="currentImage" :swiperContent="swiperPopupContent" @close="closeImageModale" />

  <Transition>
    <div v-if="isPageValid">
      <header>
        <h1>{{ page.title }}</h1>
      </header>
      <main>
        <div v-html="page.text"></div>
      </main>
    </div>
  </Transition>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useContentStore } from '../stores/content';
import { useRoute, useRouter } from 'vue-router';
import ImageModale from './ImageModale.vue';

import { VueImageZoomer } from 'vue-image-zoomer'
import 'vue-image-zoomer/dist/style.css';

// web element usage bc its 2024
// (idk how it works but it does)
import { register } from 'swiper/element/bundle';
register();

const router = useRouter();
const store = useContentStore();
const route = useRoute();

const { loading, error, href, etape, page } = storeToRefs(store);

watch(
  () => route.params.id,
  (newId) => {
    if (!newId) {
      store.emptyAll();
    } else {
      store.fetchEtapeData(newId);
      if (!etape.value?.data) {
        store.fetchStaticData(newId);
      }
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  },
  { immediate: true }
);

watch(
  () => etape.value.couleur,
  (newColor) => {
    if (newColor) {
      document.documentElement.style.setProperty('--etape-couleur', etape.value.couleur);
    }
  }
);

watch(
  () => href.value,
  (newHref) => {
    const relativePath = newHref.split('.fr')[1];
    if (relativePath && relativePath !== '' && relativePath !== '/') {
      router.push(relativePath);
    }
  }
);

const isObjectEmpty = (obj) => {
  if (!obj || typeof obj !== 'object') return true;

  return !Object.keys(obj).some((key) => {
    const value = obj[key];
    if (Array.isArray(value)) return value.length > 0;
    if (typeof value === 'object') return !isObjectEmpty(value);
    return value !== null && value !== undefined && value !== '';
  });
};

const isEtapeValid = computed(() => etape.value && !isObjectEmpty(etape.value));
const isPageValid = computed(() => page.value && !isObjectEmpty(page.value));

const vAlt = {
  mounted : (el) => {
    const images = el.querySelectorAll('img');
    images.forEach((img) => {
      const altText = img.getAttribute('alt');
      if (altText) {
        const paragraph = document.createElement('p');
        paragraph.classList.add('caption');
        paragraph.textContent = altText;
        img.after(paragraph);
      }
    });
  }
};

const isModaleOpen = ref(false);
const currentImage = ref({ src: '', alt: '' });
const swiperPopupContent = ref([]);

const body = document.querySelector('body');
const hamburger = document.querySelector('#hamburger');
const menu = document.querySelector('#menu');

const openImageModale = (src, alt, swiperMedia) => {
  currentImage.value = { src, alt };
  swiperPopupContent.value = swiperMedia;  
  isModaleOpen.value = true;
  body.classList.add('no-scroll');
  hamburger.style.opacity = 0;
  menu.style.display = "none";
};

const closeImageModale = () => {
  isModaleOpen.value = false;
  swiperPopupContent.value = [];
  body.classList.remove('no-scroll');
  menu.style.display = "flex";
  setTimeout(() => {
    hamburger.style.opacity = 1;
  }, 300);
};

const handleImageClick = (event) => {
  const img = event.target;
  if (img.tagName === 'IMG') {
    const isSwiper = img.parentElement.parentElement.tagName === 'SWIPER-SLIDE';
    let swiperMedia = [];
    if (isSwiper) {
      const swiperEl = img.parentElement.parentElement.parentElement;
      for (let swiperSlide of swiperEl.children) {
        swiperMedia.push({src: swiperSlide.querySelector('img').getAttribute('src'), alt: swiperSlide.querySelector('figcaption')?.textContent});
      }
    }
    openImageModale(img.src, img.alt, swiperMedia);
  }
};

/*     
      return {
      loading,
      error,
      etape,
      page,
      isEtapeValid,
      isPageValid
    };
 */
 </script>


<style scss>
.v-enter-active,
.v-leave-active {
  transition: all 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

.v-leave-from {
  transform: translateY(0%);
  opacity: 1;
}

:root {
  --swiper-navigation-color: #1a1918; /* cf main.scss */
  --swiper-pagination-color: var(--etape-couleur);
  --swiper-navigation-top-offset: calc(100% - 1.5rem);
  --swiper-navigation-sides-offset: 5vw; /* cf main.scss */
}

.diaporama {
  --swiper-navigation-size: 1.5rem;
}

swiper-slide img:not(.popup-img) { /* cf main.scss */
  cursor: pointer;
  transition: transform 0.3s ease-out;
  &:hover {
    transform: scale(1.01);
  }
}
</style>