'use client'

import { useState, useRef, useEffect } from 'react'

type FormData = {
  nome: string
  email: string
  cidade: string
  instagram: string
  seguidores: string
  estilo: string
  agrade: string
}

type FormErrors = Partial<Record<keyof FormData, string>>

function useInView(threshold = 0.1) {
  const ref = useRef<HTMLDivElement>(null)
  const [inView, setInView] = useState(false)
  useEffect(() => {
    const el = ref.current
    if (!el) return
    const obs = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) setInView(true) }, { threshold })
    obs.observe(el)
    return () => obs.disconnect()
  }, [threshold])
  return { ref, inView }
}

const inputBase =
  'w-full px-5 py-3.5 rounded-2xl font-medium transition-all duration-200 outline-none border-2 bg-white/90'

const inputStyle = (error: string | undefined, focused: boolean) =>
  `${inputBase} ${
    error
      ? 'border-[#ed3535] ring-2 ring-[#ed3535]/20'
      : focused
      ? 'border-[#7918d6] ring-2 ring-[#7918d6]/20'
      : 'border-[#f0e2cc] hover:border-[#ffbb1c]'
  }`

/* Star dots for parallax background */
const STARS_S = `501px 811px,1450px 1324px,1093px 780px,1469px 678px,904px 741px,1160px 781px,841px 462px,630px 267px,788px 276px,367px 234px,343px 156px,283px 342px,1062px 378px,395px 467px,17px 391px,37px 114px,767px 403px,543px 11px,78px 181px,89px 574px,697px 551px,439px 472px,491px 677px,364px 599px,34px 382px,21px 584px,66px 499px,69px 207px,19px 325px,659px 18px,731px 259px,332px 216px,913px 288px,80px 212px,326px 205px,574px 202px,473px 253px,404px 275px,322px 297px,425px 321px`
const STARS_M = `201px 211px,450px 324px,93px 280px,469px 278px,804px 341px,160px 281px,841px 262px,130px 267px,188px 276px,167px 234px,143px 256px,183px 342px,62px 378px,395px 167px,117px 91px,637px 114px,367px 103px,443px 11px,178px 181px,189px 574px,597px 251px,339px 472px,191px 177px,264px 299px,134px 282px,121px 284px,266px 199px,169px 307px,119px 125px,159px 118px,131px 159px,332px 316px,213px 288px,180px 212px,226px 205px,174px 102px,473px 153px,304px 175px,322px 197px,225px 121px`
const STARS_L = `101px 111px,150px 124px,93px 80px,169px 178px,104px 141px,60px 81px,41px 62px,30px 67px,88px 76px,67px 134px,43px 56px,83px 142px,62px 78px,95px 167px,117px 91px,137px 114px,67px 103px,143px 11px,78px 81px,89px 74px,97px 51px,39px 172px,91px 177px,64px 99px,134px 82px`

