// OOBOX site — process, FAQ, contact, footer

// ============== PROCESS ==============
function Process() {
  const steps = [
    { n: '01', t: 'Diagnóstico', d: 'Imersão profunda no contexto, dados e dores reais. Sem suposições — só observação afiada.' },
    { n: '02', t: 'Estratégia', d: 'Construímos o plano com você. Hipóteses claras, métricas de sucesso e um roadmap executável.' },
    { n: '03', t: 'Execução', d: 'Mãos no código, na mídia, nos dados. Implementamos junto, lado a lado com seu time.' },
    { n: '04', t: 'Otimização', d: 'Métricas em ciclo curto, ajustes constantes. O que não escala, descartamos. O que funciona, dobramos.' },
  ];
  return (
    <section style={{ padding: '120px 0', position: 'relative', borderTop: '1px solid var(--line)' }}>
      <div className="container">
        <div className="reveal" style={{ maxWidth: 720, marginBottom: 80 }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>NOSSO PROCESSO</div>
          <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 52px)', fontWeight: 800, letterSpacing: '-0.02em' }}>
            Um método, quatro fases. <span className="grad-text">Zero achismo.</span>
          </h2>
        </div>

        <div style={{ position: 'relative' }}>
          {/* Connector line */}
          <div style={{ position: 'absolute', top: 36, left: '6%', right: '6%', height: 1, background: 'linear-gradient(90deg, transparent, var(--violet), transparent)', opacity: 0.4 }} className="hide-mobile" />

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24, position: 'relative' }}>
            {steps.map((s, i) => (
              <div key={i} className="reveal" style={{ transitionDelay: `${i * 100}ms`, position: 'relative' }}>
                <div style={{
                  width: 72, height: 72, borderRadius: '50%',
                  border: '1px solid rgba(144, 77, 255, 0.4)',
                  background: 'var(--bg-deep)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--font-head)', fontWeight: 800, fontSize: 22,
                  marginBottom: 24, position: 'relative',
                }}>
                  <span className="grad-text">{s.n}</span>
                  <div style={{
                    position: 'absolute', inset: -1, borderRadius: '50%',
                    background: 'var(--grad)', opacity: 0.15, zIndex: -1,
                  }} />
                </div>
                <h3 style={{ fontSize: 22, fontWeight: 700, marginBottom: 12, letterSpacing: '-0.01em' }}>{s.t}</h3>
                <p style={{ fontSize: 14, color: 'var(--gray)', lineHeight: 1.65 }}>{s.d}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== TESTIMONIAL / QUOTE BANNER ==============
function QuoteBanner() {
  return (
    <section style={{ padding: '80px 0' }}>
      <div className="container">
        <div className="reveal" style={{
          padding: '80px 56px',
          borderRadius: 8, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, rgba(123, 63, 228, 0.10), rgba(144, 77, 255, 0.02) 60%)',
          border: '1px solid rgba(144, 77, 255, 0.25)',
        }}>
          <div style={{ position: 'absolute', top: -40, right: -40, opacity: 0.4 }}>
            <ExpansionShape width={500} height={350} />
          </div>
          <div style={{ position: 'absolute', bottom: -20, left: 40, opacity: 0.5 }}>
            <DigitalLines width={240} height={160} />
          </div>
          <div style={{ position: 'relative', zIndex: 2, maxWidth: 880 }}>
            <div className="eyebrow" style={{ marginBottom: 24 }}>POR TRÁS DE TODO CRESCIMENTO EXISTE:</div>
            <p style={{
              fontFamily: 'var(--font-head)', fontWeight: 600,
              fontSize: 'clamp(28px, 4vw, 44px)', lineHeight: 1.2,
              letterSpacing: '-0.02em', marginBottom: 32,
            }}>
              "A OOBOX existe para empresas que <span className="grad-text">não aceitam mais do mesmo</span>. Para quem quer ir além do óbvio e construir o próximo nível."
            </p>
            <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
              {['Diagnóstico inteligente', 'Estratégia personalizada', 'Execução com tecnologia', 'Otimização contínua'].map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-sub)', fontSize: 14, color: 'var(--gray)' }}>
                  <Icon name="check" size={14} color="var(--violet)" strokeWidth={2.4} /> {t}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== FAQ ==============
function FAQ() {
  const [open, setOpen] = React.useState(0);
  const items = [
    { q: 'Vocês são uma agência ou consultoria?', a: 'Nem uma coisa, nem outra. Somos uma boutique de tecnologia e growth — atuamos como parceiros estratégicos com mão na massa. Diagnosticamos, planejamos e executamos junto com seu time.' },
    { q: 'Qual o tamanho ideal de empresa para trabalhar com a OOBOX?', a: 'Trabalhamos com empresas em estágio de crescimento que já têm operação rodando, faturamento estável e querem dar o próximo salto com método. De startups Series A a empresas estabelecidas em busca de reposicionamento.' },
    { q: 'Como funciona o engajamento?', a: 'Começamos sempre com um diagnóstico estruturado de 2 a 4 semanas. A partir dele, definimos juntos o escopo do projeto — pode ser um sprint focado ou uma parceria de longo prazo, sempre com entregáveis claros.' },
    { q: 'Em quanto tempo vejo resultado?', a: 'Os primeiros sinais aparecem entre 4 e 8 semanas — em geral em métricas operacionais. Resultados estruturais (CAC, LTV, conversão de funil) tendem a maturar entre o 3º e o 6º mês. Não prometemos milagre, prometemos método.' },
    { q: 'Vocês trabalham com qual stack de tecnologia?', a: 'Stack-agnósticos por princípio. Avaliamos o que faz sentido para sua operação — desde HubSpot, Salesforce e RD Station, até soluções modernas como Segment, dbt, Looker, n8n e arquiteturas customizadas.' },
  ];
  return (
    <section id="conteudos" className="section" style={{ borderTop: '1px solid var(--line)' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 80, alignItems: 'flex-start' }} className="grid-pos">
          <div className="reveal">
            <div className="eyebrow" style={{ marginBottom: 16 }}>DÚVIDAS FREQUENTES</div>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 48px)', fontWeight: 800, letterSpacing: '-0.02em', marginBottom: 24 }}>
              Perguntas que ouvimos <span className="grad-text">com frequência.</span>
            </h2>
            <p style={{ fontSize: 16, color: 'var(--gray)', lineHeight: 1.6 }}>
              Não encontrou o que procura? Manda direto pra gente — respondemos rápido e sem rodeios.
            </p>
          </div>
          <div className="reveal" style={{ display: 'flex', flexDirection: 'column', gap: 0, border: '1px solid var(--line)', borderRadius: 6, overflow: 'hidden' }}>
            {items.map((it, i) => (
              <div key={i} style={{ borderBottom: i < items.length - 1 ? '1px solid var(--line)' : 'none' }}>
                <button
                  onClick={() => setOpen(open === i ? -1 : i)}
                  style={{ width: '100%', textAlign: 'left', padding: '24px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}
                >
                  <span style={{ fontFamily: 'var(--font-sub)', fontWeight: 500, fontSize: 16 }}>{it.q}</span>
                  <span style={{ color: 'var(--violet)', flexShrink: 0, transition: 'transform 0.3s', transform: open === i ? 'rotate(45deg)' : 'rotate(0)' }}>
                    <Icon name="plus" size={20} />
                  </span>
                </button>
                <div style={{
                  maxHeight: open === i ? 200 : 0,
                  overflow: 'hidden', transition: 'max-height 0.4s ease',
                }}>
                  <p style={{ padding: '0 28px 24px', fontSize: 15, color: 'var(--gray)', lineHeight: 1.65, maxWidth: 680 }}>{it.a}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== CONTACT / CTA ==============
// Turnstile site key — public, can live in client code.
// Production key from Cloudflare → Turnstile dashboard (oobox-site).
const TURNSTILE_SITE_KEY = '0x4AAAAAADKZpGqXtbhl9PPX';

function Contact() {
  const [form, setForm] = React.useState({ nome: '', email: '', empresa: '', desafio: '' });
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [captchaToken, setCaptchaToken] = React.useState(null);
  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  // Render Turnstile widget once the script has loaded.
  React.useEffect(() => {
    let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (window.turnstile && turnstileRef.current && widgetIdRef.current === null) {
        widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
          sitekey: TURNSTILE_SITE_KEY,
          theme: 'dark',
          callback: (token) => setCaptchaToken(token),
          'error-callback': () => setCaptchaToken(null),
          'expired-callback': () => setCaptchaToken(null),
        });
      } else if (!window.turnstile) {
        setTimeout(tryRender, 200);
      }
    };
    tryRender();
    return () => {
      cancelled = true;
      if (window.turnstile && widgetIdRef.current !== null) {
        try { window.turnstile.remove(widgetIdRef.current); } catch {}
        widgetIdRef.current = null;
      }
    };
  }, []);

  const resetCaptcha = () => {
    if (window.turnstile && widgetIdRef.current !== null) {
      try { window.turnstile.reset(widgetIdRef.current); } catch {}
    }
    setCaptchaToken(null);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!captchaToken) {
      setStatus('error');
      setTimeout(() => setStatus('idle'), 4000);
      return;
    }
    setStatus('sending');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          token: captchaToken,
          nome: form.nome,
          email: form.email,
          empresa: form.empresa,
          desafio: form.desafio,
        }),
      });
      if (res.ok) {
        setStatus('sent');
        setForm({ nome: '', email: '', empresa: '', desafio: '' });
        resetCaptcha();
        setTimeout(() => setStatus('idle'), 5000);
      } else {
        setStatus('error');
        resetCaptcha();
        setTimeout(() => setStatus('idle'), 5000);
      }
    } catch (err) {
      setStatus('error');
      resetCaptcha();
      setTimeout(() => setStatus('idle'), 5000);
    }
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px',
    background: 'rgba(255,255,255,0.025)',
    border: '1px solid var(--line)',
    borderRadius: 4, color: 'var(--white)',
    fontFamily: 'var(--font-body)', fontSize: 15,
    outline: 'none', transition: 'border-color 0.2s',
  };

  return (
    <section id="contato" style={{ padding: '120px 0', position: 'relative', overflow: 'hidden', borderTop: '1px solid var(--line)' }}>
      <div style={{ position: 'absolute', top: '20%', right: '-10%', width: 600, height: 600, background: 'radial-gradient(circle, rgba(144, 77, 255, 0.18), transparent 60%)', filter: 'blur(80px)', pointerEvents: 'none' }} />
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'flex-start' }} className="grid-pos">
          <div className="reveal">
            <div className="eyebrow" style={{ marginBottom: 16 }}>VAMOS CONVERSAR</div>
            <h2 style={{ fontSize: 'clamp(40px, 5.5vw, 68px)', fontWeight: 800, letterSpacing: '-0.02em', marginBottom: 32 }}>
              Pronto para sair do <span className="grad-text">óbvio?</span>
            </h2>
            <p style={{ fontSize: 18, color: 'var(--gray)', lineHeight: 1.55, marginBottom: 48, maxWidth: 480, fontFamily: 'var(--font-sub)' }}>
              Conta pra gente o seu desafio. Voltamos em até 1 dia útil com um diagnóstico inicial e próximos passos.
            </p>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 20, fontFamily: 'var(--font-sub)' }}>
              {[
                { k: 'Email', v: 'contato@oobox.com.br', href: 'mailto:contato@oobox.com.br' },
                { k: 'WhatsApp', v: '+55 35 8887-5548', href: 'https://wa.me/553588875548' },
              ].map((it, i) => (
                <a key={i} href={it.href} target={it.href.startsWith('http') ? '_blank' : undefined} rel="noopener" style={{ display: 'flex', alignItems: 'center', gap: 16, transition: 'color 0.2s' }}
                  onMouseEnter={(e) => e.currentTarget.style.color = 'var(--violet)'}
                  onMouseLeave={(e) => e.currentTarget.style.color = ''}
                >
                  <div style={{ width: 80, fontSize: 11, letterSpacing: '0.16em', color: 'var(--gray)', textTransform: 'uppercase' }}>{it.k}</div>
                  <div style={{ width: 1, height: 16, background: 'var(--line-strong)' }} />
                  <div style={{ fontSize: 16, fontWeight: 500 }}>{it.v}</div>
                </a>
              ))}
            </div>
          </div>

          <form onSubmit={handleSubmit} className="reveal" style={{
            padding: 40, borderRadius: 8,
            background: 'linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0.005))',
            border: '1px solid var(--line-strong)',
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{ position: 'absolute', top: -60, right: -60, opacity: 0.3, pointerEvents: 'none' }}>
              <ExpansionShape width={300} height={220} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18, position: 'relative', zIndex: 2 }}>
              <div>
                <label style={{ fontSize: 12, color: 'var(--gray)', fontFamily: 'var(--font-sub)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Seu nome</label>
                <input style={inputStyle} value={form.nome} onChange={(e) => setForm({...form, nome: e.target.value})} required onFocus={(e) => e.target.style.borderColor = 'var(--violet)'} onBlur={(e) => e.target.style.borderColor = 'var(--line)'} />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <label style={{ fontSize: 12, color: 'var(--gray)', fontFamily: 'var(--font-sub)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Email</label>
                  <input type="email" style={inputStyle} value={form.email} onChange={(e) => setForm({...form, email: e.target.value})} required onFocus={(e) => e.target.style.borderColor = 'var(--violet)'} onBlur={(e) => e.target.style.borderColor = 'var(--line)'} />
                </div>
                <div>
                  <label style={{ fontSize: 12, color: 'var(--gray)', fontFamily: 'var(--font-sub)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Empresa</label>
                  <input style={inputStyle} value={form.empresa} onChange={(e) => setForm({...form, empresa: e.target.value})} onFocus={(e) => e.target.style.borderColor = 'var(--violet)'} onBlur={(e) => e.target.style.borderColor = 'var(--line)'} />
                </div>
              </div>
              <div>
                <label style={{ fontSize: 12, color: 'var(--gray)', fontFamily: 'var(--font-sub)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Seu desafio</label>
                <textarea rows={4} style={{...inputStyle, resize: 'vertical', fontFamily: 'var(--font-body)' }} value={form.desafio} onChange={(e) => setForm({...form, desafio: e.target.value})} required placeholder="Conte brevemente o contexto..." onFocus={(e) => e.target.style.borderColor = 'var(--violet)'} onBlur={(e) => e.target.style.borderColor = 'var(--line)'} />
              </div>
              <div ref={turnstileRef} style={{ marginTop: 8, minHeight: 65 }} />
              <button type="submit" disabled={status === 'sending' || !captchaToken} className="btn btn-primary" style={{ marginTop: 8, justifyContent: 'center', padding: '16px 28px', opacity: (status === 'sending' || !captchaToken) ? 0.6 : 1, cursor: !captchaToken ? 'not-allowed' : 'pointer' }}>
                {status === 'sent' && '✓ Recebido — voltamos em breve'}
                {status === 'error' && '✕ Erro ao enviar — tente novamente'}
                {status === 'sending' && 'Enviando...'}
                {status === 'idle' && !captchaToken && 'Confirme o captcha acima'}
                {status === 'idle' && captchaToken && (<>Enviar mensagem <Icon name="arrow-right" size={16} /></>)}
              </button>
              <p style={{ fontSize: 11, color: 'var(--gray-dim)', marginTop: 4, textAlign: 'center', fontFamily: 'var(--font-sub)' }}>
                Ao enviar, você concorda com nossa <a href="politica-de-privacidade.html" style={{ color: 'var(--violet)' }}>política de privacidade</a>.
              </p>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

// ============== FOOTER ==============
function Footer() {
  return (
    <footer style={{ borderTop: '1px solid var(--line)', padding: '64px 0 32px', position: 'relative' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 48, marginBottom: 56 }} className="footer-grid">
          <div>
            <OoboxLogo size={0.85} withTagline />
            <p style={{ fontSize: 14, color: 'var(--gray)', lineHeight: 1.6, marginTop: 24, maxWidth: 320 }}>
              Boutique de consultoria em tecnologia e growth marketing.
            </p>
          </div>
          {[
            { t: 'EMPRESA', l: [
              { label: 'Sobre', href: '#sobre' },
              { label: 'Manifesto', href: '#sobre' },
              { label: 'Cases', href: '#cases' },
              { label: 'Conteúdos', href: '#conteudos' },
            ]},
            { t: 'SOLUÇÕES', l: [
              { label: 'Tecnologia', href: '#servicos' },
              { label: 'Growth', href: '#servicos' },
              { label: 'Dados', href: '#servicos' },
              { label: 'Estratégia', href: '#servicos' },
            ]},
            { t: 'CONTATO', l: [
              { label: 'contato@oobox.com.br', href: 'mailto:contato@oobox.com.br' },
              { label: 'WhatsApp', href: 'https://wa.me/553588875548', external: true },
              { label: 'LinkedIn (em breve)', href: '#', muted: true },
              { label: 'Instagram (em breve)', href: '#', muted: true },
            ]},
          ].map((col, i) => (
            <div key={i}>
              <div style={{ fontFamily: 'var(--font-sub)', fontSize: 11, letterSpacing: '0.18em', color: 'var(--violet)', marginBottom: 20 }}>{col.t}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {col.l.map((item, j) => (
                  <a key={j} href={item.href}
                    target={item.external ? '_blank' : undefined}
                    rel={item.external ? 'noopener' : undefined}
                    onClick={item.muted ? (e) => e.preventDefault() : undefined}
                    style={{ fontFamily: 'var(--font-sub)', fontSize: 14, color: item.muted ? 'var(--gray-dim)' : 'var(--gray)', transition: 'color 0.2s', cursor: item.muted ? 'default' : 'pointer' }}
                    onMouseEnter={(e) => { if (!item.muted) e.currentTarget.style.color = 'var(--white)'; }}
                    onMouseLeave={(e) => { if (!item.muted) e.currentTarget.style.color = 'var(--gray)'; }}
                  >{item.label}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{ paddingTop: 28, borderTop: '1px solid var(--line)', marginBottom: 20, fontFamily: 'var(--font-sub)', fontSize: 12, color: 'var(--gray-dim)' }}>
          OOBOX · CNPJ 27.327.863/0001-24
        </div>
        <div style={{
          display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
          fontFamily: 'var(--font-sub)', fontSize: 12, color: 'var(--gray-dim)',
        }}>
          <div>© 2026 OOBOX. Todos os direitos reservados.</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="politica-de-privacidade.html" style={{ color: 'var(--gray-dim)' }}>Política de privacidade</a>
            <a href="termos-de-uso.html" style={{ color: 'var(--gray-dim)' }}>Termos de uso</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Process, QuoteBanner, FAQ, Contact, Footer });
