<script lang="ts" setup>
interface CarouselSlide {
  id: string | number;
  step?: string;
  title?: string;
  description?: string;
  image?: string;
  content?: string;
  [key: string]: unknown;
}

interface Props {
  slides?: CarouselSlide[];
  autoPlay?: boolean;
  autoPlayInterval?: number;
}

const props = withDefaults(defineProps<Props>(), {
  slides: () => [],
  autoPlay: false,
  autoPlayInterval: 3000,
});

// State
const currentIndex = ref(0);
const autoPlayTimer = ref<NodeJS.Timeout | null>(null);
const isAnimating = ref(false);

// Computed
const visibleSlides = computed(() => {
  const total = props.slides.length;
  const result = [];

  for (let i = 0; i < 3; i++) {
    const slideIndex = (currentIndex.value + i) % total;
    result.push(props.slides[slideIndex]);
  }

  return result;
});

// Methods
const getCardClasses = (index: number) => {
  const baseClasses = "transition-all duration-700 ease-in-out";

  switch (index) {
    case 0: // Top card (most visible)
      return `${baseClasses} top-0 left-0 z-20`;
    case 1: // Middle card
      return `${baseClasses} top-2 right-2 sm:top-4 sm:right-4 z-10`;
    case 2: // Bottom card
      return `${baseClasses} top-4 right-4 sm:top-8 sm:right-8 z-0`;
    default:
      return `${baseClasses} opacity-0`;
  }
};

const nextSlide = () => {
  if (isAnimating.value) return;

  isAnimating.value = true;
  currentIndex.value = (currentIndex.value + 1) % props.slides.length;
  resetAutoPlay();

  // Wait for animation to complete (700ms transition + small buffer)
  setTimeout(() => {
    isAnimating.value = false;
  }, 750);
};

const previousSlide = () => {
  if (isAnimating.value) return;

  isAnimating.value = true;
  currentIndex.value =
    currentIndex.value === 0 ? props.slides.length - 1 : currentIndex.value - 1;
  resetAutoPlay();

  // Wait for animation to complete (700ms transition + small buffer)
  setTimeout(() => {
    isAnimating.value = false;
  }, 750);
};

const goToSlide = (index: number) => {
  if (index === currentIndex.value || isAnimating.value) return;

  isAnimating.value = true;
  currentIndex.value = index;
  resetAutoPlay();

  // Wait for animation to complete (700ms transition + small buffer)
  setTimeout(() => {
    isAnimating.value = false;
  }, 750);
};

const resetAutoPlay = () => {
  if (!props.autoPlay) return;
  stopAutoPlay();
  startAutoPlay();
};

const startAutoPlay = () => {
  if (props.autoPlay && !autoPlayTimer.value) {
    autoPlayTimer.value = setInterval(() => {
      // Only proceed if not currently animating
      if (!isAnimating.value) {
        nextSlide();
      }
    }, props.autoPlayInterval);
  }
};

const stopAutoPlay = () => {
  if (autoPlayTimer.value) {
    clearInterval(autoPlayTimer.value);
    autoPlayTimer.value = null;
  }
};

// Lifecycle
onMounted(() => {
  if (props.autoPlay) {
    startAutoPlay();
  }
});

onUnmounted(() => {
  stopAutoPlay();
});

// Auto-play control on hover and interaction
const _handleMouseEnter = () => {
  if (props.autoPlay) {
    stopAutoPlay();
  }
};

const _handleMouseLeave = () => {
  if (props.autoPlay) {
    startAutoPlay();
  }
};

// Error handler for Lottie animations
const handleLottieError = (error: Error) => {
  console.warn("Lottie animation error:", error.message);
  // You can add additional error handling here if needed
};