export default function ApplicationForm() {
  const { ref, inView } = useInView()
  const [form, setForm] = useState<FormData>({
    nome: '',
    email: '',
    cidade: '',
    instagram: '',
    seguidores: '',
    estilo: '',
    agrade: '',
  })
  const [errors, setErrors] = useState<FormErrors>({})
  const [focused, setFocused] = useState<string | null>(null)
  const [submitted, setSubmitted] = useState(false)
  const [loading, setLoading] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)

  const validate = (): FormErrors => {
    const e: FormErrors = {}
    if (!form.nome.trim()) e.nome = 'Informe seu nome completo.'
    if (!form.email.trim()) e.email = 'Informe seu e-mail profissional.'
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'Digite um e-mail válido.'
    if (!form.cidade.trim()) e.cidade = 'Informe sua cidade e estado.'
    if (!form.instagram.trim()) e.instagram = 'Informe o link do seu perfil.'
    else if (!form.instagram.includes('instagram.com') && !form.instagram.startsWith('@'))
      e.instagram = 'Parece que o link não é do Instagram.'
    if (!form.seguidores) e.seguidores = 'Selecione a faixa de seguidores.'
    if (!form.estilo.trim() || form.estilo.length < 20) e.estilo = 'Conta um pouco mais sobre você (mínimo 20 caracteres).'
    if (!form.agrade.trim() || form.agrade.length < 20) e.agrade = 'Escreva pelo menos 20 caracteres aqui.'
    return e
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const errs = validate()
    if (Object.keys(errs).length > 0) {
      setErrors(errs)
      return
    }
    setSubmitError(null)
    setLoading(true)
    try {
      const res = await fetch('/api/apply', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      const data = await res.json().catch(() => ({}))
      if (!res.ok) {
        throw new Error(data.error || 'Não foi possível enviar sua inscrição. Tente novamente.')
      }
      setSubmitted(true)
    } catch (err) {
      setSubmitError(err instanceof Error ? err.message : 'Não foi possível enviar sua inscrição. Tente novamente.')
    } finally {
      setLoading(false)
    }
  }

  const handleChange = (field: keyof FormData, value: string) => {
    setForm(prev => ({ ...prev, [field]: value }))
    if (errors[field]) setErrors(prev => ({ ...prev, [field]: undefined }))
  }

  return (
    <section
      id="inscricao"
      className="relative py-24 px-6 overflow-hidden"
      style={{ background: '#ffbb1c' }}
      aria-labelledby="form-title"
    >
      {/* Stars / dots parallax background — yellow-tinted at 20% opacity */}
      <div className="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden="true">
        <div
          className="absolute"
          style={{
            width: 1,
            height: 1,
            background: 'transparent',
            boxShadow: STARS_S.split(',').map(s => `${s} rgba(71,40,19,0.2)`).join(','),
            top: 0,
            left: 0,
            animation: 'animStar 50s linear infinite',
          }}
        />
        <div
          className="absolute"
          style={{
            width: 2,
            height: 2,
            background: 'transparent',
            boxShadow: STARS_M.split(',').map(s => `${s} rgba(71,40,19,0.2)`).join(','),
            top: 0,
            left: 0,
            animation: 'animStar2 100s linear infinite',
          }}
        />
        <div
          className="absolute"
          style={{
            width: 3,
            height: 3,
            background: 'transparent',
            boxShadow: STARS_L.split(',').map(s => `${s} rgba(71,40,19,0.15)`).join(','),
            top: 0,
            left: 0,
            animation: 'animStar3 150s linear infinite',
          }}
        />
      </div>

      <div className="max-w-2xl mx-auto relative">

        {/* Section header */}
        <div className="text-center mb-10">
          <div
            className="inline-flex items-center gap-2 px-4 py-2 rounded-full mb-5 text-sm font-bold uppercase tracking-widest"
            style={{ background: '#472813', color: '#ffbb1c' }}
          >
            ✦ Inscrição
          </div>
          <h2
            id="form-title"
            className="font-display font-black text-balance leading-none"
            style={{ color: '#472813', fontSize: 'clamp(2rem, 5vw, 3rem)' }}
          >
            Sua Jornada Começa Aqui ✨
          </h2>
        </div>

        {/* RGB glow wrapper */}
        <div
          className="relative rounded-3xl"
          style={{ padding: 4, overflow: 'hidden' }}
          ref={ref}
        >
          {/* RGB rotating conic gradient — before */}
          <div
            className="absolute"
            style={{
              inset: '-50%',
              background: 'conic-gradient(#ff0000, #ff7700, #ffff00, #00ff00, #0099ff, #6600ff, #ff0099, #ff0000)',
              animation: 'rgbRotate 3s linear infinite',
              borderRadius: '50%',
            }}
            aria-hidden="true"
          />
          {/* RGB rotating — offset 180deg */}
          <div
            className="absolute"
            style={{
              inset: '-50%',
              background: 'conic-gradient(#0099ff, #6600ff, #ff0099, #ff0000, #ff7700, #ffff00, #00ff00, #0099ff)',
              animation: 'rgbRotate2 3s linear infinite',
              borderRadius: '50%',
              opacity: 0.6,
            }}
            aria-hidden="true"
          />

          {/* Card content — solid white interior */}
          <div
            className="relative rounded-3xl p-8 md:p-10"
            style={{
              background: '#ffffff',
              opacity: inView ? 1 : 0,
              transform: inView ? 'translateY(0) scale(1)' : 'translateY(40px) scale(0.96)',
              transition: 'all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)',
            }}
          >
          {submitted ? (
            <div className="text-center py-10 animate-fade-in-scale">
              <div className="text-7xl mb-5 animate-bounce-pulse" aria-hidden="true">🎉</div>
              <h3 className="font-display font-black text-2xl mb-3" style={{ color: '#472813' }}>
                Inscrição enviada!
              </h3>
              <p className="text-base leading-relaxed" style={{ color: '#7a5a3a' }}>
                Nosso time vai analisar seu perfil com muito carinho e retornará em até{' '}
                <strong style={{ color: '#7918d6' }}>7 dias úteis</strong> por e-mail.
                Fique de olho! 👀
              </p>
              <div
                className="mt-6 inline-flex items-center gap-2 px-5 py-3 rounded-2xl font-display font-bold"
                style={{ background: '#62b12f', color: '#ffffff' }}
              >
                Bem-vindo(a) à Crew! 🚀
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-5" aria-label="Formulário de inscrição FAST CREW">

              {/* Nome */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="nome">
                  Nome completo <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <input
                  id="nome"
                  type="text"
                  placeholder="Ex: Ana Carolina Silva"
                  value={form.nome}
                  onChange={e => handleChange('nome', e.target.value)}
                  onFocus={() => setFocused('nome')}
                  onBlur={() => setFocused(null)}
                  className={inputStyle(errors.nome, focused === 'nome')}
                  style={{ color: '#472813', fontSize: '1rem' }}
                  aria-invalid={!!errors.nome}
                  aria-describedby={errors.nome ? 'nome-error' : undefined}
                  required
                />
                {errors.nome && (
                  <p id="nome-error" className="mt-1 text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                    {errors.nome}
                  </p>
                )}
              </div>

              {/* E-mail profissional */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="email">
                  E-mail profissional <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <input
                  id="email"
                  type="email"
                  inputMode="email"
                  autoComplete="email"
                  placeholder="Ex: seunome@email.com"
                  value={form.email}
                  onChange={e => handleChange('email', e.target.value)}
                  onFocus={() => setFocused('email')}
                  onBlur={() => setFocused(null)}
                  className={inputStyle(errors.email, focused === 'email')}
                  style={{ color: '#472813', fontSize: '1rem' }}
                  aria-invalid={!!errors.email}
                  aria-describedby={errors.email ? 'email-error' : undefined}
                  required
                />
                {errors.email && (
                  <p id="email-error" className="mt-1 text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                    {errors.email}
                  </p>
                )}
              </div>

              {/* Cidade */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="cidade">
                  Cidade e estado <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <input
                  id="cidade"
                  type="text"
                  placeholder="Ex: São Paulo, SP"
                  value={form.cidade}
                  onChange={e => handleChange('cidade', e.target.value)}
                  onFocus={() => setFocused('cidade')}
                  onBlur={() => setFocused(null)}
                  className={inputStyle(errors.cidade, focused === 'cidade')}
                  style={{ color: '#472813', fontSize: '1rem' }}
                  aria-invalid={!!errors.cidade}
                  aria-describedby={errors.cidade ? 'cidade-error' : undefined}
                  required
                />
                {errors.cidade && (
                  <p id="cidade-error" className="mt-1 text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                    {errors.cidade}
                  </p>
                )}
              </div>

              {/* Instagram */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="instagram">
                  Link do perfil no Instagram <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <div className="relative">
                  <span
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-sm font-bold"
                    style={{ color: '#7918d6' }}
                    aria-hidden="true"
                  >
                    @
                  </span>
                  <input
                    id="instagram"
                    type="url"
                    placeholder="instagram.com/seuarroba"
                    value={form.instagram}
                    onChange={e => handleChange('instagram', e.target.value)}
                    onFocus={() => setFocused('instagram')}
                    onBlur={() => setFocused(null)}
                    className={`${inputStyle(errors.instagram, focused === 'instagram')} pl-8`}
                    style={{ color: '#472813', fontSize: '1rem' }}
                    aria-invalid={!!errors.instagram}
                    aria-describedby={errors.instagram ? 'instagram-error' : undefined}
                    required
                  />
                </div>
                {errors.instagram && (
                  <p id="instagram-error" className="mt-1 text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                    {errors.instagram}
                  </p>
                )}
              </div>

              {/* Seguidores */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="seguidores">
                  Número de seguidores <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <div className="relative">
                  <select
                    id="seguidores"
                    value={form.seguidores}
                    onChange={e => handleChange('seguidores', e.target.value)}
                    onFocus={() => setFocused('seguidores')}
                    onBlur={() => setFocused(null)}
                    className={`${inputStyle(errors.seguidores, focused === 'seguidores')} appearance-none cursor-pointer pr-10`}
                    style={{ color: form.seguidores ? '#472813' : '#a09080', fontSize: '1rem' }}
                    aria-invalid={!!errors.seguidores}
                    aria-describedby={errors.seguidores ? 'seguidores-error' : undefined}
                    required
                  >
                    <option value="" disabled>Selecione a faixa</option>
                    <option value="1k-5k">1k a 5k seguidores</option>
                    <option value="5k-20k">5k a 20k seguidores</option>
                    <option value="20k+">20k+ seguidores</option>
                  </select>
                  <span className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" aria-hidden="true">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                      <path d="M4 6l4 4 4-4" stroke="#472813" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                </div>
                {errors.seguidores && (
                  <p id="seguidores-error" className="mt-1 text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                    {errors.seguidores}
                  </p>
                )}
              </div>

              {/* Estilo */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="estilo">
                  Seu estilo de influência <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <p className="text-sm mb-2" style={{ color: '#7a5a3a' }}>O que você mais gosta de postar?</p>
                <textarea
                  id="estilo"
                  rows={3}
                  placeholder="Ex: Compartilho minha rotina fitness, receitas saudáveis e dicas de bem-estar..."
                  value={form.estilo}
                  onChange={e => handleChange('estilo', e.target.value)}
                  onFocus={() => setFocused('estilo')}
                  onBlur={() => setFocused(null)}
                  className={`${inputStyle(errors.estilo, focused === 'estilo')} resize-none`}
                  style={{ color: '#472813', fontSize: '1rem' }}
                  aria-invalid={!!errors.estilo}
                  aria-describedby={errors.estilo ? 'estilo-error' : undefined}
                  required
                />
                <div className="flex justify-between items-center mt-1">
                  {errors.estilo ? (
                    <p id="estilo-error" className="text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                      {errors.estilo}
                    </p>
                  ) : <span />}
                  <span className="text-sm" style={{ color: form.estilo.length < 20 ? '#ed3535' : '#62b12f' }}>
                    {form.estilo.length}/20 mín.
                  </span>
                </div>
              </div>

              {/* Agrade */}
              <div>
                <label className="block text-base font-bold mb-1.5" style={{ color: '#472813' }} htmlFor="agrade">
                  Como a Fast&apos;n Fit agrega ao seu conteúdo? <span aria-hidden="true" style={{ color: '#ed3535' }}>*</span>
                </label>
                <textarea
                  id="agrade"
                  rows={3}
                  placeholder="Ex: Meu público ama praticidade e saúde — as marmitas se encaixam perfeitamente no que crio..."
                  value={form.agrade}
                  onChange={e => handleChange('agrade', e.target.value)}
                  onFocus={() => setFocused('agrade')}
                  onBlur={() => setFocused(null)}
                  className={`${inputStyle(errors.agrade, focused === 'agrade')} resize-none`}
                  style={{ color: '#472813', fontSize: '1rem' }}
                  aria-invalid={!!errors.agrade}
                  aria-describedby={errors.agrade ? 'agrade-error' : undefined}
                  required
                />
                <div className="flex justify-between items-center mt-1">
                  {errors.agrade ? (
                    <p id="agrade-error" className="text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                      {errors.agrade}
                    </p>
                  ) : <span />}
                  <span className="text-sm" style={{ color: form.agrade.length < 20 ? '#ed3535' : '#62b12f' }}>
                    {form.agrade.length}/20 mín.
                  </span>
                </div>
              </div>

              {submitError && (
                <p className="text-center text-sm font-medium" style={{ color: '#ed3535' }} role="alert">
                  {submitError}
                </p>
              )}

              {/* Submit */}
              <button
                type="submit"
                disabled={loading}
                className="relative group mt-2 w-full py-4 rounded-2xl font-display font-black text-lg text-white uppercase tracking-wide transition-all duration-200 focus:outline-none focus-visible:ring-4 focus-visible:ring-offset-2 focus-visible:ring-[#62b12f] disabled:opacity-70 disabled:cursor-not-allowed overflow-hidden"
                style={{
                  background: loading ? '#4d8a24' : '#62b12f',
                  border: '2.5px solid #472813',
                  boxShadow: loading ? '2px 2px 0 #472813' : '5px 5px 0 #472813',
                  transform: loading ? 'translate(3px, 3px)' : 'translate(0, 0)',
                }}
                aria-busy={loading}
              >
                <span
                  className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
                  style={{
                    background: 'linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.2) 50%, transparent 100%)',
                    backgroundSize: '200% 100%',
                    animation: 'shimmer 1.5s infinite',
                  }}
                  aria-hidden="true"
                />
                {loading ? (
                  <span className="flex items-center justify-center gap-3">
                    <svg className="animate-spin w-5 h-5" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                      <circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.3)" strokeWidth="3" />
                      <path d="M12 2a10 10 0 0110 10" stroke="white" strokeWidth="3" strokeLinecap="round" />
                    </svg>
                    Enviando sua inscrição...
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    Enviar Inscrição 🚀
                  </span>
                )}
              </button>

              <p className="text-center text-sm" style={{ color: '#7a5a3a' }}>
                Seus dados estão seguros. Retorno em até 7 dias úteis por e-mail.
              </p>
            </form>
          )}
          </div>
        </div>
      </div>
    </section>
  )
}
