<script setup>
import { motion } from 'motion-v'
import {
  ArrowRight,
  Car,
  CheckCircle2,
  Handshake,
  Headset,
  Hotel,
  Laptop,
  Map,
  Percent,
  Send,
  TrendingUp,
} from 'lucide-vue-next'
import {
  buildPartnersPageSeo,
  usePartnersContent,
} from '~/content/partners'
import { resolvePublicApiError, splitHeadline } from '~/content/utils'
import { buildPublicSeoLinks } from '~/utils/public-seo'

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

const { submitLead } = usePublicLead()
const {
  partnerAudiences,
  partnerBenefits,
  partnerForm,
  partnerSteps,
  partnersPage,
  partnersHero,
  partnersUi,
} = usePartnersContent()
const ui = usePublicUi()
const { locale } = usePublicLocale()

const defaultBusinessType = computed(() => partnerForm.value.businessTypeOptions[0] || ui.value.common.travelAgency)

const formState = reactive({
  firstName: '',
  lastName: '',
  companyName: '',
  businessType: defaultBusinessType.value,
  email: '',
  website: '',
})
const {
  combinePhone,
  handlePhoneChange,
  handlePhoneCountryCodeChange,
  isPhoneValid,
  phoneCountryCode,
  phoneNumber,
  resetPhone,
} = useInternationalPhone()

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

const heroHeadline = computed(() => splitHeadline(partnersHero.value.title || partnersHero.value.subtitle))
const runtimeConfig = useRuntimeConfig()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const partnersPageSeo = computed(() => buildPartnersPageSeo(partnersPage.value, pageOrigin.value))

const audienceIcons = {
  map: Map,
  hotel: Hotel,
  handshake: Handshake,
}

const audienceThemes = {
  map: {
    color: 'text-blue-600',
    bgColor: 'bg-blue-50',
  },
  hotel: {
    color: 'text-emerald-600',
    bgColor: 'bg-emerald-50',
  },
  handshake: {
    color: 'text-brand-orange',
    bgColor: 'bg-brand-orange/10',
  },
}

const benefitIcons = {
  percent: Percent,
  car: Car,
  laptop: Laptop,
  headset: Headset,
}

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

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

const isFormValid = computed(() => {
  return (
    formState.firstName.trim() !== ''
    && formState.lastName.trim() !== ''
    && formState.companyName.trim() !== ''
    && formState.email.trim() !== ''
    && isPhoneValid.value
  )
})

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

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/50 focus:ring-brand-orange/10'
}

function resetForm() {
  formState.firstName = ''
  formState.lastName = ''
  formState.companyName = ''
  formState.businessType = defaultBusinessType.value
  formState.email = ''
  formState.website = ''
  resetPhone()
  resetSubmitAttempt()
}

function buildMessage() {
  const businessTypeLabel = partnerForm.value.labels.businessType || 'business_type'
  const websiteLabel = partnerForm.value.labels.website || 'website'
  const parts = [`${businessTypeLabel}: ${formState.businessType}.`]

  if (formState.website.trim()) {
    parts.push(`${websiteLabel}: ${formState.website.trim()}`)
  }

  return parts.join('\n\n')
}

