<script setup>
import { motion } from 'motion-v'
import { ArrowRight, Calendar, Car, Clock, MapPin, Search, ShieldCheck, User } from 'lucide-vue-next'
import { buildManagePageSeo, useManageContent } from '~/content/manage'
import { resolvePublicApiError, splitHeadline } from '~/content/utils'
import { buildTrackRoute } from '~/utils/public-routes'
import { buildPublicSeoLinks } from '~/utils/public-seo'

definePageMeta({
  siteHeaderTheme: 'dark',
  siteHeaderOverlay: true,
})

const { lookupBooking } = usePublicBookingLookup()
const { locale } = usePublicLocale()
const {
  managePage,
  manageCapabilities,
  manageHero,
  manageLookup,
  manageSupport,
} = useManageContent()

const bookingRef = ref('')
const contactValue = ref('')
const isSubmitting = ref(false)
const lookupError = ref('')
const {
  markSubmitAttempt,
  resetSubmitAttempt,
  submitAttempted,
} = useSubmitAttempt()

const headline = computed(() => splitHeadline(manageHero.value.title))
const isFormValid = computed(() => bookingRef.value.trim() !== '' && contactValue.value.trim() !== '')
const isBookingRefEmpty = computed(() => bookingRef.value.trim() === '')
const isContactValueEmpty = computed(() => contactValue.value.trim() === '')
const runtimeConfig = useRuntimeConfig()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const managePageSeo = computed(() => buildManagePageSeo(managePage.value, pageOrigin.value))

const capabilityIcons = {
  calendar: Calendar,
  car: Car,
  'map-pin': MapPin,
  clock: Clock,
}

const capabilityThemes = {
  calendar: {
    iconClass: 'text-brand-orange',
    wrapperClass: 'bg-brand-orange/10',
  },
  car: {
    iconClass: 'text-blue-600',
    wrapperClass: 'bg-blue-50',
  },
  'map-pin': {
    iconClass: 'text-emerald-600',
    wrapperClass: 'bg-emerald-50',
  },
  clock: {
    iconClass: 'text-rose-600',
    wrapperClass: 'bg-rose-50',
  },
}

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

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

function parseLookupPayload() {
  const contact = contactValue.value.trim()
  const isEmail = contact.includes('@')

  return {
    reference: bookingRef.value.trim(),
    email: isEmail ? contact : undefined,
    phone: isEmail ? undefined : contact,
  }
}

