<script setup>
import { AnimatePresence, motion } from 'motion-v'
import {
  AlertCircle,
  ArrowLeft,
  Calendar,
  Check,
  ChevronDown,
  MapPin,
  Search,
  SlidersHorizontal,
  Tag,
} from 'lucide-vue-next'
import { format } from 'date-fns'
import { DEFAULT_PRICE_MAX, DEFAULT_PRICE_MIN } from '~/constants/search-ui'
import AppCalendar from '~/components/shared/AppCalendar.vue'
import OfferContextBanner from '~/components/offers/OfferContextBanner.vue'
import SearchCarCard from '~/components/search/SearchCarCard.vue'
import SearchCompareBar from '~/components/search/SearchCompareBar.vue'
import SearchCompareModal from '~/components/search/SearchCompareModal.vue'
import SearchSkeletonCard from '~/components/search/SearchSkeletonCard.vue'
import { resolveOfferForVehicleGroupId, useOffersContent } from '~/content/offers'
import { resolveOfferPricingTierForDays } from '~/content/offer-pricing'
import { useSearchContent } from '~/content/search'
import { resolvePublicApiError } from '~/content/utils'
import { buildRentExtrasRoute, buildRentSearchRoute, buildRentTripQuery } from '~/utils/public-routes'

const route = useRoute()
const preferredVehicleGroupId = computed(() => Number(route.query.vehicleGroupId || 0) || null)
const offersContent = useOffersContent()
const searchContent = useSearchContent()

const { currency } = usePublicPreferences()
const { locale, localizedPath } = usePublicLocale()
const { locations, loadLocations } = usePublicSiteLocations()
const { activeOfferSlug, persistOfferSlug } = usePublicOfferContext()
const { buildCatalogPayload, fetchCatalog, parseSearchQuery } = useSearchCatalog()

const activeType = ref('')
const activeBrand = ref('')
const showFilters = ref(false)
const priceRange = ref(DEFAULT_PRICE_MAX)
const compareList = ref([])

const dateRange = ref({
  from: new Date(),
  to: new Date(),
})
const pickupTime = ref('12:30')
const dropoffTime = ref('08:30')
const showDatePicker = ref(false)

const pickupLocation = ref(null)
const dropoffLocation = ref(null)
const showLocationPicker = ref(false)
const sortBy = ref('recommended')
const showSortDropdown = ref(false)
const showCompareModal = ref(false)
const compareNotice = ref('')
const isSearching = ref(false)
const isInitialCatalogPending = ref(true)

const selectedSeats = ref('')
const selectedTransmission = ref('')
const selectedEngine = ref('')
const selectedOptions = ref([])
const selectedConditions = ref([])

const promoCode = ref('')
const catalogItems = ref([])
const catalogTrip = ref(null)
const catalogError = ref('')
const isCatalogLoading = ref(false)

const animationTimers = []
const lastCatalogKey = ref('')
let compareNoticeTimer = null

function schedule(callback, delay) {
  const timer = window.setTimeout(callback, delay)
  animationTimers.push(timer)
  return timer
}

function clearTimers() {
  animationTimers.splice(0).forEach((timer) => window.clearTimeout(timer))
}

function showCompareNotice(message) {
  compareNotice.value = message

  if (compareNoticeTimer) {
    window.clearTimeout(compareNoticeTimer)
  }

  compareNoticeTimer = window.setTimeout(() => {
    compareNotice.value = ''
    compareNoticeTimer = null
  }, 2500)
}

const routeSignature = computed(() => JSON.stringify(route.query))
const activeOffer = offersContent.useResolvedOffer(activeOfferSlug)
const searchUi = computed(() => searchContent.searchUi.value)
const searchPromo = computed(() => searchContent.searchPromo.value)
const searchSortOptions = computed(() => searchContent.searchSortOptions.value)
const offerCards = computed(() => offersContent.offerCards.value || [])
const allCategoryLabel = computed(() => searchUi.value.allCategoryLabel)
const resultsLabel = computed(() => {
  if (showSkeletons.value) {
    return searchUi.value.loadingLabel || 'Loading...'
  }

  return searchContent.formatSearchResultsLabel(filteredCars.value.length)
})

watch(
  allCategoryLabel,
  (value, previousValue) => {
    const staleValues = new Set([undefined, null, '', 'All', previousValue])

    if (staleValues.has(activeType.value)) {
      activeType.value = value
    }

    if (staleValues.has(activeBrand.value)) {
      activeBrand.value = value
    }

    if (staleValues.has(selectedSeats.value)) {
      selectedSeats.value = value
    }

    if (staleValues.has(selectedTransmission.value)) {
      selectedTransmission.value = value
    }

    if (staleValues.has(selectedEngine.value)) {
      selectedEngine.value = value
    }
  },
  { immediate: true },
)

