<script setup>
import { AnimatePresence, motion } from 'motion-v'
import { ArrowRight, Clock3, Sparkles, TicketPercent } from 'lucide-vue-next'
import { useHomeContent } from '~/content/home'

const homeContent = useHomeContent()
const ui = usePublicUi()
const offerCards = computed(() => homeContent.homeOfferCards.value || [])
const activeIndex = ref(0)
let rotationTimer = null

const { localizedPath } = usePublicLocale()

const activeOffer = computed(() => offerCards.value[activeIndex.value] || null)
const liveOffersLabel = computed(() => ui.value.home.liveOffersCountTemplate.replace('{count}', String(offerCards.value.length)))
const activeOfferSummary = computed(() => {
  if (!activeOffer.value) {
    return ''
  }

  return activeOffer.value.subtitle || activeOffer.value.description || ui.value.home.offerSpotlightFallbackDescription
})

function resolveOfferRoute(offer) {
  return offer?.ctaUrl || offer?.path || localizedPath('/offers')
}

function setActiveOffer(index) {
  activeIndex.value = index
  stopRotation()
  startRotation()
}

function scrollToOffers() {
  document.getElementById('home-offers')?.scrollIntoView({
    behavior: 'smooth',
    block: 'start',
  })
}

function startRotation() {
  if (typeof window === 'undefined' || rotationTimer || offerCards.value.length <= 1) {
    return
  }

  rotationTimer = window.setInterval(() => {
    activeIndex.value = (activeIndex.value + 1) % offerCards.value.length
  }, 4800)
}

function stopRotation() {
  if (typeof window === 'undefined' || !rotationTimer) {
    return
  }

  window.clearInterval(rotationTimer)
  rotationTimer = null
}

watch(offerCards, (nextOffers) => {
  if (!nextOffers.length) {
    activeIndex.value = 0
    stopRotation()
    return
  }

  if (activeIndex.value >= nextOffers.length) {
    activeIndex.value = 0
  }

  stopRotation()
  startRotation()
}, { immediate: true })

onMounted(() => {
  startRotation()
})

onBeforeUnmount(() => {
  stopRotation()
})
</script>

