<script setup>
import { Car, Check, Clock, Shield } from 'lucide-vue-next'
import OfferContextBanner from '~/components/offers/OfferContextBanner.vue'
import { resolveOfferPricingTierForDays } from '~/content/offer-pricing'
import {
  formatPublicDayCount,
  formatPublicMoney,
  formatPublicQuoteLineLabel,
  localizePublicVehicleCategory,
  resolvePublicAssetUrl,
} from '~/content/utils'
const ui = usePublicUi()
const { locale } = usePublicLocale()
const runtimeConfig = useRuntimeConfig()

const props = defineProps({
  group: {
    type: Object,
    default: () => null,
  },
  quote: {
    type: Object,
    default: () => null,
  },
  offer: {
    type: Object,
    default: () => null,
  },
})

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

const currencyCode = computed(() => props.quote?.currency || props.group?.currency || 'USD')

const imageUrl = computed(() => {
  return resolvePublicAssetUrl(
    props.group?.imageUrl
    || props.group?.vehicle?.imageUrl
    || '',
    runtimeConfig.public.apiBaseUrl,
  )
})

const vehicleType = computed(() => localizePublicVehicleCategory(props.group?.category || props.group?.vehicle?.category || '', locale.value))
const vehicleBrand = computed(() => props.group?.model?.make || props.group?.vehicle?.make || '')
const vehicleModel = computed(() => props.group?.model?.name || props.group?.vehicle?.model || props.group?.name || '')
const vehicleHeading = computed(() => vehicleBrand.value || vehicleModel.value || '-')
const vehicleSubheading = computed(() => {
  if (!vehicleBrand.value || !vehicleModel.value || vehicleBrand.value === vehicleModel.value) {
    return vehicleBrand.value ? '' : vehicleModel.value
  }

  return vehicleModel.value
})
const viewers = computed(() => Number(props.group?.demandSignals?.viewers || 0))
const offerPricingTier = computed(() => resolveOfferPricingTierForDays(props.offer || {}, props.quote?.days || 0))
const summaryLines = computed(() => {
  return (props.quote?.lines || [])
    .filter((line) => Number(line?.amount || 0) !== 0)
    .map((line) => {
      const amount = String(line?.code || '').trim() === 'rental' && offerPricingTier.value?.newPrice
        ? Number(offerPricingTier.value.newPrice || 0) * Number(props.quote?.days || 0)
        : Number(line?.amount || 0)
      const lineForLabel = {
        ...line,
        amount,
        unitAmount: String(line?.code || '').trim() === 'rental' && offerPricingTier.value?.newPrice
          ? Number(offerPricingTier.value.newPrice || 0)
          : Number(line?.unitAmount || line?.amount || 0),
      }

      return {
        ...lineForLabel,
        localizedLabel: formatPublicQuoteLineLabel(lineForLabel, {
          locale: locale.value,
          currencyCode: currencyCode.value,
          days: props.quote?.days || 0,
        }),
      }
    })
})
const rentalPeriodLabel = computed(() => formatPublicDayCount(props.quote?.days || 0, locale.value, 'checkout.rentalPeriodCountTemplate'))
const displayTotalAmount = computed(() => summaryLines.value.reduce((total, line) => total + Number(line?.amount || 0), 0))

const paymentCopy = computed(() => {
  const prepaymentAmount = Number(props.quote?.prepaymentAmount || 0)
  const depositAmount = Number(props.quote?.depositAmount || 0)
  const finalTotal = Number(displayTotalAmount.value || 0)

  if (prepaymentAmount > 0 && prepaymentAmount < finalTotal) {
    return String(ui.value.checkout.paymentPrepaymentTemplate || ui.value.checkout.paymentSummaryFallback)
      .replace('{amount}', formatMoney(prepaymentAmount, currencyCode.value))
  }

  if (depositAmount > 0) {
    return String(ui.value.checkout.paymentDepositTemplate || ui.value.checkout.paymentSummaryFallback)
      .replace('{amount}', formatMoney(depositAmount, currencyCode.value))
  }

  return ui.value.checkout.paymentSummaryFallback
})
</script>

