// CTA + contact strip — formulaire branché sur Web3Forms
// Pour activer l'envoi réel : remplacer la valeur de WEB3FORMS_KEY par la clé
// obtenue sur https://web3forms.com avec info@creationspl.com
const WEB3FORMS_KEY = '809dc5f1-2b83-4973-bfbc-e62a590e536d';

const CTA = () => {
  const [email, setEmail] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error

  const keyConfigured = WEB3FORMS_KEY && !WEB3FORMS_KEY.startsWith('REMPLACER');

  const onSubmit = async (e) => {
    e.preventDefault();
    // anti-spam : si le champ pot-de-miel est rempli, on ignore silencieusement
    const honey = e.target.elements.botcheck;
    if (honey && honey.checked) return;

    if (!keyConfigured) {
      // clé absente : on simule pour ne pas casser le site, mais on log l'info
      console.warn('[CTA] Web3Forms non configuré — soumission simulée. Ajouter la clé dans src/cta.jsx.');
      setStatus('sent');
      return;
    }

    setStatus('sending');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_KEY,
          subject: 'Nouvelle demande de diagnostic — creationspl.com',
          from_name: 'Formulaire creationspl.com',
          email: email,
          message: message,
          page: window.location.href
        })
      });
      const data = await res.json();
      if (data.success) {
        setStatus('sent');
      } else {
        console.error('[CTA] Web3Forms error:', data);
        setStatus('error');
      }
    } catch (err) {
      console.error('[CTA] network error:', err);
      setStatus('error');
    }
  };

  return (
    <section id="contact" className="section" style={{ position: 'relative', overflow: 'hidden' }}>
      <div className="grid-bg"></div>
      <div className="wrap" style={{ position: 'relative' }}>
        <div style={{
          padding: 'clamp(40px, 6vw, 80px)',
          border: '1px solid var(--line-strong)',
          borderRadius: 20,
          background: 'linear-gradient(135deg, var(--surface), color-mix(in oklab, var(--bg-2) 90%, var(--cyan)))',
          position: 'relative',
          overflow: 'hidden'
        }}>
          <div style={{ position: 'absolute', top: -60, right: -60, width: 300, height: 300, borderRadius: '50%', background: 'radial-gradient(circle, rgba(37,212,242,0.15), transparent 70%)' }}></div>

          <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 48, alignItems: 'end' }} className="cta-grid">
            <div>
              <div className="eyebrow" style={{ marginBottom: 20 }}>Diagnostic gratuit</div>
              <h2 className="h-section">
                30 minutes. Zéro obligation.<br/>
                <span className="serif" style={{ color: 'var(--cyan)' }}>On regarde vos processus ensemble.</span>
              </h2>
              <p style={{ color: 'var(--fg-dim)', marginTop: 20, maxWidth: 520, fontSize: 16, lineHeight: 1.55 }}>
                Décrivez-nous un processus qui vous pèse. Nous revenons vers vous sous 48h avec
                un premier regard et un créneau pour en discuter. Si ce n'est pas pertinent pour
                nous, on vous le dit — et on vous oriente.
              </p>
            </div>

            <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {status !== 'sent' ? (
                <>
                  {/* pot-de-miel anti-spam : invisible pour les humains */}
                  <input type="checkbox" name="botcheck" tabIndex="-1" aria-hidden="true" style={{ position: 'absolute', left: '-9999px', opacity: 0 }} />

                  <label className="mono" style={{ marginBottom: -4 }}>courriel professionnel</label>
                  <input
                    type="email"
                    required
                    placeholder="vous@entreprise.ca"
                    className="inp"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    disabled={status === 'sending'}
                  />
                  <label className="mono" style={{ marginTop: 8, marginBottom: -4 }}>le processus qui vous coûte le plus de temps</label>
                  <textarea
                    rows="3"
                    required
                    className="inp"
                    placeholder="Ex : nous consolidons manuellement les ventes de 4 points de vente chaque lundi…"
                    style={{ resize: 'vertical', fontFamily: 'inherit' }}
                    value={message}
                    onChange={e => setMessage(e.target.value)}
                    disabled={status === 'sending'}
                  ></textarea>
                  <button
                    type="submit"
                    className="btn btn-cyan"
                    style={{ justifyContent: 'center', marginTop: 8, opacity: status === 'sending' ? 0.7 : 1 }}
                    disabled={status === 'sending'}
                  >
                    {status === 'sending' ? 'Envoi en cours…' : 'Planifier un appel'}
                    {status !== 'sending' && (
                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    )}
                  </button>
                  {status === 'error' && (
                    <div style={{ padding: '12px 16px', border: '1px solid #e5484d', borderRadius: 10, fontSize: 13.5, color: '#ff8589', lineHeight: 1.5 }}>
                      L'envoi a échoué. Réessayez, ou écrivez-nous directement à{' '}
                      <a href="mailto:info@creationspl.com" style={{ color: 'var(--cyan)', textDecoration: 'underline' }}>info@creationspl.com</a>
                    </div>
                  )}
                  <div className="mono" style={{ color: 'var(--fg-mute)', textAlign: 'center', fontSize: 10 }}>
                    Réponse sous 48h · Loi 25 · Aucune revente de données
                  </div>
                </>
              ) : (
                <div style={{ padding: 32, border: '1px dashed var(--cyan)', borderRadius: 12, textAlign: 'center' }}>
                  <div style={{ fontSize: 32, marginBottom: 8 }}>✓</div>
                  <div style={{ fontWeight: 500, marginBottom: 4 }}>Message reçu</div>
                  <div className="mono" style={{ color: 'var(--fg-dim)' }}>On revient vers vous sous 48h.</div>
                </div>
              )}
            </form>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 860px) {
          .cta-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { CTA });
