<script setup>
import { motion } from 'motion-v'
import {
  Baby,
  Briefcase,
  Car,
  Gauge,
  MapPin,
  Mountain,
  Search,
  Settings2,
  ShieldCheck,
  Zap,
} from 'lucide-vue-next'
import { useVehiclesContent } from '~/content/vehicles'
import FleetVehicleCard from '~/components/vehicles/FleetVehicleCard.vue'
import { buildPublicSeoLinks } from '~/utils/public-seo'

const activeCategory = ref('All')
const activeUseCase = ref(null)
const searchQuery = ref('')
const sortBy = ref('recommended')
const { locale } = usePublicLocale()
const runtimeConfig = useRuntimeConfig()
const vehiclesContent = useVehiclesContent()
const vehiclesPage = computed(() => vehiclesContent.vehiclesPage.value || null)
const fleetCategoryOptions = computed(() => vehiclesContent.fleetCategories.value || [])
const fleetUseCases = computed(() => vehiclesContent.fleetUseCases.value || [])
const fleetVehicles = computed(() => vehiclesContent.fleetVehicles.value || [])
const vehicleCatalogUi = computed(() => vehiclesContent.vehicleCatalogUi.value || {})
const vehicleSortOptions = computed(() => vehiclesContent.vehicleSortOptions.value || [])
const vehicleTrustCards = computed(() => vehiclesContent.vehicleTrustCards.value || [])

const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const vehiclesPageSeo = computed(() => {
  const page = vehiclesPage.value
  const localizedPath = page?.path || ''
  const localized = Array.isArray(page?.localized) ? page.localized : []
  const hreflang = Array.isArray(page?.seo?.hreflang) && page.seo.hreflang.length
    ? page.seo.hreflang
    : localized
      .filter((entry) => entry?.locale && (entry?.href || entry?.path))
      .map((entry) => ({
        locale: entry.locale,
        href: entry.href || `${pageOrigin.value}${entry.path}`,
      }))

  return {
    title: page?.seo?.title || `${page?.title || 'Fleet'} | bent.ge`,
    description: page?.seo?.description || page?.excerpt || '',
    ogTitle: page?.seo?.ogTitle || page?.seo?.title || page?.title || '',
    ogDescription: page?.seo?.ogDescription || page?.seo?.description || page?.excerpt || '',
    ogImage: page?.seo?.ogImage || page?.heroImage || page?.featuredImage || '',
    canonical: page?.seo?.canonical || (localizedPath ? `${pageOrigin.value}${localizedPath}` : ''),
    hreflang,
    xDefault: page?.seo?.xDefault || localized.find((entry) => entry?.locale === 'en')?.href || '',
    robots: page?.seo?.robots || 'index,follow',
  }
})

const useCaseIcons = {
  city: MapPin,
  mountain: Mountain,
  family: Baby,
  business: Briefcase,
}

const trustCardIcons = {
  'shield-check': ShieldCheck,
  gauge: Gauge,
  'map-pin': MapPin,
}
const priceBounds = computed(() => {
  const prices = fleetVehicles.value
    .map((car) => Number(car?.price || 0))
    .filter((price) => Number.isFinite(price) && price > 0)

  if (!prices.length) {
    return {
      min: 20,
      max: 200,
    }
  }

  return {
    min: Math.min(...prices),
    max: Math.max(...prices),
  }
})

const minPrice = ref(priceBounds.value.min)
const maxPrice = ref(priceBounds.value.max)

watch(priceBounds, (bounds) => {
  if (!Number.isFinite(minPrice.value) || minPrice.value < bounds.min || minPrice.value > bounds.max) {
    minPrice.value = bounds.min
  }

  if (!Number.isFinite(maxPrice.value) || maxPrice.value > bounds.max || maxPrice.value < bounds.min) {
    maxPrice.value = bounds.max
  }

  if (minPrice.value > maxPrice.value) {
    minPrice.value = bounds.min
    maxPrice.value = bounds.max
  }
}, { immediate: true })

