<script setup>
import { AnimatePresence, motion } from 'motion-v'
import { Briefcase, Clock, Globe, Mail, Map, MapPin, MessageSquare, Phone, Send, Shield, Star, X } from 'lucide-vue-next'
import { buildContactPageSeo, useContactContent } from '~/content/contact'
import { resolvePublicApiError, splitHeadline } from '~/content/utils'
import { buildPublicSeoLinks } from '~/utils/public-seo'

definePageMeta({
  siteHeaderTheme: 'light',
})

const { submitLead } = usePublicLead()
const {
  contactPage,
  contactDepartments,
  contactForm,
  contactHero,
  contactLocations,
  contactSupportChannels,
  contactUi,
} = useContactContent()
const ui = usePublicUi()
const { locale } = usePublicLocale()
const runtimeConfig = useRuntimeConfig()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const contactPageSeo = computed(() => buildContactPageSeo(contactPage.value, pageOrigin.value))

const mapLocation = ref(null)
const isSubmitting = ref(false)
const isSubmitted = ref(false)
const submitError = ref('')
const {
  markSubmitAttempt,
  resetSubmitAttempt,
  submitAttempted,
} = useSubmitAttempt()

const formState = reactive({
  name: '',
  email: '',
  subject: '',
  message: '',
})
const {
  combinePhone,
  handlePhoneChange,
  handlePhoneCountryCodeChange,
  isPhoneValid,
  phoneCountryCode,
  phoneNumber,
  resetPhone,
} = useInternationalPhone()

const heroHeadline = computed(() => splitHeadline(contactHero.value.title || contactHero.value.subtitle))

const departmentIcons = {
  shield: Shield,
  star: Star,
  briefcase: Briefcase,
}

const departmentThemes = {
  shield: {
    color: 'text-red-500',
    bg: 'bg-red-500/10',
    border: 'border-red-100',
  },
  star: {
    color: 'text-amber-500',
    bg: 'bg-amber-500/10',
    border: 'border-amber-100',
  },
  briefcase: {
    color: 'text-blue-500',
    bg: 'bg-blue-500/10',
    border: 'border-blue-100',
  },
}

const isFormValid = computed(() => {
  return formState.name.trim() !== ''
    && formState.email.trim() !== ''
    && isPhoneValid.value
    && formState.subject.trim() !== ''
    && formState.message.trim() !== ''
})

function fieldLabelClass(value, invalid = false) {
  const hasError = submitAttempted.value && (String(value || '').trim() === '' || invalid)
  return hasError ? 'text-red-500' : 'text-slate-500'
}

function fieldInputClass(value, invalid = false) {
  const hasError = submitAttempted.value && (String(value || '').trim() === '' || invalid)

  return hasError
    ? 'border-red-300 focus:border-red-500 focus:ring-red-500/10'
    : 'border-slate-200 focus:border-brand-orange focus:ring-brand-orange/10'
}

function resetForm() {
  formState.name = ''
  formState.email = ''
  formState.subject = ''
  formState.message = ''
  resetPhone()
  resetSubmitAttempt()
}

async function handleSubmit() {
  markSubmitAttempt()

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

  isSubmitting.value = true
  submitError.value = ''

  try {
    await submitLead({
      form: 'contact',
      name: formState.name.trim(),
      email: formState.email.trim(),
      phone: combinePhone(),
      subject: formState.subject.trim(),
      message: formState.message.trim(),
    })

    isSubmitted.value = true
    resetForm()
  } catch (error) {
    console.error('Failed to submit contact lead', error)
    submitError.value = resolvePublicApiError(error, ui.value.common.couldNotSendMessage, locale.value)
  } finally {
    isSubmitting.value = false
  }
}

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