// Expose methods for parent component
defineExpose({
  nextSlide,
  previousSlide,
  goToSlide,
  currentIndex: readonly(currentIndex),
});
</script>
<template>
  <div
    class="flex flex-col items-center justify-center px-4"
    @mouseenter="_handleMouseEnter"
    @mouseleave="_handleMouseLeave"
  >
    <!-- Cards Container -->
    <div
      class="relative isolate ml-4 min-h-[354px] w-full max-w-[1044px] md:ml-8"
    >
      <div class="relative h-full w-full pb-2 sm:pr-8 sm:pb-8">
        <TransitionGroup name="stack" tag="ul" class="relative h-full w-full">
          <li
            v-for="(slide, index) in visibleSlides"
            :key="slide.id"
            :class="getCardClasses(index)"
            class="absolute w-full transition-all duration-700 ease-in-out"
          >
            <div
              class="bg-surface-background border-surface-border min-h-[322px] w-full rounded-[24px] border p-6"
            >
              <slot :slide="slide" :index="index">
                <div
                  class="relative grid grid-cols-1 overflow-hidden md:grid-cols-6"
                >
                  <div class="col-span-6">
                    <span class="dark-text-gradient text-[66px] font-bold">
                      {{
                        `.0${((currentIndex + index) % props.slides.length) + 1}`
                      }}
                    </span>
                    <div>
                      <h3
                        class="dark-text-gradient text-[18px] font-semibold sm:text-[30px] lg:text-[32px]"
                      >
                        {{ slide.title }}
                      </h3>
                    </div>

                    <p
                      class="ws-scrollbar mt-6 max-h-[100px] overflow-auto pe-3 text-[16px] md:text-[18px]"
                    >
                      {{ slide.description }}
                    </p>
                  </div>

                  <div class="absolute end-0 top-0 col-span-1 my-auto ms-auto">
                    <!-- <NuxtImg :width="100" :height="100" :src="slide.image" /> -->
                    <div
                      class="lottie-container h-[100px] w-[100px] md:h-[150px] md:w-[150px]"
                    >
                      <ClientOnly>
                        <Lottie
                          v-if="slide.image"
                          :name="slide.image"
                          height="100"
                          width="100"
                          @error="handleLottieError"
                        />
                      </ClientOnly>
                    </div>
                  </div>
                </div>
              </slot>
            </div>
          </li>
        </TransitionGroup>
      </div>
    </div>

    <!-- Navigation Controls -->
    <div class="mt-6 flex items-center justify-center gap-6">
      <button
        :aria-label="$t('ariaLabels.prevBtn')"
        class="prev-button-latest-models bg-surface-background border-surface-border rounded-ws-rounded flex-shrink-0 cursor-pointer border p-3"
        :disabled="isAnimating"
        :class="{ 'cursor-not-allowed opacity-50': isAnimating }"
        @click="previousSlide"
      >
        <SvgGradientFullArrowRight class="ltr:scale-x-[-1] rtl:scale-x-[1]" />
      </button>

      <!-- Custom Pagination Dots -->
      <div class="custom-pagination-container">
        <div
          v-for="(slide, index) in slides"
          :key="`pagination-${slide.id}`"
          class="pagination-dot"
          :class="{
            active: currentIndex === index,
            'cursor-not-allowed opacity-50': isAnimating,
          }"
          @click="goToSlide(index)"
        />
      </div>

      <button
        :aria-label="$t('ariaLabels.nextBtn')"
        class="next-button-latest-models bg-surface-background border-surface-border rounded-ws-rounded flex-shrink-0 cursor-pointer border p-3"
        :disabled="isAnimating"
        :class="{ 'cursor-not-allowed opacity-50': isAnimating }"
        @click="nextSlide"
      >
        <SvgGradientFullArrowLeft class="ltr:scale-x-[-1] rtl:scale-x-[1]" />
      </button>
    </div>
  </div>
</template>
<style scoped>
.lottie-container {
  filter: brightness(0) saturate(100%);
}

.dark .lottie-container {
  filter: brightness(0) saturate(100%) invert(1);
}
/* Stack animation transitions */
.stack-enter-active,
.stack-leave-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.stack-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.stack-leave-to {
  opacity: 0;
  transform: translateX(100vw) scale(1.02);
}

[dir="rtl"] .stack-leave-to {
  transform: translateX(-100vw) scale(1.02);
}

.stack-move {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.carousel-container.animating {
  pointer-events: none;
}

.carousel-container.animating .navigation-dots,
.carousel-container.animating .navigation-arrows {
  pointer-events: auto;
}

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

@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(--surface-background);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid var(--surface-border);
}

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

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

/* Navigation button disabled state */
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

button:disabled:hover {
  transform: none;
}

/* Pagination dot disabled state */
.pagination-dot.opacity-50 {
  cursor: not-allowed;
  pointer-events: none;
}

.pagination-dot.opacity-50:hover {
  transform: none;
}

.dark .pagination-dot {
  background-color: rgba(75, 85, 99, 0.5);
}

.dark .pagination-dot.active {
  background-color: var(--foreground);
}
</style>