useSeoMeta({
  title: () => vehiclesPageSeo.value.title,
  description: () => vehiclesPageSeo.value.description,
  ogTitle: () => vehiclesPageSeo.value.ogTitle,
  ogDescription: () => vehiclesPageSeo.value.ogDescription,
  ogImage: () => vehiclesPageSeo.value.ogImage,
  robots: () => vehiclesPageSeo.value.robots,
})

useHead(() => ({
  link: buildPublicSeoLinks(vehiclesPageSeo.value),
}))

const resultsLabel = computed(() => vehiclesContent.formatVehicleResultsLabel(filteredVehicles.value.length))

const filteredVehicles = computed(() => {
  const baseMatches = fleetVehicles.value.filter((car) => {
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      if (!car.brand.toLowerCase().includes(query) && !car.model.toLowerCase().includes(query)) {
        return false
      }
    }

    if (activeCategory.value !== 'All' && car.category !== activeCategory.value) {
      return false
    }

    if (activeUseCase.value && !car.useCases.includes(activeUseCase.value)) {
      return false
    }

    return true
  })

  const ranged = baseMatches.filter((car) => {
    const price = Number(car.price || 0)

    return price >= minPrice.value && price <= maxPrice.value
  })

  const source = ranged.length
    ? ranged
    : baseMatches.length
      ? [...baseMatches].sort((left, right) => {
        const leftDistance = Math.abs(Number(left.price || 0) - maxPrice.value)
        const rightDistance = Math.abs(Number(right.price || 0) - maxPrice.value)

        if (leftDistance !== rightDistance) {
          return leftDistance - rightDistance
        }

        return Number(left.price || 0) - Number(right.price || 0)
      }).slice(0, 3)
      : []

  if (sortBy.value === 'price-low') {
    source.sort((left, right) => left.price - right.price)
  } else if (sortBy.value === 'price-high') {
    source.sort((left, right) => right.price - left.price)
  } else if (sortBy.value === 'rating') {
    source.sort((left, right) => right.rating - left.rating)
  }

  return source
})

const minPriceLabel = computed(() => vehicleCatalogUi.value.minPriceLabel || 'Min Price')
const maxPriceLabel = computed(() => vehicleCatalogUi.value.maxPriceLabel || 'Max Price')

function resetFilters() {
  searchQuery.value = ''
  activeCategory.value = 'All'
  activeUseCase.value = null
}
</script>

