<script setup>
import { AnimatePresence, motion } from 'motion-v'
import {
  ArrowLeft,
  BellRing,
  Calendar,
  Car,
  ChevronRight,
  Clock,
  DollarSign,
  MapPin,
  MessageSquare,
  RefreshCw,
  Search,
  ShieldCheck,
} from 'lucide-vue-next'
import { formatPublicDateRange, formatPublicDateTime, formatPublicMoney, resolvePublicApiError, resolvePublicAssetUrl } from '~/content/utils'
import { useRequestContent } from '~/content/request'
import { resolvePrivateFlowToken } from '~/utils/private-flow-route'
import { buildTrackRoute } from '~/utils/public-routes'

const props = defineProps({
  token: {
    type: String,
    default: '',
  },
})

const { createOfferPortal, fetchRequest } = usePublicRequest()
const { locale, localizedPath } = usePublicLocale()
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
const requestToken = computed(() => String(props.token || '').trim() || resolvePrivateFlowToken(route, '/request', 'token'))
const requestContent = useRequestContent(() => requestToken.value)
const requestPage = computed(() => requestContent.requestPage.value || null)
const requestTrackerUi = computed(() => requestContent.requestTrackerUi.value || {})
const requestBudgetTierLabels = computed(() => requestContent.requestBudgetTierLabels.value || {})
const AUTO_REFRESH_SECONDS = 20

const isLoading = ref(true)
const isRefreshing = ref(false)
const loadError = ref('')
const offerActionError = ref('')
const activeOfferActionId = ref('')
const requestData = ref(null)
const refreshCountdown = ref(AUTO_REFRESH_SECONDS)
let refreshTimer = null

const summary = computed(() => requestData.value?.summary || null)
const requestStatus = computed(() => requestData.value?.status || null)
const offers = computed(() => requestData.value?.offers || [])
const agentUpdates = computed(() => requestData.value?.agentUpdates || [])
const booking = computed(() => requestData.value?.booking || null)
const bookingPortalDestination = computed(() => {
  if (booking.value?.publicPortalToken) {
    return buildTrackRoute(booking.value.publicPortalToken, {}, {
      locale: locale.value,
    }).path
  }

  return booking.value?.publicPortalUrl || ''
})
const bookingPortalIsExternal = computed(() => /^https?:\/\//.test(bookingPortalDestination.value))
const offerTimelineEvents = computed(() => (requestData.value?.timeline || []).filter((item) => item.type === 'offer'))
const requestHeaderTitle = computed(() => {
  if (summary.value?.id) {
    return `Request #${summary.value.id}`
  }

  return requestPage.value?.title || requestTrackerUi.value.statusEyebrow || 'Request'
})
const currentStatusLabel = computed(() => {
  if (requestStatus.value?.label) {
    return requestStatus.value.label
  }

  return offers.value.length ? requestTrackerUi.value.offersReadyLabel : requestTrackerUi.value.agentWorkingLabel
})

function formatDateTime(value) {
  return formatPublicDateTime(value, locale.value) || requestTrackerUi.value.pendingLabel
}

function formatDateRange(start, end) {
  return formatPublicDateRange(start, end, locale.value) || requestTrackerUi.value.pendingLabel
}

function formatMoney(amount, currencyCode) {
  return formatPublicMoney(amount, currencyCode || 'USD', locale.value, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  })
}

function replaceTokens(template, replacements) {
  return Object.entries(replacements).reduce((result, [key, value]) => result.replaceAll(`:${key}`, String(value ?? '')), String(template || ''))
}

function buildBudgetLabel() {
  const budget = summary.value?.budget || {}

  if (budget.amount) {
    return formatMoney(budget.amount, budget.currency)
  }

  if (summary.value?.budgetTier && requestBudgetTierLabels.value[summary.value.budgetTier]) {
    return requestBudgetTierLabels.value[summary.value.budgetTier]
  }

  return requestTrackerUi.value.pendingLabel
}

