<template>
  <Teleport to="body">
    <Transition name="inquiry-fade">
      <div
        v-if="isOpen"
        class="fixed inset-0 z-[100] bg-[#050505]/95 backdrop-blur-xl flex items-center justify-center p-4"
        @click.self="closeModal"
      >
        <div class="relative w-full max-w-4xl bg-[#080808] border border-white/10 overflow-y-auto overflow-x-hidden flex flex-col md:flex-row shadow-2xl max-h-[95vh]">
          <div class="hidden md:flex w-1/3 bg-[#0c0c0c] border-r border-white/5 p-12 flex-col justify-between relative overflow-hidden shrink-0">
            <div class="absolute top-0 left-0 w-full h-full bg-noise opacity-10"></div>
            <div class="absolute -top-20 -left-20 w-64 h-64 bg-art-accent/10 rounded-full blur-[80px]"></div>
            <div class="relative z-10">
              <h3 class="font-serif text-3xl text-white italic mb-6 leading-tight">
                共创<br>无限<br>可能
              </h3>
              <p class="font-mono text-xs text-white/40 leading-relaxed">
                告诉我你的构想。<br>
                我将提供架构与代码，<br>
                将想象变为现实。
              </p>
            </div>
            <div class="relative z-10 font-mono text-[10px] text-white/20 tracking-widest">
              LAT: 30.2741° N<br>
              LONG: 120.1551° E<br>
              HANGZHOU, CN
            </div>
          </div>
          <div class="w-full md:w-2/3 p-10 md:p-16 relative bg-[#080808]">
            <button
              type="button"
              @click="closeModal"
              class="absolute top-6 right-6 p-2 text-white/30 hover:text-white hover:bg-white/5 rounded-full transition-colors z-20"
              aria-label="关闭"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
            <form id="inquiry-form" class="space-y-10 relative z-10" @submit.prevent="handleSubmit">
              <div class="space-y-8">
                <p class="font-mono text-xs text-art-accent uppercase tracking-widest border-b border-white/10 pb-2 mb-6">01 身份识别</p>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                  <div class="relative group/input">
                    <input
                      name="name"
                      type="text"
                      class="inquiry-input peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent"
                      placeholder=" "
                      v-model="formData.name"
                      required
                    >
                    <label
                      class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all pointer-events-none peer-focus:-top-4 peer-focus:text-art-accent peer-[:not(:placeholder-shown)]:-top-4 peer-[:not(:placeholder-shown)]:text-white/50 peer-autofill:-top-4 peer-autofill:text-white/50"
                    >您的称呼</label>
                  </div>
                  <div class="relative group/input">
                    <input
                      name="company"
                      type="text"
                      class="inquiry-input peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent"
                      placeholder=" "
                      v-model="formData.company"
                    >
                    <label
                      class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all pointer-events-none peer-focus:-top-4 peer-focus:text-art-accent peer-[:not(:placeholder-shown)]:-top-4 peer-[:not(:placeholder-shown)]:text-white/50 peer-autofill:-top-4 peer-autofill:text-white/50"
                    >公司 / 组织</label>
                  </div>
                </div>

                <div class="space-y-4">
                  <label class="text-xs font-mono text-white/30 block">联系方式类型</label>
                  <RadioGroup
                    name="contactMethod"
                    :options="contactOptions"
                    v-model="formData.contactMethod"
                  />
                </div>

                <div class="relative group/input">
                  <EmailAutocomplete
                    v-if="formData.contactMethod === 'email'"
                    name="contactValue"
                    label="邮箱地址"
                    v-model="formData.contactValue"
                    required
                  />
                  <div v-else class="relative group/input">
                    <input
                      name="contactValue"
                      type="text"
                      class="inquiry-input peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent"
                      placeholder=" "
                      v-model="formData.contactValue"
                      required
                    >
                    <label
                      class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all pointer-events-none peer-focus:-top-4 peer-focus:text-art-accent peer-[:not(:placeholder-shown)]:-top-4 peer-[:not(:placeholder-shown)]:text-white/50 peer-autofill:-top-4 peer-autofill:text-white/50"
                    >{{ getContactLabel }}</label>
                  </div>
                </div>
              </div>

              <div class="space-y-6">
                <p class="font-mono text-xs text-art-accent uppercase tracking-widest border-b border-white/10 pb-2 mb-6">02 项目细节</p>
                <div class="space-y-3">
                  <label class="text-xs font-mono text-white/30 block mb-2">预估预算范围</label>
                  <div class="flex flex-wrap gap-3">
                    <label class="cursor-pointer group">
                      <input type="radio" name="budget" value="1w-5w" class="peer hidden" v-model="formData.budget">
                      <span class="px-4 py-2 border border-white/10 rounded-none text-xs font-mono text-white/50 hover:border-art-accent hover:text-white transition-all peer-checked:bg-art-accent peer-checked:text-black peer-checked:border-art-accent">1w - 5w</span>
                    </label>
                    <label class="cursor-pointer group">
                      <input type="radio" name="budget" value="5w-20w" class="peer hidden" v-model="formData.budget">
                      <span class="px-4 py-2 border border-white/10 rounded-none text-xs font-mono text-white/50 hover:border-art-accent hover:text-white transition-all peer-checked:bg-art-accent peer-checked:text-black peer-checked:border-art-accent">5w - 20w</span>
                    </label>
                    <label class="cursor-pointer group">
                      <input type="radio" name="budget" value="20w+" class="peer hidden" v-model="formData.budget">
                      <span class="px-4 py-2 border border-white/10 rounded-none text-xs font-mono text-white/50 hover:border-art-accent hover:text-white transition-all peer-checked:bg-art-accent peer-checked:text-black peer-checked:border-art-accent">20w +</span>
                    </label>
                  </div>
                </div>
                <br>
                <div class="relative group/input mt-32">
                  <textarea
                    name="description"
                    :rows="3"
                    class="inquiry-input peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent resize-none min-h-[40px] max-h-[100px]"
                    placeholder=" "
                    v-model="formData.description"
                    @input="autoResizeTextarea"
                  ></textarea>
                  <label
                    class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all pointer-events-none peer-focus:-top-4 peer-focus:text-art-accent peer-[:not(:placeholder-shown)]:-top-4 peer-[:not(:placeholder-shown)]:text-white/50 peer-autofill:-top-4 peer-autofill:text-white/50"
                  >一句话描述需求</label>
                </div>
              </div>
              <div class="pt-6">
                <button
                  type="submit"
                  class="group relative w-full overflow-hidden bg-art-accent text-black rounded-full font-bold hover:scale-105 transition-transform"
                  :disabled="isSubmitting"
                >
                  <div class="absolute inset-0 w-0 bg-white transition-all duration-[250ms] ease-out group-hover:w-full"></div>
                  <span class="relative flex items-center justify-between z-10 px-8 py-4">
                    <span class="font-mono uppercase tracking-widest text-sm">{{ isSubmitting ? '发送中...' : '发送' }}</span>
                    <svg v-if="!isSubmitting" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform group-hover:translate-x-1">
                      <line x1="5" y1="12" x2="19" y2="12"></line>
                      <polyline points="12 5 19 12 12 19"></polyline>
                    </svg>
                    <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin">
                      <path d="M21 12a9 9 0 1 1-6.219-8.56"></path>
                    </svg>
                  </span>
                </button>
                <p class="mt-4 text-[10px] text-white/20 font-mono text-center tracking-widest">SECURED BY DIGITAL FINGERPRINTING</p>
              </div>
            </form>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import RadioGroup from './ui/RadioGroup.vue'
