'use client'

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

const faqs = [
  {
    question: 'Como funciona a seleção?',
    answer:
      'Nosso time analisa seu perfil com muito carinho. O retorno acontece em até 7 dias úteis por e-mail! Avaliamos engajamento, consistência de conteúdo e afinidade com os valores da Fast\'n Fit.',
  },
  {
    question: 'Preciso de exclusividade?',
    answer:
      'De jeito nenhum! Acreditamos em parcerias reais e naturais. Você pode continuar trabalhando com outras marcas tranquilamente — só pedimos autenticidade e carinho ao falar de nós.',
  },
  {
    question: 'Onde preciso morar?',
    answer:
      'Como nossas marmitas são ultracongeladas, validamos o CEP na inscrição para garantir a entrega perfeita. Estamos expandindo nossa área de entrega constantemente — se ainda não chegamos até você, logo chegaremos!',
  },
  {
    question: 'Existe algum custo para participar?',
    answer:
      'Não! A participação na FAST CREW é 100% gratuita. Você recebe os kits, os cupons e o suporte — sem pagar nada por isso. O nosso único pedido é conteúdo genuíno.',
  },
  {
    question: 'Com que frequência preciso postar?',
    answer:
      'Combinamos o volume de postagens individualmente com cada parceiro. Queremos que o conteúdo pareça natural para sua audiência, não forçado. Conversamos sobre isso após a aprovação.',
  },
]

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 }
}

function AccordionItem({
  faq,
  index,
  isOpen,
  onToggle,
  inView,
}: {
  faq: typeof faqs[0]
  index: number
  isOpen: boolean
  onToggle: () => void
  inView: boolean
}) {
  const contentRef = useRef<HTMLDivElement>(null)

  return (
    <div
      className="rounded-2xl overflow-hidden transition-all duration-300"
      style={{
        border: `2.5px solid ${isOpen ? '#ffbb1c' : '#f0e2cc'}`,
        boxShadow: isOpen ? '4px 4px 0 #ffbb1c' : '3px 3px 0 #f0e2cc',
        opacity: inView ? 1 : 0,
        transform: inView ? 'translateY(0)' : 'translateY(20px)',
        transition: `opacity 0.5s ease ${index * 0.08}s, transform 0.5s ease ${index * 0.08}s, border-color 0.2s, box-shadow 0.2s`,
      }}
    >
      <button
        onClick={onToggle}
        className="w-full flex items-center justify-between gap-4 px-6 py-5 text-left transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#7918d6]"
        style={{ background: isOpen ? '#fffbf0' : '#ffffff' }}
        aria-expanded={isOpen}
        aria-controls={`faq-answer-${index}`}
        id={`faq-question-${index}`}
      >
        <span
          className="font-display font-black text-xl leading-snug pr-2"
          style={{ color: '#472813' }}
        >
          {faq.question}
        </span>
        <span
          className="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300"
          style={{
            background: isOpen ? '#ffbb1c' : '#f0e2cc',
            transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
          }}
          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.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </span>
      </button>

      <div
        id={`faq-answer-${index}`}
        role="region"
        aria-labelledby={`faq-question-${index}`}
        ref={contentRef}
        style={{
          maxHeight: isOpen ? `${contentRef.current?.scrollHeight ?? 200}px` : '0',
          overflow: 'hidden',
          transition: 'max-height 0.35s cubic-bezier(0.4, 0, 0.2, 1)',
        }}
      >
        <div
          className="px-6 pb-5 pt-2 text-base leading-relaxed"
          style={{
            color: '#7a5a3a',
            borderTop: `1.5px solid ${isOpen ? '#ffbb1c' : 'transparent'}`,
          }}
        >
          {faq.answer}
        </div>
      </div>
    </div>
  )
}

export default function FAQSection() {
  const { ref, inView } = useInView()
  const [openIndex, setOpenIndex] = useState<number | null>(0)

  return (
    <section
      id="faq"
      className="relative py-24 px-6 overflow-hidden"
      style={{ background: '#ffffff' }}
      aria-labelledby="faq-title"
    >
      {/* Subtle background pattern */}
      <div
        className="absolute inset-0 pointer-events-none opacity-[0.025]"
        style={{
          backgroundImage: `repeating-linear-gradient(0deg, #472813 0px, #472813 1px, transparent 0px, transparent 40px),
            repeating-linear-gradient(90deg, #472813 0px, #472813 1px, transparent 0px, transparent 40px)`,
        }}
        aria-hidden="true"
      />

      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div
          ref={ref}
          className="text-center mb-12"
          style={{
            opacity: inView ? 1 : 0,
            transform: inView ? 'translateY(0)' : 'translateY(30px)',
            transition: 'all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)',
          }}
        >
          <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: '#fff8e7', border: '2px solid #ffbb1c', color: '#472813' }}
          >
            ✦ FAQ
          </div>
          <h2
            id="faq-title"
            className="font-display font-black text-balance leading-none"
            style={{ color: '#472813', fontSize: 'clamp(2rem, 5vw, 3rem)' }}
          >
            Ficou alguma dúvida?
          </h2>
          <p className="mt-3 text-base leading-relaxed" style={{ color: '#7a5a3a' }}>
            Respondemos as perguntas mais frequentes da nossa comunidade.
          </p>
        </div>

        {/* Accordion */}
        <div className="flex flex-col gap-3" role="list">
          {faqs.map((faq, i) => (
            <AccordionItem
              key={i}
              faq={faq}
              index={i}
              isOpen={openIndex === i}
              onToggle={() => setOpenIndex(openIndex === i ? null : i)}
              inView={inView}
            />
          ))}
        </div>

        {/* Still have questions? */}
        <div
          className="mt-10 flex flex-col sm:flex-row items-center justify-between gap-4 p-6 rounded-3xl"
          style={{
            background: '#fff8e7',
            border: '2px solid #ffbb1c',
            opacity: inView ? 1 : 0,
            transform: inView ? 'translateY(0)' : 'translateY(20px)',
            transition: 'all 0.6s ease 0.4s',
          }}
        >
          <div>
            <p className="font-display font-black text-base" style={{ color: '#472813' }}>
              Ainda tem dúvidas?
            </p>
            <p className="text-sm" style={{ color: '#7a5a3a' }}>
              Fale direto com a gente no Instagram.
            </p>
          </div>
          <a
            href="https://instagram.com/fastnfitoficial"
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2 px-5 py-2.5 rounded-2xl font-display font-black text-sm transition-all duration-200 hover:-translate-y-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#7918d6]"
            style={{
              background: '#472813',
              color: '#ffbb1c',
              boxShadow: '3px 3px 0 #ffbb1c',
            }}
            aria-label="Fale conosco no Instagram @fastnfitoficial (abre em nova aba)"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />
            </svg>
            @fastnfitoficial
          </a>
        </div>
      </div>
    </section>
  )
}
