<script setup>
import { AnimatePresence, motion } from 'motion-v'
import { ArrowRight, Sparkles, X } from 'lucide-vue-next'
import { matchHomeOfferToCarType } from '~/utils/offer-marketing'

const ui = usePublicUi()

const props = defineProps({
  offers: {
    type: Array,
    default: () => [],
  },
  selectedCar: {
    type: String,
    default: '',
  },
  selectedCarLabel: {
    type: String,
    default: '',
  },
  isActive: {
    type: Boolean,
    default: false,
  },
})

const { localizedPath } = usePublicLocale()
const isModalOpen = ref(false)
const dismissedCarTypes = ref(new Set())

const matchedOffer = computed(() => matchHomeOfferToCarType(props.offers, props.selectedCar))
const isDismissed = computed(() => dismissedCarTypes.value.has(props.selectedCar))
const shouldShowPrompt = computed(() => props.isActive && matchedOffer.value && !isDismissed.value)

const modalOffers = computed(() => {
  const seenOfferIds = new Set()

  return [matchedOffer.value, ...props.offers]
    .filter((offer) => {
      const id = offer?.id || offer?.slug

      if (!id || seenOfferIds.has(id)) {
        return false
      }

      seenOfferIds.add(id)
      return true
    })
    .slice(0, 3)
})

const marketingPrompt = computed(() => {
  if (!shouldShowPrompt.value) {
    return null
  }

  const offer = matchedOffer.value
  const carLabel = props.selectedCarLabel || ui.value.home.offerPromptMatchPrefix
  const price = offer.newPrice ? ` ${offer.newPrice}` : ''

  return {
    id: `match-${props.selectedCar}-${offer.id || offer.slug}`,
    description: `${carLabel} ${ui.value.home.offerPromptMatchSuffix} ${offer.name}${price}.`,
  }
})

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

function dismissPrompt() {
  if (!props.selectedCar) {
    return
  }

  dismissedCarTypes.value = new Set([...dismissedCarTypes.value, props.selectedCar])
  isModalOpen.value = false
}

watch(() => props.selectedCar, () => {
  isModalOpen.value = false
})
</script>

