<script setup>
import { motion } from 'motion-v'
import {
  ArrowRight,
  Briefcase,
  Building2,
  CalendarDays,
  Car,
  CheckCircle2,
  Clock,
  CreditCard,
  FileText,
  ShieldCheck,
} from 'lucide-vue-next'
import {
  buildCorporatePageSeo,
  useCorporateContent,
} from '~/content/corporate'
import { resolvePublicApiError, splitHeadline } from '~/content/utils'
import { buildPublicSeoLinks } from '~/utils/public-seo'

const { submitLead } = usePublicLead()
const {
  corporatePage,
  corporateBenefits,
  corporateComparisonRows,
  corporateForm,
  corporateHero,
  corporateServiceHighlights,
  corporateStats,
  corporateUi,
} = useCorporateContent()
const ui = usePublicUi()
const { locale } = usePublicLocale()

const formState = reactive({
  companyName: '',
  contactName: '',
  email: '',
  fleetSize: '',
  message: '',
})
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(corporateHero.value.title || corporateHero.value.subtitle))
const primaryStat = computed(() => corporateStats.value[0] || null)
const runtimeConfig = useRuntimeConfig()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const corporatePageSeo = computed(() => buildCorporatePageSeo(corporatePage.value, pageOrigin.value))

const comparisonIcons = {
  'credit-card': CreditCard,
  'calendar-days': CalendarDays,
  clock: Clock,
}

const benefitIcons = {
  briefcase: Briefcase,
  'file-text': FileText,
  car: Car,
  'shield-check': ShieldCheck,
}

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

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

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

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

function fieldInputClass(value, invalid = false) {
  const hasError = submitAttempted.value && (String(value || '').trim() === '' || invalid)
  return hasError
    ? 'border-red-300 focus:ring-red-200 focus:border-red-400'
    : 'border-slate-200 focus:ring-brand-orange/20 focus:border-brand-orange'
}

function handleChange(event) {
  formState[event.target.name] = event.target.value
}

function resetForm() {
  formState.companyName = ''
  formState.contactName = ''
  formState.email = ''
  formState.fleetSize = ''
  formState.message = ''
  resetPhone()
  resetSubmitAttempt()
}

