<script setup>
import { AnimatePresence, motion } from 'motion-v'
import {
  ArrowRight,
  Car,
  ChevronDown,
  CreditCard,
  FileText,
  HelpCircle,
  LifeBuoy,
  Mail,
  MapPin,
  PhoneCall,
  Search,
  ShieldCheck,
} from 'lucide-vue-next'
import {
  buildFaqPageSeo,
  useFaqContent,
} from '~/content/faq'
import { buildPublicSeoLinks } from '~/utils/public-seo'

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

const { localizedPath } = usePublicLocale()
const faqContent = useFaqContent()
const faqContentPage = computed(() => faqContent.faqContentPage.value)
const faqUi = computed(() => faqContent.faqUi.value)
const faqCategoryIcons = {
  car: Car,
  'credit-card': CreditCard,
  'file-text': FileText,
  'life-buoy': LifeBuoy,
  'map-pin': MapPin,
  'shield-check': ShieldCheck,
}

const faqCategories = computed(() => faqContent.faqCategories.value.map((category) => ({
  ...category,
  icon: faqCategoryIcons[category.iconKey] || HelpCircle,
})))

const activeCategory = ref('')
const searchQuery = ref('')
const openItems = reactive({})

watch(faqCategories, (categories) => {
  if (!activeCategory.value && categories[0]?.id) {
    activeCategory.value = categories[0].id
  }
}, { immediate: true })

function toggleItem(question) {
  openItems[question] = !openItems[question]
}

const filteredData = computed(() => {
  if (!searchQuery.value.trim()) {
    return faqCategories.value.find((category) => category.id === activeCategory.value)?.faqs || []
  }

  const query = searchQuery.value.toLowerCase()
  const results = []

  faqCategories.value.forEach((category) => {
    category.faqs.forEach((faq) => {
      if (faq.q.toLowerCase().includes(query) || faq.a.toLowerCase().includes(query)) {
        results.push({
          ...faq,
          category: category.title,
        })
      }
    })
  })

  return results
})

const activeCategoryMeta = computed(() => {
  return faqCategories.value.find((category) => category.id === activeCategory.value) || faqCategories.value[0]
})

const runtimeConfig = useRuntimeConfig()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const faqPageSeo = computed(() => buildFaqPageSeo(faqContentPage.value, pageOrigin.value))

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

useHead(() => ({
  link: buildPublicSeoLinks(faqPageSeo.value),
}))
</script>