<template>
  <div v-if="marketingPrompt" class="pt-1">
    <AnimatePresence mode="wait">
      <motion.div
        :key="marketingPrompt.id"
        layout
        :initial="{ opacity: 0, height: 0, marginTop: 0 }"
        :animate="{ opacity: 1, height: 'auto', marginTop: 12 }"
        :exit="{ opacity: 0, height: 0, marginTop: 0 }"
        :transition="{ duration: 0.22, ease: 'easeOut' }"
        class="overflow-hidden"
      >
        <div class="relative flex items-start gap-3 rounded-xl border border-blue-100 bg-blue-50 p-3">
          <button
            type="button"
            class="absolute right-2 top-2 text-blue-400 transition-colors duration-300 hover:text-blue-600"
            @click="dismissPrompt"
          >
            <X class="h-4 w-4" />
          </button>

          <div class="mt-0.5 shrink-0 rounded-lg bg-blue-100 p-1.5 text-blue-600">
            <Sparkles class="h-4 w-4" />
          </div>

          <div class="pr-6">
            <p class="text-xs font-medium leading-relaxed text-blue-900">
              {{ marketingPrompt.description }}
            </p>
            <button
              type="button"
              class="relative z-50 mt-1 cursor-pointer text-xs font-bold text-blue-600 underline decoration-blue-300 underline-offset-2 transition-colors duration-300 hover:text-blue-700"
              @click="isModalOpen = true"
            >
              {{ ui.home.allOffersLabel }}
            </button>
          </div>
        </div>
      </motion.div>
    </AnimatePresence>

    <Teleport to="body">
      <AnimatePresence>
        <motion.div
          v-if="isModalOpen"
          key="offer-modal"
          class="fixed inset-0 z-[99999] flex items-center justify-center p-4 sm:p-6"
        >
          <motion.div
            :initial="{ opacity: 0 }"
            :animate="{ opacity: 1 }"
            :exit="{ opacity: 0 }"
            class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
            @click="isModalOpen = false"
          />

          <motion.div
            :initial="{ opacity: 0, scale: 0.95, y: 20 }"
            :animate="{ opacity: 1, scale: 1, y: 0 }"
            :exit="{ opacity: 0, scale: 0.95, y: 20 }"
            class="relative z-10 w-full max-w-md overflow-hidden rounded-3xl bg-white shadow-2xl"
          >
            <div class="p-6">
              <button
                type="button"
                class="absolute right-4 top-4 rounded-full bg-slate-100 p-2 text-slate-500 transition-colors duration-300 hover:bg-slate-200"
                @click="isModalOpen = false"
              >
                <X class="h-5 w-5" />
              </button>

              <div class="mb-6 flex items-center gap-3">
                <div class="rounded-xl bg-brand-orange/10 p-2.5 text-brand-orange">
                  <Sparkles class="h-6 w-6" />
                </div>
                <div class="pr-10">
                  <h3 class="font-display text-xl font-bold text-slate-900">
                    {{ ui.home.offerMatchLabel }}
                  </h3>
                  <p class="text-sm text-slate-500">
                    {{ marketingPrompt.description }}
                  </p>
                </div>
              </div>

              <div class="space-y-4">
                <NuxtLink
                  v-for="offer in modalOffers"
                  :key="offer.id || offer.slug"
                  :to="resolveOfferRoute(offer)"
                  class="group block cursor-pointer rounded-2xl border border-slate-100 p-4 transition-colors duration-300 hover:border-brand-orange/30"
                  @click="isModalOpen = false"
                >
      <div class="flex gap-4">
                    <img
                      v-if="offer.image"
                      :src="offer.image"
                      :alt="offer.name"
                      class="h-20 w-24 shrink-0 rounded-xl object-cover"
                    >
                    <div
                      v-else
                      class="flex h-20 w-24 shrink-0 items-center justify-center rounded-xl bg-slate-100 border border-slate-200"
                    >
                      <div class="h-8 w-8 rounded-lg bg-white shadow-sm border border-slate-200" />
                    </div>
                    <div class="min-w-0">
                      <div
                        v-if="offer.badge || offer.discountLabel"
                        class="mb-1 text-[10px] font-bold uppercase tracking-wider text-brand-orange"
                      >
                        {{ offer.discountLabel || offer.badge }}
                      </div>
                      <h4 class="font-bold text-slate-900 transition-colors duration-300 group-hover:text-brand-orange">
                        {{ offer.name }}
                      </h4>
                      <div class="mt-1 text-xs leading-relaxed text-slate-500">
                        {{ offer.subtitle || offer.description }}
                      </div>
                      <div v-if="offer.newPrice || offer.oldPrice" class="mt-2 flex items-center gap-2 text-sm font-bold">
                        <span v-if="offer.oldPrice" class="text-slate-400 line-through">
                          {{ offer.oldPrice }}
                        </span>
                        <span v-if="offer.newPrice" class="text-brand-orange">
                          {{ offer.newPrice }}
                        </span>
                      </div>
                    </div>
                    <ArrowRight class="ml-auto mt-1 h-4 w-4 shrink-0 text-slate-300 transition-colors duration-300 group-hover:text-brand-orange" />
                  </div>
                </NuxtLink>
              </div>

              <button
                type="button"
                class="mt-6 w-full rounded-xl bg-slate-900 py-3.5 font-bold text-white transition-colors duration-300 hover:bg-slate-800"
                @click="isModalOpen = false"
              >
                {{ ui.common.back }}
              </button>
            </div>
          </motion.div>
        </motion.div>
      </AnimatePresence>
    </Teleport>
  </div>
</template>