function buildMessage() {
  const details = formState.message.trim()
  const fleetSizeLabel = corporateForm.value.fleetSizeOptions.find((option) => option.value === formState.fleetSize)?.label || formState.fleetSize
  const fleetSizeFieldLabel = corporateForm.value.labels.fleetSize || 'Fleet size'
  const parts = [`${fleetSizeFieldLabel}: ${fleetSizeLabel}.`]

  if (details) {
    parts.push(details)
  }

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

async function handleSubmit() {
  markSubmitAttempt()

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

  isSubmitting.value = true
  submitError.value = ''

  try {
      await submitLead({
        form: 'corporate',
        name: formState.contactName.trim(),
        email: formState.email.trim(),
        phone: combinePhone(),
        subject: corporateHero.value.title || 'Corporate Request',
        company: formState.companyName.trim(),
        message: buildMessage(),
      meta: {
        fleet_size: formState.fleetSize,
      },
    })

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

function scrollToForm() {
  if (import.meta.client) {
    document.getElementById('contact-form')?.scrollIntoView({ behavior: 'smooth' })
  }
}
</script>

<template>
  <div>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 py-12 md:py-20 flex flex-col">
      <div class="grid lg:grid-cols-2 gap-12 lg:gap-24 items-center mb-24">
        <motion.div
          :initial="{ opacity: 0, y: 20 }"
          :animate="{ opacity: 1, y: 0 }"
          :transition="{ duration: 0.6 }"
          class="flex flex-col"
        >
          <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-slate-100 text-slate-800 text-xs font-bold tracking-widest uppercase mb-6 w-fit">
            <Building2 class="w-4 h-4" />
            {{ corporateHero.badge }}
          </div>
          <h1 class="text-5xl md:text-6xl lg:text-7xl font-display font-semibold tracking-tight text-slate-900 leading-[1.1] mb-6">
            {{ heroHeadline.leading }} <br><span class="text-brand-orange">{{ heroHeadline.accent }}</span>
          </h1>
          <p class="text-lg text-slate-600 mb-8 max-w-md leading-relaxed">
            {{ corporateHero.description }}
          </p>

          <div class="flex flex-col sm:flex-row gap-4">
            <button
              type="button"
              class="bg-slate-900 text-white px-8 py-4 rounded-full font-bold text-sm tracking-wider uppercase hover:bg-brand-orange transition-colors duration-300 flex items-center justify-center gap-2"
              @click="scrollToForm"
            >
              {{ corporateHero.ctaLabel }}
              <ArrowRight class="w-4 h-4" />
            </button>
          </div>
        </motion.div>

        <motion.div
          :initial="{ opacity: 0, scale: 0.95 }"
          :animate="{ opacity: 1, scale: 1 }"
          :transition="{ duration: 0.6, delay: 0.2 }"
          class="relative"
        >
          <div class="aspect-[4/3] rounded-[2rem] overflow-hidden relative">
            <img
              :src="corporateHero.image"
              :alt="corporateHero.imageAlt"
              class="w-full h-full object-cover"
            >
            <div class="absolute inset-0 bg-gradient-to-tr from-slate-900/40 to-transparent" />
          </div>

          <div v-if="primaryStat" class="absolute -bottom-8 -left-8 bg-white p-6 rounded-3xl shadow-[0_20px_40px_-15px_rgba(0,0,0,0.1)] border border-slate-100 hidden md:flex flex-col gap-2">
            <div class="text-4xl font-display font-bold text-slate-900">{{ primaryStat.value }}</div>
            <div class="text-sm font-medium text-slate-500 uppercase tracking-wider">{{ primaryStat.label }}</div>
          </div>
        </motion.div>
      </div>

      <div class="mb-24">
        <div class="text-center mb-12">
          <h2 class="text-3xl md:text-4xl font-display font-semibold text-slate-900 mb-4">{{ corporateUi.comparisonHeading }}</h2>
          <p class="text-slate-600 max-w-2xl mx-auto">{{ corporateUi.comparisonDescription }}</p>
        </div>

        <div class="grid md:grid-cols-3 gap-6">
          <div
            v-for="(row, index) in corporateComparisonRows"
            :key="row.title"
            :class="[
              'rounded-3xl p-8 border',
              index === 1 ? 'bg-slate-900 border-slate-800 text-white relative overflow-hidden' : 'bg-slate-50 border-slate-100',
            ]"
          >
            <div v-if="index === 1" class="absolute top-0 right-0 w-32 h-32 bg-brand-orange/20 rounded-full blur-3xl" />
            <div
              :class="[
                'w-12 h-12 rounded-2xl flex items-center justify-center mb-6',
                index === 1 ? 'bg-white/10 text-brand-orange' : 'bg-white shadow-sm text-slate-400',
              ]"
            >
              <component :is="comparisonIcons[row.iconKey]" class="w-6 h-6" />
            </div>
            <h3 class="text-xl font-bold mb-3" :class="index === 1 ? 'text-white' : 'text-slate-900'">{{ row.title }}</h3>
            <p class="text-sm leading-relaxed" :class="index === 1 ? 'text-slate-300' : 'text-slate-600'">{{ row.description }}</p>
          </div>
        </div>
      </div>

      <div class="mb-24 bg-white rounded-[3rem] p-8 md:p-16 border border-slate-100 shadow-sm">
        <div class="grid md:grid-cols-2 gap-16">
          <div>
            <h2 class="text-3xl md:text-4xl font-display font-semibold text-slate-900 mb-6">{{ corporateUi.benefitsHeading }}</h2>
            <p class="text-slate-600 mb-8 leading-relaxed">
              {{ corporateHero.description }}
            </p>
            <ul class="space-y-4">
              <li
                v-for="item in corporateServiceHighlights"
                :key="item.title"
                class="flex items-start gap-3"
              >
                <CheckCircle2 class="w-5 h-5 text-brand-orange shrink-0 mt-0.5" />
                <span class="text-slate-700 font-medium">{{ item.title }}</span>
              </li>
            </ul>
          </div>

          <div class="grid sm:grid-cols-2 gap-6">
            <div v-for="benefit in corporateBenefits" :key="benefit.title" class="flex flex-col gap-3">
              <div class="w-10 h-10 rounded-xl bg-slate-50 flex items-center justify-center text-slate-900 border border-slate-100">
                <component :is="benefitIcons[benefit.iconKey]" class="w-6 h-6" />
              </div>
              <h4 class="font-bold text-slate-900">{{ benefit.title }}</h4>
              <p class="text-sm text-slate-500 leading-relaxed">{{ benefit.description }}</p>
            </div>
          </div>
        </div>
      </div>

      <div id="contact-form" class="max-w-3xl mx-auto w-full scroll-mt-24">
        <div class="bg-slate-50 rounded-[2.5rem] p-8 md:p-12 border border-slate-100">
          <div class="text-center mb-10">
            <h2 class="text-3xl font-display font-semibold text-slate-900 mb-3">{{ corporateForm.title }}</h2>
            <p class="text-slate-600">{{ corporateForm.description }}</p>
          </div>

          <motion.div
            v-if="isSubmitted"
            :initial="{ opacity: 0, scale: 0.95 }"
            :animate="{ opacity: 1, scale: 1 }"
            class="bg-white rounded-3xl p-8 text-center border border-emerald-100 shadow-sm"
          >
            <div class="w-16 h-16 bg-emerald-50 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle2 class="w-8 h-8" />
            </div>
            <h3 class="text-2xl font-bold text-slate-900 mb-2">{{ corporateForm.successTitle }}</h3>
            <p class="text-slate-600 mb-6">{{ corporateForm.successDescription }}</p>
            <button
              type="button"
              class="text-brand-orange font-bold text-sm tracking-wider uppercase hover:text-slate-900 transition-colors"
              @click="isSubmitted = false"
            >
              {{ corporateForm.successResetLabel }}
            </button>
          </motion.div>

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

            <div class="grid md:grid-cols-2 gap-6">
              <div class="space-y-2">
                <label :class="['text-xs font-bold uppercase tracking-wider ml-1', fieldLabelClass(formState.email)]">{{ corporateForm.labels.email }}</label>
                <input
                  name="email"
                  type="email"
                  required
                  :value="formState.email"
                  :class="['w-full bg-white border rounded-2xl px-4 py-3.5 text-slate-900 focus:outline-none focus:ring-2 transition-all', fieldInputClass(formState.email)]"
                  :placeholder="corporateForm.placeholders.email"
                  @input="handleChange"
                >
              </div>
              <div class="space-y-2">
                <label :class="['text-xs font-bold uppercase tracking-wider ml-1', fieldLabelClass(phoneNumber, !isPhoneValid)]">{{ corporateForm.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-white border rounded-2xl px-4 py-3.5 text-slate-900 focus:outline-none focus:ring-2 transition-all text-center font-medium', fieldInputClass(phoneCountryCode, phoneCountryCode === '+')]"
                    placeholder="+995"
                    @input="handlePhoneCountryCodeChange"
                  >
                  <input
                    name="phone"
                    type="tel"
                    inputmode="tel"
                    autocomplete="tel-national"
                    required
                    :value="phoneNumber"
                    :class="['w-full bg-white border rounded-2xl px-4 py-3.5 text-slate-900 focus:outline-none focus:ring-2 transition-all', fieldInputClass(phoneNumber, !isPhoneValid)]"
                    :placeholder="corporateForm.placeholders.phone"
                    @input="handlePhoneChange"
                  >
                </div>
                <p v-if="submitAttempted && (!phoneNumber || !isPhoneValid)" class="text-xs text-red-500 ml-1 mt-1">
                  {{ corporateForm.phoneError }}
                </p>
              </div>
            </div>

            <div class="space-y-2">
                <label :class="['text-xs font-bold uppercase tracking-wider ml-1', fieldLabelClass(formState.fleetSize)]">{{ corporateForm.labels.fleetSize }}</label>
              <select
                name="fleetSize"
                required
                :value="formState.fleetSize"
                :class="['w-full bg-white border rounded-2xl px-4 py-3.5 text-slate-900 focus:outline-none focus:ring-2 transition-all appearance-none', fieldInputClass(formState.fleetSize)]"
                @change="handleChange"
              >
                <option value="" disabled>{{ corporateForm.selectPlaceholder || ui.common.selectOption }}</option>
                <option v-for="option in corporateForm.fleetSizeOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>

            <div class="space-y-2">
                <label :class="['text-xs font-bold uppercase tracking-wider ml-1', fieldLabelClass(formState.message)]">{{ corporateForm.labels.message }}</label>
              <textarea
                name="message"
                :value="formState.message"
                rows="4"
                :class="['w-full bg-white border rounded-2xl px-4 py-3.5 text-slate-900 focus:outline-none focus:ring-2 transition-all resize-none', fieldInputClass(formState.message)]"
                :placeholder="corporateForm.placeholders.message"
                @input="handleChange"
              />
            </div>

            <div v-if="submitAttempted && !isFormValid" class="rounded-2xl 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 py-4 rounded-2xl font-bold text-sm tracking-wider uppercase transition-colors duration-300 bg-brand-orange text-white hover:bg-[#E66000] disabled:pointer-events-none"
            >
              <span class="inline-flex items-center justify-center gap-2">
                <span v-if="isSubmitting" class="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                <span>{{ isSubmitting ? corporateForm.submittingLabel || ui.common.sendingRequest : corporateForm.submitLabel }}</span>
              </span>
            </button>
            <p v-if="submitError" class="text-center text-sm text-red-500">
              {{ submitError }}
            </p>
            <p class="text-center text-xs text-slate-400 mt-4">
              {{ corporateForm.privacyNotice }}
            </p>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