useHead(() => ({
  link: buildPublicSeoLinks(contactPageSeo.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-[#030303] text-white pt-16 pb-32 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-7xl mx-auto relative z-10">
          <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"
          >
            <MapPin class="w-4 h-4 text-brand-orange" />
            <span class="text-xs font-bold uppercase tracking-widest text-white">{{ contactHero.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"
          >
            {{ heroHeadline.leading }} <span class="text-brand-orange">{{ heroHeadline.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 max-w-2xl"
          >
            {{ contactHero.description }}
          </motion.p>

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

    <div class="max-w-7xl mx-auto px-4 sm:px-6 -mt-16 relative z-20 w-full flex-1">
      <div v-if="contactLocations.length" class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <motion.div
          v-for="(loc, idx) in contactLocations"
          :key="loc.id"
          :initial="{ opacity: 0, y: 20 }"
          :animate="{ opacity: 1, y: 0 }"
          :transition="{ delay: idx * 0.1 }"
          class="bg-white p-8 rounded-[2rem] shadow-xl shadow-slate-200/50 border border-slate-100 flex flex-col hover:shadow-2xl hover:-translate-y-1 transition-all duration-300"
        >
          <div class="flex justify-between items-start mb-8">
            <div>
              <h3 class="font-display font-bold text-2xl text-slate-900 mb-2">{{ loc.name }}</h3>
              <span class="text-[10px] font-bold uppercase tracking-wider text-brand-orange bg-brand-orange/10 px-3 py-1.5 rounded-lg">
                {{ loc.city }}
              </span>
            </div>
            <div class="w-12 h-12 rounded-2xl bg-slate-50 flex items-center justify-center border border-slate-100 shrink-0">
              <MapPin class="w-5 h-5 text-slate-400" />
            </div>
          </div>

          <div class="space-y-4 mb-8 flex-1">
            <div v-if="loc.address" class="flex items-start gap-4 text-slate-600">
              <MapPin class="w-5 h-5 mt-0.5 shrink-0 text-slate-400" />
              <span class="leading-relaxed">{{ loc.address }}</span>
            </div>
            <div v-if="loc.phone" class="flex items-center gap-4 text-slate-600">
              <Phone class="w-5 h-5 shrink-0 text-slate-400" />
              <span class="font-medium">{{ loc.phone }}</span>
            </div>
            <div v-if="loc.hours" class="flex items-center gap-4 text-slate-600">
              <Clock class="w-5 h-5 shrink-0 text-slate-400" />
              <span>{{ loc.hours }}</span>
            </div>
          </div>

          <button
            class="w-full py-4 rounded-xl bg-slate-50 hover:bg-slate-900 text-slate-900 hover:text-white font-bold text-xs uppercase tracking-widest transition-colors flex items-center justify-center gap-2 group"
            @click="mapLocation = loc"
          >
            <Map class="w-4 h-4 text-slate-400 group-hover:text-white transition-colors" />
            {{ contactUi.viewMapLabel }}
          </button>
        </motion.div>
      </div>

      <motion.div
        v-else
        :initial="{ opacity: 0, y: 20 }"
        :animate="{ opacity: 1, y: 0 }"
        class="bg-white rounded-[2rem] border border-slate-100 shadow-xl shadow-slate-200/30 p-10 text-center"
      >
        <h2 class="text-2xl font-display font-bold text-slate-900 mb-3">{{ contactUi.locationsEmptyTitle }}</h2>
        <p class="text-slate-500 max-w-2xl mx-auto">{{ contactUi.locationsEmptyDescription }}</p>
      </motion.div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 mt-24 w-full">
      <div class="mb-10">
        <h2 class="text-3xl font-display font-bold text-slate-900">{{ contactUi.departmentsTitle }}</h2>
        <p class="text-slate-500 mt-2 text-lg">{{ contactUi.departmentsDescription }}</p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <motion.div
          v-for="(dept, idx) in contactDepartments"
          :key="dept.name"
          :initial="{ opacity: 0, y: 20 }"
          :while-in-view="{ opacity: 1, y: 0 }"
          :viewport="{ once: true }"
          :transition="{ delay: idx * 0.1 }"
          :class="['bg-white p-8 rounded-3xl shadow-xl shadow-slate-200/30 border hover:shadow-2xl hover:-translate-y-1 transition-all duration-300', departmentThemes[dept.iconKey]?.border]"
        >
          <div :class="['w-14 h-14 rounded-2xl flex items-center justify-center mb-6', departmentThemes[dept.iconKey]?.bg]">
            <component :is="departmentIcons[dept.iconKey]" :class="['w-7 h-7', departmentThemes[dept.iconKey]?.color]" />
          </div>
          <h3 class="text-xl font-display font-bold text-slate-900 mb-3">{{ dept.name }}</h3>
          <p class="text-slate-500 mb-6 text-sm leading-relaxed">{{ dept.description }}</p>

          <div class="space-y-3 pt-6 border-t border-slate-100">
            <a :href="`tel:${dept.phone.replace(/\s/g, '')}`" class="flex items-center gap-3 text-slate-900 hover:text-brand-orange transition-colors font-medium">
              <div class="w-8 h-8 rounded-full bg-slate-50 flex items-center justify-center border border-slate-100">
                <Phone class="w-3.5 h-3.5" />
              </div>
              {{ dept.phone }}
            </a>
            <a :href="`mailto:${dept.email}`" class="flex items-center gap-3 text-slate-900 hover:text-brand-orange transition-colors font-medium">
              <div class="w-8 h-8 rounded-full bg-slate-50 flex items-center justify-center border border-slate-100">
                <Mail class="w-3.5 h-3.5" />
              </div>
              {{ dept.email }}
            </a>
          </div>
        </motion.div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 mt-24 w-full">
      <div class="bg-[#030303] rounded-3xl overflow-hidden flex flex-col lg:flex-row shadow-2xl">
        <div class="w-full lg:w-5/12 p-10 lg:p-16 flex flex-col justify-center relative overflow-hidden">
          <div class="absolute inset-0 bg-brand-orange/10 blur-[100px] rounded-full transform -translate-x-1/2 -translate-y-1/2 pointer-events-none" />

          <h2 class="text-3xl lg:text-4xl font-display font-bold text-white mb-4 relative z-10">
            {{ contactUi.inquiryTitle }}
          </h2>
          <p class="text-slate-400 mb-10 relative z-10 text-lg">
            {{ contactUi.inquiryDescription }}
          </p>

          <div class="space-y-8 relative z-10">
            <div v-if="contactSupportChannels.emailValue" class="flex items-center gap-5 text-white">
              <div class="w-14 h-14 rounded-2xl bg-white/5 flex items-center justify-center border border-white/10 backdrop-blur-sm">
                <Globe class="w-6 h-6 text-brand-orange" />
              </div>
              <div>
                <div class="text-sm text-slate-400 mb-1">{{ contactSupportChannels.emailLabel }}</div>
                <div class="font-bold text-lg">{{ contactSupportChannels.emailValue }}</div>
              </div>
            </div>
            <div v-if="contactSupportChannels.phoneValue" class="flex items-center gap-5 text-white">
              <div class="w-14 h-14 rounded-2xl bg-white/5 flex items-center justify-center border border-white/10 backdrop-blur-sm">
                <MessageSquare class="w-6 h-6 text-brand-orange" />
              </div>
              <div>
                <div class="text-sm text-slate-400 mb-1">{{ contactSupportChannels.phoneLabel }}</div>
                <div class="font-bold text-lg">{{ contactSupportChannels.phoneValue }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="w-full lg:w-7/12 bg-white p-10 lg:p-16">
          <motion.div
            v-if="isSubmitted"
            :initial="{ opacity: 0, scale: 0.95 }"
            :animate="{ opacity: 1, scale: 1 }"
            class="bg-emerald-50 border border-emerald-100 rounded-2xl p-10 text-center h-full flex flex-col items-center justify-center"
          >
            <div class="w-20 h-20 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <Send class="w-10 h-10 text-emerald-600" />
            </div>
            <h3 class="text-3xl font-display font-bold text-slate-900 mb-3">{{ contactUi.successTitle }}</h3>
            <p class="text-slate-600 mb-8 text-lg max-w-md mx-auto">
              {{ contactUi.successDescription }}
            </p>
            <button
              class="px-8 py-4 bg-white text-slate-900 border border-slate-200 rounded-xl font-bold uppercase tracking-wider text-sm hover:bg-slate-50 transition-colors shadow-sm"
              @click="isSubmitted = false"
            >
              {{ contactUi.successButtonLabel }}
            </button>
          </motion.div>

          <form v-else novalidate class="space-y-6" @submit.prevent="handleSubmit">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div class="space-y-2">
                <label for="name" :class="['text-xs font-bold uppercase tracking-wider', fieldLabelClass(formState.name)]">{{ contactForm.labels.name }}</label>
                <input
                  id="name"
                  v-model="formState.name"
                  type="text"
                  required
                  :class="['w-full bg-slate-50 border rounded-xl px-5 py-4 outline-none focus:bg-white focus:ring-4 transition-all text-slate-900', fieldInputClass(formState.name)]"
                  :placeholder="contactForm.placeholders.name"
                >
              </div>
              <div class="space-y-2">
                <label for="email" :class="['text-xs font-bold uppercase tracking-wider', fieldLabelClass(formState.email)]">{{ contactForm.labels.email }}</label>
                <input
                  id="email"
                  v-model="formState.email"
                  type="email"
                  required
                  :class="['w-full bg-slate-50 border rounded-xl px-5 py-4 outline-none focus:bg-white focus:ring-4 transition-all text-slate-900', fieldInputClass(formState.email)]"
                  :placeholder="contactForm.placeholders.email"
                >
              </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div class="space-y-2">
                <label
                  for="phone"
                  :class="[
                    'text-xs font-bold uppercase tracking-wider',
                    fieldLabelClass(phoneNumber, !isPhoneValid),
                  ]"
                >
                  {{ contactForm.labels.phone }}
                </label>
                <div class="grid grid-cols-[6rem_minmax(0,1fr)] gap-3">
                  <input
                    :value="phoneCountryCode"
                    type="tel"
                    inputmode="tel"
                    autocomplete="tel-country-code"
                    required
                    :class="['w-full bg-slate-50 border rounded-xl px-4 py-4 outline-none focus:bg-white focus:ring-4 transition-all text-slate-900 text-center font-medium', fieldInputClass(phoneCountryCode, phoneCountryCode === '+')]"
                    placeholder="+995"
                    @input="handlePhoneCountryCodeChange"
                  >
                  <input
                    id="phone"
                    :value="phoneNumber"
                    type="tel"
                    inputmode="tel"
                    autocomplete="tel-national"
                    required
                    :class="['w-full bg-slate-50 border rounded-xl px-5 py-4 outline-none focus:bg-white focus:ring-4 transition-all text-slate-900', fieldInputClass(phoneNumber, !isPhoneValid)]"
                    :placeholder="contactForm.placeholders.phone"
                    @input="handlePhoneChange"
                  >
                </div>
                <p v-if="submitAttempted && (!phoneNumber || !isPhoneValid)" class="text-xs text-red-500 mt-1">
                  {{ contactForm.phoneValidationMessage }}
                </p>
              </div>
              <div class="space-y-2">
                <label for="subject" :class="['text-xs font-bold uppercase tracking-wider', fieldLabelClass(formState.subject)]">{{ contactForm.labels.subject }}</label>
                <input
                  id="subject"
                  v-model="formState.subject"
                  type="text"
                  required
                  :class="['w-full bg-slate-50 border rounded-xl px-5 py-4 outline-none focus:bg-white focus:ring-4 transition-all text-slate-900', fieldInputClass(formState.subject)]"
                  :placeholder="contactForm.placeholders.subject"
                >
              </div>
            </div>

            <div class="space-y-2">
              <label for="message" :class="['text-xs font-bold uppercase tracking-wider', fieldLabelClass(formState.message)]">{{ contactForm.labels.message }}</label>
              <textarea
                id="message"
                v-model="formState.message"
                required
                rows="5"
                :class="['w-full bg-slate-50 border rounded-xl px-5 py-4 outline-none focus:bg-white focus:ring-4 transition-all resize-none text-slate-900', fieldInputClass(formState.message)]"
                :placeholder="contactForm.placeholders.message"
              />
            </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 px-8 py-5 rounded-xl font-bold uppercase tracking-wider text-sm transition-all flex items-center justify-center gap-3 mt-4 bg-brand-orange text-white hover:bg-[#E66000] shadow-lg shadow-brand-orange/20 disabled:pointer-events-none"
            >
              <div v-if="isSubmitting" class="w-5 h-5 border-2 border-white/40 border-t-white rounded-full animate-spin" />
              <template v-else>
                {{ contactForm.submitLabel }}
                <Send class="w-4 h-4" />
              </template>
            </button>

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

    <AnimatePresence>
      <div v-if="mapLocation" class="fixed inset-0 z-[100] flex items-center justify-center p-4 sm:p-6">
        <motion.div
          :initial="{ opacity: 0 }"
          :animate="{ opacity: 1 }"
          :exit="{ opacity: 0 }"
          class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
          @click="mapLocation = null"
        />
        <motion.div
          :initial="{ opacity: 0, scale: 0.95, y: 20 }"
          :animate="{ opacity: 1, scale: 1, y: 0 }"
          :exit="{ opacity: 0, scale: 0.95, y: 20 }"
          class="relative w-full max-w-5xl bg-white rounded-[2rem] shadow-2xl overflow-hidden flex flex-col h-[600px] max-h-[85vh]"
        >
          <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-white relative z-10">
            <div>
              <h3 class="font-display font-bold text-xl text-slate-900">{{ mapLocation.name }}</h3>
              <p class="text-sm text-slate-500">{{ mapLocation.address }}</p>
            </div>
            <button
              :aria-label="contactUi.mapModalCloseLabel"
              class="w-10 h-10 rounded-full bg-slate-50 hover:bg-slate-100 flex items-center justify-center text-slate-500 transition-colors"
              @click="mapLocation = null"
            >
              <X class="w-5 h-5" />
            </button>
          </div>
          <div class="flex-1 bg-slate-100 relative">
            <iframe
              :src="mapLocation.mapSrc"
              class="absolute inset-0 w-full h-full border-0 grayscale-[0.2] contrast-100"
              allowfullscreen
              loading="lazy"
              referrerpolicy="no-referrer-when-downgrade"
            />
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  </div>
</template>