const locationLabel = computed(() => {
  if (!pickupLocation.value) {
    return searchUi.value.defaultLocationLabel
  }

  if (dropoffLocation.value && dropoffLocation.value.id !== pickupLocation.value.id) {
    return `${pickupLocation.value.name} → ${dropoffLocation.value.name}`
  }

  return pickupLocation.value.name
})

const hiddenToolbarTypes = computed(() => {
  return new Set([
    'minivan',
    'vans',
    'van',
    String(searchUi.value.typeVansLabel || '').trim().toLowerCase(),
  ].filter(Boolean))
})

const typeOptions = computed(() => {
  return [
    allCategoryLabel.value,
    ...new Set(
      catalogItems.value
        .map((item) => item.type)
        .filter(Boolean)
        .filter((type) => !hiddenToolbarTypes.value.has(String(type).trim().toLowerCase())),
    ),
  ]
})

const brandOptions = computed(() => {
  return [allCategoryLabel.value, ...new Set(catalogItems.value.map((item) => item.brand).filter(Boolean))]
})

const seatOptions = computed(() => {
  const numericSeats = [...new Set(catalogItems.value.map((item) => Number(item.seats || 0)).filter((value) => value > 0))].sort((a, b) => a - b)
  const base = numericSeats.filter((value) => value < 7).map((value) => String(value))

  if (numericSeats.some((value) => value >= 7)) {
    base.push('7+')
  }

  return [allCategoryLabel.value, ...base]
})

const transmissionOptions = computed(() => {
  return [allCategoryLabel.value, ...new Set(catalogItems.value.map((item) => item.transmission).filter(Boolean))]
})

const engineOptions = computed(() => {
  return [allCategoryLabel.value, ...new Set(catalogItems.value.map((item) => item.engine).filter(Boolean))]
})

const optionFilters = computed(() => {
  return [...new Set(catalogItems.value.flatMap((item) => item.options || []))]
})

const conditionFilters = computed(() => {
  return [...new Set(catalogItems.value.flatMap((item) => item.conditions || []))]
})

const priceRangeLimit = computed(() => {
  const maxPrice = Math.max(...catalogItems.value.map((item) => Number(item.price || 0)), DEFAULT_PRICE_MAX)
  return Math.max(DEFAULT_PRICE_MAX, Math.ceil(maxPrice / 50) * 50)
})

const currentPayload = computed(() => {
  if (!pickupLocation.value?.backendId || !dropoffLocation.value?.backendId || !dateRange.value?.from || !dateRange.value?.to) {
    return null
  }

  return buildCatalogPayload({
    pickupLocationId: pickupLocation.value.backendId,
    dropoffLocationId: dropoffLocation.value.backendId,
    pickupDate: dateRange.value.from,
    dropoffDate: dateRange.value.to,
    pickupTime: pickupTime.value,
    dropoffTime: dropoffTime.value,
    currency: currency.value,
    promoCode: promoCode.value,
    offerSlug: activeOfferSlug.value || undefined,
  })
})

const filteredCars = computed(() => {
  return [...catalogItems.value].filter((car) => {
    if (activeType.value !== allCategoryLabel.value && car.type !== activeType.value) {
      return false
    }

    if (activeBrand.value !== allCategoryLabel.value && car.brand !== activeBrand.value) {
      return false
    }

    if (car.price > priceRange.value) {
      return false
    }

    if (selectedSeats.value !== allCategoryLabel.value) {
      if (selectedSeats.value === '7+' && car.seats < 7) {
        return false
      }

      if (selectedSeats.value !== '7+' && String(car.seats) !== selectedSeats.value) {
        return false
      }
    }

    if (selectedTransmission.value !== allCategoryLabel.value && car.transmission !== selectedTransmission.value) {
      return false
    }

    if (selectedEngine.value !== allCategoryLabel.value && car.engine !== selectedEngine.value) {
      return false
    }

    if (selectedOptions.value.length > 0 && !selectedOptions.value.every((option) => car.options.includes(option))) {
      return false
    }

    if (selectedConditions.value.length > 0 && !selectedConditions.value.every((condition) => car.conditions.includes(condition))) {
      return false
    }

    return true
  }).sort((left, right) => {
    if (preferredVehicleGroupId.value) {
      const leftPreferred = Number(left.vehicleGroupId) === preferredVehicleGroupId.value
      const rightPreferred = Number(right.vehicleGroupId) === preferredVehicleGroupId.value

      if (leftPreferred !== rightPreferred) {
        return leftPreferred ? -1 : 1
      }
    }

    if (sortBy.value === 'price-low') {
      return left.price - right.price
    }

    if (sortBy.value === 'price-high') {
      return right.price - left.price
    }

    if (sortBy.value === 'rating') {
      return (right.rating || 0) - (left.rating || 0)
    }

    return 0
  })
})

