/* ══════════════════════════════════════════════════
   LEAD FORM — formulário comercial, pronto para o CRM.

   Três camadas, para que a integração real mexa em um lugar só:
   • LEAD_FIELDS / validateLead  → regras de cada campo
   • toPayload / sendLead        → o ÚNICO ponto que conversa com os destinos
                                   (CRM_CONFIG e SHEETS_CONFIG, js/config.jsx)
   • <LeadForm/>                 → UI, estados e acessibilidade

   Sem endpoint configurado não existe envio fictício: o visitante vê o
   erro e os dados continuam preenchidos para tentar de novo.

   Anti-spam em camadas: campo-isca (`website`), tempo mínimo de
   preenchimento (`elapsedMs`, conferido no servidor) e, se houver
   TURNSTILE_SITE_KEY, o captcha invisível da Cloudflare. O CRM também limita
   os envios por IP, e a planilha limita o total de envios.
══════════════════════════════════════════════════ */

const onlyDigits = v => String(v || '').replace(/\D/g, '');

/* (11) 98765-4321 while typing; accepts landlines (10 digits) too. */
const maskPhone = v => {
  const d = onlyDigits(v).replace(/^55(?=\d{10,11}$)/, '').slice(0, 11);
  if (d.length <= 2) return d.length ? `(${d}` : '';
  if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
};

const FREE_MAIL = /@(gmail|hotmail|outlook|live|yahoo|icloud|uol|bol|terra|ig)\.(com|com\.br)$/i;

const LEAD_FIELDS = {
  nome:     v => { const n = v.trim().length; return n < 3 ? 'Informe seu nome.' : n > 120 ? 'Use até 120 caracteres.' : ''; },
  empresa:  v => { const n = v.trim().length; return n < 2 ? 'Informe o nome da empresa.' : n > 120 ? 'Use até 120 caracteres.' : ''; },
  email:    v => !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim()) || v.trim().length > 254 ? 'Informe um e-mail válido.' : '',
  whatsapp: v => { const n = onlyDigits(v).length; return n < 10 || n > 11 ? 'Informe o WhatsApp com DDD.' : ''; },
  mensagem: v => v.length > 800 ? 'Use até 800 caracteres.' : '',
};
const validateLead = values =>
  Object.fromEntries(Object.entries(LEAD_FIELDS).map(([k, rule]) => [k, rule(values[k] ?? '')]).filter(([, e]) => e));

/* Acceptance happens by submitting: the notice right above the button tells
   the visitor that sending means agreeing to the privacy policy. The version
   (with "envio" = accepted on submit) is recorded with the lead — bump it
   whenever that notice or the policy changes in substance. */
const CONSENT_VERSION = '2026-10-d-envio';

/* Origin of the visit (UTM/referrer) captured by js/analytics.js. */
const leadSource = () => {
  try { return JSON.parse(sessionStorage.getItem('entregga_src') || 'null') || {}; } catch (e) { return {}; }
};

/* The shape sent to every destination. */
const toPayload = (values, extra = {}) => ({
  name:     values.nome.trim(),
  company:  values.empresa.trim(),
  email:    values.email.trim().toLowerCase(),
  phone:    '+55' + onlyDigits(values.whatsapp),
  message:  values.mensagem.trim(),
  source:   { page: location.href.split('#')[0], ...leadSource() },
  createdAt: new Date().toISOString(),
  website:  values.website,      // honeypot, checked again by the CRM (docs/integracao-crm.md)
  consent:  { accepted: true, version: CONSENT_VERSION },   // see CONSENT_VERSION
  ...extra,                      // elapsedMs, turnstileToken
});

const postLead = async (cfg, body) => {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), cfg.timeoutMs);
  try {
    const res = await fetch(cfg.endpoint, {
      method: 'POST',
      headers: cfg.plainText
        ? { 'Content-Type': 'text/plain;charset=utf-8' }   // "simple request": no CORS preflight
        : { 'Content-Type': 'application/json', ...cfg.headers },
      body,
      signal: ctrl.signal,
    });
    /* Only an explicit { ok: true } counts as saved: a login page or any
       non-JSON answer must never show "Recebemos seu contato". */
    const out = await res.json().catch(() => null);
    if (!res.ok || !out || out.ok !== true) {
      const err = new Error(`Destino recusou: ${(out && out.error) || res.status}`);
      err.code = out && out.error;
      err.fields = out && out.fields;
      throw err;
    }
  } finally {
    clearTimeout(timer);
  }
};

/* Waits for both destinations, so the visitor only leaves once each one had
   its chance. One saving is enough; a failure on the other is only measured.
   Only when both fail does the CRM's answer decide what the visitor sees. */
