<script setup>
import { AnimatePresence, motion } from 'motion-v'
import {
  AlertCircle,
  ArrowRight,
  Calendar,
  Check,
  ChevronDown,
  Clock,
  MapPin,
  ShieldCheck,
  Tag,
} from 'lucide-vue-next'
import { differenceInDays, format } from 'date-fns'
import HeroTimePopover from '~/components/home/hero/HeroTimePopover.vue'
import AppCalendar from '~/components/shared/AppCalendar.vue'
import { resolvePublicApiError } from '~/content/utils'
import { resolveOfferForVehicleGroupId, useOffersContent } from '~/content/offers'
import { resolveOfferPricingTierForDays } from '~/content/offer-pricing'
import { useVehiclesContent } from '~/content/vehicles'
import { buildRentExtrasRoute, buildRentTripQuery, RENT_TRIP_QUERY_KEYS } from '~/utils/public-routes'

const props = defineProps({
  car: {
    type: Object,
    required: true,
  },
})

const route = useRoute()
const { locale } = usePublicLocale()
const vehiclesContent = useVehiclesContent()
const offersContent = useOffersContent()
const { baseDay, buildDate } = usePublicDateDefaults()
const { activeOfferSlug } = usePublicOfferContext()

const builderRef = ref(null)
const activePopover = ref(null)
const pickupLocation = ref(null)
const dropoffLocation = ref(null)
const returnToSameLocation = ref(true)
const pickupTime = ref('12:30')
const dropoffTime = ref('08:30')
const dateRange = ref({
  from: buildDate(0),
  to: buildDate(3),
})
const quoteData = ref(null)
const quoteError = ref('')
const isLoadingQuote = ref(false)
const quoteRequestId = ref(0)
const hasHydratedState = ref(false)

const { locations, loadLocations } = usePublicSiteLocations()
const { currency } = usePublicPreferences()
const { buildCatalogPayload, parseSearchQuery } = useSearchCatalog()
const { fetchQuote } = usePublicBooking()
const vehicleBookingBuilderUi = computed(() => vehiclesContent.vehicleBookingBuilderUi.value || {})
const vehicleDetailUi = computed(() => vehiclesContent.vehicleDetailUi.value || {})
const vehicleGroupId = computed(() => Number(props.car?.vehicleGroupId || 0) || null)
const offerCards = computed(() => offersContent.offerCards.value || [])
const resolvedOfferBySlug = offersContent.useResolvedOffer(activeOfferSlug)
const activeOffer = computed(() => {
  if (resolvedOfferBySlug.value) {
    return resolvedOfferBySlug.value
  }

  return resolveOfferForVehicleGroupId(offerCards.value, vehicleGroupId.value)
})
const offerPricingTier = computed(() => resolveOfferPricingTierForDays(activeOffer.value || {}, selectedDays.value))

const effectiveDropoffLocation = computed(() => {
  return returnToSameLocation.value ? pickupLocation.value : dropoffLocation.value
})

const selectedDays = computed(() => {
  if (quoteSummary.value?.days) {
    return Number(quoteSummary.value.days)
  }

  if (!dateRange.value?.from || !dateRange.value?.to) {
    return 1
  }

  return Math.max(1, differenceInDays(dateRange.value.to, dateRange.value.from))
})

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

  return buildCatalogPayload({
    pickupLocationId: pickupLocation.value.backendId,
    dropoffLocationId: effectiveDropoffLocation.value.backendId,
    pickupDate: dateRange.value.from,
    dropoffDate: dateRange.value.to,
    pickupTime: pickupTime.value,
    dropoffTime: dropoffTime.value,
    currency: currency.value,
    promoCode: String(route.query.promoCode || ''),
    offerSlug: activeOffer.value?.slug || activeOfferSlug.value || undefined,
  })
})

const quotePayload = computed(() => {
  if (!currentPayload.value || !vehicleGroupId.value) {
    return null
  }

  return {
    ...currentPayload.value,
    vehicle_group_id: vehicleGroupId.value,
    extras: [],
  }
})