<template>
  <motion.section
    v-if="offerCards.length"
    :initial="{ opacity: 0, y: 14 }"
    :animate="{ opacity: 1, y: 0 }"
    :transition="{ duration: 0.55, ease: 'easeOut' }"
    class="relative overflow-hidden rounded-[1.5rem] border border-white/50 bg-white/72 px-4 py-2.5 shadow-[0_18px_50px_rgba(15,23,42,0.06)] backdrop-blur-2xl md:px-5"
    @mouseenter="stopRotation"
    @mouseleave="startRotation"
  >
    <div class="absolute inset-y-0 -left-12 w-32 rounded-full bg-brand-orange/8 blur-3xl pointer-events-none" />
    <div class="absolute right-0 top-0 h-24 w-24 rounded-full bg-amber-400/8 blur-3xl pointer-events-none" />

    <div class="relative z-10 flex flex-col gap-3 lg:flex-row lg:items-center lg:gap-4">
      <div class="flex min-w-0 items-center gap-3 lg:w-[148px] lg:shrink-0">
        <AnimatePresence mode="wait">
          <motion.div
            v-if="activeOffer"
            :key="`${activeOffer.id}-image`"
            :initial="{ opacity: 0, x: -10, scale: 0.96 }"
            :animate="{ opacity: 1, x: 0, scale: 1 }"
            :exit="{ opacity: 0, x: 10, scale: 0.96 }"
            :transition="{ duration: 0.28, ease: 'easeOut' }"
            class="relative h-[64px] w-[96px] overflow-hidden rounded-[1rem] border border-white/70 bg-slate-100 shadow-sm"
          >
            <img
              v-if="activeOffer.image"
              :src="activeOffer.image"
              :alt="activeOffer.name"
              class="h-full w-full object-cover"
              referrerpolicy="no-referrer"
            >
            <div class="absolute inset-0 bg-gradient-to-r from-slate-900/10 via-transparent to-slate-900/20" />
            <div
              v-if="activeOffer.badge"
              class="absolute left-1.5 top-1.5 inline-flex items-center gap-1 rounded-full bg-white/88 px-1.5 py-0.5 text-[9px] font-medium text-slate-800 shadow-sm"
            >
              <TicketPercent class="h-3 w-3 text-brand-orange" />
              {{ activeOffer.badge }}
            </div>
          </motion.div>
        </AnimatePresence>

        <div class="flex items-center gap-1.5 lg:hidden">
          <button
            v-for="(offer, index) in offerCards"
            :key="offer.id"
            type="button"
            :class="[
              'h-2.5 rounded-full transition-all duration-300',
              index === activeIndex ? 'w-8 bg-brand-orange' : 'w-2.5 bg-slate-300 hover:bg-slate-400',
            ]"
            :aria-label="`Show ${offer.name}`"
            @click="setActiveOffer(index)"
          />
        </div>
      </div>

      <div class="min-w-0 flex-1">
        <div class="flex flex-wrap items-center gap-2">
          <div class="inline-flex items-center gap-2 rounded-full border border-brand-orange/20 bg-brand-orange/[0.07] px-2.5 py-1 text-[11px] font-medium text-brand-orange">
            <span class="relative flex h-2.5 w-2.5">
              <span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-brand-orange/50" />
              <span class="relative inline-flex h-2.5 w-2.5 rounded-full bg-brand-orange" />
            </span>
            {{ ui.home.liveNowLabel }}
          </div>
          <div class="inline-flex items-center gap-2 rounded-full border border-slate-200/80 bg-white/70 px-2.5 py-1 text-[11px] font-medium text-slate-500">
            <Sparkles class="h-3.5 w-3.5 text-amber-500" />
            {{ liveOffersLabel }}
          </div>
        </div>

        <div class="mt-1.5 min-h-[44px]">
          <AnimatePresence mode="wait">
            <motion.div
              v-if="activeOffer"
              :key="activeOffer.id"
              :initial="{ opacity: 0, y: 8, filter: 'blur(4px)' }"
              :animate="{ opacity: 1, y: 0, filter: 'blur(0px)' }"
              :exit="{ opacity: 0, y: -8, filter: 'blur(4px)' }"
              :transition="{ duration: 0.28, ease: 'easeOut' }"
              class="min-w-0"
            >
              <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
                <span class="text-sm font-medium text-slate-500">{{ ui.home.liveNowLabel }}</span>
                <span class="text-lg font-semibold text-slate-900 md:text-[1.25rem]">{{ activeOffer.name }}</span>
                <span
                  v-if="activeOffer.newPrice"
                  class="inline-flex items-center rounded-full border border-slate-200/80 bg-white/80 px-2 py-0.5 text-[11px] font-medium text-slate-800"
                >
                  {{ activeOffer.newPrice }}
                </span>
                <span
                  v-if="activeOffer.validUntil"
                  class="inline-flex items-center gap-1 rounded-full border border-slate-200/80 bg-white/80 px-2 py-0.5 text-[11px] font-medium text-slate-500"
                >
                  <Clock3 class="h-3 w-3 text-amber-500" />
                  {{ activeOffer.validUntil }}
                </span>
              </div>

              <p class="mt-0.5 line-clamp-1 pr-2 text-xs text-slate-500">
                {{ activeOfferSummary }}
              </p>
            </motion.div>
          </AnimatePresence>
        </div>

        <div class="mt-1.5 hidden items-center gap-1.5 lg:flex">
          <button
            v-for="(offer, index) in offerCards"
            :key="offer.id"
            type="button"
            :class="[
              'h-2.5 rounded-full transition-all duration-300',
              index === activeIndex ? 'w-8 bg-brand-orange' : 'w-2.5 bg-slate-300 hover:bg-slate-400',
            ]"
            :aria-label="`Show ${offer.name}`"
            @click="setActiveOffer(index)"
          />
        </div>
      </div>

      <div class="flex flex-wrap items-center gap-2 lg:ml-auto">
        <NuxtLink
          :to="resolveOfferRoute(activeOffer)"
          class="inline-flex items-center gap-2 rounded-full bg-brand-orange px-3.5 py-2 text-sm font-medium text-white shadow-lg shadow-brand-orange/20 transition-all duration-300 hover:bg-[#E66000]"
        >
          {{ ui.home.openOfferLabel }}
          <ArrowRight class="h-3.5 w-3.5" />
        </NuxtLink>

        <button
          type="button"
          class="inline-flex items-center gap-2 rounded-full border border-white/80 bg-white/80 px-3.5 py-2 text-sm font-medium text-slate-700 shadow-sm transition-all duration-300 hover:border-brand-orange/20 hover:text-brand-orange"
          @click="scrollToOffers"
        >
          {{ ui.home.viewOnPageLabel }}
        </button>

        <NuxtLink
          :to="localizedPath('/offers')"
          class="inline-flex items-center gap-2 rounded-full border border-white/80 bg-white/70 px-3.5 py-2 text-sm font-medium text-slate-600 transition-colors duration-300 hover:text-slate-900"
        >
          {{ ui.home.allOffersLabel }}
        </NuxtLink>
      </div>
    </div>
  </motion.section>
</template>