async function handleSubmit() {
  markSubmitAttempt()

  if (!isFormValid.value || isSubmitting.value) {
    return
  }

  isSubmitting.value = true
  lookupError.value = ''

  try {
    const booking = await lookupBooking(parseLookupPayload())
    const token = booking?.public_portal_token

    if (!token) {
      throw new Error('Booking token was not returned.')
    }

    await navigateTo(buildTrackRoute(token, {}, {
      locale: locale.value,
    }))
  } catch (error) {
    console.error('Failed to lookup public booking', error)
    lookupError.value = resolvePublicApiError(error, manageLookup.value.lookupError, locale.value)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<template>
  <div class="min-h-screen flex flex-col font-sans">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 mt-6 w-full">
      <div class="bg-slate-900 text-white pt-16 pb-24 px-4 sm:px-6 relative overflow-hidden rounded-[2.5rem] shadow-2xl">
        <div class="absolute inset-0 overflow-hidden pointer-events-none">
          <div class="absolute top-[-20%] right-[-10%] w-[50%] h-[50%] rounded-full bg-brand-orange/20 blur-[120px]" />
          <div class="absolute bottom-[-20%] left-[-10%] w-[50%] h-[50%] rounded-full bg-blue-500/10 blur-[120px]" />
        </div>

        <div class="max-w-3xl mx-auto relative z-10 text-center">
          <motion.div
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-md border border-white/10 mb-6"
          >
            <User class="w-4 h-4 text-brand-orange" />
            <span class="text-xs font-bold uppercase tracking-widest text-white">{{ manageHero.badge }}</span>
          </motion.div>

          <motion.h1
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.1 }"
            class="text-4xl md:text-5xl lg:text-6xl font-display font-black tracking-tight uppercase leading-[1.1] mb-6"
          >
            {{ headline.leading }} <span class="text-brand-orange">{{ headline.accent }}</span>
          </motion.h1>

          <motion.p
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.2 }"
            class="text-slate-400 text-lg"
          >
            {{ manageHero.description }}
          </motion.p>

        </div>
      </div>
    </div>

    <div class="flex-grow max-w-7xl mx-auto px-4 sm:px-6 py-12 w-full">
      <div class="grid lg:grid-cols-2 gap-12 items-start">
        <motion.div
          :initial="{ opacity: 0, x: -20 }"
          :animate="{ opacity: 1, x: 0 }"
          :transition="{ delay: 0.3 }"
          class="bg-white rounded-3xl p-8 shadow-xl border border-slate-100 relative overflow-hidden"
        >
          <div class="absolute top-0 right-0 w-32 h-32 bg-brand-orange/5 rounded-bl-full -z-10" />

          <h2 class="text-2xl font-display font-bold text-slate-900 mb-2">{{ manageLookup.title }}</h2>
          <p class="text-slate-500 mb-8">{{ manageLookup.description }}</p>

          <form class="space-y-6" @submit.prevent="handleSubmit">
            <div>
              <label :class="['block text-sm font-semibold mb-2', submitAttempted && isBookingRefEmpty ? 'text-red-500' : 'text-slate-700']">{{ manageLookup.labels.reference }}</label>
              <div class="relative">
                <Search class="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <input
                  v-model="bookingRef"
                  type="text"
                  :placeholder="manageLookup.placeholders.reference"
                  :class="['w-full bg-slate-50 border rounded-xl py-3 pl-12 pr-4 focus:outline-none focus:ring-2 transition-all', submitAttempted && isBookingRefEmpty ? 'border-red-300 focus:ring-red-200 focus:border-red-400' : 'border-slate-200 focus:ring-brand-orange/50 focus:border-brand-orange']"
                >
              </div>
            </div>

            <div>
              <label :class="['block text-sm font-semibold mb-2', submitAttempted && isContactValueEmpty ? 'text-red-500' : 'text-slate-700']">{{ manageLookup.labels.contact }}</label>
              <div class="relative">
                <User class="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <input
                  v-model="contactValue"
                  type="text"
                  :placeholder="manageLookup.placeholders.contact"
                  :class="['w-full bg-slate-50 border rounded-xl py-3 pl-12 pr-4 focus:outline-none focus:ring-2 transition-all', submitAttempted && isContactValueEmpty ? 'border-red-300 focus:ring-red-200 focus:border-red-400' : 'border-slate-200 focus:ring-brand-orange/50 focus:border-brand-orange']"
                >
              </div>
            </div>

            <div v-if="submitAttempted && !isFormValid" class="rounded-xl border border-red-100 bg-red-50/80 px-4 py-3 text-sm text-red-600">
              {{ ui.common.fillRequiredFields }}
            </div>

            <button
              type="submit"
              :disabled="isSubmitting"
              class="w-full font-bold py-4 rounded-xl transition-colors flex items-center justify-center gap-2 bg-brand-orange text-white hover:bg-[#E66000] disabled:pointer-events-none"
            >
              <template v-if="isSubmitting">
                <div class="w-5 h-5 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                {{ manageLookup.submittingLabel }}
              </template>
              <template v-else>
                {{ manageLookup.submitLabel }}
                <ArrowRight class="w-5 h-5" />
              </template>
            </button>

            <p v-if="lookupError" class="text-sm text-red-500">
              {{ lookupError }}
            </p>
          </form>

          <div class="mt-8 pt-8 border-t border-slate-100 flex items-start gap-4">
            <div class="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center flex-shrink-0">
              <ShieldCheck class="w-5 h-5 text-slate-600" />
            </div>
            <div>
              <h4 class="text-sm font-bold text-slate-900">{{ manageLookup.secureTitle }}</h4>
              <p class="text-sm text-slate-500 mt-1">
                {{ manageLookup.secureDescription }}
              </p>
            </div>
          </div>
        </motion.div>

        <motion.div
          :initial="{ opacity: 0, x: 20 }"
          :animate="{ opacity: 1, x: 0 }"
          :transition="{ delay: 0.4 }"
          class="space-y-8"
        >
          <div>
            <h3 class="text-2xl font-display font-bold text-slate-900 mb-6">{{ manageLookup.capabilitiesHeading }}</h3>

            <div class="space-y-6">
              <div v-for="item in manageCapabilities" :key="item.title" class="flex gap-4">
                <div :class="['w-12 h-12 rounded-2xl flex items-center justify-center flex-shrink-0', capabilityThemes[item.iconKey]?.wrapperClass]">
                  <component :is="capabilityIcons[item.iconKey]" :class="['w-6 h-6', capabilityThemes[item.iconKey]?.iconClass]" />
                </div>
                <div>
                  <h4 class="text-lg font-bold text-slate-900">{{ item.title }}</h4>
                  <p class="text-slate-600 mt-1">{{ item.description }}</p>
                </div>
              </div>
            </div>
          </div>

          <div class="bg-slate-900 rounded-3xl p-8 text-white">
            <h4 class="text-lg font-bold mb-2">{{ manageSupport.title }}</h4>
            <p class="text-slate-400 mb-6">{{ manageSupport.description }}</p>
            <div class="flex flex-col sm:flex-row gap-4">
              <a :href="`tel:${manageSupport.phone.replace(/\s/g, '')}`" class="bg-white/10 hover:bg-white/20 text-white px-6 py-3 rounded-xl font-bold transition-colors text-center">
                {{ manageSupport.phone }}
              </a>
              <a :href="`mailto:${manageSupport.email}`" class="bg-brand-orange hover:bg-orange-600 text-white px-6 py-3 rounded-xl font-bold transition-colors text-center">
                {{ manageSupport.emailLabel }}
              </a>
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  </div>
</template>