const tripQuery = computed(() => {
  return buildRentTripQuery({
    pickupLocationId: pickupLocation.value?.backendId || undefined,
    dropoffLocationId: effectiveDropoffLocation.value?.backendId || pickupLocation.value?.backendId || undefined,
    pickupAt: currentPayload.value?.pickup_at,
    dropoffAt: currentPayload.value?.dropoff_at,
    promoCode: String(route.query.promoCode || '') || undefined,
    returnToSameLocation: returnToSameLocation.value ? '1' : '0',
    driverAge: route.query.driverAge || undefined,
  })
})

const extrasRoute = computed(() => buildRentExtrasRoute(vehicleGroupId.value, tripQuery.value, {
  locale: locale.value,
}))
const quoteSummary = computed(() => quoteData.value?.quote || null)
const summaryLines = computed(() => {
  return (quoteSummary.value?.lines || []).filter((line) => Number(line?.amount || 0) !== 0)
})
const currencyCode = computed(() => quoteSummary.value?.currency || currency.value || 'USD')
const canContinue = computed(() => {
  return Boolean(vehicleGroupId.value && currentPayload.value && quoteSummary.value && !isLoadingQuote.value && !quoteError.value)
})
const liveRateBandLabel = computed(() => {
  if (offerPricingTier.value?.label) {
    return offerPricingTier.value.label
  }

  if (quoteSummary.value?.rateBand?.name) {
    return quoteSummary.value.rateBand.name
  }

  return `${selectedDays.value} ${selectedDays.value === 1 ? vehicleDetailUi.value.daySingularLabel : vehicleDetailUi.value.dayPluralLabel}`
})
const headerPriceLabel = computed(() => {
  const discountedDailyRate = Number(offerPricingTier.value?.newPrice || 0)

  if (discountedDailyRate > 0) {
    return formatMoney(discountedDailyRate)
  }

  if (!quoteSummary.value?.dailyRate) {
    return null
  }

  return formatMoney(quoteSummary.value.dailyRate)
})
const totalLabel = computed(() => {
  const discountedDailyRate = Number(offerPricingTier.value?.newPrice || 0)

  if (discountedDailyRate > 0) {
    return formatMoney(discountedDailyRate * selectedDays.value)
  }

  if (!quoteSummary.value?.finalTotal) {
    return null
  }

  return formatMoney(quoteSummary.value.finalTotal)
})
const depositLabel = computed(() => {
  const amount = Number(quoteSummary.value?.depositAmount || 0)
  return amount > 0 ? formatMoney(amount) : '—'
})
const dueAfterApprovalLabel = computed(() => {
  const amount = Number(quoteSummary.value?.prepaymentAmount || 0)
  return amount > 0 ? formatMoney(amount) : '—'
})
const pickupLocationLabel = computed(() => pickupLocation.value?.name || vehicleBookingBuilderUi.value.selectLocationLabel)
const dropoffLocationLabel = computed(() => effectiveDropoffLocation.value?.name || vehicleBookingBuilderUi.value.selectLocationLabel)
const isRefreshingQuote = computed(() => isLoadingQuote.value && !!quoteSummary.value)

function formatMoney(amount) {
  const numericAmount = Number(amount || 0)
  const hasFraction = Math.round(numericAmount) !== numericAmount

  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currencyCode.value || 'USD',
    minimumFractionDigits: hasFraction ? 2 : 0,
    maximumFractionDigits: hasFraction ? 2 : 0,
  }).format(numericAmount)
}

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

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

    if (matched) {
      return matched
    }
  }

  return locations.value[fallbackIndex] || null
}

