// CTA + Briefing form

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

// Espera o window._sb nascer (mesmo padrão defensivo de services/works).
// Resolve null se o SDK do CDN não vier — daí o submit avisa em vez de quebrar.
function waitForSbContact(tries = 20) {
  return new Promise((resolve) => {
    let n = 0;
    (function check() {
      if (window._sb) return resolve(window._sb);
      if (n++ >= tries) return resolve(null);
      setTimeout(check, 100);
    })();
  });
}

// Outline STUND that fills on scroll
function CTAOutline() {
  const [fill, setFill] = useStateC(0);
  const ref = useRefC(null);

  useEffectC(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const vh = window.innerHeight;
      // Map: when section bottom enters → 0; when section top reaches mid-viewport → 1
      const start = vh;
      const end = vh * 0.2;
      const p = Math.max(0, Math.min(1, (start - r.top) / (start - end)));
      setFill(p);
    };
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const text = 'VAMOS CONSTRUIR ALGO INESQUECÍVEL';
  return (
    <div ref={ref} style={{ position: 'relative', overflow: 'hidden', padding: '40px 0' }}>
      <div className="display" style={{
        fontSize: 'clamp(48px, 9vw, 160px)',
        fontWeight: 600,
        letterSpacing: '-0.04em',
        lineHeight: 0.95,
        textAlign: 'center',
        position: 'relative',
        color: 'transparent',
        WebkitTextStroke: '1.5px var(--accent)',
      }}>
        {text}
        <span style={{
          position: 'absolute', inset: 0,
          color: 'var(--accent)',
          WebkitTextStroke: '1.5px var(--accent)',
          clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)`,
          transition: 'clip-path 0.1s linear',
        }}>
          {text}
        </span>
      </div>
    </div>
  );
}

function MaskedPhone({ value, onChange }) {
  const handle = (e) => {
    let v = e.target.value.replace(/\D/g, '').slice(0, 11);
    if (v.length > 6) v = `(${v.slice(0, 2)}) ${v.slice(2, 7)}-${v.slice(7)}`;
    else if (v.length > 2) v = `(${v.slice(0, 2)}) ${v.slice(2)}`;
    else if (v.length > 0) v = `(${v}`;
    onChange(v);
  };
  return <Input value={value} onChange={handle} placeholder="(11) 90000-0000"
                type="tel" inputMode="numeric" autoComplete="tel" />;
}

function Input({ value, onChange, placeholder, type = 'text', inputMode, autoComplete }) {
  return (
    <input
      type={type}
      inputMode={inputMode}
      autoComplete={autoComplete}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      data-cursor="min"
      style={{
        width: '100%',
        padding: '14px 0',
        background: 'transparent',
        border: 'none',
        borderBottom: '1px solid var(--line)',
        color: 'var(--fg)',
        fontFamily: 'var(--body)',
        fontSize: 16,
        outline: 'none',
        cursor: 'none',
        transition: 'border-color 0.3s',
      }}
      onFocus={(e) => e.target.style.borderBottomColor = 'var(--accent)'}
      onBlur={(e) => e.target.style.borderBottomColor = 'var(--line)'}
    />
  );
}

function Field({ label, num, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--accent)' }}>{num}</span>
        <span className="mono uppercase tracked" style={{ fontSize: 10, color: 'var(--fg-dim)' }}>
          {label}
        </span>
      </div>
      {children}
    </label>
  );
}

const SERVICE_OPTS = [
  'Direção Criativa', 'Produção de Vídeo', 'Edição',
  'Redes Sociais', 'Fotografia', 'Identidade Visual',
  'Branding', 'Catálogo / E-commerce', 'Comercial / Anúncio',
  'Cobertura de Evento', 'Conteúdo Institucional', 'Reels / TikTok',
  'Foto de Produto', 'Flyer / VideoFlyer', 'StoryMaker',
  'Documentário', 'Music Video', 'Ainda não sei',
];
const BUDGETS = ['até 5k', '5–15k', '15–30k', '30k+', 'a definir'];

function BriefForm() {
  const [data, setData] = useStateC({
    nome: '', email: '', tel: '', empresa: '',
    servs: [], budget: '', objetivo: '', dor: '', prazo: '', msg: '',
  });
  const [sent, setSent] = useStateC(false);
  const [sending, setSending] = useStateC(false);
  const [error, setError] = useStateC('');

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleServ = (s) => set('servs', data.servs.includes(s) ? data.servs.filter(x => x !== s) : [...data.servs, s]);

  const submit = async (e) => {
    e.preventDefault();
    if (sending || sent) return;
    setError('');

    // Validação mínima: nome + ao menos um contato (email ou telefone).
    const nome = data.nome.trim();
    const email = data.email.trim();
    const tel = data.tel.trim();
    if (!nome || (!email && !tel)) {
      setError('Preencha seu nome e ao menos um contato (email ou telefone).');
      return;
    }

    // Consolida campos sem coluna própria (objetivo/dor/prazo) em observacoes.
    const observacoes = [
      data.objetivo.trim() && `Objetivo: ${data.objetivo.trim()}`,
      data.dor.trim() && `Dor: ${data.dor.trim()}`,
      data.prazo.trim() && `Prazo: ${data.prazo.trim()}`,
    ].filter(Boolean).join('\n') || null;

    // Monta o payload mapeando o estado do form -> colunas da tabela `leads`.
    // status e fonte ficam de fora (o banco preenche: 'novo' / 'landing').
    const payload = {
      nome,
      email: email || null,
      whatsapp: tel || null,
      empresa: data.empresa.trim() || null,
      servicos_interesse: data.servs.length ? data.servs.join(', ') : null,
      orcamento_estimado: data.budget || null,
      mensagem: data.msg.trim() || null,
      observacoes,
    };

    setSending(true);
    try {
      const sb = await waitForSbContact();
      if (!sb) throw new Error('Supabase indisponível');
      const { error: insertError } = await sb.from('leads').insert(payload);
      if (insertError) throw insertError;
      setSent(true);
    } catch (err) {
      console.error('Falha ao enviar briefing:', err);
      setError('Não conseguimos enviar agora. Tente de novo ou fale no WhatsApp.');
    } finally {
      setSending(false);
    }
  };

  return (
    <form onSubmit={submit} style={{ marginTop: 60 }}>
      <fieldset disabled={sent || sending} className="brief-grid" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48,
        border: 'none', padding: 0, margin: 0, minInlineSize: 'auto',
      }}>
      <Field label="Nome" num="01">
        <Input value={data.nome} onChange={(e) => set('nome', e.target.value)} placeholder="Como te chamamos?" autoComplete="name" />
      </Field>
      <Field label="Email" num="02">
        <Input type="email" inputMode="email" autoComplete="email" value={data.email} onChange={(e) => set('email', e.target.value)} placeholder="voce@dominio.com" />
      </Field>
      <Field label="Telefone" num="03">
        <MaskedPhone value={data.tel} onChange={(v) => set('tel', v)} />
      </Field>
      <Field label="Empresa / projeto" num="04">
        <Input value={data.empresa} onChange={(e) => set('empresa', e.target.value)} placeholder="Loja, marca, restaurante, banda, evento, profissional autônomo…" />
      </Field>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Tipo de serviço (multi-select)" num="05">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 12 }}>
            {SERVICE_OPTS.map((s) => {
              const on = data.servs.includes(s);
              return (
                <button key={s} type="button" data-cursor="link" onClick={() => toggleServ(s)}
                  style={{
                    padding: '10px 16px',
                    border: `1px solid ${on ? 'var(--accent)' : 'var(--line)'}`,
                    color: on ? 'var(--accent)' : 'var(--fg)',
                    background: on ? 'rgba(240,85,3,0.08)' : 'transparent',
                    borderRadius: 999,
                    fontSize: 13,
                    fontFamily: 'var(--body)',
                    transition: 'all 0.2s',
                  }}>
                  {s}
                </button>
              );
            })}
          </div>
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Investimento estimado" num="06">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 12 }}>
            {BUDGETS.map((b) => {
              const on = data.budget === b;
              return (
                <button key={b} type="button" data-cursor="link" onClick={() => set('budget', b)}
                  style={{
                    padding: '10px 18px',
                    border: `1px solid ${on ? 'var(--accent)' : 'var(--line)'}`,
                    color: on ? 'var(--accent)' : 'var(--fg)',
                    background: on ? 'rgba(240,85,3,0.08)' : 'transparent',
                    fontFamily: 'var(--mono)',
                    fontSize: 12,
                    letterSpacing: '0.05em',
                    textTransform: 'uppercase',
                    transition: 'all 0.2s',
                  }}>
                  {b}
                </button>
              );
            })}
          </div>
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Objetivo com esse serviço" num="07">
          <textarea
            value={data.objetivo}
            onChange={(e) => set('objetivo', e.target.value)}
            placeholder="O que você quer alcançar? Ex: vender mais a coleção nova, lançar a marca, atrair público pro evento, virar referência no segmento…"
            rows={4}
            data-cursor="min"
            style={{
              width: '100%', padding: '14px 0',
              background: 'transparent', border: 'none',
              borderBottom: '1px solid var(--line)',
              color: 'var(--fg)',
              fontFamily: 'var(--body)', fontSize: 16,
              outline: 'none', cursor: 'none', resize: 'vertical',
            }}
            onFocus={(e) => e.target.style.borderBottomColor = 'var(--accent)'}
            onBlur={(e) => e.target.style.borderBottomColor = 'var(--line)'}
          />
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Qual a dor que você enfrenta hoje" num="08">
          <textarea
            value={data.dor}
            onChange={(e) => set('dor', e.target.value)}
            placeholder="O que não está funcionando? Ex: conteúdo sem identidade, foto ruim espantando cliente, marca sem cara, dificuldade pra explicar o que faço…"
            rows={4}
            data-cursor="min"
            style={{
              width: '100%', padding: '14px 0',
              background: 'transparent', border: 'none',
              borderBottom: '1px solid var(--line)',
              color: 'var(--fg)',
              fontFamily: 'var(--body)', fontSize: 16,
              outline: 'none', cursor: 'none', resize: 'vertical',
            }}
            onFocus={(e) => e.target.style.borderBottomColor = 'var(--accent)'}
            onBlur={(e) => e.target.style.borderBottomColor = 'var(--line)'}
          />
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Prazo desejado" num="09">
          <Input value={data.prazo} onChange={(e) => set('prazo', e.target.value)} placeholder="Ex: lançamento em junho/2026 …" />
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1' }}>
        <Field label="Algo mais que devemos saber" num="10">
          <textarea
            value={data.msg}
            onChange={(e) => set('msg', e.target.value)}
            placeholder="Referências, contexto extra, perguntas… (opcional)"
            rows={5}
            data-cursor="min"
            style={{
              width: '100%', padding: '14px 0',
              background: 'transparent', border: 'none',
              borderBottom: '1px solid var(--line)',
              color: 'var(--fg)',
              fontFamily: 'var(--body)', fontSize: 16,
              outline: 'none', cursor: 'none', resize: 'vertical',
            }}
            onFocus={(e) => e.target.style.borderBottomColor = 'var(--accent)'}
            onBlur={(e) => e.target.style.borderBottomColor = 'var(--line)'}
          />
        </Field>
      </div>

      <div style={{ gridColumn: '1 / -1', marginTop: 24 }}>
        <button type="submit" data-cursor="link" data-magnetic="true"
          style={{
            background: sent ? 'transparent' : 'var(--accent)',
            color: sent ? 'var(--accent)' : '#050505',
            border: `1px solid ${sent ? 'var(--accent)' : 'transparent'}`,
            padding: '20px 40px',
            fontFamily: 'var(--mono)',
            fontSize: 12,
            letterSpacing: '0.2em',
            textTransform: 'uppercase',
            display: 'inline-flex', alignItems: 'center', gap: 16,
            transition: 'background 0.4s, color 0.4s, border-color 0.4s, transform 0.4s cubic-bezier(.2,.8,.2,1)',
            opacity: sending ? 0.6 : 1,
          }}>
          {sent ? '✓ Briefing enviado' : sending ? 'Enviando…' : 'Enviar briefing'}
          {!sent && (
            <span style={{
              display: 'inline-block',
              transition: 'transform 0.3s',
              animation: sending ? 'none' : 'arrowSlide 1.6s ease-in-out infinite',
            }}>→</span>
          )}
        </button>

        {sent && (
          <div style={{ marginTop: 28 }}>
            <div className="mono uppercase tracked" style={{
              fontSize: 10, color: 'var(--accent)', marginBottom: 8,
            }}>
              ↳ Briefing recebido
            </div>
            <div style={{
              fontSize: 15, color: 'var(--fg-dim)',
              lineHeight: 1.5, maxWidth: 520,
            }}>
              Recebemos seu briefing — a gente responde em breve. Obrigado!
            </div>
          </div>
        )}
        {error && (
          <div className="mono" style={{
            marginTop: 20, fontSize: 13, lineHeight: 1.5,
            color: '#ff6b4a',
          }}>
            {error}
          </div>
        )}
      </div>
      </fieldset>
      <style>{`
        @keyframes arrowSlide {
          0%, 100% { transform: translateX(0); }
          50% { transform: translateX(6px); }
        }
        @media (max-width: 768px) {
          .brief-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </form>
  );
}

function CTA() {
  const [open, setOpen] = useStateC(false);
  return (
    <section id="contato" className="section" style={{
      padding: '180px 6vw', background: '#050505', position: 'relative',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 16, marginBottom: 60,
      }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.1em' }}>
          05 / CONTATO
        </span>
        <span style={{ width: 60, height: 1, background: 'var(--accent)' }} />
      </div>

      <CTAOutline />

      <div className="cta-buttons" style={{
        marginTop: 80,
        display: 'flex', justifyContent: 'center', gap: 20, flexWrap: 'wrap',
      }}>
        <button onClick={() => setOpen(!open)} data-cursor="link" data-magnetic="true"
          className="display"
          style={{
            background: open ? 'transparent' : 'var(--accent)',
            color: open ? 'var(--accent)' : '#050505',
            border: '1px solid var(--accent)',
            padding: '24px 40px',
            fontSize: 22, fontWeight: 500,
            letterSpacing: '-0.02em',
            display: 'inline-flex', alignItems: 'center', gap: 16,
            transition: 'all 0.3s',
          }}>
          <span style={{
            width: 8, height: 8,
            background: open ? 'var(--accent)' : '#050505',
            transform: open ? 'rotate(45deg)' : 'rotate(0)',
            transition: 'transform 0.4s',
          }} />
          {open ? 'Fechar briefing' : 'Briefing detalhado'}
        </button>
        <a href="https://wa.me/5511915636178?text=Oi%20Stund!%20Cheguei%20pelo%20site%20e%20queria%20conversar%20sobre%20um%20projeto." target="_blank" rel="noreferrer" data-cursor="link" data-magnetic="true"
          className="display"
          style={{
            background: 'transparent',
            color: 'var(--fg)',
            border: '1px solid var(--line)',
            padding: '24px 40px',
            fontSize: 22, fontWeight: 500,
            letterSpacing: '-0.02em',
            display: 'inline-flex', alignItems: 'center', gap: 16,
            transition: 'all 0.3s',
          }}>
          Falar no WhatsApp
          <span>↗</span>
        </a>
      </div>

      <div style={{
        maxHeight: open ? 2400 : 0,
        overflow: 'hidden',
        transition: 'max-height 0.8s cubic-bezier(.2,.8,.2,1)',
      }}>
        <div style={{
          marginTop: 80,
          padding: '48px 0',
          borderTop: '1px solid var(--line)',
        }}>
          <div className="mono uppercase tracked" style={{
            fontSize: 10, color: 'var(--accent)', marginBottom: 8,
          }}>
            ↳ FORMULÁRIO DE BRIEFING · 09 / 09
          </div>
          <div className="display" style={{
            fontSize: 'clamp(32px, 4vw, 56px)',
            fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1.05,
          }}>
            O que <em style={{ color: 'var(--accent)', fontStyle: 'normal' }}>você</em> quer<br />
            que o mundo sinta?
          </div>
          <div style={{
            marginTop: 20,
            fontSize: 15,
            color: 'var(--fg-dim)',
            maxWidth: 520,
            lineHeight: 1.5,
          }}>
            Quanto mais detalhe você nos der, mais certeira vai ser a resposta. Tudo o que escrever aqui chega direto na nossa caixa.
          </div>
          <BriefForm />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CTA, CTAOutline, BriefForm });
