<template>
  <div class="dialog__inner">
    <header class="tracks-header | flex">
      <div class="tracks">
        <Selector
          v-for="(track, index) in tracks"
          :key="track.slug"
          :label="track.title"
          :items="track.variations"
          :isCompareModeEnabled="isCompareModeEnabled"
          :index="index"
        />
      </div>

      <button
        class="btn | ml-auto"
        :class="{ 'btn--secondary': isCompareModeEnabled }"
        @click="isCompareModeEnabled = !isCompareModeEnabled"
      >
        <span>{{
          isCompareModeEnabled
            ? 'Quitter le mode comparer'
            : 'Comparer les pistes'
        }}</span>
      </button>
    </header>

    <div class="track">
      <template
        v-for="activeTrack in activeTracks"
        :key="activeTrack.slug || activeTrack.title"
      >
        <!-- accès sûr avec optional chaining -->
        <Interactive360
          v-if="activeTrack?.files?.length > 1"
          :activeTrack="activeTrack"
        />
        <SingleImage
          v-else-if="activeTrack?.files?.length === 1"
          :file="activeTrack.files[0]"
          :backgroundColor="activeTrack.backgroundColor"
        />
        <div v-else class="track-empty | bg-white rounded-xl w-full p-32">
          <p>Contenu non disponible pour cette piste</p>
        </div>
      </template>

      <div
        v-if="isCompareModeEnabled && activeTracks.length < 2"
        class="track-empty | bg-white rounded-xl w-full p-32"
      >
        <p>Sélectionnez sur la piste que vous souhaitez comparer</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, watch, onMounted, onBeforeMount } from 'vue';
import { storeToRefs } from 'pinia';
import { usePageStore } from '../../../stores/page';
import { useDialogStore } from '../../../stores/dialog';
import { useVirtualSampleStore } from '../../../stores/virtualSample';
import { useRoute, useRouter } from 'vue-router';
import Interactive360 from './Interactive360.vue';
import SingleImage from './SingleImage.vue';
import Selector from '../../Selector.vue';
import slugify from 'slugify';

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

const { page } = storeToRefs(usePageStore());
const { isCommentsOpen, isCommentPanelEnabled, activeTracks, openedFile } =
  storeToRefs(useDialogStore());
const { isCompareModeEnabled } = storeToRefs(useVirtualSampleStore());

// computed tracks à partir de la structure page
const tracks = computed(() => {
  const raw =
    page.value.steps.find((step) => step.slug === 'virtual-sample')?.files
      ?.dynamic || {};
  const list = [];

  for (const key in raw) {
    list.push({
      title: key,
      slug: slugify(key),
      variations: raw[key] || [],
    });
  }

  return list;
});

function normalizeSlug(slug) {
  return slug.replace(/_/g, '-');
}

function getVariationSlug(variation) {
  return variation.slug || (variation.title ? slugify(variation.title) : null);
}

function findVariationByHash(hashValue) {
  const allVariations = tracks.value.flatMap((track) => track.variations || []);
  const normalizedHash = normalizeSlug(hashValue);

  return allVariations.find((variation) => {
    const variationSlug = getVariationSlug(variation);
    if (!variationSlug) return false;

    const normalizedVariationSlug = normalizeSlug(variationSlug);
    return normalizedVariationSlug === normalizedHash;
  });
}

function getInitialVariation() {
  if (route?.hash && route.hash.length > 0) {
    const hashValue = route.hash.substring(1);
    const variationFromHash = findVariationByHash(hashValue);
    if (variationFromHash) return variationFromHash;
  }

  return tracks.value[0]?.variations?.[0] || null;
}

function initializeActiveTracks() {
  const initialVariation = getInitialVariation();
  activeTracks.value = initialVariation ? [initialVariation] : [];
}

function normalizeUrlHash() {
  if (route?.hash && route.hash.includes('_')) {
    const normalizedHash = normalizeSlug(route.hash);
    router.replace({ ...route, hash: normalizedHash });
  }
}

function openCommentsIfRequested() {
  if (route.query?.comments) {
    isCommentsOpen.value = true;
  }
}

function scrollToHashTarget() {
  if (!route?.hash || route.hash.length === 0) return;

  const selectorId = route.hash.replace('#', '#track--');
  const targetButton = document.querySelector(selectorId);
  if (targetButton) {
    targetButton.scrollIntoView();
  }
}

onBeforeMount(() => {
  initializeActiveTracks();
});

onMounted(() => {
  openCommentsIfRequested();
  normalizeUrlHash();
  scrollToHashTarget();
});

const isSingleImage = computed(() => {
  return (
    activeTracks.value?.length === 1 &&
    activeTracks.value[0]?.files?.length === 1
  );
});

const singleFile = computed(() => {
  return isSingleImage.value ? activeTracks.value[0].files[0] : null;
});

function updateOpenedFile(file) {
  if (file) {
    openedFile.value = file;
  }
}

function enableCompareModeUI() {
  isCommentsOpen.value = false;
  isCommentPanelEnabled.value = false;
}

function disableCompareModeUI() {
  isCommentPanelEnabled.value = true;

  if (activeTracks.value.length === 2) {
    activeTracks.value.pop();
  }
}

function updateUrlHash(firstTrack) {
  const trackSlug = getVariationSlug(firstTrack);
  if (!trackSlug) return;

  const currentHash = route.hash ? route.hash.substring(1) : '';
  const normalizedTrackSlug = normalizeSlug(trackSlug);

  if (currentHash !== normalizedTrackSlug) {
    router.replace({ ...route, hash: '#' + normalizedTrackSlug });
  }
}

watch(singleFile, updateOpenedFile, { immediate: true });

watch(isCompareModeEnabled, (isEnabled) => {
  isEnabled ? enableCompareModeUI() : disableCompareModeUI();
});

watch(
  activeTracks,
  (tracks) => {
    if (tracks && tracks.length > 0) {
      updateUrlHash(tracks[0]);
    }
  },
  { deep: true }
);
</script>

<style>
.track figure {
  position: relative;
}

.track .drag-zone {
  position: absolute;
  inset: 0;
  z-index: 2;
}
</style>