import EmailAutocomplete from './ui/EmailAutocomplete.vue'
import { submitInquiry } from '../services/api'

const isOpen = ref(false)
const isSubmitting = ref(false)

const formData = ref({
  name: '',
  company: '',
  contactMethod: 'wechat',
  contactValue: '',
  budget: '1w-5w',
  description: ''
})

const contactOptions = [
  { label: '微信', value: 'wechat', icon: 'message-circle' },
  { label: '邮箱', value: 'email', icon: 'mail' },
  { label: '电话', value: 'phone', icon: 'phone' }
]

const getContactLabel = computed(() => {
  switch (formData.value.contactMethod) {
    case 'wechat': return '微信号'
    case 'phone': return '手机号码'
    default: return '联系方式'
  }
})

const openModal = () => {
  isOpen.value = true
  document.body.style.overflow = 'hidden'
}

const closeModal = () => {
  isOpen.value = false
  document.body.style.overflow = ''
}

const handleEscape = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && isOpen.value) {
    closeModal()
  }
}

const handleSubmit = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true

  try {
    await submitInquiry({
      name: formData.value.name,
      company: formData.value.company,
      contactMethod: formData.value.contactMethod,
      contactValue: formData.value.contactValue,
      budget: formData.value.budget,
      description: formData.value.description
    })

    closeModal()
    showToast('合作咨询已发送，我们会尽快与您联系！')
    formData.value = {
      name: '',
      company: '',
      contactMethod: 'wechat',
      contactValue: '',
      budget: '1w-5w',
      description: ''
    }
  } catch (error) {
    console.error(error)
    showToast('发送失败，请稍后重试', 'error')
  } finally {
    isSubmitting.value = false
  }
}

const autoResizeTextarea = (event: Event) => {
  const textarea = event.target as HTMLTextAreaElement
  textarea.style.height = ''
  textarea.style.height = textarea.scrollHeight + 'px'
}

const showToast = (message: string, type: string = 'success') => {
  const container = document.getElementById('toast-container')
  if (container) {
    const toast = document.createElement('div')
    toast.className = `toast ${type === 'success' ? 'toast-success' : 'toast-error'}`
    toast.innerHTML = `<i data-lucide="${type === 'success' ? 'check-circle' : 'alert-circle'}" class="w-5 h-5 ${type === 'success' ? 'text-[#d4b383]' : 'text-red-500'}"></i><span class="text-sm font-medium">${message}</span>`
    container.appendChild(toast)
    if ((window as any).lucide) {
      (window as any).lucide.createIcons()
    }
    requestAnimationFrame(() => toast.classList.add('show'))
    setTimeout(() => {
      toast.classList.remove('show')
      setTimeout(() => toast.remove(), 400)
    }, 3000)
  }
}

onMounted(() => {
  if (typeof window !== 'undefined') {
    ;(window as any).openInquiry = openModal
    ;(window as any).closeInquiry = closeModal
  }
  document.addEventListener('keydown', handleEscape)
})

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    delete (window as any).openInquiry
    delete (window as any).closeInquiry
  }
  document.removeEventListener('keydown', handleEscape)
  document.body.style.overflow = ''
})
</script>

<style scoped>
.inquiry-input:-webkit-autofill,
.inquiry-input:-webkit-autofill:hover,
.inquiry-input:-webkit-autofill:focus,
.inquiry-input:-webkit-autofill:active {
  -webkit-box-shadow: 0 0 0 1000px #080808 inset !important;
  -webkit-text-fill-color: white !important;
  caret-color: white;
  transition: background-color 5000s ease-in-out 0s;
}

.inquiry-fade-enter-active,
.inquiry-fade-leave-active {
  transition: opacity 0.25s ease;
}

.inquiry-fade-enter-from,
.inquiry-fade-leave-to {
  opacity: 0;
}
</style>
