<script lang="ts" setup>
import type { ShortVideo } from "~/types/Marketing";

// Query and data
const { projects } = defineProps<{ projects: ShortVideo[] }>();

// State
const currentIndex = ref(0);
const videoRefs = ref<(HTMLVideoElement | null)[]>([]);
const playingVideoIndex = ref<number | null>(null);
const youtubeEmbedUrls = ref<Map<number, string>>(new Map());

// YouTube utilities
const YOUTUBE_REGEX =
  /(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;

const isYouTubeVideo = (url: string): boolean => {
  return url.includes("youtube") || url.includes("youtu.be");
};

const getYouTubeVideoId = (url: string): string | null => {
  const match = url.match(YOUTUBE_REGEX);
  return match ? match[1] : null;
};

const getYouTubeThumbnail = (url: string): string => {
  const videoId = getYouTubeVideoId(url);
  return videoId
    ? `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`
    : "";
};

const getYouTubeEmbedUrl = (url: string, autoplay = false): string => {
  const videoId = getYouTubeVideoId(url);
  if (!videoId) return "";

  const params = new URLSearchParams({
    mute: "1",
    ...(autoplay && { autoplay: "1" }),
  });

  return `https://www.youtube.com/embed/${videoId}?${params.toString()}`;
};

// Slide positioning logic
const getSlidePosition = (index: number): string => {
  const total = projects.length;
  if (total === 0) return "hidden";

  const prev = (currentIndex.value - 1 + total) % total;
  const next = (currentIndex.value + 1) % total;
  const secondPrev = (currentIndex.value - 2 + total) % total;
  const secondNext = (currentIndex.value + 2) % total;

  if (index === prev) return "left";
  if (index === currentIndex.value) return "center";
  if (index === next) return "right";
  if (index === secondPrev || index === secondNext) return "preload";
  return "hidden";
};

// Navigation
const goToPrevious = () => {
  if (projects.length === 0) return;
  currentIndex.value =
    (currentIndex.value - 1 + projects.length) % projects.length;
};

const goToNext = () => {
  if (projects.length === 0) return;
  currentIndex.value = (currentIndex.value + 1) % projects.length;
};

const goToSlide = (index: number) => {
  if (index >= 0 && index < projects.length) {
    currentIndex.value = index;
  }
};

// Video management
const setVideoRef = (
  el: Element | ComponentPublicInstance | null,
  index: number,
) => {
  if (index < 0) return;

  // Ensure array is large enough
  while (videoRefs.value.length <= index) {
    videoRefs.value.push(null);
  }
  videoRefs.value[index] = el instanceof HTMLVideoElement ? el : null;
};

const playVideo = (index: number) => {
  const project = projects[index];
  if (!project || index < 0 || index >= projects.length) {
    console.warn(`Invalid video index: ${index}`);
    return;
  }

  // Set the playing video index
  playingVideoIndex.value = index;

  try {
    if (isYouTubeVideo(project.url)) {
      // Set YouTube embed URL with autoplay
      const embedUrl = getYouTubeEmbedUrl(project.url, true);
      youtubeEmbedUrls.value.set(index, embedUrl);
    } else {
      // Play HTML5 video
      const video = videoRefs.value[index];
      if (video?.tagName === "VIDEO") {
        video.play().catch((error) => {
          console.warn("Could not play video:", error);
          // Reset playing state on failure
          playingVideoIndex.value = null;
        });
      }
    }
  } catch (error) {
    console.error("Error playing video:", error);
    // Reset playing state on error
    playingVideoIndex.value = null;
  }
};

watch(currentIndex, () => {
  if (playingVideoIndex.value !== null) {
    const video = videoRefs.value[playingVideoIndex.value];
    if (video instanceof HTMLVideoElement) {
      video.pause();
    }
    playingVideoIndex.value = null;
  }
});
</script>

<template>
  <div v-if="projects?.length > 0" dir="rtl" class="relative w-full overflow-hidden" role="region"
    aria-label="Video gallery">
    <div class="gallery-container">
      <div v-for="(project, index) in projects" :key="index" :class="['gallery-slide', getSlidePosition(index)]">
        <div class="relative z-10 h-full w-full overflow-hidden rounded-2xl">
          <!-- YouTube video with overlay -->
          <template v-if="isYouTubeVideo(project.url)">
            <template v-if="playingVideoIndex !== index">
              <NuxtImg :src="getYouTubeThumbnail(project.url)" class="gallery-media" :alt="project.title" />
            </template>
            <template v-else>
              <iframe class="gallery-media" :src="youtubeEmbedUrls.get(index) || ''" frameborder="0" allowfullscreen
                allow="autoplay; encrypted-media" />
            </template>
          </template>

          <!-- MP4 video -->
          <template v-else>
            <video :ref="(el) => setVideoRef(el, index)" :src="project.url" class="gallery-media" controls muted loop />
          </template>

          <!-- Overlay -->
          <div v-if="playingVideoIndex !== index"
            class="absolute inset-0 flex cursor-pointer items-center justify-center rounded-2xl bg-[rgba(0,0,0,0.5)]"
            @click="playVideo(index)">
            <SvgVideoButton class="h-[40px] w-[40px]" />
          </div>
        </div>
      </div>
    </div>

    <div class="relative z-[10] mt-6 flex items-center justify-center gap-6">
      <button
        class="bg-surface-background border-surface-border rounded-ws-rounded flex-shrink-0 cursor-pointer border p-3"
        :disabled="projects.length === 0" aria-label="Previous video" @click="goToPrevious">
        <SvgGradientFullArrowLeft class="rtl:scale-x-[-1]" />
      </button>

      <!-- Custom Pagination Dots -->
      <div class="custom-pagination-container">
        <div v-for="(project, index) in projects" :key="`pagination-${index}`" class="pagination-dot"
          :class="{ active: currentIndex === index }" @click="goToSlide(index)" />
      </div>

      <button
        class="bg-surface-background border-surface-border rounded-ws-rounded flex-shrink-0 cursor-pointer border p-3"
        :disabled="projects.length === 0" aria-label="Next video" @click="goToNext">
        <SvgGradientFullArrowRight class="rtl:scale-x-[-1]" />
      </button>
    </div>
  </div>
</template>

<style scoped>
.gallery-container {
  position: relative;
  height: 580px;
  width: 100%;
}

.gallery-slide {
  position: absolute;
  top: 0;
  width: 70%;
  height: 100%;
  opacity: 0;
  transform: scale(0.8);
  transition: all 400ms cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1;
  pointer-events: none;
  border-radius: 16px;
}

.gallery-slide.center {
  left: 50%;
  transform: translateX(-50%) scale(1);
  opacity: 1;
  z-index: 5;
  pointer-events: auto;
}

.gallery-slide::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--surface-background);
  border-radius: inherit;
}