async function handleSubmit() {
  markSubmitAttempt()

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

  isSubmitting.value = true
  submitError.value = ''

  try {
      await submitLead({
        form: 'partners',
        name: `${formState.firstName.trim()} ${formState.lastName.trim()}`.trim(),
        email: formState.email.trim(),
        phone: combinePhone(),
        subject: partnersHero.value.title || ui.value.common.partnerRequest,
        company: formState.companyName.trim(),
        message: buildMessage(),
      meta: {
        business_type: formState.businessType,
        website: formState.website.trim() || null,
      },
    })

    isSubmitted.value = true
    resetForm()
  } catch (error) {
    console.error('Failed to submit partner application', error)
    submitError.value = resolvePublicApiError(error, ui.value.common.couldNotSubmitApplication, locale.value)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<template>
  <div class="min-h-screen bg-white">
    <section class="relative pt-32 pb-20 md:pt-40 md:pb-32 overflow-hidden bg-[#0a0a0a] rounded-b-[3rem]">
      <div class="absolute inset-0 z-0">
        <img :src="partnersHero.image" :alt="partnersHero.imageAlt" class="w-full h-full object-cover opacity-30">
        <div class="absolute inset-0 bg-gradient-to-t from-[#0a0a0a] via-[#0a0a0a]/80 to-transparent" />
      </div>
      <div class="max-w-6xl mx-auto px-4 sm:px-6 relative z-10">
        <motion.div
          :initial="{ opacity: 0, y: 20 }"
          :animate="{ opacity: 1, y: 0 }"
          :transition="{ duration: 0.8 }"
          class="max-w-3xl"
        >
          <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-md text-white border border-white/20 text-xs font-bold tracking-widest uppercase mb-6">
            <TrendingUp class="w-4 h-4 text-brand-orange" />
            {{ partnersHero.badge }}
          </div>
          <h1 class="text-white text-5xl md:text-7xl font-display font-black uppercase tracking-tight mb-6">
            {{ heroHeadline.leading }} <span class="text-brand-orange">{{ heroHeadline.accent }}</span>
          </h1>
          <p class="text-slate-300 text-lg md:text-xl mb-10 leading-relaxed">
            {{ partnersHero.description }}
          </p>
          <div class="flex flex-wrap gap-4">
            <a :href="partnersHero.ctaUrl || '#apply'" class="bg-brand-orange text-white px-8 py-4 rounded-full font-bold uppercase tracking-widest hover:bg-amber-500 transition-colors duration-300 flex items-center gap-2">
              {{ partnersHero.ctaLabel }}
              <ArrowRight class="w-5 h-5" />
            </a>
          </div>
        </motion.div>
      </div>
    </section>

    <section class="py-24 bg-white">
      <div class="max-w-6xl mx-auto px-4 sm:px-6">
        <div class="text-center max-w-3xl mx-auto mb-16">
          <h2 class="text-3xl md:text-4xl font-display font-black text-slate-900 uppercase tracking-tight mb-6">
            {{ partnersUi.audiencesHeading }}
          </h2>
          <p class="text-slate-600 text-lg">
            {{ partnersUi.audiencesDescription }}
          </p>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <motion.div
            v-for="(audience, index) in partnerAudiences"
            :key="audience.title"
            :initial="{ opacity: 0, y: 20 }"
            :while-in-view="{ opacity: 1, y: 0 }"
            :viewport="{ once: true }"
            :transition="{ delay: index * 0.1, duration: 0.5 }"
            class="bg-slate-50 rounded-[2rem] p-8 border border-slate-100 hover:shadow-lg transition-all duration-300 hover:-translate-y-1"
          >
            <div :class="`w-14 h-14 rounded-2xl ${audienceThemes[audience.iconKey]?.bgColor} flex items-center justify-center mb-6`">
              <component :is="audienceIcons[audience.iconKey]" :class="`w-7 h-7 ${audienceThemes[audience.iconKey]?.color}`" />
            </div>
            <h3 class="text-xl font-bold text-slate-900 mb-3">{{ audience.title }}</h3>
            <p class="text-slate-600 leading-relaxed">{{ audience.description }}</p>
          </motion.div>
        </div>
      </div>
    </section>

    <section class="py-24 bg-slate-900 text-white rounded-[3rem] mx-4 sm:mx-6 lg:mx-8 my-12">
      <div class="max-w-6xl mx-auto px-4 sm:px-6">
        <div class="mb-16 md:flex md:items-end md:justify-between">
          <div class="max-w-2xl">
            <h2 class="text-3xl md:text-5xl font-display font-black uppercase tracking-tight mb-6">
              {{ partnersUi.benefitsHeading }}
            </h2>
            <p class="text-slate-400 text-lg">
              {{ partnersUi.benefitsDescription }}
            </p>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div
            v-for="benefit in partnerBenefits"
            :key="benefit.title"
            class="bg-white/5 border border-white/10 rounded-3xl p-8 hover:bg-white/10 transition-colors duration-300"
          >
            <div class="flex items-start gap-6">
              <div class="w-12 h-12 rounded-full bg-brand-orange/20 flex items-center justify-center shrink-0">
                <component :is="benefitIcons[benefit.iconKey]" class="w-6 h-6 text-brand-orange" />
              </div>
              <div>
                <h4 class="text-xl font-bold mb-2">{{ benefit.title }}</h4>
                <p class="text-slate-400 leading-relaxed">{{ benefit.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="py-24 bg-white">
      <div class="max-w-6xl mx-auto px-4 sm:px-6">
        <div class="text-center mb-16">
          <h2 class="text-3xl md:text-4xl font-display font-black text-slate-900 uppercase tracking-tight mb-6">
            {{ partnersUi.stepsHeading }}
          </h2>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-8 relative">
          <div class="hidden md:block absolute top-12 left-[15%] right-[15%] h-[2px] bg-slate-100 z-0" />
          <div v-for="step in partnerSteps" :key="step.step" class="relative z-10 text-center">
            <div class="w-24 h-24 mx-auto bg-white border-4 border-slate-50 rounded-full flex items-center justify-center shadow-xl mb-6">
              <span class="text-3xl font-display font-black text-brand-orange">{{ step.step }}</span>
            </div>
            <h4 class="text-xl font-bold text-slate-900 mb-3">{{ step.title }}</h4>
            <p class="text-slate-600">{{ step.description }}</p>
          </div>
        </div>
      </div>
    </section>

    <section id="apply" class="py-24 bg-slate-50">
      <div class="max-w-4xl mx-auto px-4 sm:px-6">
        <div class="bg-white rounded-[2rem] shadow-xl border border-slate-100 overflow-hidden">
          <div class="grid grid-cols-1 md:grid-cols-5">
            <div class="md:col-span-2 bg-slate-900 p-10 text-white flex flex-col justify-between">
              <div>
                <h3 class="text-2xl font-display font-black uppercase tracking-tight mb-4">{{ partnerForm.title }}</h3>
                <p class="text-slate-400 mb-8">
                  {{ partnerForm.description }}
                </p>
                <ul class="space-y-4">
                  <li v-for="highlight in partnerForm.highlights" :key="highlight" class="flex items-center gap-3 text-sm text-slate-300">
                    <CheckCircle2 class="w-5 h-5 text-brand-orange" /> {{ highlight }}
                  </li>
                </ul>
              </div>
            </div>

            <div class="md:col-span-3 p-10">
              <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">{{ partnerForm.successTitle }}</h3>
                <p class="text-slate-600 mb-8 text-lg max-w-md mx-auto">
                  {{ partnerForm.successDescription }}
                </p>
                <button
                  type="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"
                >
                  {{ partnerForm.successResetLabel }}
                </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>
                      <label :class="['block text-sm font-bold uppercase tracking-wider mb-2', fieldLabelClass(formState.firstName)]">{{ partnerForm.labels.firstName }}</label>
                      <input v-model="formState.firstName" type="text" required :class="['w-full bg-slate-50 border rounded-xl px-4 py-3 focus:outline-none focus:ring-2 transition-colors', fieldInputClass(formState.firstName)]" :placeholder="partnerForm.placeholders.firstName">
                    </div>
                    <div>
                      <label :class="['block text-sm font-bold uppercase tracking-wider mb-2', fieldLabelClass(formState.lastName)]">{{ partnerForm.labels.lastName }}</label>
                      <input v-model="formState.lastName" type="text" required :class="['w-full bg-slate-50 border rounded-xl px-4 py-3 focus:outline-none focus:ring-2 transition-colors', fieldInputClass(formState.lastName)]" :placeholder="partnerForm.placeholders.lastName">
                    </div>
                  </div>

                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div>
                      <label :class="['block text-sm font-bold uppercase tracking-wider mb-2', fieldLabelClass(formState.companyName)]">{{ partnerForm.labels.companyName }}</label>
                      <input v-model="formState.companyName" type="text" required :class="['w-full bg-slate-50 border rounded-xl px-4 py-3 focus:outline-none focus:ring-2 transition-colors', fieldInputClass(formState.companyName)]" :placeholder="partnerForm.placeholders.companyName">
                    </div>
                    <div>
                      <label class="block text-sm font-bold text-slate-700 uppercase tracking-wider mb-2">{{ partnerForm.labels.businessType }}</label>
                      <select v-model="formState.businessType" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-brand-orange/50 focus:border-brand-orange transition-colors appearance-none">
                        <option v-for="option in partnerForm.businessTypeOptions" :key="option" :value="option">
                          {{ option }}
                        </option>
                      </select>
                    </div>
                  </div>

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

                  <div>
                    <label class="block text-sm font-bold text-slate-700 uppercase tracking-wider mb-2">{{ partnerForm.labels.website }}</label>
                    <input v-model="formState.website" type="url" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-brand-orange/50 focus:border-brand-orange transition-colors" :placeholder="partnerForm.placeholders.website">
                  </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 uppercase tracking-widest py-4 rounded-xl transition-colors duration-300 flex items-center justify-center gap-3 bg-brand-orange text-white hover:bg-[#E66000] 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" />
                    <span>{{ isSubmitting ? (partnerForm.submittingLabel || ui.common.sendingRequest) : partnerForm.submitLabel }}</span>
                  </button>

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