<template>
  <div class="min-h-screen font-sans text-slate-900 flex flex-col relative overflow-hidden">
    <main class="flex-1 flex flex-col relative z-10">
      <section class="relative pt-12 pb-20 overflow-hidden">
        <div class="max-w-6xl mx-auto px-4 sm:px-6 relative z-10">
          <div class="text-center max-w-3xl mx-auto mb-12">
            <motion.div
              :initial="{ opacity: 0, y: 20 }"
              :animate="{ opacity: 1, y: 0 }"
              class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/60 backdrop-blur-md border border-white/60 shadow-sm mb-6"
            >
              <Car class="w-4 h-4 text-brand-orange" />
              <span class="text-xs font-bold uppercase tracking-widest text-slate-700">{{ vehicleCatalogUi.heroBadge }}</span>
            </motion.div>
            <motion.h1
              :initial="{ opacity: 0, y: 20 }"
              :animate="{ opacity: 1, y: 0 }"
              :transition="{ delay: 0.1 }"
              class="text-4xl md:text-5xl lg:text-6xl font-display font-black text-slate-900 tracking-tight uppercase leading-[1.1] mb-6"
            >
              <template v-if="vehicleCatalogUi.heroTitleLead">
                {{ vehicleCatalogUi.heroTitleLead }} <br>
                <span class="text-brand-orange">{{ vehicleCatalogUi.heroTitleAccent }}</span>
              </template>
              <template v-else>
                <span class="text-brand-orange">{{ vehicleCatalogUi.heroTitleAccent }}</span>
              </template>
            </motion.h1>
            <motion.p
              :initial="{ opacity: 0, y: 20 }"
              :animate="{ opacity: 1, y: 0 }"
              :transition="{ delay: 0.2 }"
              class="text-slate-500 text-lg font-light"
            >
              {{ vehicleCatalogUi.heroDescription }}
            </motion.p>

          </div>

          <motion.div
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.3 }"
            class="max-w-5xl mx-auto"
          >
            <div class="bg-white/60 backdrop-blur-2xl rounded-[2.5rem] p-3 sm:p-6 md:p-8 shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-white/60">
              <div class="relative mb-4 sm:mb-8">
                <div class="absolute inset-y-0 left-4 sm:left-6 flex items-center pointer-events-none">
                  <Search class="w-5 h-5 text-slate-400" />
                </div>
                <input
                  v-model="searchQuery"
                  type="text"
                  :placeholder="vehicleCatalogUi.searchPlaceholder"
                  class="w-full bg-white/50 border border-white/60 backdrop-blur-md rounded-2xl py-3 sm:py-4 pl-12 sm:pl-14 pr-4 sm:pr-6 text-slate-900 font-medium placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-orange/20 focus:bg-white/80 transition-all shadow-inner"
                >
              </div>

              <div>
                <div class="flex items-center gap-2 mb-4">
                  <Zap class="w-4 h-4 text-brand-orange" />
                  <h3 class="text-sm font-bold uppercase tracking-wider text-slate-900">{{ vehicleCatalogUi.journeyTitle }}</h3>
                </div>
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-4">
                  <button
                    v-for="useCase in fleetUseCases"
                    :key="useCase.id"
                    :class="[
                      'flex items-center gap-2.5 p-2.5 sm:flex-col sm:items-start sm:gap-0 sm:p-4 rounded-2xl border transition-all duration-300 text-left group min-h-[76px] sm:min-h-0',
                      activeUseCase === useCase.id
                        ? 'bg-white/80 backdrop-blur-md border-brand-orange/30 ring-1 ring-brand-orange/20 shadow-md'
                        : 'bg-white/40 backdrop-blur-md border-white/60 hover:border-white hover:bg-white/60 hover:shadow-md',
                    ]"
                    @click="activeUseCase = activeUseCase === useCase.id ? null : useCase.id"
                  >
                    <div
                      :class="[
                        'w-9 h-9 rounded-xl flex items-center justify-center shrink-0 sm:mb-3 transition-colors shadow-sm',
                        activeUseCase === useCase.id ? 'bg-brand-orange text-white' : 'bg-white/80 text-slate-500 group-hover:text-brand-orange',
                      ]"
                    >
                      <component :is="useCaseIcons[useCase.id]" class="w-4 h-4" />
                    </div>
                    <div class="min-w-0">
                      <h4 :class="['font-bold text-sm sm:mb-1', activeUseCase === useCase.id ? 'text-brand-orange' : 'text-slate-900']">
                        {{ useCase.label }}
                      </h4>
                      <p class="hidden sm:block text-[11px] text-slate-500 font-medium leading-relaxed">
                        {{ useCase.desc }}
                      </p>
                    </div>
                  </button>
                </div>
              </div>
            </div>
          </motion.div>
        </div>
      </section>

      <section class="pb-24 flex-1">
        <div class="max-w-6xl mx-auto px-4 sm:px-6">
      <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-6 mb-10">
            <div class="bg-white/40 backdrop-blur-md border border-white/60 p-1.5 rounded-2xl shadow-sm inline-flex overflow-x-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
              <button
                v-for="category in fleetCategoryOptions"
                :key="category.value"
                :class="[
                  'py-2.5 px-6 rounded-xl text-xs font-bold tracking-wider uppercase transition-all whitespace-nowrap',
                  activeCategory === category.value ? 'bg-white shadow-md text-slate-900' : 'text-slate-600 hover:bg-white/40 hover:text-slate-900',
                ]"
                @click="activeCategory = category.value; activeUseCase = null"
              >
                {{ category.label }}
              </button>
            </div>

            <div class="flex flex-wrap items-center gap-4">
              <div class="flex flex-col gap-3 bg-white/60 backdrop-blur-md border border-white/60 rounded-xl px-4 py-3 shadow-sm min-w-[280px]">
                <div class="flex items-center justify-between gap-3">
                  <span class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ minPriceLabel }}:</span>
                  <span class="text-sm font-bold text-slate-900 w-12 text-right">${{ minPrice }}</span>
                </div>
                <input
                  v-model.number="minPrice"
                  type="range"
                  :min="priceBounds.min"
                  :max="maxPrice"
                  step="10"
                  class="w-full accent-brand-orange"
                >
                <div class="flex items-center justify-between gap-3">
                  <span class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ maxPriceLabel }}:</span>
                  <span class="text-sm font-bold text-slate-900 w-12 text-right">${{ maxPrice }}</span>
                </div>
                <input
                  v-model.number="maxPrice"
                  type="range"
                  :min="minPrice"
                  :max="priceBounds.max"
                  step="10"
                  class="w-full accent-brand-orange"
                >
              </div>

              <div class="flex items-center gap-3 bg-white/60 backdrop-blur-md border border-white/60 rounded-xl px-4 py-2 shadow-sm">
                <span class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ vehicleCatalogUi.sortByLabel }}:</span>
                <select v-model="sortBy" class="text-sm font-bold text-slate-900 bg-transparent focus:outline-none cursor-pointer">
                  <option
                    v-for="option in vehicleSortOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </option>
                </select>
              </div>

              <div class="flex items-center gap-2 text-sm font-medium text-slate-500 ml-2">
                <Settings2 class="w-4 h-4" />
                <span><strong class="text-slate-900">{{ filteredVehicles.length }}</strong> {{ resultsLabel.replace(`${filteredVehicles.length} `, '') }}</span>
              </div>
            </div>
          </div>

          <div class="relative min-h-[36rem] lg:min-h-[42rem]">
            <TransitionGroup
              name="vehicle-grid"
              tag="div"
              class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
            >
              <FleetVehicleCard
                v-for="(car, index) in filteredVehicles"
                :key="car.id"
                :vehicle="car"
                :smart-match="Boolean(activeUseCase && car.useCases.includes(activeUseCase))"
              />
            </TransitionGroup>

            <div v-if="filteredVehicles.length === 0" class="col-span-full py-20 text-center flex flex-col items-center">
              <div class="w-20 h-20 bg-slate-100 rounded-full flex items-center justify-center mb-6">
                <Search class="w-8 h-8 text-slate-400" />
              </div>
              <h3 class="text-2xl font-display font-bold text-slate-900 mb-2">{{ vehicleCatalogUi.emptyTitle }}</h3>
              <p class="text-slate-500 max-w-md">
                {{ vehicleCatalogUi.emptyDescription }}
              </p>
              <button
                class="mt-8 px-6 py-3 bg-slate-900 text-white rounded-xl font-bold uppercase tracking-wider text-xs hover:bg-brand-orange transition-colors"
                @click="resetFilters"
              >
                {{ vehicleCatalogUi.clearFiltersLabel }}
              </button>
            </div>
          </div>
        </div>
      </section>

      <section class="bg-slate-900 text-white py-16 mt-auto">
        <div class="max-w-6xl mx-auto px-4 sm:px-6">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-8 text-center divide-y md:divide-y-0 md:divide-x divide-white/10">
            <div
              v-for="card in vehicleTrustCards"
              :key="card.title"
              class="flex flex-col items-center px-4 py-4 md:py-0"
            >
              <component :is="trustCardIcons[card.iconKey] || ShieldCheck" class="w-10 h-10 text-brand-orange mb-4" />
              <h4 class="text-lg font-bold mb-2">{{ card.title }}</h4>
              <p class="text-sm text-slate-400">{{ card.description }}</p>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<style scoped>
.vehicle-grid-enter-active,
.vehicle-grid-leave-active,
.vehicle-grid-move {
  transition:
    transform 280ms ease,
    opacity 220ms ease;
}

.vehicle-grid-enter-from,
.vehicle-grid-leave-to {
  opacity: 0;
  transform: translateY(14px) scale(0.985);
}

.vehicle-grid-leave-active {
  position: absolute;
  width: calc(25% - 1.125rem);
}

@media (max-width: 1279px) {
  .vehicle-grid-leave-active {
    width: calc(33.333% - 1rem);
  }
}

@media (max-width: 1023px) {
  .vehicle-grid-leave-active {
    width: calc(50% - 0.75rem);
  }
}

@media (max-width: 767px) {
  .vehicle-grid-leave-active {
    width: 100%;
  }
}
</style>