function formatOfferStatus(status) {
  if (['active', 'sent', 'ready'].includes(String(status || '').toLowerCase())) {
    return requestTrackerUi.value.offersReadyLabel
  }

  if (String(status || '').toLowerCase() === 'accepted') {
    return requestTrackerUi.value.openBookingLabel
  }

  return requestTrackerUi.value.finalizingLabel
}

function resolveOfferTitle(offer) {
  const vehicleName = [offer?.vehicle?.make, offer?.vehicle?.model].filter(Boolean).join(' ').trim()

  if (vehicleName) {
    return vehicleName
  }

  return offer?.vehicleGroup?.name || offer?.title || requestTrackerUi.value.customOfferLabel
}

function resolveOfferVehicleImage(offer) {
  return resolvePublicAssetUrl(offer?.vehicle?.imageUrl || '', runtimeConfig.public.apiBaseUrl)
}

function resolveOfferPrice(offer) {
  if (offer.dailyRate !== null && offer.dailyRate !== undefined) {
    return {
      label: replaceTokens(requestTrackerUi.value.offerAtPriceDailyTemplate, {
        price: formatMoney(offer.dailyRate, offer.currency),
        unit: requestTrackerUi.value.offerDailyUnitLabel,
      }).trim(),
      amount: formatMoney(offer.dailyRate, offer.currency),
      unit: requestTrackerUi.value.offerDailyUnitLabel,
    }
  }

  if (offer.totalPrice !== null && offer.totalPrice !== undefined) {
    return {
      label: replaceTokens(requestTrackerUi.value.offerAtPriceTotalTemplate, {
        price: formatMoney(offer.totalPrice, offer.currency),
      }).trim(),
      amount: formatMoney(offer.totalPrice, offer.currency),
      unit: requestTrackerUi.value.offerTotalUnitLabel,
    }
  }

  return {
    label: '',
    amount: '',
    unit: '',
  }
}

function buildOfferNote(offer) {
  const notes = []

  if (offer.note) {
    notes.push(offer.note)
  }

  if (offer.totalPrice) {
    notes.push(replaceTokens(requestTrackerUi.value.noteTotalTemplate, {
      amount: formatMoney(offer.totalPrice, offer.currency),
    }))
  }

  if (offer.deposit) {
    notes.push(replaceTokens(requestTrackerUi.value.noteDepositTemplate, {
      amount: formatMoney(offer.deposit, offer.currency),
    }))
  }

  if (offer.prepayment) {
    notes.push(replaceTokens(requestTrackerUi.value.notePrepaymentTemplate, {
      amount: formatMoney(offer.prepayment, offer.currency),
    }))
  }

  return notes.join(' ')
}

function resolveOfferUpdateTime(index, offer) {
  const timelineEvent = offerTimelineEvents.value[index]

  if (timelineEvent?.happenedAt) {
    return formatDateTime(timelineEvent.happenedAt)
  }

  if (offer.expiresAt) {
    return formatDateTime(offer.expiresAt)
  }

  return requestTrackerUi.value.liveTimeLabel
}

function resolveOfferComparison(offer) {
  return offer?.comparison || null
}

function hasOfferSavings(offer) {
  return Number(resolveOfferComparison(offer)?.savingsAmount || 0) > 0
}

function resolveOfferSavingsLabel(offer) {
  const comparison = resolveOfferComparison(offer)

  if (!comparison) {
    return ''
  }

  if (comparison.savingsLabel) {
    return comparison.savingsLabel
  }

  if (comparison.savingsAmount) {
    return `${requestTrackerUi.value.savePrefixLabel} ${formatMoney(comparison.savingsAmount, offer?.currency)}`
  }

  return ''
}

function resolveOfferAcceptAction(offer) {
  return offer?.acceptAction || null
}

function resolveOfferDestination(offer) {
  const action = resolveOfferAcceptAction(offer)

  if (action?.publicPortalToken) {
    return buildTrackRoute(action.publicPortalToken, {}, {
      locale: locale.value,
    }).path
  }

  return action?.publicPortalUrl || ''
}

function offerDestinationIsExternal(offer) {
  return /^https?:\/\//.test(resolveOfferDestination(offer))
}

function isOfferActionPending(offer) {
  return activeOfferActionId.value === String(offer?.id || '')
}

