<script setup>
import { motion, useInView } from 'motion-v'
import { ArrowRight, Clock, Tag } from 'lucide-vue-next'
import { useHomeContent } from '~/content/home'
import { applyImageSourceFallback, buildOfferImageAttrs } from '~/utils/public-image-derivatives'

const props = defineProps({
  showViewAll: {
    type: Boolean,
    default: true,
  },
})

const homeContent = useHomeContent()
const homeOfferCards = computed(() => homeContent.homeOfferCards.value || [])
const homeOffersSection = computed(() => homeContent.homeOffersSection.value || {})
const { localizedPath } = usePublicLocale()
const root = ref(null)
const isInView = useInView(root, { once: true, margin: '-100px' })

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.15,
      delayChildren: 0.1,
    },
  },
}

const cardVariants = {
  hidden: { opacity: 0, y: 50, scale: 0.95 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: {
      duration: 0.8,
      ease: [0.21, 0.47, 0.32, 0.98],
    },
  },
}

const badgeVariants = {
  hidden: { opacity: 0, scale: 15, z: 1000, y: 300 },
  visible: {
    opacity: 1,
    scale: 1,
    z: 0,
    y: 0,
    transition: {
      type: 'spring',
      damping: 12,
      stiffness: 100,
      mass: 0.8,
      delay: 0.4,
      duration: 0.8,
    },
  },
}

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

function offerCardImageAttrs(offer) {
  return buildOfferImageAttrs(offer?.image, {
    variant: 'card',
    sizes: '(min-width: 1024px) 313px, (min-width: 768px) 33vw, 100vw',
  })
}

function handleOfferImageError(event, offer) {
  applyImageSourceFallback(event, offer?.image)
}
</script>