<template>
  <div class="sticky top-28 space-y-6">
    <div class="bg-white/60 backdrop-blur-xl border border-brand-orange/20 rounded-2xl p-4 flex items-center gap-4 shadow-[0_8px_30px_rgba(249,115,22,0.05)]">
      <div class="w-10 h-10 rounded-full bg-brand-orange/10 flex items-center justify-center shrink-0">
        <Clock class="w-5 h-5 text-brand-orange" />
      </div>

      <div>
        <h4 class="text-sm font-bold text-slate-900">
          {{ viewers > 0 ? ui.checkout.highDemand : ui.checkout.liveAvailability }}
        </h4>
        <p class="text-xs text-slate-500">
          {{ viewers > 0 ? ui.checkout.viewingPeople.replace('{count}', String(viewers)) : ui.checkout.availabilityChecked }}
        </p>
      </div>
    </div>

    <div class="bg-white/60 backdrop-blur-2xl rounded-[2.5rem] p-8 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] border border-white/50 relative overflow-hidden">
      <div class="absolute top-0 left-1/2 -translate-x-1/2 w-full h-32 bg-brand-orange/5 blur-[60px] pointer-events-none" />

      <div v-if="offer" class="mb-5 relative z-10">
        <OfferContextBanner :offer="offer" compact />
      </div>

      <h3 class="text-xl font-display font-bold text-slate-900 mb-6 relative z-10">
        {{ ui.checkout.reservationRequest }}
      </h3>

      <div class="flex gap-4 mb-8 relative z-10">
        <div class="relative">
          <img
            v-if="imageUrl"
            :src="imageUrl"
            :alt="vehicleModel || vehicleBrand || ui.checkout.selectedVehicle"
            class="w-24 h-24 object-cover rounded-2xl shadow-sm"
          >
          <div
            v-else
            class="w-24 h-24 rounded-2xl shadow-sm bg-slate-100 text-slate-400 flex items-center justify-center"
          >
            <Car class="w-8 h-8" />
          </div>
          <div class="absolute -top-2 -right-2 w-6 h-6 bg-emerald-500 rounded-full border-2 border-white flex items-center justify-center shadow-sm">
            <Check class="w-3 h-3 text-white" />
          </div>
        </div>

        <div>
          <div v-if="vehicleType" class="text-xs font-bold uppercase tracking-widest text-brand-orange mb-1">{{ vehicleType }}</div>
          <h4 class="font-bold text-slate-900 text-lg leading-tight">{{ vehicleHeading }}</h4>
          <p v-if="vehicleSubheading" class="text-slate-500">{{ vehicleSubheading }}</p>
        </div>
      </div>

      <div class="space-y-4 mb-8 relative z-10">
        <div class="flex justify-between text-slate-600 text-sm">
          <span>{{ ui.checkout.rentalPeriod }}</span>
          <span class="font-medium text-slate-900">
            {{ rentalPeriodLabel }}
          </span>
        </div>

        <div
          v-for="line in summaryLines"
          :key="line.code || line.label"
          :class="[
            'flex justify-between text-sm',
            Number(line.amount || 0) >= 0 ? 'text-slate-600' : 'text-emerald-600 font-medium',
          ]"
        >
          <span>{{ line.localizedLabel || line.label }}</span>
          <span class="font-medium" :class="Number(line.amount || 0) >= 0 ? 'text-slate-900' : 'text-emerald-600'">
            {{ formatMoney(line.amount, currencyCode) }}
          </span>
        </div>
      </div>

      <div class="border-t border-slate-200/50 pt-6 mb-8 flex justify-between items-end relative z-10">
        <div>
          <div class="text-sm text-slate-500 mb-1">{{ ui.checkout.totalAmount }}</div>
          <div class="text-xs text-slate-400">{{ ui.checkout.includesAllTaxes }}</div>
        </div>

        <div class="font-display font-bold text-4xl tracking-tighter text-slate-900">
          {{ formatMoney(displayTotalAmount, currencyCode) }}
        </div>
      </div>

      <div class="bg-white/50 backdrop-blur-sm border border-white/60 rounded-2xl p-4 flex items-start gap-3 relative z-10 shadow-sm">
        <Shield class="w-5 h-5 text-emerald-500 shrink-0 mt-0.5" />
        <p class="text-xs text-slate-500 leading-relaxed">
          <strong class="text-slate-900">{{ ui.checkout.secureBooking }}</strong>
          {{ paymentCopy }}
        </p>
      </div>
    </div>
  </div>
</template>
