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

const props = defineProps<{
  testimonials?: Testimonial[];
}>();
const { locale } = useI18n();
const dir = computed(() => (locale.value === "ar" ? "rtl" : "ltr"));

const swiperRef = ref(null);
const currentSlide = ref(0);
const resetKey = ref(0);

const playingId = ref<number | null>(null);
const cardResetTokens = ref<Record<string, number>>({});
const suppressUntil = ref<number>(0);

const incResetToken = (id: number) => {
  const key = String(id);
  cardResetTokens.value[key] = (cardResetTokens.value[key] || 0) + 1;
};

const handlePlay = (id: number) => {
  // Stop previous card if different
  if (playingId.value !== null && playingId.value !== id) {
    incResetToken(playingId.value);
  }
  playingId.value = id;
  swiper.instance.value?.autoplay?.stop();
};

const handlePause = (id: number) => {
  if (playingId.value === id) {
    playingId.value = null;
  }
  swiper.instance.value?.autoplay?.start();
};

const len = props.testimonials ? props.testimonials.length : 0;

const swiper = useSwiper(swiperRef, {
  slidesPerView: 3,
  spaceBetween: 20,
  autoplay: {
    delay: 2000,
    disableOnInteraction: false,
    pauseOnMouseEnter: true,
  },
  keyboard: {
    enabled: true,
  },
  loop: len > 3,
  grabCursor: true,
  on: {
    slideChange: (swiper) => {
      currentSlide.value = swiper.realIndex;
      resetKey.value++;
      if (playingId.value !== null && Date.now() > suppressUntil.value) {
        incResetToken(playingId.value);
        playingId.value = null;
        swiper.autoplay?.start();
      }
    },
    beforeResize: () => {
      suppressUntil.value = Date.now() + 600;
    },
    resize: () => {
      suppressUntil.value = Date.now() + 600;
    },
  },
  breakpoints: {
    320: {
      slidesPerView: 1,
      spaceBetween: 10,
    },
    720: {
      slidesPerView: 2,
      spaceBetween: 15,
    },
    1024: {
      slidesPerView: 3,
      spaceBetween: 20,
    },
  },
});

const goToSlide = (index: number) => {
  if (swiper.instance.value) {
    swiper.instance.value.slideToLoop(index);
  }
};
</script>

<template>
  <div class="relative">
    <div
      v-if="testimonials && testimonials.length === 0"
      class="container mx-auto flex items-center justify-center"
    >
      <EmptyState />
    </div>
    <div v-else class="min-h-[430.78px]">
      <swiper-container
        v-if="testimonials"
        ref="swiperRef"
        :key="'testimonials-' + dir"
        :dir="dir"
        :init="false"
      >
        <swiper-slide v-for="testimonial in testimonials" :key="testimonial.id">
          <TestimonialsCard
            :id="testimonial.id"
            :full-name="testimonial.full_name"
            :job-position="testimonial.job_position"
            :image="testimonial.image"
            :audio-url="testimonial.audio_url"
            :video-url="testimonial.video_url"
            :comment="testimonial.comment"
            :video-reset-token="cardResetTokens[String(testimonial.id)] || 0"
            :audio-reset-token="cardResetTokens[String(testimonial.id)] || 0"
            @play="handlePlay(testimonial.id)"
            @pause="handlePause(testimonial.id)"
          />
        </swiper-slide>
      </swiper-container>

      <swiper-container
        v-else
        ref="swiperRef"
        :key="'skeleton-' + dir"
        :dir="dir"
        :init="false"
      >
        <swiper-slide v-for="i in 6" :key="i">
          <SkeletonsTestimonialCardSkeleton :id="i" class="w-full" />
        </swiper-slide>
      </swiper-container>
    </div>
    <!-- Navigation Controls -->
    <div
      v-if="testimonials && testimonials.length > 0"
      class="mt-6 flex items-center justify-center gap-6"
    >
      <button
        class="prev-button-latest-models bg-surface-background border-surface-border rounded-ws-rounded flex-shrink-0 cursor-pointer border p-3"
        :aria-label="$t('ariaLabels.prevBtn')"
        @click="swiper.prev()"
      >
        <SvgGradientFullArrowLeft class="rtl:scale-x-[-1]" />
      </button>

      <!-- Custom Pagination Dots -->
      <div v-if="testimonials" class="custom-pagination-container">
        <div
          v-for="(testimonial, index) in testimonials"
          :key="`pagination-${testimonial.id}`"
          class="pagination-dot"
          :class="{ active: currentSlide === index }"
          @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"
        @click="swiper.next()"
      >
        <SvgGradientFullArrowRight class="rtl:scale-x-[-1]" />
      </button>
    </div>
  </div>
</template>

<style scoped>
swiper-slide {
  height: auto;
  display: flex;
  align-items: stretch;
}

swiper-container {
  width: 100%;
  height: auto;
}

.card {
  height: 100%;
}

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

/* Mobile screens - smaller dots and closer spacing */
@media (max-width: 640px) {
  .custom-pagination-container {
    gap: 0.25rem;
    max-width: 300px;
  }

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

/* Extra small screens - even tighter spacing */
@media (max-width: 480px) {
  .custom-pagination-container {
    gap: 0.5rem;
    max-width: 250px;
  }

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

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

/* Large tablet screens */
@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);
}

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

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