function initializeTripState() {
  if (!locations.value.length || !vehicleGroupId.value) {
    return
  }

  const hasRouteTrip = Boolean(route.query.pickupLocationId && route.query.pickupAt && route.query.dropoffAt)

  if (hasRouteTrip) {
    const parsed = parseSearchQuery(route.query)
    pickupLocation.value = resolveLocationByBackendId(parsed.pickupLocationId, 0)
    dropoffLocation.value = resolveLocationByBackendId(parsed.dropoffLocationId || parsed.pickupLocationId, 1) || pickupLocation.value
    returnToSameLocation.value = Number(parsed.pickupLocationId || 0) === Number(parsed.dropoffLocationId || parsed.pickupLocationId || 0)
    pickupTime.value = parsed.pickupTime
    dropoffTime.value = parsed.dropoffTime
    dateRange.value = {
      from: parsed.pickupDate,
      to: parsed.dropoffDate,
    }
  } else {
    pickupLocation.value = resolveLocationByBackendId(null, 0)
    dropoffLocation.value = resolveLocationByBackendId(null, 1) || pickupLocation.value
    returnToSameLocation.value = true
    pickupTime.value = '12:30'
    dropoffTime.value = '08:30'
    dateRange.value = {
      from: buildDate(0),
      to: buildDate(3),
    }
  }

  hasHydratedState.value = true
}

function togglePopover(name) {
  activePopover.value = activePopover.value === name ? null : name
}

function selectLocation(target, location) {
  if (target === 'pickup') {
    pickupLocation.value = location
  } else {
    dropoffLocation.value = location
  }

  activePopover.value = null
}

function syncTripQueryToUrl(query) {
  if (!import.meta.client || !hasHydratedState.value) {
    return
  }

  const nextUrl = new URL(window.location.href)

  RENT_TRIP_QUERY_KEYS.forEach((key) => {
    nextUrl.searchParams.delete(key)
  })

  Object.entries(query).forEach(([key, value]) => {
    nextUrl.searchParams.set(key, String(value))
  })

  window.history.replaceState(window.history.state, '', `${nextUrl.pathname}${nextUrl.search}${nextUrl.hash}`)
}

function handleClickOutside(event) {
  const builderElement = builderRef.value?.$el || builderRef.value

  if (builderElement && typeof builderElement.contains === 'function' && !builderElement.contains(event.target)) {
    activePopover.value = null
  }
}

async function loadQuote() {
  if (import.meta.server) {
    return
  }

  if (!quotePayload.value) {
    quoteData.value = null
    quoteError.value = ''
    return
  }

  isLoadingQuote.value = true
  const requestId = quoteRequestId.value + 1
  quoteRequestId.value = requestId

  try {
    const nextQuote = await fetchQuote(quotePayload.value)

    if (requestId !== quoteRequestId.value) {
      return
    }

    quoteData.value = nextQuote
    quoteError.value = ''
  } catch (error) {
    console.error('Failed to load vehicle detail quote', error)

    if (requestId !== quoteRequestId.value) {
      return
    }

    quoteData.value = null
    quoteError.value = resolvePublicApiError(error, vehicleBookingBuilderUi.value.livePricingUnavailableLabel || 'We could not lock live pricing for this trip.', locale.value)
  } finally {
    if (requestId === quoteRequestId.value) {
      isLoadingQuote.value = false
    }
  }
}

watch(
  [vehicleGroupId, () => route.fullPath, () => locations.value.length],
  () => {
    if (!locations.value.length || !vehicleGroupId.value) {
      return
    }

    initializeTripState()
  },
  { immediate: true },
)

watch(
  () => returnToSameLocation.value,
  (value) => {
    if (value) {
      activePopover.value = activePopover.value === 'dropoff-location' ? null : activePopover.value
      return
    }

    if (!dropoffLocation.value || dropoffLocation.value.id === pickupLocation.value?.id) {
      dropoffLocation.value = resolveLocationByBackendId(route.query.dropoffLocationId, 1) || pickupLocation.value
    }
  },
)

watch(
  tripQuery,
  (value) => {
    syncTripQueryToUrl(value)
  },
  { deep: true },
)

watch(
  quotePayload,
  async () => {
    if (!hasHydratedState.value) {
      return
    }

    await loadQuote()
  },
  { immediate: true },
)

onMounted(async () => {
  document.addEventListener('mousedown', handleClickOutside)
  await loadLocations()
})

onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside)
})
</script>