const sendLead = async (values, extra) => {
  const dests = [['crm', CRM_CONFIG], ['sheets', SHEETS_CONFIG]].filter(([, cfg]) => cfg.endpoint);
  if (!dests.length) throw new Error('Formulário sem destino');
  const body = JSON.stringify(toPayload(values, extra));
  const results = await Promise.allSettled(dests.map(([, cfg]) => postLead(cfg, body)));
  results.forEach((r, i) => {
    if (r.status === 'rejected' && window.entregga) {
      window.entregga.track('lead_destination_error', { destination: dests[i][0], message: String(r.reason.message || r.reason).slice(0, 80) });
    }
  });
  const saved = dests.filter((_, i) => results[i].status === 'fulfilled').map(([name]) => name);
  if (!saved.length) throw results[0].reason;
  return saved;
};

/* ── Cloudflare Turnstile (loaded only when a site key is configured) ── */
let turnstileScript = null;
const loadTurnstile = () => turnstileScript || (turnstileScript = new Promise((resolve, reject) => {
  const s = document.createElement('script');
  s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
  s.async = true;
  s.onload = resolve;
  s.onerror = () => { turnstileScript = null; reject(new Error('turnstile')); };
  document.head.appendChild(s);
}));

/* Remount it (new `key`) to get a fresh token: tokens are single-use. */
const TurnstileBox = ({ onToken }) => {
  const ref = useRef(null);
  useEffect(() => {
    let id = null, cancelled = false;
    loadTurnstile().then(() => {
      if (cancelled || !ref.current) return;
      id = window.turnstile.render(ref.current, {
        sitekey: TURNSTILE_SITE_KEY,
        appearance: 'interaction-only',   // stays invisible unless Cloudflare needs a click
        language: 'pt-br',
        callback: onToken,
        'expired-callback': () => onToken(''),
        'error-callback': () => onToken(''),
      });
    }).catch(() => onToken(''));
    return () => { cancelled = true; if (id !== null && window.turnstile) window.turnstile.remove(id); };
  }, []);
  return <div ref={ref} className="lf-captcha"/>;
};

const EMPTY_LEAD = { nome:'', empresa:'', email:'', whatsapp:'', mensagem:'', website:'' };

/* CRM field name → form field name, to show its validation next to the field. */
const CRM_TO_FORM = { name:'nome', company:'empresa', email:'email', phone:'whatsapp', message:'mensagem' };
const crmFieldErrors = (fields = {}) =>
  Object.fromEntries(Object.entries(fields).filter(([k]) => CRM_TO_FORM[k]).map(([k, msg]) => [CRM_TO_FORM[k], msg]));