<template>
  <div class="min-h-screen font-sans text-slate-900 pb-24 relative flex flex-col">
    <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-6xl 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"
          >
            <LifeBuoy class="w-4 h-4 text-brand-orange" />
            <span class="text-xs font-bold uppercase tracking-widest text-white">{{ faqContentPage.subtitle || faqContentPage.title }}</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"
          >
            {{ faqContentPage.title }}
          </motion.h1>

          <motion.p
            v-if="faqContentPage.excerpt"
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.15 }"
            class="max-w-3xl mx-auto text-base md:text-lg text-slate-300 leading-relaxed mb-8"
          >
            {{ faqContentPage.excerpt }}
          </motion.p>

          <motion.div
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.2 }"
            class="max-w-2xl mx-auto relative"
          >
            <div class="relative flex items-center">
              <Search class="absolute left-6 w-6 h-6 text-slate-400" />
              <input
                v-model="searchQuery"
                type="text"
                :placeholder="faqUi.searchPlaceholder"
                class="w-full bg-white/10 backdrop-blur-xl border border-white/20 text-white placeholder:text-slate-400 rounded-full py-5 pl-16 pr-6 outline-none focus:bg-white/20 focus:border-brand-orange/50 transition-all text-lg shadow-2xl"
              >
            </div>
          </motion.div>
        </div>
      </div>
    </div>

    <div class="max-w-6xl mx-auto px-4 sm:px-6 -mt-8 relative z-20 w-full flex-1 flex flex-col lg:flex-row gap-8">
      <div class="w-full lg:w-80 shrink-0">
        <div class="bg-white rounded-3xl shadow-xl shadow-slate-200/40 border border-slate-100 p-4 sticky top-24">
          <h3 class="text-xs font-bold uppercase tracking-widest text-slate-400 mb-4 px-4">{{ faqUi.categoriesHeading }}</h3>
          <div class="space-y-1">
            <button
              v-for="category in faqCategories"
              :key="category.id"
              type="button"
              :class="[
                'w-full flex items-center gap-4 px-4 py-3 rounded-2xl transition-all duration-300 text-left',
                activeCategory === category.id && !searchQuery
                  ? 'bg-brand-orange text-white shadow-md shadow-brand-orange/20'
                  : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900',
              ]"
              @click="activeCategory = category.id; searchQuery = ''"
            >
              <component :is="category.icon" :class="`w-5 h-5 ${activeCategory === category.id && !searchQuery ? 'text-white' : 'text-slate-400'}`" />
              <span class="font-semibold text-sm">{{ category.title }}</span>
            </button>
          </div>

          <div class="mt-8 p-6 bg-slate-50 rounded-2xl border border-slate-100 text-center">
            <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm">
              <PhoneCall class="w-5 h-5 text-brand-orange" />
            </div>
            <h4 class="font-bold text-slate-900 mb-2">{{ faqUi.supportTitle }}</h4>
            <p class="text-sm text-slate-500 mb-4">{{ faqUi.supportDescription }}</p>
            <a :href="`tel:${faqUi.supportPhone}`" class="inline-block w-full py-3 bg-slate-900 text-white rounded-xl text-xs font-bold uppercase tracking-wider hover:bg-slate-800 transition-colors">
              {{ faqUi.supportCtaLabel }}
            </a>
          </div>
        </div>
      </div>

      <div class="flex-1">
        <div class="bg-white rounded-3xl shadow-xl shadow-slate-200/40 border border-slate-100 p-6 sm:p-10 min-h-[500px]">
          <div v-if="searchQuery" class="mb-8">
            <h2 class="text-2xl font-display font-bold text-slate-900 mb-2">
              {{ faqUi.searchResultsTitle }}
            </h2>
            <p class="text-slate-500">
              {{ faqContent.formatFaqSearchResults(filteredData.length, searchQuery) }}
            </p>
          </div>
          <div v-else class="mb-8">
            <h2 class="text-3xl font-display font-bold text-slate-900 mb-3">
              {{ activeCategoryMeta.title }}
            </h2>
            <p class="text-slate-500 text-lg">
              {{ activeCategoryMeta.description }}
            </p>
          </div>

          <div v-if="filteredData.length > 0" class="space-y-4">
            <motion.div
              v-for="(item, index) in filteredData"
              :key="item.q"
              :initial="{ opacity: 0, y: 10 }"
              :animate="{ opacity: 1, y: 0 }"
              :transition="{ delay: index * 0.05 }"
              :class="[
                'border transition-all duration-300 rounded-2xl overflow-hidden',
                openItems[item.q] ? 'border-brand-orange/30 bg-brand-orange/5' : 'border-slate-100 bg-white hover:border-slate-200 hover:shadow-sm',
              ]"
            >
              <button
                type="button"
                class="w-full px-6 py-5 flex items-start sm:items-center justify-between text-left gap-4"
                @click="toggleItem(item.q)"
              >
                <div>
                  <div v-if="searchQuery" class="text-[10px] font-bold uppercase tracking-widest text-brand-orange mb-1">
                    {{ item.category }}
                  </div>
                  <h3 class="text-lg font-bold text-slate-900 leading-snug">{{ item.q }}</h3>
                </div>
                <ChevronDown :class="['w-5 h-5 text-slate-400 transition-transform shrink-0 mt-1 sm:mt-0', openItems[item.q] ? 'rotate-180 text-brand-orange' : '']" />
              </button>

              <AnimatePresence>
                <motion.div
                  v-if="openItems[item.q]"
                  :initial="{ height: 0, opacity: 0 }"
                  :animate="{ height: 'auto', opacity: 1 }"
                  :exit="{ height: 0, opacity: 0 }"
                  :transition="{ duration: 0.25, ease: 'easeOut' }"
                  class="overflow-hidden"
                >
                  <div class="px-6 pb-6 text-slate-600 leading-relaxed">
                    {{ item.a }}
                  </div>
                </motion.div>
              </AnimatePresence>
            </motion.div>
          </div>

          <div v-else class="py-20 text-center">
            <Search class="w-10 h-10 text-slate-300 mx-auto mb-4" />
            <h3 class="text-2xl font-display font-bold text-slate-900 mb-2">{{ faqUi.emptySearchTitle }}</h3>
            <p class="text-slate-500 mb-8">{{ faqContent.formatFaqEmptySearch(searchQuery) }}</p>
            <div class="flex flex-col sm:flex-row justify-center gap-4">
              <button class="inline-flex items-center justify-center gap-2 bg-slate-900 text-white px-6 py-3 rounded-xl text-sm font-bold uppercase tracking-wider hover:bg-slate-800 transition-colors" @click="searchQuery = ''">
                <PhoneCall class="w-4 h-4" />
                {{ faqUi.clearSearchLabel }}
              </button>
              <a :href="`mailto:${faqUi.footerEmail}`" class="inline-flex items-center justify-center gap-2 bg-slate-100 text-slate-900 px-6 py-3 rounded-xl text-sm font-bold uppercase tracking-wider hover:bg-slate-200 transition-colors">
                <Mail class="w-4 h-4" />
                {{ faqUi.footerEmailLabel }}
              </a>
            </div>
          </div>
        </div>

        <div class="mt-8 bg-slate-900 rounded-3xl p-8 md:p-10 text-white overflow-hidden relative">
          <div class="absolute top-0 right-0 w-56 h-56 bg-brand-orange/20 blur-[80px] rounded-full pointer-events-none" />
          <div class="relative z-10 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
            <div class="max-w-2xl">
              <h3 class="text-3xl font-display font-bold mb-3">{{ faqUi.footerTitle }}</h3>
              <p class="text-slate-300 leading-relaxed">
                {{ faqUi.footerDescription }}
              </p>
            </div>
            <NuxtLink
              :to="localizedPath('/rent')"
              class="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-white text-slate-900 font-bold uppercase tracking-wider hover:bg-brand-orange hover:text-white transition-colors"
            >
              {{ faqUi.footerBookingLabel }}
              <ArrowRight class="w-4 h-4" />
            </NuxtLink>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