<template>
  <div ref="builderRef">
    <div class="sticky top-24 bg-white/80 backdrop-blur-2xl border border-white/60 p-6 md:p-8 rounded-[2rem] shadow-[0_8px_30px_rgb(0,0,0,0.08)]">
      <div class="flex items-end justify-between mb-6 pb-6 border-b border-slate-100">
        <div>
          <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">{{ vehicleDetailUi.dailyRateLabel }}</div>
          <div v-if="headerPriceLabel" class="flex items-baseline gap-1">
            <span class="text-4xl font-black text-brand-orange">{{ headerPriceLabel }}</span>
            <span class="text-sm font-bold text-slate-500">{{ vehicleDetailUi.pricePerDaySuffix }}</span>
          </div>
          <div v-else class="h-10 w-36 rounded-2xl bg-slate-100 animate-pulse" />
        </div>

        <div v-if="isRefreshingQuote" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-amber-50 text-amber-700 text-[10px] font-bold uppercase tracking-wider">
          <motion.div
            :animate="{ rotate: 360 }"
            :transition="{ duration: 1, repeat: Infinity, ease: 'linear' }"
            class="w-3.5 h-3.5 border-2 border-amber-200 border-t-amber-500 rounded-full"
          />
          {{ vehicleBookingBuilderUi.livePricingUpdatingLabel }}
        </div>
      </div>

      <div class="grid grid-cols-1 gap-3 mb-3">
        <div class="relative">
          <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">{{ vehicleBookingBuilderUi.pickupLocationLabel }}</div>
          <button
            type="button"
            class="w-full flex items-center justify-between gap-3 px-4 py-3 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-xl transition-all group text-left"
            @click="togglePopover('pickup-location')"
          >
            <div class="flex items-center gap-3 min-w-0">
              <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center group-hover:text-brand-orange transition-colors">
                <MapPin class="w-4 h-4 text-slate-600 group-hover:text-brand-orange" />
              </div>
              <div class="min-w-0">
                <div class="font-bold text-slate-900 text-sm truncate">{{ pickupLocationLabel }}</div>
                <div v-if="pickupLocation?.city" class="text-xs text-slate-500 mt-0.5 truncate">{{ pickupLocation.city }}</div>
              </div>
            </div>
            <ChevronDown class="w-4 h-4 text-slate-400 shrink-0" />
          </button>

          <AnimatePresence>
            <motion.div
              v-if="activePopover === 'pickup-location'"
              :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 right-0 mt-2 bg-white rounded-2xl shadow-2xl border border-slate-100 p-2 z-50"
            >
              <button
                v-for="location in locations"
                :key="`pickup-${location.id}`"
                type="button"
                :class="[
                  'w-full text-left px-4 py-3 rounded-xl transition-all duration-200',
                  pickupLocation?.id === location.id
                    ? 'bg-brand-orange/10 text-brand-orange'
                    : 'text-slate-700 hover:bg-slate-50',
                ]"
                @click="selectLocation('pickup', location)"
              >
                <div class="font-bold text-sm">{{ location.name }}</div>
                <div class="text-[11px] text-slate-500 mt-0.5">{{ location.city || location.code }}</div>
              </button>
            </motion.div>
          </AnimatePresence>
        </div>

        <label class="flex items-center justify-between px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl">
          <div>
            <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">{{ vehicleBookingBuilderUi.sameLocationLabel }}</div>
            <div class="text-xs text-slate-500">{{ vehicleBookingBuilderUi.livePricingFootnoteLabel }}</div>
          </div>
          <div class="relative">
            <div :class="['relative w-10 h-6 rounded-full transition-colors duration-300', returnToSameLocation ? 'bg-brand-orange' : 'bg-slate-200']">
              <motion.div
                class="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-md"
                :animate="{ x: returnToSameLocation ? 16 : 0 }"
                :transition="{ type: 'spring', stiffness: 400, damping: 28 }"
              />
            </div>
            <input v-model="returnToSameLocation" type="checkbox" class="sr-only">
          </div>
        </label>

        <div class="relative">
          <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">{{ vehicleBookingBuilderUi.dropoffLocationLabel }}</div>
          <button
            type="button"
            :disabled="returnToSameLocation"
            :class="[
              'w-full flex items-center justify-between gap-3 px-4 py-3 border rounded-xl transition-all text-left',
              returnToSameLocation
                ? 'bg-slate-50 border-slate-200 text-slate-400 cursor-default'
                : 'bg-slate-50 hover:bg-slate-100 border-slate-200 group',
            ]"
            @click="!returnToSameLocation && togglePopover('dropoff-location')"
          >
            <div class="flex items-center gap-3 min-w-0">
              <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center">
                <MapPin class="w-4 h-4" :class="returnToSameLocation ? 'text-slate-300' : 'text-slate-600 group-hover:text-brand-orange'" />
              </div>
              <div class="min-w-0">
                <div class="font-bold text-sm truncate">{{ dropoffLocationLabel }}</div>
                <div class="text-xs mt-0.5 truncate" :class="returnToSameLocation ? 'text-slate-400' : 'text-slate-500'">
                  {{ returnToSameLocation ? vehicleBookingBuilderUi.sameLocationLabel : (effectiveDropoffLocation?.city || effectiveDropoffLocation?.code || '') }}
                </div>
              </div>
            </div>
            <ChevronDown v-if="!returnToSameLocation" class="w-4 h-4 text-slate-400 shrink-0" />
          </button>

          <AnimatePresence>
            <motion.div
              v-if="activePopover === 'dropoff-location' && !returnToSameLocation"
              :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 right-0 mt-2 bg-white rounded-2xl shadow-2xl border border-slate-100 p-2 z-50"
            >
              <button
                v-for="location in locations"
                :key="`dropoff-${location.id}`"
                type="button"
                :class="[
                  'w-full text-left px-4 py-3 rounded-xl transition-all duration-200',
                  effectiveDropoffLocation?.id === location.id
                    ? 'bg-brand-orange/10 text-brand-orange'
                    : 'text-slate-700 hover:bg-slate-50',
                ]"
                @click="selectLocation('dropoff', location)"
              >
                <div class="font-bold text-sm">{{ location.name }}</div>
                <div class="text-[11px] text-slate-500 mt-0.5">{{ location.city || location.code }}</div>
              </button>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>

      <div class="relative mb-3 z-20">
        <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">{{ vehicleDetailUi.rentalPeriodLabel }}</div>
        <button
          type="button"
          class="w-full flex items-center justify-between px-4 py-3 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-xl transition-all group"
          @click="togglePopover('dates')"
        >
          <div class="flex items-center gap-3">
            <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center group-hover:text-brand-orange transition-colors">
              <Calendar class="w-4 h-4 text-slate-600 group-hover:text-brand-orange" />
            </div>
            <div class="text-left">
              <div class="font-bold text-slate-900 text-sm">
                {{ dateRange?.from ? format(dateRange.from, 'MMM d') : vehicleDetailUi.pickupLabel }}
                <span class="text-slate-400 mx-2">→</span>
                {{ dateRange?.to ? format(dateRange.to, 'MMM d') : vehicleDetailUi.dropoffLabel }}
              </div>
              <div class="text-xs text-slate-500 mt-0.5">
                {{ selectedDays }} {{ selectedDays === 1 ? vehicleDetailUi.daySingularLabel : vehicleDetailUi.dayPluralLabel }}
              </div>
            </div>
          </div>
          <ChevronDown class="w-4 h-4 text-slate-400" />
        </button>

        <AnimatePresence>
          <motion.div
            v-if="activePopover === 'dates'"
            :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-1/2 -translate-x-1/2 mt-2 bg-white border border-slate-100 rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.15)] p-4 z-50 w-max"
          >
            <AppCalendar
              mode="range"
              :selected="dateRange"
              :number-of-months="1"
              :disabled="{ before: baseDay }"
              class="font-sans flex justify-center"
              @select="dateRange = $event"
            />
            <div class="mt-4 pt-4 border-t border-slate-200/50 flex justify-end">
              <button
                type="button"
                class="px-6 py-2.5 bg-slate-900 text-white rounded-xl text-sm font-bold hover:bg-brand-orange transition-colors shadow-lg shadow-slate-900/20"
                @click="activePopover = null"
              >
                {{ vehicleDetailUi.confirmDatesLabel }}
              </button>
            </div>
          </motion.div>
        </AnimatePresence>
      </div>

      <div class="grid grid-cols-2 gap-3 mb-6">
        <div class="relative">
          <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">{{ vehicleBookingBuilderUi.pickupTimeLabel }}</div>
          <button
            type="button"
            class="w-full flex items-center justify-between gap-3 px-4 py-3 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-xl transition-all group"
            @click="togglePopover('pickup-time')"
          >
            <div class="flex items-center gap-3">
              <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center">
                <Clock class="w-4 h-4 text-slate-600 group-hover:text-brand-orange" />
              </div>
              <div class="font-bold text-slate-900 text-sm">{{ pickupTime }}</div>
            </div>
            <ChevronDown class="w-4 h-4 text-slate-400 shrink-0" />
          </button>

          <AnimatePresence>
            <HeroTimePopover
              v-if="activePopover === 'pickup-time'"
              :selected-time="pickupTime"
              @select="(time) => { pickupTime = time; activePopover = null }"
            />
          </AnimatePresence>
        </div>

        <div class="relative">
          <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">{{ vehicleBookingBuilderUi.dropoffTimeLabel }}</div>
          <button
            type="button"
            class="w-full flex items-center justify-between gap-3 px-4 py-3 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-xl transition-all group"
            @click="togglePopover('dropoff-time')"
          >
            <div class="flex items-center gap-3">
              <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center">
                <Clock class="w-4 h-4 text-slate-600 group-hover:text-brand-orange" />
              </div>
              <div class="font-bold text-slate-900 text-sm">{{ dropoffTime }}</div>
            </div>
            <ChevronDown class="w-4 h-4 text-slate-400 shrink-0" />
          </button>

          <AnimatePresence>
            <HeroTimePopover
              v-if="activePopover === 'dropoff-time'"
              :selected-time="dropoffTime"
              align="right"
              @select="(time) => { dropoffTime = time; activePopover = null }"
            />
          </AnimatePresence>
        </div>
      </div>

      <div class="mb-6 bg-slate-50 rounded-xl p-4 border border-slate-100">
        <div v-if="quoteError" class="flex items-start gap-2 text-red-600 text-sm font-medium">
          <AlertCircle class="w-4 h-4 shrink-0 mt-0.5" />
          <div>
            <div class="font-bold">{{ vehicleBookingBuilderUi.livePricingUnavailableLabel }}</div>
            <div class="text-red-500 mt-0.5">{{ quoteError }}</div>
          </div>
        </div>

        <template v-else-if="!quoteSummary">
          <div class="flex items-center gap-2 text-slate-700 font-bold text-sm mb-3">
            <motion.div
              :animate="{ rotate: 360 }"
              :transition="{ duration: 1, repeat: Infinity, ease: 'linear' }"
              class="w-4 h-4 border-2 border-slate-200 border-t-brand-orange rounded-full"
            />
            {{ vehicleBookingBuilderUi.livePricingLoadingLabel }}
          </div>
          <div class="space-y-2">
            <div class="h-3 rounded-full bg-slate-200/70 animate-pulse" />
            <div class="h-3 rounded-full bg-slate-200/50 animate-pulse w-4/5" />
          </div>
        </template>

        <template v-else>
          <div class="flex items-center gap-2 text-emerald-600 font-bold text-sm mb-3">
            <ShieldCheck class="w-4 h-4" />
            {{ vehicleBookingBuilderUi.livePricingLabel }}
          </div>

          <div class="space-y-2 text-sm">
            <div class="flex items-center justify-between gap-4 text-slate-600">
              <span>{{ vehicleBookingBuilderUi.rateBandLabel }}</span>
              <span class="font-bold text-slate-900 text-right">{{ liveRateBandLabel }}</span>
            </div>
            <div class="flex items-center justify-between gap-4 text-slate-600">
              <span>{{ vehicleBookingBuilderUi.depositLabel }}</span>
              <span class="font-bold text-slate-900 text-right">{{ depositLabel }}</span>
            </div>
            <div class="flex items-center justify-between gap-4 text-slate-600">
              <span>{{ vehicleBookingBuilderUi.dueAfterApprovalLabel }}</span>
              <span class="font-bold text-slate-900 text-right">{{ dueAfterApprovalLabel }}</span>
            </div>
          </div>
        </template>
      </div>

      <div v-if="summaryLines.length" class="space-y-3 mb-6 pt-6 border-t border-slate-100">
        <div
          v-for="line in summaryLines"
          :key="line.code"
          class="flex justify-between gap-4 text-sm text-slate-600"
        >
          <span>{{ line.label }}</span>
          <span class="font-medium text-right">{{ formatMoney(line.amount) }}</span>
        </div>

        <div class="flex justify-between gap-4 text-lg font-black text-slate-900 pt-3 border-t border-slate-100">
          <span>{{ vehicleDetailUi.totalLabel }}</span>
          <span>{{ totalLabel }}</span>
        </div>
      </div>

      <NuxtLink
        v-if="canContinue"
        :to="extrasRoute"
        class="w-full flex items-center justify-center gap-2 bg-brand-orange text-white hover:bg-[#E66000] px-6 py-4 rounded-xl font-bold uppercase tracking-wider text-sm transition-all shadow-lg shadow-brand-orange/20 group"
      >
        <Calendar class="w-4 h-4" />
        {{ vehicleDetailUi.bookingCtaLabel }}
        <ArrowRight class="w-4 h-4 group-hover:translate-x-1 transition-transform" />
      </NuxtLink>

      <button
        v-else
        type="button"
        disabled
        class="w-full flex items-center justify-center gap-2 bg-brand-orange text-white px-6 py-4 rounded-xl font-bold uppercase tracking-wider text-sm disabled:pointer-events-none"
      >
        <Calendar class="w-4 h-4" />
        {{ vehicleDetailUi.bookingCtaLabel }}
      </button>

      <p class="text-center text-xs text-slate-400 mt-4 font-medium flex items-center justify-center gap-1.5">
        <ShieldCheck class="w-3.5 h-3.5 text-emerald-500" />
        {{ vehicleDetailUi.bookingFootnote }}
      </p>
    </div>

    <div class="fixed bottom-0 left-0 right-0 bg-white/90 backdrop-blur-xl border-t border-slate-200 p-4 lg:hidden z-50 shadow-[0_-10px_40px_rgba(0,0,0,0.05)]">
      <div class="flex items-center justify-between gap-4 max-w-7xl mx-auto">
        <div>
          <div class="text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-0.5">
            {{ vehicleDetailUi.mobileTotalPrefix }} {{ selectedDays }} {{ selectedDays === 1 ? vehicleDetailUi.daySingularLabel : vehicleDetailUi.dayPluralLabel }}
          </div>
          <div v-if="totalLabel" class="text-2xl font-black text-slate-900 leading-none">{{ totalLabel }}</div>
          <div v-else class="h-8 w-24 rounded-xl bg-slate-100 animate-pulse" />
          <div v-if="isRefreshingQuote" class="text-[10px] font-bold text-amber-600 mt-1">{{ vehicleBookingBuilderUi.livePricingUpdatingLabel }}</div>
        </div>

        <NuxtLink
          v-if="canContinue"
          :to="extrasRoute"
          class="flex-1 bg-brand-orange text-white hover:bg-slate-900 px-6 py-3.5 rounded-xl font-bold uppercase tracking-wider text-sm transition-all text-center shadow-lg shadow-brand-orange/20"
        >
          {{ vehicleDetailUi.mobileBookingCtaLabel }}
        </NuxtLink>

        <button
          v-else
          type="button"
          disabled
          class="flex-1 bg-brand-orange text-white px-6 py-3.5 rounded-xl font-bold uppercase tracking-wider text-sm disabled:pointer-events-none"
        >
          {{ vehicleDetailUi.mobileBookingCtaLabel }}
        </button>
      </div>
    </div>
  </div>
</template>