<template>
  <section id="home-offers" ref="root" class="py-12 md:py-20 relative">
    <div class="relative z-10 w-full">
      <div class="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-16">
        <div class="max-w-2xl">
          <motion.div
            :initial="{ opacity: 0, y: 10 }"
            :animate="isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 10 }"
            :transition="{ duration: 0.6 }"
            class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/60 backdrop-blur-md border border-white/40 shadow-sm text-[10px] font-bold tracking-[0.2em] text-slate-500 uppercase mb-4"
          >
            <Tag class="w-3.5 h-3.5 text-brand-orange" />
            {{ homeOffersSection.eyebrow }}
          </motion.div>
          <motion.h2
            :initial="{ opacity: 0, y: 20 }"
            :animate="isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }"
            :transition="{ duration: 0.6, delay: 0.1 }"
            class="text-4xl md:text-5xl lg:text-6xl font-display font-black text-slate-900 tracking-tight"
          >
            {{ homeOffersSection.title?.replace(` ${homeOffersSection.accent}`, '') }}
            <span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-orange to-amber-500"> {{ homeOffersSection.accent }}</span>
          </motion.h2>
        </div>
        <motion.div
          v-if="props.showViewAll"
          :initial="{ opacity: 0, x: 20 }"
          :animate="isInView ? { opacity: 1, x: 0 } : { opacity: 0, x: 20 }"
          :transition="{ duration: 0.6, delay: 0.2 }"
        >
          <NuxtLink :to="localizedPath('/offers')" class="inline-flex items-center gap-2 text-brand-orange hover:text-brand-orange/80 transition-colors font-semibold">
            {{ homeOffersSection.viewAllLabel }} <ArrowRight class="w-5 h-5" />
          </NuxtLink>
        </motion.div>
      </div>

      <motion.div
        v-if="homeOfferCards.length"
        :variants="containerVariants"
        initial="hidden"
        :animate="isInView ? 'visible' : 'hidden'"
        class="grid grid-cols-1 md:grid-cols-3 gap-6 lg:gap-8 perspective-[2000px]"
      >
        <motion.div
          v-for="offer in homeOfferCards"
          :key="offer.id"
          :variants="cardVariants"
          class="group relative bg-white/40 backdrop-blur-2xl rounded-[2.5rem] overflow-hidden border border-white/60 shadow-[0_8px_32px_rgba(0,0,0,0.04)] hover:shadow-[0_24px_48px_rgba(0,0,0,0.08)] hover:bg-white/60 transition-all duration-500"
        >
          <div class="absolute inset-0 w-[200%] translate-x-[-150%] skew-x-[-30deg] bg-gradient-to-r from-transparent via-white/50 to-transparent group-hover:translate-x-[50%] transition-transform duration-1000 ease-in-out z-30 pointer-events-none" />

          <div class="p-4 pb-0 relative">
            <div class="relative h-56 rounded-[2rem] overflow-hidden shadow-inner">
              <div class="absolute inset-0 bg-slate-900/10 z-10 group-hover:bg-transparent transition-colors duration-500" />
              <img
                v-if="offer.image"
                v-bind="offerCardImageAttrs(offer)"
                :alt="offer.name"
                class="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-1000 ease-out"
                loading="lazy"
                decoding="async"
                referrerpolicy="no-referrer"
                @error="handleOfferImageError($event, offer)"
              >
              <div v-else class="flex h-full w-full items-center justify-center bg-slate-100">
                <div class="h-16 w-16 rounded-[1.5rem] border border-slate-200 bg-white/80 shadow-[0_10px_24px_-16px_rgba(15,23,42,0.35)]" />
              </div>

              <div class="absolute top-4 left-4 z-20">
                <div class="bg-white/80 backdrop-blur-md text-slate-800 text-[10px] font-bold uppercase tracking-wider px-3 py-1.5 rounded-full shadow-sm">
                  {{ offer.category }}
                </div>
              </div>
            </div>

            <div class="absolute -top-2 -right-2 z-30 pointer-events-none">
              <motion.div
                :variants="badgeVariants"
                class="bg-gradient-to-br from-brand-orange to-amber-500 text-white font-black text-2xl px-5 py-3 rounded-2xl shadow-[0_20px_40px_rgba(251,146,60,0.4)] border border-white/40 transform rotate-12 group-hover:rotate-0 transition-transform duration-500"
                :style="{ transformStyle: 'preserve-3d' }"
              >
                {{ offer.badge }}
              </motion.div>
            </div>
          </div>

          <div class="p-6 pt-8 relative z-20">
            <div class="flex items-center justify-between mb-2">
              <h3 class="text-2xl font-bold text-slate-900">{{ offer.name }}</h3>
            </div>

            <div v-if="offer.rating && offer.reviews" class="flex items-center gap-2 mb-4">
              <div class="flex items-center gap-0.5">
                <svg
                  v-for="index in 5"
                  :key="index"
                  :class="[
                    'w-3.5 h-3.5',
                    index <= Math.floor(Number.parseFloat(offer.rating)) ? 'text-amber-400 fill-amber-400' : 'text-slate-300 fill-slate-300'
                  ]"
                  viewBox="0 0 20 20"
                >
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                </svg>
              </div>
              <div class="flex items-center gap-1">
                <span class="text-xs font-bold text-slate-700">{{ offer.rating }}</span>
                <span class="text-xs text-slate-400">({{ offer.reviews }} reviews)</span>
              </div>
            </div>

            <p class="text-slate-500 text-sm mb-6 line-clamp-2 leading-relaxed">{{ offer.description }}</p>

            <div v-if="offer.newPrice" class="flex items-end justify-between mb-6">
              <div>
                <p class="text-slate-400 text-[11px] font-bold uppercase tracking-wider mb-1">{{ homeOffersSection.offerPriceLabel }}</p>
                <div class="flex items-baseline gap-2">
                  <span class="text-3xl font-black text-slate-900">{{ offer.newPrice }}</span>
                  <span v-if="offer.oldPrice" class="text-slate-400 line-through text-sm font-medium">{{ offer.oldPrice }}</span>
                  <span class="text-slate-500 text-sm font-medium">{{ homeOffersSection.perDayLabel }}</span>
                </div>
              </div>
            </div>

            <div class="flex items-center justify-between pt-6 border-t border-slate-200/50">
              <div class="flex items-center gap-2 text-slate-500 text-sm font-medium">
                <Clock class="w-4 h-4 text-brand-orange" />
                Valid until {{ offer.validUntil }}
              </div>

              <NuxtLink
                :to="resolveOfferRoute(offer)"
                class="h-10 rounded-full bg-slate-100 flex items-center justify-center text-slate-600 group-hover:bg-brand-orange group-hover:text-white transition-all duration-300 shadow-sm overflow-hidden px-0 group-hover:px-4 gap-2 w-10 group-hover:w-32"
              >
                <span class="text-sm font-bold whitespace-nowrap opacity-0 w-0 group-hover:opacity-100 group-hover:w-auto transition-all duration-300">
                  {{ offer.ctaLabel }}
                </span>
                <ArrowRight class="w-5 h-5 shrink-0 transform group-hover:-rotate-45 transition-transform" />
              </NuxtLink>
            </div>
          </div>
        </motion.div>
      </motion.div>

      <div
        v-else
        class="rounded-[2.5rem] border border-white/60 bg-white/50 backdrop-blur-2xl px-8 py-16 text-center shadow-[0_8px_32px_rgba(0,0,0,0.04)]"
      >
        <h3 class="text-2xl font-display font-bold text-slate-900 mb-3">{{ homeOffersSection.emptyTitle }}</h3>
        <p class="text-slate-500 max-w-xl mx-auto">{{ homeOffersSection.emptyDescription }}</p>
      </div>
    </div>
  </section>
</template>