const showSkeletons = computed(() => isInitialCatalogPending.value || isCatalogLoading.value || isSearching.value)

function resolveLocationByBackendId(id, fallbackIndex = 0) {
  const numericId = Number(id || 0)

  if (numericId > 0) {
    const found = locations.value.find((location) => Number(location.backendId) === numericId)

    if (found) {
      return found
    }
  }

  return locations.value[fallbackIndex] || null
}

function syncStateFromRoute() {
  if (!locations.value.length) {
    return
  }

  const parsed = parseSearchQuery(route.query)

  pickupLocation.value = resolveLocationByBackendId(parsed.pickupLocationId, 0)
  dropoffLocation.value = resolveLocationByBackendId(parsed.dropoffLocationId || parsed.pickupLocationId, 0)
  dateRange.value = {
    from: parsed.pickupDate,
    to: parsed.dropoffDate,
  }
  pickupTime.value = parsed.pickupTime
  dropoffTime.value = parsed.dropoffTime
  promoCode.value = parsed.promoCode
}

async function refreshCatalog(force = false) {
  if (import.meta.server) {
    return
  }

  if (!currentPayload.value) {
    isInitialCatalogPending.value = false
    return
  }

  const nextKey = JSON.stringify(currentPayload.value)

  if (!force && lastCatalogKey.value === nextKey) {
    return
  }

  lastCatalogKey.value = nextKey
  isCatalogLoading.value = true
  catalogError.value = ''

  try {
    const catalog = await fetchCatalog(currentPayload.value)
    catalogTrip.value = catalog.trip
    catalogItems.value = catalog.items.map((item) => enrichCarWithOffer(item))
    compareList.value = compareList.value
      .map((selectedCar) => enrichCarWithOffer(catalog.items.find((item) => item.id === selectedCar.id) || selectedCar))
      .filter(Boolean)

    if (catalog.promoInvalid && promoCode.value) {
      promoCode.value = ''
      await commitTripState()
    }
  } catch (error) {
    console.error('Failed to load public catalog', error)
    catalogItems.value = []
    catalogTrip.value = null
    catalogError.value = resolvePublicApiError(error, searchUi.value.catalogLoadFailedLabel, locale.value)
  } finally {
    isCatalogLoading.value = false
    isInitialCatalogPending.value = false
  }
}

function toggleCompare(car) {
  const existing = compareList.value.find((item) => item.id === car.id)

  if (existing) {
    compareList.value = compareList.value.filter((item) => item.id !== car.id)
    return
  }

  if (compareList.value.length >= 3) {
    showCompareNotice(searchUi.value.compareLimitMessage)
    return
  }

  compareList.value = [...compareList.value, car]
}

function clearFilters() {
  activeType.value = allCategoryLabel.value
  activeBrand.value = allCategoryLabel.value
  priceRange.value = priceRangeLimit.value
  selectedSeats.value = allCategoryLabel.value
  selectedTransmission.value = allCategoryLabel.value
  selectedEngine.value = allCategoryLabel.value
  selectedOptions.value = []
  selectedConditions.value = []
  sortBy.value = 'recommended'
}

function buildSearchQuery() {
  return buildRentTripQuery({
    pickupLocationId: pickupLocation.value?.backendId || undefined,
    dropoffLocationId: dropoffLocation.value?.backendId || pickupLocation.value?.backendId || undefined,
    pickupAt: currentPayload.value?.pickup_at,
    dropoffAt: currentPayload.value?.dropoff_at,
    promoCode: promoCode.value || undefined,
    prefillExtra: route.query.prefillExtra || undefined,
    prefillExtras: route.query.prefillExtras || undefined,
    returnToSameLocation: pickupLocation.value?.backendId === dropoffLocation.value?.backendId ? '1' : '0',
    driverAge: route.query.driverAge || '21-65',
    offerSlug: activeOfferSlug.value || undefined,
    vehicleId: route.query.vehicleId || undefined,
  })
}

function resolveSelectedVehicleId(car) {
  return Number(car?.vehicle?.id || 0) || undefined
}

function resolveOfferForCar(car) {
  return resolveOfferForVehicleGroupId(
    offerCards.value,
    car?.vehicleGroupId || car?.id || car?.vehicle?.id || null,
  )
}