const LeadForm = () => {
  const [values, setValues]   = useState(EMPTY_LEAD);
  const [touched, setTouched] = useState({});
  const [status, setStatus]   = useState('idle');   // idle | sending | sent | error | captcha | limit | invalid
  const [crmErrors, setCrmErrors] = useState({});
  const [captcha, setCaptcha] = useState('');
  const [captchaKey, setCaptchaKey] = useState(0);
  const started = useRef(false);
  const shownAt = useRef(Date.now());
  const captchaOn = Boolean(TURNSTILE_SITE_KEY) && Boolean(CRM_CONFIG.endpoint);
  const errors = { ...crmErrors, ...validateLead(values) };

  /* A CTA elsewhere on the page sent the visitor here: note why (never over
     what they already wrote) and put the cursor in the first field. Touch
     screens skip the focus so the keyboard doesn't cover the form mid-scroll. */
  useEffect(() => {
    const onIntent = e => {
      const text = LEAD_INTENTS[e.detail] || '';
      if (text) setValues(s => s.mensagem ? s : { ...s, mensagem: text });
      if (window.matchMedia('(hover: hover)').matches) {
        const first = document.querySelector('.lead-form [name="nome"]');
        first && first.focus({ preventScroll: true });
      }
    };
    window.addEventListener('entregga:lead-intent', onIntent);
    return () => window.removeEventListener('entregga:lead-intent', onIntent);
  }, []);

  const set = k => e => {
    const v = k === 'whatsapp' ? maskPhone(e.target.value) : e.target.value;
    setValues(s => ({ ...s, [k]: v }));
    setCrmErrors(({ [k]: _edited, ...rest }) => rest);
    if (status !== 'idle' && status !== 'sending') setStatus('idle');
  };
  const blur = k => () => setTouched(t => ({ ...t, [k]: true }));
  const focus = () => {
    if (started.current) return;
    started.current = true;
    window.entregga && window.entregga.track('lead_form_start', { location: 'contato' });
  };
  const show = k => touched[k] && errors[k];

  const submit = async e => {
    e.preventDefault();
    if (status === 'sending') return;
    if (values.website) return;                       // honeypot: bots fill hidden fields
    setTouched({ nome:1, empresa:1, email:1, whatsapp:1, mensagem:1 });
    if (Object.keys(errors).length) {
      window.entregga && window.entregga.track('lead_form_invalid', { fields: Object.keys(errors).join(',') });
      const first = e.currentTarget.querySelector(`[name="${Object.keys(errors)[0]}"]`);
      first && first.focus();
      return;
    }
    if (captchaOn && !captcha) { setStatus('captcha'); return; }
    setStatus('sending');
    try {
      const saved = await sendLead(values, { elapsedMs: Date.now() - shownAt.current, ...(captchaOn ? { turnstileToken: captcha } : {}) });
      window.entregga && window.entregga.track('generate_lead', { method: 'form', channel: saved.join('+') });
      setStatus('sent');
    } catch (err) {
      window.entregga && window.entregga.track('lead_form_error', { message: String(err.message || err).slice(0, 80) });
      if (err.code === 'validation') setCrmErrors(crmFieldErrors(err.fields));
      setStatus({ captcha:'captcha', rate_limited:'limit', validation:'invalid' }[err.code] || 'error');
    } finally {
      if (captchaOn) { setCaptcha(''); setCaptchaKey(n => n + 1); }   // tokens are single-use
    }
  };

  if (status === 'sent') {
    return (
      <div className="lead-done" role="status">
        <span className="lead-done-ic"><ICheck sz={22} stroke={2.6}/></span>
        <h3>Recebemos seu contato.</h3>
        <p>Um especialista da Entregga vai falar com você em breve pelo WhatsApp ou e-mail informado.</p>
        <div className="lead-done-actions">
          <button type="button" className="btn-link" onClick={() => { setValues(EMPTY_LEAD); setTouched({}); setStatus('idle'); started.current = false; shownAt.current = Date.now(); }}>
            Enviar outro contato
          </button>
        </div>
      </div>
    );
  }

  const field = (k, label, props = {}) => (
    <label className={`lf ${show(k) ? 'has-err' : ''} ${props.wide ? 'lf-wide' : ''}`}>
      <span className="lf-label">{label}{props.optional && <em> (opcional)</em>}</span>
      {props.textarea
        ? <textarea name={k} rows={4} value={values[k]} onChange={set(k)} onBlur={blur(k)} onFocus={focus}
                    placeholder={props.placeholder} aria-invalid={!!show(k)} aria-describedby={show(k) ? `${k}-err` : undefined}/>
        : <input name={k} type={props.type || 'text'} value={values[k]} onChange={set(k)} onBlur={blur(k)} onFocus={focus}
                 placeholder={props.placeholder} autoComplete={props.autoComplete} inputMode={props.inputMode}
                 aria-invalid={!!show(k)} aria-describedby={show(k) ? `${k}-err` : undefined} required={!props.optional}/>}
      {show(k) && <span className="lf-err" id={`${k}-err`}>{errors[k]}</span>}
      {k === 'email' && !show(k) && FREE_MAIL.test(values.email.trim()) &&
        <span className="lf-hint">Se possível, use o e-mail da empresa.</span>}
    </label>
  );

  return (
    <form className="lead-form" noValidate onSubmit={submit} aria-label="Formulário de contato comercial">
      <div className="lf-grid">
        {field('nome', 'Nome', { autoComplete:'name', placeholder:'Seu nome' })}
        {field('empresa', 'Empresa', { autoComplete:'organization', placeholder:'Nome da empresa' })}
        {field('email', 'E-mail corporativo', { type:'email', autoComplete:'email', inputMode:'email', placeholder:'voce@empresa.com.br' })}
        {field('whatsapp', 'WhatsApp', { type:'tel', autoComplete:'tel-national', inputMode:'tel', placeholder:'(11) 90000-0000' })}
        {field('mensagem', 'Como podemos ajudar?', { textarea:true, wide:true, optional:true,
               placeholder:'Ex.: volume de avisos por mês, número de entregadores, como a operação funciona hoje.' })}
      </div>
      {captchaOn && <TurnstileBox key={captchaKey} onToken={setCaptcha}/>}
      {/* honeypot — hidden from people and assistive tech */}
      <input className="lf-hp" type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true"
             value={values.website} onChange={set('website')}/>
      {status === 'captcha' && (
        <div className="lf-alert" role="alert">
          Estamos confirmando que o envio é seguro. Aguarde um instante e tente de novo.
        </div>
      )}
      {status === 'limit' && (
        <div className="lf-alert" role="alert">
          Recebemos muitos envios da sua rede em pouco tempo. Aguarde alguns minutos e tente de novo.
        </div>
      )}
      {status === 'invalid' && (
        <div className="lf-alert" role="alert">
          Confira os dados informados e tente de novo.
        </div>
      )}
      {status === 'error' && (
        <div className="lf-alert" role="alert">
          Não foi possível enviar agora. Seus dados continuam aqui: tente de novo em alguns instantes.
        </div>
      )}
      <div className="lf-foot">
        <button type="submit" className="btn-brand btn-lg" disabled={status === 'sending'} aria-busy={status === 'sending'}>
          {status === 'sending' ? <><span className="spinner" aria-hidden="true"/> Enviando…</> : <>Quero falar com um especialista <IArrow sz={16}/></>}
        </button>
        <p className="lf-legal">Ao enviar, você concorda com a <a href="privacidade.html" target="_blank" rel="noopener">Política
          de privacidade</a> e autoriza a Entregga a entrar em contato sobre este pedido.</p>
      </div>
    </form>
  );
};