async function openOfferBooking(offer) {
  const action = resolveOfferAcceptAction(offer)

  if (!action) {
    return
  }

  const readyDestination = resolveOfferDestination(offer)

  if (readyDestination) {
    if (offerDestinationIsExternal(offer) && import.meta.client) {
      window.location.href = readyDestination
      return
    }

    await navigateTo(readyDestination)
    return
  }

  offerActionError.value = ''
  activeOfferActionId.value = String(offer.id || '')

  try {
    const portal = await createOfferPortal(requestToken.value, offer.id, action.endpoint)
    const nextDestination = portal?.publicPortalToken
      ? buildTrackRoute(portal.publicPortalToken, {}, {
          locale: locale.value,
        }).path
      : (portal?.publicPortalUrl || '')

    if (nextDestination) {
      if (/^https?:\/\//.test(nextDestination) && import.meta.client) {
        window.location.href = nextDestination
        return
      }

      await navigateTo(nextDestination)
      return
    }

    requestData.value = await fetchRequest(requestToken.value)
  } catch (error) {
    console.error('Failed to open request offer booking portal', error)
    offerActionError.value = resolvePublicApiError(error, requestTrackerUi.value.openBookingErrorLabel, locale.value)
  } finally {
    activeOfferActionId.value = ''
  }
}

const activeStep = computed(() => {
  if (offers.value.length || booking.value?.publicPortalToken) {
    return 3
  }

  if (agentUpdates.value.length) {
    return 2
  }

  if ((requestData.value?.timeline || []).length > 1) {
    return 1
  }

  return 0
})

const timelineSteps = computed(() => {
  const timeline = requestData.value?.timeline || []
  const offerEvent = timeline.find((item) => item.type === 'offer')
  const updateEvent = timeline.find((item) => item.type === 'update')

  return [
    {
      id: 'received',
      label: requestTrackerUi.value.timelineReceivedLabel,
      icon: Clock,
      time: formatDateTime(summary.value?.createdAt),
    },
    {
      id: 'scanning',
      label: requestTrackerUi.value.timelineScanningLabel,
      icon: Search,
      time: updateEvent ? formatDateTime(updateEvent.happenedAt || updateEvent.createdAt) : requestTrackerUi.value.pendingLabel,
    },
    {
      id: 'negotiating',
      label: requestTrackerUi.value.timelineNegotiatingLabel,
      icon: MessageSquare,
      time: agentUpdates.value[0] ? formatDateTime(agentUpdates.value[0].createdAt) : (activeStep.value >= 2 ? requestTrackerUi.value.inProgressLabel : requestTrackerUi.value.pendingLabel),
    },
    {
      id: 'ready',
      label: requestTrackerUi.value.timelineOffersLabel,
      icon: ShieldCheck,
      time: offerEvent ? formatDateTime(offerEvent.happenedAt) : requestTrackerUi.value.pendingLabel,
    },
  ]
})

const liveUpdates = computed(() => {
  if (!summary.value) {
    return []
  }

  const items = [
    {
      id: 'request-created',
      time: formatDateTime(summary.value.createdAt),
      text: replaceTokens(requestTrackerUi.value.liveRequestReceivedTemplate, {
        reference: summary.value.id,
      }),
      type: 'system',
    },
  ]

  if (!agentUpdates.value.length && !offers.value.length) {
    items.push({
      id: 'scan-in-progress',
      time: requestTrackerUi.value.liveTimeLabel,
      text: 'We are checking live availability and pricing for you now.',
      type: 'system',
    })
  }

  agentUpdates.value.forEach((update) => {
    items.push({
      id: `agent-${update.id}`,
      time: formatDateTime(update.createdAt),
      text: `${requestTrackerUi.value.agentUpdateLabel} ${update.message}`,
      type: 'agent',
    })
  })

  offers.value.forEach((offer, index) => {
    const price = resolveOfferPrice(offer)

    items.push({
      id: `offer-${offer.id}`,
      time: resolveOfferUpdateTime(index, offer),
      text: replaceTokens(requestTrackerUi.value.liveOfferReadyTemplate, {
        offer: resolveOfferTitle(offer),
        price: price.label,
      }),
      type: 'success',
    })
  })

  return items
})