function enrichCarWithOffer(car) {
  const offer = resolveOfferForCar(car)

  if (!offer) {
    return car
  }

  const tripDays = Number(catalogTrip.value?.days || 0)
    || Math.max(
      1,
      Math.round(
        (new Date(currentPayload.value?.dropoff_at).getTime() - new Date(currentPayload.value?.pickup_at).getTime())
        / 86400000,
      ) || 1,
    )
  const tier = resolveOfferPricingTierForDays(offer, tripDays)

  if (!tier) {
    return {
      ...car,
      activeOffer: offer,
      pricingTiers: offer.pricingTiers || [],
    }
  }

  return {
    ...car,
    activeOffer: offer,
    pricingTiers: offer.pricingTiers || [],
    price: Number(tier.newPrice || car.price || 0),
    oldPrice: Number(tier.oldPrice || car.oldPrice || car.compareAtPrice || 0),
    compareAtPrice: Number(tier.oldPrice || car.oldPrice || car.compareAtPrice || 0),
  }
}

async function commitTripState() {
  await navigateTo(
    buildRentSearchRoute(buildSearchQuery(), {
      locale: locale.value,
    }),
    {
      replace: true,
    },
  )
}

async function applyLocation(location) {
  pickupLocation.value = location
  dropoffLocation.value = location
  showLocationPicker.value = false
  await commitTripState()
}

async function applyDates() {
  showDatePicker.value = false
  await commitTripState()
}

async function bookVehicle(car) {
  const vehicleId = resolveSelectedVehicleId(car)

  if (!vehicleId) {
    return
  }

  const matchedOffer = resolveOfferForCar(car)

  if (matchedOffer?.slug) {
    persistOfferSlug(matchedOffer.slug)
  }

  await navigateTo(buildRentExtrasRoute(car.vehicleGroupId, {
    ...buildSearchQuery(),
    vehicleId,
  }, {
    locale: locale.value,
  }))
}

watch(
  [activeType, activeBrand, priceRange, sortBy, selectedSeats, selectedTransmission, selectedEngine, selectedOptions, selectedConditions],
  () => {
    clearTimers()
    isSearching.value = true
    schedule(() => {
      isSearching.value = false
    }, 800)
  },
  { deep: true },
)

watch(
  typeOptions,
  (options) => {
    if (!options.includes(activeType.value)) {
      activeType.value = allCategoryLabel.value
    }
  },
  { immediate: true },
)

watch(
  brandOptions,
  (options) => {
    if (!options.includes(activeBrand.value)) {
      activeBrand.value = allCategoryLabel.value
    }
  },
  { immediate: true },
)

watch(
  priceRangeLimit,
  (value) => {
    if (priceRange.value > value) {
      priceRange.value = value
    }
  },
  { immediate: true },
)

watch(
  [routeSignature, () => locations.value.length, () => currency.value],
  async ([, locationsCount]) => {
    if (!locationsCount) {
      return
    }

    syncStateFromRoute()
    await refreshCatalog()
  },
  { immediate: true },
)

onMounted(async () => {
  await loadLocations()
})

onBeforeUnmount(() => {
  clearTimers()

  if (compareNoticeTimer) {
    window.clearTimeout(compareNoticeTimer)
  }
})

const selectedSortLabel = computed(() => {
  return searchSortOptions.value.find((option) => option.value === sortBy.value)?.label || searchUi.value.sortRecommendedLabel
})
</script>