.gallery-slide.left {
  left: 15%;
  transform: translateX(-26.3%) scale(0.9);
  opacity: 0.6;
  z-index: 3;
}

.gallery-slide.right {
  left: 85%;
  transform: translateX(-73.7%) scale(0.9);
  opacity: 0.6;
  z-index: 3;
}

.gallery-slide.preload {
  opacity: 0;
  pointer-events: none;
  z-index: 0;
}

.gallery-slide.hidden {
  display: none;
}

.gallery-media {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16px;
}

/* Custom Pagination Styles */
.custom-pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.5rem;
  padding: 0;
  margin: 0;
}

/* Responsive pagination dots */
@media (max-width: 640px) {
  .custom-pagination-container {
    gap: 0.25rem;
    max-width: 300px;
  }

  .pagination-dot {
    width: 18px;
    height: 5px;
  }
}

@media (max-width: 480px) {
  .custom-pagination-container {
    gap: 0.5rem;
    max-width: 250px;
  }

  .pagination-dot {
    width: 16px;
    height: 4px;
  }
}

@media (min-width: 641px) and (max-width: 768px) {
  .pagination-dot {
    width: 24px;
    height: 6px;
  }
}

@media (min-width: 769px) and (max-width: 1024px) {
  .pagination-dot {
    width: 28px;
    height: 7px;
  }
}

.pagination-dot {
  width: 32px;
  height: 8px;
  border-radius: 2px;
  background-color: var(--foreground);
  cursor: pointer;
  transition: all 0.3s ease;
}

.pagination-dot:hover {
  transform: scale(1.1);
}

.pagination-dot.active {
  background-color: var(--color-accent);
  transform: scale(1.02);
}

/* .dark .pagination-dot {
  background-color: var(--color-white);
} */

.dark .pagination-dot.active {
  background-color: var(--color-accent);
}

@media (max-width: 450px) {
  .gallery-container {
    height: 580px;
  }

  .gallery-slide {
    left: 100%;
    width: 100%;
    transform: translateX(100%);
  }

  .gallery-slide.center {
    left: 0;
    transform: translateX(0);
    opacity: 1;
    z-index: 2;
    pointer-events: auto;
  }

  .gallery-slide.left {
    left: 0;
    transform: translateX(-100%);
    opacity: 0;
    z-index: 1;
  }

  .gallery-slide.right {
    left: 0;
    transform: translateX(100%);
    opacity: 0;
    z-index: 1;
  }

  .gallery-slide.hidden {
    display: none;
  }
}
</style>