const refreshCountdownLabel = computed(() => `${Math.max(1, refreshCountdown.value)}s`)

function clearRefreshTimer() {
  if (!import.meta.client || refreshTimer === null) {
    return
  }

  window.clearInterval(refreshTimer)
  refreshTimer = null
}

function startRefreshTimer() {
  clearRefreshTimer()

  if (!import.meta.client || !requestToken.value) {
    return
  }

  refreshCountdown.value = AUTO_REFRESH_SECONDS
  refreshTimer = window.setInterval(async () => {
    if (isLoading.value || isRefreshing.value) {
      return
    }

    if (refreshCountdown.value > 1) {
      refreshCountdown.value -= 1
      return
    }

    refreshCountdown.value = AUTO_REFRESH_SECONDS
    await loadRequest({ silent: true })
  }, 1000)
}

async function loadRequest(options = {}) {
  const silent = Boolean(options?.silent)

  if (!requestToken.value) {
    clearRefreshTimer()
    loadError.value = requestTrackerUi.value.missingTokenLabel
    isLoading.value = false
    isRefreshing.value = false
    requestData.value = null
    return
  }

  if (silent) {
    isRefreshing.value = true
  } else {
    isLoading.value = true
  }
  loadError.value = ''
  offerActionError.value = ''

  try {
    requestData.value = await fetchRequest(requestToken.value)
  } catch (error) {
    console.error('Failed to load public request', error)
    requestData.value = null
    loadError.value = resolvePublicApiError(error, requestTrackerUi.value.loadErrorLabel, locale.value)
  } finally {
    if (silent) {
      isRefreshing.value = false
    } else {
      isLoading.value = false
    }
  }
}

async function refreshNow() {
  refreshCountdown.value = AUTO_REFRESH_SECONDS
  await loadRequest({ silent: true })
}

watch(requestToken, async () => {
  await loadRequest()
  startRefreshTimer()
}, { immediate: true })

onBeforeUnmount(() => {
  clearRefreshTimer()
})
</script>