<template>
  <div class="min-h-screen font-sans text-slate-900 pb-24 relative">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 pt-6 md:pt-8 pb-5">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
          <NuxtLink
            :to="localizedPath('/')"
            class="w-10 h-10 rounded-full bg-white/80 border border-white/70 shadow-sm flex items-center justify-center text-slate-600 hover:bg-brand-orange hover:text-white transition-colors"
          >
            <ArrowLeft class="w-5 h-5" />
          </NuxtLink>
          <div class="text-xl font-display font-bold tracking-tight">
            {{ searchUi.headerTitle }}
          </div>
        </div>
      </div>
    </div>

    <div v-if="activeOffer" class="max-w-6xl mx-auto px-4 sm:px-6 mb-5">
      <OfferContextBanner :offer="activeOffer" compact />
    </div>

    <div class="sticky top-1 sm:top-3 z-40 px-4 mt-0 mb-6">
      <div class="max-w-6xl mx-auto">
        <div class="bg-slate-900/95 backdrop-blur-2xl text-white rounded-[2rem] p-1.5 sm:p-2 shadow-2xl shadow-slate-900/20 border border-white/10 flex flex-col lg:flex-row items-center gap-1.5 sm:gap-2">
          <div class="flex-1 flex flex-col sm:flex-row w-full bg-white/5 rounded-[1.5rem] p-1 relative border border-white/5">
            <button
              type="button"
              class="flex-1 flex items-center gap-3 px-4 py-3 hover:bg-white/10 rounded-2xl transition-all duration-300 text-left group"
              @click="showLocationPicker = !showLocationPicker; showDatePicker = false; showFilters = false"
            >
              <div class="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center shrink-0 group-hover:scale-110 transition-transform duration-300">
                <MapPin class="w-5 h-5 text-brand-orange" />
              </div>
              <div>
                <div class="text-[10px] font-bold uppercase tracking-wider text-slate-400 group-hover:text-slate-300 transition-colors">
                  {{ searchUi.locationLabel }}
                </div>
                <div class="font-semibold text-sm text-white">
                  {{ locationLabel }}
                </div>
              </div>
            </button>

            <div class="w-px bg-white/10 hidden sm:block mx-1 my-2" />

            <button
              type="button"
              class="flex-1 flex items-center gap-3 px-4 py-3 hover:bg-white/10 rounded-2xl transition-all duration-300 text-left group"
              @click="showDatePicker = !showDatePicker; showLocationPicker = false; showFilters = false"
            >
              <div class="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center shrink-0 group-hover:scale-110 transition-transform duration-300">
                <Calendar class="w-5 h-5 text-brand-orange" />
              </div>
              <div>
                <div class="text-[10px] font-bold uppercase tracking-wider text-slate-400 group-hover:text-slate-300 transition-colors">
                  {{ searchUi.datesLabel }}
                </div>
                <div class="font-semibold text-sm text-white">
                  {{ dateRange?.from ? format(dateRange.from, 'MMM d') : searchUi.pickupPlaceholderLabel }} -
                  {{ dateRange?.to ? format(dateRange.to, 'MMM d') : searchUi.dropoffPlaceholderLabel }}
                </div>
              </div>
            </button>

            <AnimatePresence>
              <motion.div
                v-if="showLocationPicker"
                :initial="{ opacity: 0, y: 10, scale: 0.95 }"
                :animate="{ opacity: 1, y: 0, scale: 1 }"
                :exit="{ opacity: 0, y: 10, scale: 0.95 }"
                :transition="{ duration: 0.2 }"
                class="absolute top-full left-0 mt-4 w-full sm:w-72 bg-white rounded-2xl shadow-2xl border border-slate-100 p-2 z-50 text-slate-900"
              >
                <button
                  v-for="location in locations"
                  :key="location.id"
                  type="button"
                  :class="[
                    'w-full text-left px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200',
                    pickupLocation?.id === location.id
                      ? 'bg-brand-orange/10 text-brand-orange font-bold'
                      : 'text-slate-700 hover:bg-slate-50 hover:pl-5',
                  ]"
                  @click="applyLocation(location)"
                >
                  {{ location.name }}
                </button>
              </motion.div>
            </AnimatePresence>

            <AnimatePresence>
              <motion.div
                v-if="showDatePicker"
                :initial="{ opacity: 0, y: 10, scale: 0.95 }"
                :animate="{ opacity: 1, y: 0, scale: 1 }"
                :exit="{ opacity: 0, y: 10, scale: 0.95 }"
                :transition="{ duration: 0.2 }"
                class="absolute top-full right-0 mt-4 bg-white rounded-3xl shadow-2xl border border-slate-100 p-4 z-50 text-slate-900 w-max"
              >
                <AppCalendar
                  mode="range"
                  :selected="dateRange"
                  :number-of-months="1"
                  :disabled="{ before: new Date() }"
                  class="font-sans"
                  @select="(range) => dateRange = range"
                />
                <div class="mt-4 flex justify-end">
                  <button
                  type="button"
                  class="px-6 py-2 bg-slate-900 text-white rounded-xl text-sm font-bold hover:bg-brand-orange transition-colors shadow-lg shadow-slate-900/20"
                  @click="applyDates"
                >
                    {{ searchUi.applyDatesLabel }}
                </button>
              </div>
            </motion.div>
            </AnimatePresence>
          </div>

          <div class="flex items-center gap-2 w-full lg:w-auto px-2 lg:px-0">
            <div class="flex-1 lg:w-auto overflow-x-auto hide-scrollbar flex items-center gap-2 py-2 lg:py-0">
              <button
                v-for="type in typeOptions"
                :key="type"
                type="button"
                :class="[
                  'px-5 py-3 rounded-2xl text-sm font-semibold whitespace-nowrap transition-all duration-300',
                  activeType === type
                    ? 'bg-brand-orange text-white shadow-[0_0_20px_rgba(249,115,22,0.3)]'
                    : 'bg-white/5 text-slate-300 hover:bg-white/10 hover:text-white',
                ]"
                @click="activeType = type"
              >
                {{ type }}
              </button>
            </div>

            <button
              type="button"
              :class="[
                'w-12 h-12 shrink-0 rounded-2xl flex items-center justify-center transition-all duration-300',
                showFilters
                  ? 'bg-white text-slate-900 shadow-[0_0_20px_rgba(255,255,255,0.2)]'
                  : 'bg-white/5 text-slate-300 hover:bg-white/10 hover:text-white',
              ]"
              @click="showFilters = !showFilters; showDatePicker = false; showLocationPicker = false"
            >
              <SlidersHorizontal class="w-5 h-5" />
            </button>
          </div>
        </div>

        <AnimatePresence>
          <motion.div
            v-if="showFilters"
            :initial="{ opacity: 0, y: -20, height: 0 }"
            :animate="{ opacity: 1, y: 0, height: 'auto' }"
            :exit="{ opacity: 0, y: -20, height: 0 }"
            class="overflow-hidden mt-4"
          >
            <div class="bg-white/60 backdrop-blur-xl rounded-[2rem] p-6 lg:p-8 shadow-xl shadow-slate-200/50 border border-white/60 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              <div class="space-y-8">
                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.brandLabel }}
                  </h3>
                  <div class="flex flex-wrap gap-2">
                    <button
                      v-for="brand in brandOptions"
                      :key="brand"
                      type="button"
                      :class="[
                        'px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-300',
                        activeBrand === brand
                          ? 'bg-slate-900 text-white shadow-md'
                          : 'bg-white/40 backdrop-blur-md text-slate-600 hover:bg-white/60 border border-white/60',
                      ]"
                      @click="activeBrand = brand"
                    >
                      {{ brand }}
                    </button>
                  </div>
                </div>

                <div>
                  <div class="flex items-center justify-between mb-4">
                    <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400">
                      {{ searchUi.maxPriceLabel }}
                    </h3>
                    <span class="text-sm font-bold text-slate-900">
                      ${{ priceRange }}
                    </span>
                  </div>
                  <input
                    v-model.number="priceRange"
                    type="range"
                    :min="DEFAULT_PRICE_MIN"
                    :max="priceRangeLimit"
                    step="50"
                    class="w-full accent-brand-orange"
                  >
                  <div class="flex justify-between text-[10px] text-slate-400 font-bold uppercase tracking-wider mt-2">
                    <span>${{ DEFAULT_PRICE_MIN }}</span>
                    <span>${{ priceRangeLimit }}+</span>
                  </div>
                </div>
              </div>

              <div class="space-y-8">
                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.seatsLabel }}
                  </h3>
                  <div class="flex flex-wrap gap-2">
                    <button
                      v-for="seat in seatOptions"
                      :key="seat"
                      type="button"
                      :class="[
                        'px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-300',
                        selectedSeats === seat
                          ? 'bg-slate-900 text-white shadow-md'
                          : 'bg-white/40 backdrop-blur-md text-slate-600 hover:bg-white/60 border border-white/60',
                      ]"
                      @click="selectedSeats = seat"
                    >
                      {{ seat }}
                    </button>
                  </div>
                </div>

                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.transmissionLabel }}
                  </h3>
                  <div class="flex flex-wrap gap-2">
                    <button
                      v-for="transmission in transmissionOptions"
                      :key="transmission"
                      type="button"
                      :class="[
                        'px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-300',
                        selectedTransmission === transmission
                          ? 'bg-slate-900 text-white shadow-md'
                          : 'bg-white/40 backdrop-blur-md text-slate-600 hover:bg-white/60 border border-white/60',
                      ]"
                      @click="selectedTransmission = transmission"
                    >
                      {{ transmission }}
                    </button>
                  </div>
                </div>

                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.engineLabel }}
                  </h3>
                  <div class="flex flex-wrap gap-2">
                    <button
                      v-for="engine in engineOptions"
                      :key="engine"
                      type="button"
                      :class="[
                        'px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-300',
                        selectedEngine === engine
                          ? 'bg-slate-900 text-white shadow-md'
                          : 'bg-white/40 backdrop-blur-md text-slate-600 hover:bg-white/60 border border-white/60',
                      ]"
                      @click="selectedEngine = engine"
                    >
                      {{ engine }}
                    </button>
                  </div>
                </div>
              </div>

              <div class="space-y-8">
                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.featuresLabel }}
                  </h3>
                  <div class="flex flex-col gap-3">
                    <label
                      v-for="option in optionFilters"
                      :key="option"
                      class="flex items-center gap-3 cursor-pointer group"
                    >
                      <div
                        :class="[
                          'w-5 h-5 rounded border flex items-center justify-center transition-colors',
                          selectedOptions.includes(option)
                            ? 'bg-brand-orange border-brand-orange text-white'
                            : 'border-white/60 bg-white/40 backdrop-blur-md group-hover:border-brand-orange',
                        ]"
                      >
                        <Check v-if="selectedOptions.includes(option)" class="w-3 h-3" />
                      </div>
                      <span class="text-sm font-medium text-slate-700 group-hover:text-slate-900">
                        {{ option }}
                      </span>
                      <input
                        type="checkbox"
                        class="hidden"
                        :checked="selectedOptions.includes(option)"
                        @change="($event) => { if ($event.target.checked) { selectedOptions = [...selectedOptions, option] } else { selectedOptions = selectedOptions.filter((entry) => entry !== option) } }"
                      >
                    </label>
                  </div>
                </div>

                <div>
                  <h3 class="text-xs font-bold uppercase tracking-wider text-slate-400 mb-4">
                    {{ searchUi.conditionsLabel }}
                  </h3>
                  <div class="flex flex-col gap-3">
                    <label
                      v-for="condition in conditionFilters"
                      :key="condition"
                      class="flex items-center gap-3 cursor-pointer group"
                    >
                      <div
                        :class="[
                          'w-5 h-5 rounded border flex items-center justify-center transition-colors',
                          selectedConditions.includes(condition)
                            ? 'bg-brand-orange border-brand-orange text-white'
                            : 'border-white/60 bg-white/40 backdrop-blur-md group-hover:border-brand-orange',
                        ]"
                      >
                        <Check v-if="selectedConditions.includes(condition)" class="w-3 h-3" />
                      </div>
                      <span class="text-sm font-medium text-slate-700 group-hover:text-slate-900">
                        {{ condition }}
                      </span>
                      <input
                        type="checkbox"
                        class="hidden"
                        :checked="selectedConditions.includes(condition)"
                        @change="($event) => { if ($event.target.checked) { selectedConditions = [...selectedConditions, condition] } else { selectedConditions = selectedConditions.filter((entry) => entry !== condition) } }"
                      >
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
        </AnimatePresence>
      </div>
    </div>

    <main class="max-w-6xl mx-auto px-4">
      <div class="flex items-center justify-between mb-6 relative">
        <div>
          <h2 class="text-lg font-bold text-slate-900">
            {{ resultsLabel }}
          </h2>
          <p v-if="catalogError" class="text-xs text-red-500 mt-1 flex items-center gap-1.5">
            <AlertCircle class="w-3.5 h-3.5" /> {{ catalogError }}
          </p>
        </div>

        <div class="relative">
          <button
            type="button"
            class="flex items-center gap-2 text-sm text-slate-500 font-medium hover:text-brand-orange transition-colors"
            @click="showSortDropdown = !showSortDropdown"
          >
            {{ searchUi.sortByLabel }}: <span class="text-slate-900">{{ selectedSortLabel }}</span>
            <ChevronDown class="w-4 h-4" />
          </button>

          <AnimatePresence>
            <motion.div
              v-if="showSortDropdown"
              :initial="{ opacity: 0, y: 10 }"
              :animate="{ opacity: 1, y: 0 }"
              :exit="{ opacity: 0, y: 10 }"
              class="absolute top-full right-0 mt-2 w-48 bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl border border-white/60 py-2 z-30"
            >
              <button
                v-for="option in searchSortOptions"
                :key="option.value"
                type="button"
                :class="[
                  'w-full text-left px-4 py-2 text-sm font-medium transition-colors',
                  sortBy === option.value ? 'bg-brand-orange/10 text-brand-orange' : 'text-slate-700 hover:bg-slate-50',
                ]"
                @click="sortBy = option.value; showSortDropdown = false"
              >
                {{ option.label }}
              </button>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>

      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <template v-if="showSkeletons">
          <SearchSkeletonCard
            v-for="index in 8"
            :key="`skeleton-${index}`"
          />
        </template>

        <template v-else>
          <AnimatePresence mode="popLayout">
            <template
              v-for="(car, index) in filteredCars"
              :key="car.id"
            >
              <motion.div
                v-if="index === 4"
                key="secret-deals-banner"
                :initial="{ opacity: 0, y: 20 }"
                :animate="{ opacity: 1, y: 0 }"
                class="col-span-full my-4"
              >
                <div class="bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 rounded-[2rem] p-8 md:p-10 flex flex-col md:flex-row items-center justify-between gap-8 shadow-2xl shadow-slate-900/20 relative overflow-hidden border border-white/10">
                  <div class="absolute top-0 right-0 w-96 h-96 bg-brand-orange/20 rounded-full blur-[100px] -translate-y-1/2 translate-x-1/3 pointer-events-none" />
                  <div class="absolute bottom-0 left-0 w-64 h-64 bg-blue-500/20 rounded-full blur-[80px] translate-y-1/2 -translate-x-1/3 pointer-events-none" />

                  <div class="relative z-10 flex items-start md:items-center gap-5">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-brand-orange to-amber-500 flex items-center justify-center shrink-0 shadow-lg shadow-brand-orange/30">
                      <Tag class="w-7 h-7 text-white" />
                    </div>
                    <div>
                      <h3 class="text-2xl font-display font-bold text-white mb-2 tracking-tight">
                        {{ searchPromo.title }}
                      </h3>
                      <p class="text-slate-300 text-sm max-w-md leading-relaxed">
                        {{ searchPromo.descriptionPrefix }}
                        <span class="text-brand-orange font-bold"> {{ searchPromo.accentLabel }} </span>
                        {{ searchPromo.descriptionSuffix }}
                      </p>
                    </div>
                  </div>

                  <div class="relative z-10 flex flex-col sm:flex-row gap-3 w-full md:w-auto shrink-0">
                    <NuxtLink
                      v-if="searchPromo.primaryHref"
                      :to="searchPromo.primaryHref"
                      class="px-8 py-3.5 rounded-xl font-bold transition-all shadow-lg shadow-brand-orange/20 bg-brand-orange text-white hover:bg-brand-orange/90 hover:shadow-brand-orange/40 hover:-translate-y-0.5 text-center"
                    >
                      {{ searchPromo.primaryLabel }}
                    </NuxtLink>
                    <button
                      v-else
                      type="button"
                      disabled
                      class="px-8 py-3.5 rounded-xl font-bold transition-all shadow-lg shadow-brand-orange/20 bg-brand-orange text-white cursor-default"
                    >
                      {{ searchPromo.primaryLabel }}
                    </button>

                    <NuxtLink
                      v-if="searchPromo.secondaryHref"
                      :to="searchPromo.secondaryHref"
                      class="px-8 py-3.5 rounded-xl font-bold transition-all border bg-white/10 text-white border-white/5 hover:bg-white/20 hover:border-white/20 text-center"
                    >
                      {{ searchPromo.secondaryLabel }}
                    </NuxtLink>
                    <button
                      v-else
                      type="button"
                      disabled
                      class="px-8 py-3.5 rounded-xl font-bold transition-all border bg-white/10 text-white border-white/5 cursor-default"
                    >
                      {{ searchPromo.secondaryLabel }}
                    </button>
                  </div>
                </div>
              </motion.div>

              <SearchCarCard
                :car="car"
                :index="index"
                :is-comparing="compareList.some((entry) => entry.id === car.id)"
                :date-range="dateRange"
                :can-book="Boolean(resolveSelectedVehicleId(car))"
                @compare="toggleCompare"
                @book="bookVehicle"
              />
            </template>
          </AnimatePresence>
        </template>

        <div
          v-if="filteredCars.length === 0 && !showSkeletons"
          class="col-span-full py-20 text-center"
        >
          <div class="w-24 h-24 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <Search class="w-10 h-10 text-slate-400" />
          </div>
          <h3 class="text-2xl font-display font-bold text-slate-900 mb-2">
            {{ searchUi.emptyTitle }}
          </h3>
          <p class="text-slate-500 max-w-md mx-auto">
            {{ searchUi.emptyDescription }}
          </p>
          <button
            type="button"
            class="mt-8 px-6 py-3 bg-slate-900 text-white rounded-full font-bold hover:bg-brand-orange transition-colors"
            @click="clearFilters"
          >
            {{ searchUi.clearFiltersLabel }}
          </button>
        </div>
      </div>
    </main>

    <SearchCompareBar
      :compare-list="compareList"
      :notice="compareNotice"
      @clear="compareList = []"
      @open="showCompareModal = true"
      @remove="toggleCompare"
    />

    <SearchCompareModal
      :open="showCompareModal"
      :compare-list="compareList"
      @close="showCompareModal = false"
      @remove="(car) => { toggleCompare(car); if (compareList.length < 2) { showCompareModal = false } }"
      @book="bookVehicle"
      @browse="showCompareModal = false"
    />
  </div>
</template>
