<script setup>
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { AnimatePresence, motion } from 'motion-v'
import {
  ArrowLeft,
  Check,
  ChevronDown,
  MessageCircle,
  PhoneCall,
  Send,
  Shield,
  ShieldCheck,
  Sparkles,
  X,
} from 'lucide-vue-next'

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  car: {
    type: Object,
    default: null,
  },
  insuranceOptions: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits([
  'open',
  'close',
  'backdrop-click',
  'primary-action',
  'secondary-action',
])

const DAYS = 7

const EXTRA_INFO = {
  driver: { pricePerDay: 8, label: 'Additional driver' },
  seat: { pricePerDay: 7, label: 'Child seat' },
  wifi: { pricePerDay: 5, label: 'Wi-Fi hotspot' },
  gps: { pricePerDay: 5, label: 'GPS Navigation' },
  roof_box: { pricePerDay: 10, label: 'Roof Box' },
  stroller: { pricePerDay: 6, label: 'Baby Stroller' },
}

const EXTRA_ORDER = Object.keys(EXTRA_INFO)

function createExtrasState() {
  return {
    driver: false,
    seat: false,
    wifi: false,
    gps: false,
    roof_box: false,
    stroller: false,
  }
}

const step = ref('configure')
const selectedInsuranceId = ref('')
const showPriceDetails = ref(false)
const showAllExtras = ref(false)
const isEditingTrip = ref(false)
const contactMethod = ref('whatsapp')
const phoneNumber = ref('')
const countryCode = ref('+995')
const extras = ref(createExtrasState())

const carTitle = computed(() => props.car?.name ?? '')
const carCategory = computed(() => props.car?.category ?? '')
const carTransmission = computed(() => props.car?.specs?.transmission ?? '')
const carFuel = computed(() => props.car?.specs?.fuel ?? '')
const carSeats = computed(() => props.car?.specs?.seats ?? '')
const carImage = computed(() => props.car?.image ?? '')
const carPricePerDay = computed(() => props.car?.price ?? '')
const carTrunk = computed(() => props.car?.trunk ?? '')

const insuranceOptions = computed(() => (Array.isArray(props.insuranceOptions) ? props.insuranceOptions : [])
  .filter((item) => String(item?.kind || item?.kindLabel || '').trim().toLowerCase() === 'insurance')
  .sort((left, right) => Number(left?.sortOrder || 0) - Number(right?.sortOrder || 0)))
const includedInsuranceOptions = computed(() => insuranceOptions.value.filter((item) => isIncludedInsurance(item)))
const paidInsuranceOptions = computed(() => insuranceOptions.value.filter((item) => !isIncludedInsurance(item)))
const recommendedInsuranceId = computed(() => {
  if (!paidInsuranceOptions.value.length) {
    return ''
  }

  const recommendedOption = [...paidInsuranceOptions.value]
    .sort((left, right) => Number(right?.price || 0) - Number(left?.price || 0) || Number(left?.sortOrder || 0) - Number(right?.sortOrder || 0))[0]

  return String(recommendedOption?.id || '').trim()
})
const selectedInsuranceOption = computed(() => insuranceOptions.value.find((item) => String(item?.id || '').trim() === selectedInsuranceId.value)
  || includedInsuranceOptions.value[0]
  || paidInsuranceOptions.value[0]
  || null)