<template>
  <div class="min-h-screen font-sans text-slate-900 pb-20 relative overflow-x-hidden">
    <div class="absolute top-[-10%] left-[-5%] w-[50vw] h-[50vw] max-w-[600px] max-h-[600px] bg-brand-orange/10 rounded-full blur-[100px] pointer-events-none" />
    <div class="absolute bottom-[-10%] right-[-5%] w-[50vw] h-[50vw] max-w-[600px] max-h-[600px] bg-blue-500/5 rounded-full blur-[100px] pointer-events-none" />

    <header class="bg-white/60 backdrop-blur-xl shadow-sm border-b border-white sticky top-0 z-50">
      <div class="max-w-6xl mx-auto px-4 h-16 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 shadow-sm border border-white flex items-center justify-center text-slate-600 hover:bg-white hover:text-brand-orange transition-colors">
            <ArrowLeft class="w-5 h-5" />
          </NuxtLink>
          <div>
            <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{{ requestTrackerUi.statusEyebrow }}</div>
            <h1 class="text-lg font-black text-slate-900 leading-none mt-0.5">{{ requestHeaderTitle }}</h1>
          </div>
        </div>
        <div class="flex items-center gap-2 bg-brand-orange/10 text-brand-orange px-4 py-2 rounded-full border border-white shadow-sm backdrop-blur-md">
          <div class="w-2 h-2 rounded-full bg-brand-orange animate-pulse" />
          <span class="text-[10px] font-bold uppercase tracking-wider">{{ currentStatusLabel }}</span>
        </div>
      </div>
    </header>

    <main class="max-w-6xl mx-auto px-4 pt-8 relative z-10">
      <div v-if="isLoading" class="bg-white/70 backdrop-blur-xl rounded-[2.5rem] p-10 border border-white shadow-sm text-center">
        <motion.div
          :animate="{ rotate: 360 }"
          :transition="{ duration: 1, repeat: Infinity, ease: 'linear' }"
          class="w-12 h-12 border-4 border-brand-orange/20 border-t-brand-orange rounded-full mx-auto mb-6"
        />
        <h2 class="text-2xl font-display font-black text-slate-900 mb-2">{{ requestTrackerUi.loadingLabel }}</h2>
      </div>

      <div v-else-if="loadError || !summary" class="bg-white/70 backdrop-blur-xl rounded-[2.5rem] p-10 border border-white shadow-sm text-center">
        <h2 class="text-2xl font-display font-black text-slate-900 mb-3">{{ requestTrackerUi.loadErrorLabel }}</h2>
        <p class="text-slate-500">{{ loadError }}</p>
      </div>

      <div v-else class="grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-8">
        <div class="lg:col-span-5 space-y-6 lg:space-y-8">
          <section class="bg-white/60 backdrop-blur-xl rounded-[2.5rem] p-6 lg:p-8 shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-white relative overflow-hidden group">
            <div class="absolute inset-0 bg-gradient-to-br from-white/40 via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none" />

            <h2 class="text-xl font-display font-black text-slate-900 mb-8 uppercase tracking-tight">{{ requestTrackerUi.processTimelineTitle }}</h2>
            <div class="space-y-6 relative z-10">
              <div v-for="(step, idx) in timelineSteps" :key="step.id" class="flex gap-5 relative">
                <div
                  v-if="idx !== timelineSteps.length - 1"
                  :class="[
                    'absolute left-6 top-12 bottom-[-24px] w-[2px] rounded-full',
                    idx < activeStep ? 'bg-gradient-to-b from-emerald-400 to-emerald-200' : 'bg-black/5',
                  ]"
                />

                <div
                  :class="[
                    'w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 relative z-10 transition-all duration-500 shadow-sm border border-white',
                    idx < activeStep
                      ? 'bg-emerald-500 text-white'
                      : idx === activeStep
                        ? 'bg-brand-orange text-white shadow-[0_0_20px_rgba(255,107,0,0.3)]'
                        : 'bg-white/80 text-slate-400',
                  ]"
                >
                  <component :is="step.icon" class="w-5 h-5" />
                  <div v-if="idx === activeStep" class="absolute inset-0 rounded-2xl border-2 border-brand-orange animate-ping opacity-20" />
                </div>

                <div class="flex-1 pt-2.5">
                  <div class="flex items-center justify-between mb-1">
                    <h3
                      :class="[
                        'font-bold text-sm uppercase tracking-wider',
                        idx === activeStep ? 'text-slate-900' : idx < activeStep ? 'text-slate-700' : 'text-slate-400',
                      ]"
                    >
                      {{ step.label }}
                    </h3>
                    <span :class="['text-[10px] font-bold uppercase tracking-widest', idx === activeStep ? 'text-brand-orange' : 'text-slate-400']">
                      {{ step.time }}
                    </span>
                  </div>
                  <p v-if="idx === activeStep" class="text-sm text-slate-500 mt-1">{{ requestTrackerUi.activeStepDescription }}</p>
                </div>
              </div>
            </div>
          </section>

          <section class="bg-slate-900/95 backdrop-blur-xl rounded-[2.5rem] p-6 lg:p-8 shadow-2xl border border-white/10 text-slate-300 relative overflow-hidden">
            <div class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-brand-orange via-emerald-500 to-blue-500" />
            <div class="absolute -top-24 -right-24 w-48 h-48 bg-brand-orange/20 rounded-full blur-[60px] pointer-events-none" />

            <div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between relative z-10">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center border border-white/5">
                  <BellRing class="w-5 h-5 text-brand-orange" />
                </div>
                <h2 class="text-xl font-display font-black text-white uppercase tracking-tight">{{ requestTrackerUi.liveUpdatesTitle }}</h2>
              </div>

              <div class="flex items-center">
                <button
                  type="button"
                  class="inline-flex items-center overflow-hidden rounded-full border border-white/10 bg-white/10 text-[11px] font-bold uppercase tracking-wider text-white transition-colors hover:bg-white/15 disabled:opacity-60"
                  :disabled="isRefreshing"
                  title="Refresh now"
                  @click="refreshNow"
                >
                  <span class="inline-flex items-center px-4 py-2.5">
                    <RefreshCw :class="isRefreshing ? 'animate-spin' : ''" class="h-4 w-4" />
                  </span>
                  <span class="h-5 w-px bg-white/20" />
                  <span class="px-4 py-2.5 text-white/85 tabular-nums">{{ refreshCountdownLabel }}</span>
                </button>
              </div>
            </div>

            <div class="space-y-3 relative z-10">
              <AnimatePresence :initial="false">
                <motion.div
                  v-for="update in liveUpdates"
                  :key="update.id"
                  :initial="{ opacity: 0, y: 12 }"
                  :animate="{ opacity: 1, y: 0 }"
                  class="rounded-2xl border border-white/10 bg-white/5 px-4 py-3"
                >
                  <div class="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-500">
                    {{ update.time || requestTrackerUi.pendingLabel }}
                  </div>
                  <div
                    :class="[
                      'text-sm font-medium leading-relaxed',
                      update.type === 'agent'
                        ? 'text-blue-300'
                        : update.type === 'success'
                          ? 'text-emerald-300'
                          : 'text-slate-200',
                    ]"
                  >
                    {{ update.text }}
                  </div>
                </motion.div>
              </AnimatePresence>

              <div class="rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm leading-relaxed text-slate-300">
                {{ offers.length ? 'New results will appear here automatically.' : 'We are checking available cars and pricing. New results will appear here automatically.' }}
              </div>
            </div>
          </section>
        </div>

        <div class="lg:col-span-7 space-y-6 lg:space-y-8">
          <section class="bg-white/60 backdrop-blur-xl rounded-[2.5rem] p-6 lg:p-8 shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-white flex flex-col sm:flex-row gap-6 items-center justify-between relative overflow-hidden group">
            <div class="absolute inset-0 bg-gradient-to-br from-white/40 via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none" />

            <div class="relative z-10 text-center sm:text-left">
              <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/80 backdrop-blur-md border border-white text-[9px] font-bold tracking-[0.2em] text-slate-500 uppercase mb-4 shadow-sm">
                {{ requestTrackerUi.yourRequestLabel }}
              </div>
              <h2 class="text-2xl md:text-3xl font-display font-black text-slate-900 flex items-center justify-center sm:justify-start gap-3 uppercase tracking-tight">
                <div class="w-10 h-10 rounded-full bg-brand-orange/10 flex items-center justify-center">
                  <Car class="w-5 h-5 text-brand-orange" />
                </div>
                {{ summary.carType || requestTrackerUi.requestedVehicleLabel }}
              </h2>
            </div>

            <div class="flex flex-wrap justify-center sm:justify-end gap-3 relative z-10">
              <div class="flex items-center gap-2 bg-white/80 backdrop-blur-md px-4 py-2.5 rounded-xl border border-white shadow-sm">
                <MapPin class="w-4 h-4 text-brand-orange" />
                <span class="text-xs font-bold text-slate-700 uppercase tracking-wider">{{ summary.location?.city || summary.location?.name || requestTrackerUi.pendingLabel }}</span>
              </div>
              <div class="flex items-center gap-2 bg-white/80 backdrop-blur-md px-4 py-2.5 rounded-xl border border-white shadow-sm">
                <Calendar class="w-4 h-4 text-brand-orange" />
                <span class="text-xs font-bold text-slate-700 uppercase tracking-wider">{{ formatDateRange(summary.pickupAt, summary.dropoffAt) }}</span>
              </div>
              <div class="flex items-center gap-2 bg-white/80 backdrop-blur-md px-4 py-2.5 rounded-xl border border-white shadow-sm">
                <DollarSign class="w-4 h-4 text-brand-orange" />
                <span class="text-xs font-bold text-slate-700 uppercase tracking-wider">{{ buildBudgetLabel() }}</span>
              </div>
            </div>
          </section>

          <section>
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6 px-2">
              <h2 class="text-2xl md:text-3xl font-display font-black text-slate-900 uppercase tracking-tight">{{ requestTrackerUi.offersTitle }}</h2>

              <div class="flex flex-wrap items-center gap-3">
                <component
                  :is="bookingPortalIsExternal ? 'a' : NuxtLink"
                  v-if="bookingPortalDestination"
                  :href="bookingPortalIsExternal ? bookingPortalDestination : undefined"
                  :to="bookingPortalIsExternal ? undefined : bookingPortalDestination"
                  :rel="bookingPortalIsExternal ? 'noreferrer' : undefined"
                  class="bg-slate-900 text-white px-5 py-2.5 rounded-xl font-bold text-xs uppercase tracking-wider hover:bg-brand-orange transition-colors flex items-center justify-center gap-2 shadow-md"
                >
                  {{ requestTrackerUi.openBookingLabel }}
                  <ChevronRight class="w-4 h-4" />
                </component>

                <div class="text-[10px] font-bold uppercase tracking-widest text-slate-500 bg-white/60 backdrop-blur-md border border-white shadow-sm px-4 py-2 rounded-full">
                  {{ currentStatusLabel }}
                </div>
              </div>
            </div>

            <div v-if="offerActionError" class="mb-4 bg-red-50/80 backdrop-blur-sm rounded-2xl p-4 flex gap-3 text-red-600 text-sm font-medium border border-red-100/70">
              <MessageSquare class="w-5 h-5 shrink-0" />
              <p>{{ offerActionError }}</p>
            </div>

            <div v-if="offers.length" class="space-y-4">
              <motion.div
                v-for="offer in offers"
                :key="offer.id"
                :initial="{ opacity: 0, y: 20 }"
                :animate="{ opacity: 1, y: 0 }"
                class="bg-white/80 backdrop-blur-xl rounded-3xl p-3 sm:p-4 shadow-sm border border-white/60 transition-all duration-300 hover:shadow-md group"
              >
                <div class="flex flex-col sm:flex-row gap-4 sm:gap-5">
                  <div class="w-full sm:w-48 h-40 sm:h-auto rounded-2xl overflow-hidden relative shrink-0 bg-slate-100">
                    <img v-if="resolveOfferVehicleImage(offer)" :src="resolveOfferVehicleImage(offer)" :alt="resolveOfferTitle(offer)" class="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-500">
                    <div v-else class="absolute inset-0 bg-gradient-to-br from-slate-200 to-slate-100 flex items-center justify-center p-6 text-center text-slate-500 font-bold">
                      {{ resolveOfferTitle(offer) }}
                    </div>
                  </div>

                  <div class="flex-1 flex flex-col justify-between py-1">
                    <div>
                      <div class="flex justify-between items-start mb-2 gap-3">
                        <div>
                          <div class="text-[10px] font-bold uppercase tracking-widest text-brand-orange mb-2">
                            {{ requestTrackerUi.customOfferLabel }}
                          </div>
                          <h3 class="font-display font-bold text-xl text-slate-900 leading-tight">{{ resolveOfferTitle(offer) }}</h3>
                        </div>
                        <span
                          class="flex items-center gap-1.5 text-[9px] font-bold uppercase tracking-widest text-brand-orange bg-brand-orange/10 px-2.5 py-1 rounded-lg shrink-0"
                        >
                          <span class="w-1.5 h-1.5 rounded-full bg-brand-orange animate-pulse" />
                          {{ formatOfferStatus(offer.status) }}
                        </span>
                      </div>

                      <div v-if="resolveOfferComparison(offer)" class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3">
                        <div class="rounded-xl bg-slate-50/80 border border-slate-200/70 px-4 py-3">
                          <div class="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">
                            {{ resolveOfferComparison(offer).referenceLabel || requestTrackerUi.standardRateLabel }}
                          </div>
                          <div class="text-base font-bold text-slate-500 line-through">
                            {{ formatMoney(resolveOfferComparison(offer).referencePrice, offer.currency) || requestTrackerUi.pendingLabel }}
                          </div>
                        </div>

                        <div
                          v-if="hasOfferSavings(offer)"
                          class="rounded-xl bg-emerald-50/80 border border-emerald-100/80 px-4 py-3"
                        >
                          <div class="text-[10px] font-bold uppercase tracking-widest text-emerald-600/70 mb-1">
                            {{ requestTrackerUi.savePrefixLabel }}
                          </div>
                          <div class="text-base font-bold text-emerald-600">
                            {{ resolveOfferSavingsLabel(offer) }}
                          </div>
                        </div>
                      </div>

                      <div class="flex items-start gap-2.5 mt-3 bg-blue-50/50 rounded-xl p-3 border border-blue-100/50">
                        <div class="w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center shrink-0 mt-0.5">
                          <MessageSquare class="w-3 h-3 text-blue-600" />
                        </div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                          {{ buildOfferNote(offer) || requestTrackerUi.offerPublishedLabel }}
                        </p>
                      </div>
                    </div>

                    <div class="flex flex-col sm:flex-row sm:items-end justify-between mt-5 gap-4">
                      <div class="flex flex-col gap-1">
                        <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                          {{ requestTrackerUi.offerPriceLabel }}
                        </div>
                        <div class="flex items-baseline gap-1">
                          <span class="text-3xl font-black text-emerald-600 tracking-tight">{{ resolveOfferPrice(offer).amount || requestTrackerUi.pendingLabel }}</span>
                          <span v-if="resolveOfferPrice(offer).unit" class="text-xs font-bold text-slate-500 uppercase tracking-widest">/ {{ resolveOfferPrice(offer).unit }}</span>
                        </div>
                      </div>

                      <component
                        :is="offerDestinationIsExternal(offer) ? 'a' : NuxtLink"
                        v-if="resolveOfferDestination(offer)"
                        :href="offerDestinationIsExternal(offer) ? resolveOfferDestination(offer) : undefined"
                        :to="offerDestinationIsExternal(offer) ? undefined : resolveOfferDestination(offer)"
                        :rel="offerDestinationIsExternal(offer) ? 'noreferrer' : undefined"
                        class="bg-slate-900 text-white px-8 py-3 rounded-xl font-bold text-sm uppercase tracking-wider hover:bg-brand-orange transition-colors flex items-center justify-center gap-2 shadow-md w-full sm:w-auto"
                      >
                        {{ resolveOfferAcceptAction(offer)?.label || requestTrackerUi.openBookingLabel }}
                        <ChevronRight class="w-4 h-4" />
                      </component>

                      <button
                        v-else-if="resolveOfferAcceptAction(offer)"
                        type="button"
                        :disabled="isOfferActionPending(offer)"
                        class="bg-brand-orange text-white px-8 py-3 rounded-xl font-bold text-sm uppercase tracking-wider hover:bg-[#E66000] transition-colors flex items-center justify-center gap-2 shadow-lg shadow-brand-orange/20 w-full sm:w-auto disabled:pointer-events-none"
                        @click="openOfferBooking(offer)"
                      >
                        <span>{{ isOfferActionPending(offer) ? requestTrackerUi.openingBookingLabel : (resolveOfferAcceptAction(offer)?.label || requestTrackerUi.openBookingLabel) }}</span>
                        <ChevronRight class="w-4 h-4" />
                      </button>

                      <button
                        v-else
                        type="button"
                        disabled
                        class="bg-brand-orange text-white px-8 py-3 rounded-xl font-bold text-sm uppercase tracking-wider flex items-center justify-center gap-2 w-full sm:w-auto disabled:pointer-events-none"
                      >
                        {{ requestTrackerUi.awaitingBookingLabel }}
                      </button>
                    </div>
                  </div>
                </div>
              </motion.div>
            </div>

            <motion.div
              v-else
              :initial="{ opacity: 0, y: 20 }"
              :animate="{ opacity: 1, y: 0 }"
              class="bg-white/80 backdrop-blur-xl rounded-3xl p-10 border border-white/60 text-center"
            >
              <h3 class="text-2xl font-display font-black text-slate-900 mb-3">{{ requestTrackerUi.emptyOffersTitle }}</h3>
              <p class="text-slate-500 max-w-2xl mx-auto">{{ requestTrackerUi.emptyOffersDescription }}</p>
            </motion.div>
          </section>
        </div>
      </div>
    </main>
  </div>
</template>