const selectedInsurancePricingType = computed(() => String(selectedInsuranceOption.value?.pricingType || '').trim().toLowerCase())
const selectedInsurancePrice = computed(() => Number(selectedInsuranceOption.value?.price || 0))
const selectedInsuranceTotal = computed(() => {
  if (!selectedInsuranceOption.value || selectedInsurancePricingType.value === 'included') {
    return 0
  }

  return selectedInsurancePricingType.value === 'per_day'
    ? selectedInsurancePrice.value * DAYS
    : selectedInsurancePrice.value
})
const selectedInsuranceName = computed(() => {
  if (!selectedInsuranceOption.value) {
    return ''
  }

  return selectedInsurancePricingType.value === 'included'
    ? 'Included'
    : String(selectedInsuranceOption.value?.name || '').trim()
})
const selectedInsurancePriceLabel = computed(() => {
  if (!selectedInsuranceOption.value || selectedInsurancePricingType.value === 'included') {
    return ''
  }

  return `+$${selectedInsurancePrice.value}${selectedInsurancePricingType.value === 'per_day' ? '/day' : ''}`
})
const selectedInsuranceTotalLabel = computed(() => {
  if (!selectedInsuranceOption.value) {
    return '$0'
  }

  if (selectedInsurancePricingType.value === 'included') {
    return 'Included'
  }

  return `$${selectedInsuranceTotal.value}`
})
const includedInsuranceSummaryText = computed(() => {
  const names = includedInsuranceOptions.value
    .map((option) => String(option?.name || '').trim())
    .filter(Boolean)

  if (!names.length) {
    return ''
  }

  if (names.length === 1) {
    return `${names[0]} is already included in the rental package.`
  }

  if (names.length === 2) {
    return `${names[0]} and ${names[1]} are already included in the rental package.`
  }

  return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} are already included in the rental package.`
})
const refundableDeposit = computed(() => Number(props.car?.deposit || props.car?.filterMeta?.deposit?.amount || 0))
const extrasTotal = computed(() => Object.entries(extras.value).reduce(
  (total, [key, enabled]) => total + (enabled ? EXTRA_INFO[key].pricePerDay * DAYS : 0),
  0,
))
const visibleExtras = computed(() => (showAllExtras.value ? EXTRA_ORDER : EXTRA_ORDER.slice(0, 3)))

function isIncludedInsurance(option) {
  return String(option?.pricingType || '').trim().toLowerCase() === 'included'
}

function isPerDayInsurance(option) {
  return String(option?.pricingType || '').trim().toLowerCase() === 'per_day'
}

function selectInsuranceOption(option) {
  selectedInsuranceId.value = String(option?.id || '').trim()
}

function syncInsuranceSelection(force = false) {
  const currentExists = insuranceOptions.value.some((option) => String(option?.id || '').trim() === selectedInsuranceId.value)

  if (!force && currentExists) {
    return
  }

  const defaultOption = includedInsuranceOptions.value[0] || paidInsuranceOptions.value[0] || null
  selectedInsuranceId.value = defaultOption ? String(defaultOption.id || '').trim() : ''
}

function isSelectedInsurance(option) {
  return String(option?.id || '').trim() === selectedInsuranceId.value
}

function isRecommendedInsurance(option) {
  return String(option?.id || '').trim() === recommendedInsuranceId.value
}

function getInsuranceUnitPriceLabel(option) {
  if (isIncludedInsurance(option)) {
    return 'Included'
  }

  const price = Number(option?.price || 0)

  return `+$${price}${isPerDayInsurance(option) ? '/day' : ''}`
}

function getInsuranceTotalPriceLabel(option) {
  if (isIncludedInsurance(option)) {
    return 'Included'
  }

  const price = Number(option?.price || 0)

  return `$${isPerDayInsurance(option) ? price * DAYS : price}`
}

function getInsuranceTotalCaption(option) {
  if (isIncludedInsurance(option)) {
    return 'Included'
  }

  return `(${getInsuranceTotalPriceLabel(option).replace('$', '')} total)`
}

const insuranceIconByKey = {
  shield: Shield,
  'shield-check': ShieldCheck,
}

function resolveInsuranceIcon(option) {
  return insuranceIconByKey[String(option?.iconKey || '').trim()] || ShieldCheck
}

function resetState() {
  step.value = 'configure'
  selectedInsuranceId.value = ''
  showPriceDetails.value = false
  showAllExtras.value = false
  isEditingTrip.value = false
  contactMethod.value = 'whatsapp'
  phoneNumber.value = ''
  countryCode.value = '+995'
  extras.value = createExtrasState()
}

function closeModal() {
  resetState()
  emit('close', { car: props.car })
}

function handleBackdropClick() {
  emit('backdrop-click', { car: props.car })
  closeModal()
}

function handlePrimaryAction() {
  emit('primary-action', {
    car: props.car,
    step: step.value,
    insuranceId: selectedInsuranceId.value,
    insuranceType: selectedInsurancePricingType.value,
    insurance: selectedInsuranceOption.value,
  })
}

function handleSecondaryAction() {
  emit('secondary-action', {
    car: props.car,
    step: step.value,
    insuranceId: selectedInsuranceId.value,
    insuranceType: selectedInsurancePricingType.value,
    insurance: selectedInsuranceOption.value,
  })
}

function handleBackToHome() {
  handleSecondaryAction()
  resetState()
}

function toggleExtra(key) {
  extras.value = {
    ...extras.value,
    [key]: !extras.value[key],
  }
}

function setScrollLock(locked) {
  if (typeof document === 'undefined') return

  if (locked) {
    document.body.style.overflow = 'hidden'
    document.body.style.overscrollBehavior = 'none'
    document.body.style.touchAction = 'none'
    document.documentElement.style.overflow = 'hidden'
    document.body.dataset.scrollLock = 'true'
    return
  }

  document.body.style.overflow = ''
  document.body.style.overscrollBehavior = ''
  document.body.style.touchAction = ''
  document.documentElement.style.overflow = ''
  delete document.body.dataset.scrollLock
}

watch(
  () => props.open,
  (isOpen) => {
    setScrollLock(Boolean(isOpen))

    if (isOpen) {
      resetState()
      syncInsuranceSelection(true)
      emit('open', {
        car: props.car,
        insuranceId: selectedInsuranceId.value,
        insurance: selectedInsuranceOption.value,
      })
    }
  },
  { immediate: true },
)

watch(
  () => insuranceOptions.value.map((option) => String(option?.id || '').trim()).join('|'),
  () => {
    syncInsuranceSelection(false)
  },
  { immediate: true },
)

onBeforeUnmount(() => {
  setScrollLock(false)
})
</script>

<template>
  <Teleport to="body">
    <AnimatePresence>
      <motion.div
        v-if="open"
        :initial="{ opacity: 0 }"
        :animate="{ opacity: 1 }"
        :exit="{ opacity: 0 }"
        class="fixed inset-0 z-[200] overflow-y-auto overscroll-contain"
      >
        <div
          class="fixed inset-0 bg-slate-900/20 backdrop-blur-md"
          @click="handleBackdropClick"
        />

        <div class="min-h-full flex flex-col py-4 sm:py-8 lg:py-12 items-center justify-start sm:px-4 lg:px-8 pointer-events-none relative z-10 w-full">
          <motion.div
            :initial="{ scale: 0.95, opacity: 0, y: 20 }"
            :animate="{ scale: 1, opacity: 1, y: 0 }"
            :exit="{ scale: 0.95, opacity: 0, y: 20 }"
            class="w-full max-w-[960px] min-h-[700px] bg-white/95 backdrop-blur-lg rounded-[32px] shadow-[0_24px_60px_-12px_rgba(0,0,0,0.15)] flex flex-col md:flex-row border border-white/60 relative z-10 overflow-hidden pointer-events-auto shrink-0"
          >
          <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(96,165,250,0.16),transparent_42%),radial-gradient(circle_at_bottom_left,rgba(52,211,153,0.10),transparent_38%),linear-gradient(180deg,rgba(255,255,255,0.28),rgba(255,255,255,0.10))]" />
          <div class="pointer-events-none absolute inset-x-[-10%] top-[18%] h-[48%] rounded-full bg-slate-100/25 blur-[90px]" />

          <button
            type="button"
            class="absolute top-5 right-5 md:top-6 md:right-6 p-2 rounded-full hover:bg-slate-100 transition-colors z-20 text-slate-400 hover:text-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-200"
            @click="closeModal"
          >
            <X class="w-5 h-5" stroke-width="2.5" />
          </button>

          <motion.div
            v-if="step === 'success'"
            key="success"
            :initial="{ opacity: 0, scale: 0.95 }"
            :animate="{ opacity: 1, scale: 1 }"
            class="flex-1 flex flex-col items-center justify-center p-10 text-center min-h-[500px] w-full"
          >
            <div class="w-24 h-24 bg-emerald-100 rounded-full flex items-center justify-center mb-6">
              <Check class="w-12 h-12 text-emerald-500" stroke-width="3" />
            </div>
            <h2 class="text-4xl font-bold text-slate-900 mb-4 tracking-tight">
              Request Sent!
            </h2>
            <p class="text-slate-500 font-medium mb-8 max-w-md leading-relaxed text-lg">
              We've received your booking request for the <strong>{{ carTitle }}</strong>. We'll contact you shortly via <strong class="capitalize">{{ contactMethod }}</strong> at <strong>{{ countryCode }} {{ phoneNumber }}</strong> to confirm your reservation.
            </p>
            <button
              type="button"
              class="px-8 py-4 bg-slate-100 text-slate-900 font-bold rounded-2xl hover:bg-slate-200 transition-colors"
              @click="handleBackToHome"
            >
              Back to Home
            </button>
          </motion.div>

          <template v-else>
            <div class="flex-1 md:w-[62%] p-6 md:p-10 flex flex-col z-10 relative md:rounded-l-[32px]">
              <AnimatePresence mode="wait">
                <motion.div
                  v-if="step === 'configure'"
                  key="configure"
                  :initial="{ opacity: 0, x: -10 }"
                  :animate="{ opacity: 1, x: 0 }"
                  :exit="{ opacity: 0, x: -10 }"
                  :transition="{ duration: 0.2 }"
                  class="flex flex-col h-full"
                >
                <div class="mb-6 flex flex-col sm:flex-row justify-between items-start gap-6">
                  <div class="flex-1 mt-1">
                    <div class="flex flex-wrap items-center gap-2 mb-2">
                      <span
                        v-if="carCategory"
                        class="inline-flex items-center bg-white/50 backdrop-blur-sm border border-white/60 text-slate-600 text-[10px] font-bold uppercase tracking-widest px-2.5 py-1.5 rounded-md shadow-[0_2px_10px_rgba(0,0,0,0.02)]"
                      >
                        {{ carCategory }}
                      </span>
                      <span class="inline-flex items-center bg-gradient-to-r from-amber-100/80 to-amber-50/80 backdrop-blur-sm border border-amber-200/60 text-amber-700 text-[10px] font-bold uppercase tracking-widest px-2.5 py-1.5 rounded-md shadow-[0_2px_10px_rgba(251,191,36,0.1)]">
                        <Sparkles class="w-3 h-3 mr-1" /> Smart choice
                      </span>
                    </div>
                    <h1 class="text-3xl font-bold text-slate-900 tracking-tight leading-none mb-2">
                      {{ carTitle }}
                    </h1>
                    <p class="text-slate-500 text-sm font-medium">
                      {{ carCategory }}
                    </p>

                    <div class="flex flex-wrap items-center gap-x-3 gap-y-2 mt-4 text-[13px] font-medium text-slate-600 capitalize">
                      <span v-if="carTransmission" class="flex items-center gap-1.5"><span class="text-[10px] text-slate-400">●</span> {{ carTransmission }}</span>
                      <span v-if="carFuel" class="flex items-center gap-1.5"><span class="text-[10px] text-slate-400">●</span> {{ carFuel }}</span>
                      <span v-if="carSeats !== '' && carSeats !== null && carSeats !== undefined" class="flex items-center gap-1.5"><span class="text-[10px] text-slate-400">●</span> {{ carSeats }} seats</span>
                    </div>
                  </div>

                  <div class="w-full sm:w-[260px] h-[140px] shrink-0 bg-white/40 backdrop-blur-md border border-white/60 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.8)] rounded-2xl flex items-center justify-center relative mt-2 sm:mt-0 p-3 group">
                    <div class="absolute inset-0 bg-gradient-to-tr from-white/20 to-transparent rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                    <img
                      :src="carImage"
                      :alt="carTitle"
                      class="w-full h-full object-contain drop-shadow-[0_15px_15px_rgba(0,0,0,0.15)] relative z-10 transition-transform duration-500 group-hover:scale-105"
                      referrerpolicy="no-referrer"
                    >
                    <span
                      v-if="carTrunk"
                      class="absolute bottom-3 right-3 text-[10px] text-slate-500 font-bold uppercase bg-white/90 shadow-sm backdrop-blur-md px-2 py-1 rounded z-20 transition-all border border-slate-100"
                    >
                      {{ carTrunk }}
                    </span>
                  </div>
                </div>

                <div
                  v-if="isEditingTrip"
                  class="bg-white/50 backdrop-blur-xl border border-white/60 rounded-2xl p-4 sm:p-5 mb-8 shadow-[0_8px_30px_rgb(0,0,0,0.04)]"
                >
                  <div class="flex flex-col gap-4">
                    <div>
                      <label class="text-[10px] uppercase tracking-wider text-slate-500 font-bold mb-1.5 block">Pickup & Drop-off Location</label>
                      <input
                        type="text"
                        class="w-full bg-white/60 backdrop-blur-sm border border-white/80 shadow-sm rounded-xl px-4 py-3 text-sm font-semibold text-slate-900 focus:outline-none focus:border-blue-500 focus:bg-white/90 transition-colors"
                        value="Tbilisi, Georgia"
                      >
                    </div>
                    <div class="flex flex-col sm:flex-row gap-4">
                      <div class="flex-1 relative">
                        <label class="text-[10px] uppercase tracking-wider text-slate-500 font-bold mb-1.5 block">From</label>
                        <input
                          type="date"
                          class="custom-date-input w-full bg-white/60 backdrop-blur-sm border border-white/80 shadow-sm rounded-xl px-4 py-3 text-sm font-semibold text-slate-900 focus:outline-none focus:border-blue-500 focus:bg-white/90 transition-colors appearance-none min-h-[46px]"
                          value="2024-05-10"
                        >
                      </div>
                      <div class="flex-1 relative">
                        <label class="text-[10px] uppercase tracking-wider text-slate-500 font-bold mb-1.5 block">To</label>
                        <input
                          type="date"
                          class="custom-date-input w-full bg-white/60 backdrop-blur-sm border border-white/80 shadow-sm rounded-xl px-4 py-3 text-sm font-semibold text-slate-900 focus:outline-none focus:border-blue-500 focus:bg-white/90 transition-colors appearance-none min-h-[46px]"
                          value="2024-05-17"
                        >
                      </div>
                    </div>
                    <div class="flex justify-end gap-2 mt-2 pt-4 border-t border-slate-100">
                      <button
                        type="button"
                        class="px-5 py-2.5 text-xs font-bold text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-xl transition-colors"
                        @click="isEditingTrip = false"
                      >
                        Cancel
                      </button>
                      <button
                        type="button"
                        class="px-5 py-2.5 text-xs font-bold bg-slate-900 text-white rounded-xl hover:bg-black transition-colors focus:ring-2 focus:ring-slate-300"
                        @click="isEditingTrip = false"
                      >
                        Save Details
                      </button>
                    </div>
                  </div>
                </div>

                <div
                  v-else
                  class="bg-white/40 backdrop-blur-md border border-white/60 rounded-2xl p-4 mb-8 flex flex-col sm:flex-row items-center justify-between gap-4 transition-all hover:bg-white/60 hover:shadow-sm"
                >
                  <div class="flex items-center gap-6 sm:gap-8 min-w-0 w-full sm:w-auto">
                    <div class="min-w-0 flex-1 sm:flex-initial">
                      <p class="text-[10px] uppercase tracking-wider text-slate-400 font-bold mb-1">Location</p>
                      <p class="text-sm font-semibold text-slate-900 truncate">Tbilisi, Georgia</p>
                    </div>

                    <div class="h-8 w-[1px] bg-slate-200 shrink-0" />

                    <div class="min-w-0 flex-1 sm:flex-initial">
                      <p class="text-[10px] uppercase tracking-wider text-slate-400 font-bold mb-1">Duration</p>
                      <p class="text-sm font-semibold text-slate-900 truncate">May 10 — May 17 · 7 days</p>
                    </div>
                  </div>

                  <button
                    type="button"
                    class="text-blue-600 text-sm font-bold hover:text-blue-700 hover:underline underline-offset-2 transition-all p-2 -m-2 shrink-0"
                    @click="isEditingTrip = true"
                  >
                    Edit
                  </button>
                </div>

                <div v-if="insuranceOptions.length" class="mb-8">
                  <div class="mb-4">
                    <h3 class="text-lg font-bold text-slate-900 tracking-tight">
                      Choose your protection
                    </h3>
                    <p class="text-xs text-slate-500 mt-0.5">
                      Included coverages are grouped first. Paid upgrades follow below.
                    </p>
                  </div>

                  <div class="grid grid-cols-1 lg:grid-cols-3 gap-3 md:gap-4">
                    <button
                      v-if="includedInsuranceOptions.length"
                      type="button"
                      class="group relative overflow-hidden flex h-full min-h-[340px] flex-col rounded-[32px] border-2 p-5 md:p-6 text-left transition-all duration-200 bg-emerald-50/65 backdrop-blur-sm"
                      :class="selectedInsurancePricingType === 'included'
                        ? 'border-emerald-500 ring-1 ring-emerald-200/70 shadow-sm'
                        : 'border-emerald-200/70 hover:border-emerald-300 hover:shadow-sm'"
                      @click="selectInsuranceOption(includedInsuranceOptions[0])"
                    >
                      <div class="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(16,185,129,0.10),transparent_45%),linear-gradient(180deg,rgba(255,255,255,0.78),rgba(255,255,255,0.38))] pointer-events-none" />
                      <div class="relative z-10 flex h-full flex-col">
                        <div class="flex items-start justify-between gap-4">
                          <div class="min-w-0">
                            <div class="text-[24px] sm:text-[26px] font-bold text-slate-900 leading-tight">
                              Included
                            </div>
                            <div class="mt-3 text-[13px] sm:text-[14px] font-bold uppercase tracking-[0.28em] text-emerald-600">
                              FREE
                            </div>
                          </div>
                          <div class="w-14 h-14 sm:w-16 sm:h-16 rounded-full bg-emerald-500 flex items-center justify-center text-white shrink-0 shadow-sm">
                            <Check class="w-7 h-7 sm:w-8 sm:h-8" stroke-width="3" />
                          </div>
                        </div>

                        <p v-if="includedInsuranceSummaryText" class="mt-auto pt-10 text-[16px] sm:text-[17px] font-medium text-slate-600 leading-relaxed max-w-[28rem]">
                          {{ includedInsuranceSummaryText }}
                        </p>
                      </div>
                    </button>

                    <button
                      v-for="option in paidInsuranceOptions"
                      :key="option.id"
                      type="button"
                      class="group relative overflow-visible flex h-full min-h-[340px] flex-col rounded-[32px] border-2 p-5 md:p-6 text-left transition-all duration-200 bg-white/95 backdrop-blur-sm"
                      :class="isSelectedInsurance(option)
                        ? isRecommendedInsurance(option)
                          ? 'border-emerald-500 bg-emerald-50/70 shadow-sm'
                          : 'border-slate-900 bg-white shadow-sm'
                        : 'border-slate-200/70 hover:border-slate-300 hover:-translate-y-0.5 hover:shadow-sm'"
                      @click="selectInsuranceOption(option)"
                    >
                      <span
                        v-if="isRecommendedInsurance(option)"
                        class="absolute -top-[10px] left-1/2 -translate-x-1/2 text-white text-[9px] font-bold uppercase tracking-wider px-2.5 py-0.5 rounded-full shadow-sm z-10"
                        :class="isSelectedInsurance(option) ? 'bg-emerald-600' : 'bg-blue-600'"
                      >
                        Recommended
                      </span>

                      <motion.div
                        v-if="isSelectedInsurance(option)"
                        :initial="{ scale: 0 }"
                        :animate="{ scale: 1 }"
                        class="absolute top-4 right-4 w-8 h-8 rounded-full flex items-center justify-center z-10 shadow-sm"
                        :class="isRecommendedInsurance(option) ? 'bg-emerald-500' : 'bg-slate-900'"
                      >
                        <Check class="w-4 h-4 text-white" stroke-width="3" />
                      </motion.div>

                      <div class="relative z-10 flex h-full flex-col">
                        <div class="flex items-start justify-between gap-4">
                          <div :class="['w-14 h-14 sm:w-16 sm:h-16 rounded-full flex items-center justify-center shrink-0 transition-colors border', isSelectedInsurance(option) ? (isRecommendedInsurance(option) ? 'bg-emerald-500 text-white border-emerald-500/30' : 'bg-slate-900 text-white border-slate-900/60') : 'bg-white text-slate-500 border-slate-200/80']">
                            <component :is="resolveInsuranceIcon(option)" class="w-6 h-6 sm:w-7 sm:h-7" />
                          </div>
                          <div class="text-right shrink-0">
                            <div class="font-black text-[20px] sm:text-[22px] text-blue-600 leading-none tracking-tight">
                              {{ getInsuranceUnitPriceLabel(option) }}
                            </div>
                            <div class="mt-1 text-[9px] sm:text-[10px] font-semibold tracking-[0.18em] text-slate-400">
                              {{ getInsuranceTotalCaption(option) }}
                            </div>
                          </div>
                        </div>

                        <div class="mt-6 text-[18px] sm:text-[20px] font-bold text-slate-900 leading-tight max-w-[12rem]">
                          {{ option.name }}
                        </div>

                        <div v-if="option.kindLabel" class="mt-4 text-[10px] font-bold uppercase tracking-[0.32em] text-slate-400">
                          {{ option.kindLabel }}
                        </div>

                        <p class="mt-auto pt-7 text-[15px] sm:text-[16px] font-medium text-slate-600 leading-relaxed max-w-[18rem]">
                          {{ option.description }}
                        </p>
                      </div>
                    </button>
                  </div>
                </div>

                <div class="mb-4">
                  <div class="flex justify-between items-end mb-3">
                    <h3 class="text-sm font-bold text-slate-900 tracking-tight">
                      Popular extras
                    </h3>
                    <button
                      type="button"
                      class="text-blue-600 text-[11px] font-bold hover:text-blue-700 hover:underline underline-offset-2 transition-colors focus:outline-none"
                      @click="showAllExtras = !showAllExtras"
                    >
                      {{ showAllExtras ? 'Show less' : 'View all extras' }}
                    </button>
                  </div>

                  <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <AnimatePresence>
                      <motion.button
                        v-for="key in visibleExtras"
                        :key="key"
                        type="button"
                        :initial="{ opacity: 0, scale: 0.95 }"
                        :animate="{ opacity: 1, scale: 1 }"
                        :exit="{ opacity: 0, scale: 0.95 }"
                        class="flex items-center gap-3 p-3 border outline-none rounded-xl transition-all duration-200 text-left group"
                        :class="extras[key]
                          ? 'border-slate-400 bg-slate-100/80 backdrop-blur-sm shadow-[0_0_0_1px_rgba(148,163,184,0.3)]'
                          : 'border-white/60 bg-white/40 backdrop-blur-sm hover:border-slate-300 hover:shadow-sm'"
                        @click="toggleExtra(key)"
                      >
                        <div
                          class="w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors"
                          :class="extras[key] ? 'border-slate-900 bg-slate-900' : 'border-slate-300 group-hover:border-slate-400'"
                        >
                          <Check v-if="extras[key]" class="w-3 h-3 text-white" stroke-width="4" />
                        </div>
                        <div class="leading-tight">
                          <p
                            class="text-[11px] font-bold transition-colors"
                            :class="extras[key] ? 'text-slate-900' : 'text-slate-700'"
                          >
                            {{ EXTRA_INFO[key].label }}
                          </p>
                          <p
                            class="text-[10px] font-medium transition-colors"
                            :class="extras[key] ? 'text-slate-600' : 'text-slate-400'"
                          >
                            +${{ EXTRA_INFO[key].pricePerDay }}/day
                          </p>
                        </div>
                      </motion.button>
                    </AnimatePresence>
                  </div>
                </div>

                <div class="mt-auto pt-8 border-t border-slate-100 flex flex-wrap gap-x-8 gap-y-4 text-slate-500">
                  <div class="flex items-center gap-2 max-w-fit">
                    <div class="w-4 h-4 bg-emerald-100/80 text-emerald-600 rounded-full flex items-center justify-center text-[9px] font-extrabold shrink-0">
                      ✓
                    </div>
                    <span class="text-[10px] font-bold text-slate-500">No charge today</span>
                  </div>
                  <div class="flex items-center gap-2 max-w-fit">
                    <div class="w-4 h-4 bg-emerald-100/80 text-emerald-600 rounded-full flex items-center justify-center text-[9px] font-extrabold shrink-0">
                      ✓
                    </div>
                    <span class="text-[10px] font-bold text-slate-500">Free cancellation 48h prior</span>
                  </div>
                  <div class="flex items-center gap-2 max-w-fit">
                    <div class="w-4 h-4 bg-slate-100 text-slate-600 rounded-full flex items-center justify-center text-[9px] shrink-0 font-bold">
                      🔒
                    </div>
                    <span class="text-[10px] font-bold text-slate-500">Secure booking</span>
                  </div>
                </div>
                </motion.div>

                <motion.div
                  v-else
                  key="contact"
                  :initial="{ opacity: 0, x: 10 }"
                  :animate="{ opacity: 1, x: 0 }"
                  :exit="{ opacity: 0, x: 10 }"
                  :transition="{ duration: 0.2 }"
                  class="flex flex-col h-full"
                >
                <button
                  type="button"
                  class="flex items-center text-slate-500 hover:text-slate-900 text-sm font-bold mb-6 transition-colors w-fit group"
                  @click="step = 'configure'"
                >
                  <ArrowLeft class="w-4 h-4 mr-1.5 transition-transform group-hover:-translate-x-1" /> Back to details
                </button>

                <h2 class="text-2xl font-bold text-slate-900 mb-1 tracking-tight">
                  How should we contact you?
                </h2>
                <p class="text-slate-500 text-sm mb-8 font-medium">
                  We'll send your booking confirmation and pickup details soon.
                </p>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-8">
                  <button
                    type="button"
                    class="flex flex-col items-center justify-center p-4 rounded-2xl border-2 transition-all duration-200 outline-none"
                    :class="contactMethod === 'whatsapp'
                      ? 'border-[#25D366] bg-[#25D366]/10 backdrop-blur-sm text-[#075E54] shadow-sm'
                      : 'border-white/60 bg-white/40 backdrop-blur-sm hover:border-slate-300 text-slate-500 hover:text-slate-700'"
                    @click="contactMethod = 'whatsapp'"
                  >
                    <MessageCircle class="w-8 h-8 mb-2" :class="contactMethod === 'whatsapp' ? 'text-[#25D366]' : ''" />
                    <span class="font-bold text-sm">WhatsApp</span>
                  </button>
                  <button
                    type="button"
                    class="flex flex-col items-center justify-center p-4 rounded-2xl border-2 transition-all duration-200 outline-none"
                    :class="contactMethod === 'telegram'
                      ? 'border-[#0088cc] bg-[#0088cc]/10 backdrop-blur-sm text-[#0088cc] shadow-sm'
                      : 'border-white/60 bg-white/40 backdrop-blur-sm hover:border-slate-300 text-slate-500 hover:text-slate-700'"
                    @click="contactMethod = 'telegram'"
                  >
                    <Send class="w-8 h-8 mb-2" :class="contactMethod === 'telegram' ? 'text-[#0088cc]' : ''" />
                    <span class="font-bold text-sm">Telegram</span>
                  </button>
                  <button
                    type="button"
                    class="flex flex-col items-center justify-center p-4 rounded-2xl border-2 transition-all duration-200 outline-none"
                    :class="contactMethod === 'viber'
                      ? 'border-[#7360f2] bg-[#7360f2]/10 backdrop-blur-sm text-[#7360f2] shadow-sm'
                      : 'border-white/60 bg-white/40 backdrop-blur-sm hover:border-slate-300 text-slate-500 hover:text-slate-700'"
                    @click="contactMethod = 'viber'"
                  >
                    <PhoneCall class="w-8 h-8 mb-2" :class="contactMethod === 'viber' ? 'text-[#7360f2]' : ''" />
                    <span class="font-bold text-sm">Viber</span>
                  </button>
                </div>

                <div class="mb-auto">
                  <label class="block text-[11px] font-bold text-slate-900 uppercase tracking-wider mb-2">Phone Number</label>
                  <div class="flex bg-white/50 backdrop-blur-xl border border-white/80 rounded-2xl overflow-hidden focus-within:ring-[3px] focus-within:ring-slate-200 focus-within:border-slate-500 transition-all shadow-sm">
                    <div class="flex items-center bg-white/40 border-r border-white/60 px-4 group relative">
                      <span class="text-lg mr-2 leading-none">🇬🇪</span>
                      <select
                        v-model="countryCode"
                        class="bg-transparent text-sm font-bold text-slate-700 focus:outline-none appearance-none cursor-pointer pr-4 h-full"
                      >
                        <option value="+995">+995</option>
                        <option value="+1">+1</option>
                        <option value="+44">+44</option>
                        <option value="+33">+33</option>
                        <option value="+49">+49</option>
                      </select>
                      <ChevronDown class="w-3.5 h-3.5 text-slate-400 absolute right-4 pointer-events-none group-focus-within:text-slate-600 transition-colors" />
                    </div>
                    <input
                      v-model="phoneNumber"
                      type="tel"
                      placeholder="555 123 456"
                      class="flex-1 px-4 py-4 bg-transparent text-slate-900 font-bold text-lg placeholder:text-slate-400 placeholder:font-medium focus:outline-none w-full"
                    >
                  </div>
                </div>
                </motion.div>
              </AnimatePresence>
            </div>

            <div class="w-full md:w-[38%] bg-white/40 backdrop-blur-md border-t md:border-t-0 md:border-l border-white/60 p-6 md:p-10 shrink-0 relative z-0 md:rounded-r-[32px] rounded-b-[32px] md:rounded-bl-none">
              <div class="sticky top-6 flex flex-col self-start">
              <h2 class="text-xl font-bold text-slate-900 mb-6 tracking-tight">
                Booking summary
              </h2>

              <div class="bg-gradient-to-r from-amber-50/80 to-orange-50/50 backdrop-blur-sm border border-amber-200/50 rounded-xl p-3 mb-6 flex items-start shadow-[0_4px_12px_rgba(251,191,36,0.08)]">
                <span class="text-amber-500 font-extrabold shrink-0 mr-2.5 mt-0.5">
                  <Sparkles class="w-4 h-4" />
                </span>
              <p class="text-[11px] text-amber-900 font-medium leading-relaxed">
                  <strong class="font-bold">Excellent value!</strong> Travelers highly rate this car for comfort and fuel economy on 7+ day trips.
                </p>
              </div>

              <div class="mb-6">
                <div class="flex justify-between items-center mb-1">
                  <p class="text-sm font-semibold text-slate-500">Due now</p>
                  <p class="text-[32px] leading-tight font-bold text-slate-900">$0</p>
                </div>
                <p class="text-xs text-emerald-600 font-bold">You won't be charged today</p>
              </div>

              <div class="space-y-4 mb-8">
                <div class="flex justify-between items-start">
                  <div>
                    <p class="text-sm font-bold text-slate-900">Paid at pickup</p>
                    <p class="text-[11px] text-slate-500 font-medium mt-0.5">Remaining balance at arrival</p>
                  </div>
                  <p class="text-lg font-bold text-slate-900 leading-none mt-0.5">
                    <template v-if="carPricePerDay !== ''">
                      ${{ Number(carPricePerDay) * DAYS + selectedInsuranceTotal + extrasTotal }}
                    </template>
                  </p>
                </div>

                <div class="flex justify-between items-start pt-5 border-t border-slate-200">
                  <div>
                    <p class="text-sm font-bold text-slate-900">Refundable deposit</p>
                    <p class="text-[11px] text-slate-500 font-medium mt-0.5">Returned after vehicle inspection</p>
                  </div>
                  <p class="text-lg font-bold text-slate-900 leading-none mt-0.5">
                    {{ refundableDeposit === 0 ? '$0' : `$${refundableDeposit}` }}
                  </p>
                </div>
              </div>

              <button
                type="button"
                class="flex items-center justify-between w-full py-3 px-0 text-slate-500 text-[11px] tracking-wide uppercase font-bold border-b border-slate-200 mb-6 hover:text-slate-800 transition-colors focus:outline-none group"
                @click="showPriceDetails = !showPriceDetails"
              >
                <span>View price details</span>
                <span class="text-base leading-none bg-slate-200/50 w-5 h-5 rounded-full flex items-center justify-center transition-colors group-hover:bg-slate-200 text-slate-600">
                  {{ showPriceDetails ? '-' : '+' }}
                </span>
              </button>

              <AnimatePresence>
                <motion.div
                  v-if="showPriceDetails"
                  :initial="{ height: 0, opacity: 0 }"
                  :animate="{ height: 'auto', opacity: 1 }"
                  :exit="{ height: 0, opacity: 0 }"
                  class="overflow-hidden mb-2 -mt-4 text-[12px] font-medium text-slate-600"
                >
                    <div class="space-y-3 py-4 border-b border-slate-200 mb-6">
                      <div class="flex justify-between">
                      <span v-if="carPricePerDay !== ''">Car rental (${{ carPricePerDay }} × 7d)</span>
                      <span v-if="carPricePerDay !== ''" class="text-slate-900 font-bold">${{ Number(carPricePerDay) * DAYS }}</span>
                      </div>
                    <div class="flex justify-between text-blue-700">
                      <div class="min-w-0">
                        <span>Protection</span>
                        <div v-if="selectedInsuranceName" class="text-[10px] font-medium text-slate-400 mt-0.5 truncate">
                          {{ selectedInsuranceName }}
                        </div>
                      </div>
                      <div class="text-right">
                        <div class="font-bold">{{ selectedInsuranceTotalLabel }}</div>
                        <div v-if="selectedInsurancePriceLabel" class="text-[10px] font-medium text-slate-400 mt-0.5">
                          {{ selectedInsurancePriceLabel }}
                        </div>
                      </div>
                    </div>
                    <div v-if="extrasTotal > 0" class="flex justify-between">
                      <span>Extras</span>
                      <span class="text-slate-900 font-bold">${{ extrasTotal }}</span>
                    </div>
                    <div class="flex justify-between text-slate-400">
                      <span>Taxes & fees</span>
                      <span>Included</span>
                    </div>
                  </div>
                </motion.div>
              </AnimatePresence>

              <div class="mt-6 pt-4 border-t border-slate-200/60 md:border-t-0 md:pt-0">
                <button
                  v-if="step === 'configure'"
                  type="button"
                  class="relative w-full bg-slate-900 hover:bg-black text-white rounded-2xl py-4 flex flex-col items-center justify-center shadow-[0_8px_16px_-6px_rgba(0,0,0,0.3)] transition-all hover:shadow-[0_12px_20px_-8px_rgba(0,0,0,0.4)] hover:-translate-y-0.5 focus:ring-4 focus:ring-slate-300 outline-none overflow-hidden group"
                  @click="handlePrimaryAction(); step = 'contact'"
                >
                  <div class="absolute inset-0 bg-white/10 translate-y-full group-hover:translate-y-0 transition-transform duration-300 ease-out" />
                  <span class="block font-bold text-lg relative z-10 leading-tight">Reserve now</span>
                  <span class="block text-[11px] font-medium text-white/70 mt-0.5 relative z-10">$0 due today</span>
                </button>

                <button
                  v-else
                  type="button"
                  :disabled="!phoneNumber.trim()"
                  class="relative w-full bg-blue-600 hover:bg-blue-700 text-white disabled:bg-slate-300 disabled:text-slate-500 disabled:shadow-none disabled:hover:translate-y-0 disabled:cursor-not-allowed rounded-2xl py-4 flex flex-col items-center justify-center shadow-[0_8px_16px_-6px_rgba(37,99,235,0.3)] transition-all hover:shadow-[0_12px_20px_-8px_rgba(37,99,235,0.4)] hover:-translate-y-0.5 focus:ring-4 focus:ring-blue-300 outline-none overflow-hidden group"
                  @click="handlePrimaryAction(); step = 'success'"
                >
                  <div class="absolute inset-0 bg-white/10 translate-y-full group-hover:translate-y-0 transition-transform duration-300 ease-out" />
                  <span class="block font-bold text-lg relative z-10 leading-tight">Confirm Reservation</span>
                  <span class="block text-[11px] font-medium text-white/80 mt-0.5 relative z-10 capitalize">Via {{ contactMethod }}</span>
                </button>

                <p class="text-center text-[10px] text-slate-400 font-medium mt-4 px-2 leading-relaxed">
                  Free cancellation up to 48h before pickup · Secure 256-bit encrypted booking
                </p>
              </div>
            </div>
          </div>
          </template>
          </motion.div>
        </div>
      </motion.div>
    </AnimatePresence>
  </Teleport>
</template>

<style>
.custom-date-input::-webkit-calendar-picker-indicator {
  opacity: 0;
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  cursor: pointer;
}
</style>
