/* global React, GamacaPrimitives */
const { useState } = React;

function encode(data) {
  return Object.keys(data)
    .map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(data[k]))
    .join("&");
}

function ContactSection() {
  const [status, setStatus] = useState("idle"); // idle | submitting | success | error
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    message: "",
    "bot-field": "",
  });

  const handleChange = (e) =>
    setForm({ ...form, [e.target.name]: e.target.value });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("submitting");
    try {
      const res = await fetch("/", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: encode({ "form-name": "contact", ...form }),
      });
      if (!res.ok) throw new Error("Network");
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  };

  const inputCls =
    "w-full px-4 py-3 bg-white border border-stone-200 rounded-md text-stone-900 placeholder-stone-400 focus:outline-none focus:border-stone-900 focus:ring-1 focus:ring-stone-900 transition";
  const labelCls =
    "block text-xs uppercase tracking-widest text-stone-500 mb-2 font-medium";

  return (
    <section id="contact" className="py-24 bg-white">
      <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h2 className="text-4xl font-bold text-stone-900 mb-6">
            Prêt à engager le futur ?
          </h2>
          <p className="text-lg text-stone-500">
            Discutons de votre "Where to Play" et testons le "How to Win".
            <br />
            Premier échange sans engagement.
          </p>
        </div>

        {status === "success" ? (
          <div className="bg-stone-50 border border-stone-200 rounded-lg p-12 text-center">
            <div className="text-2xl font-bold text-stone-900 mb-3">
              Message bien reçu.
            </div>
            <p className="text-stone-500">
              Nous revenons vers vous sous 24h ouvrées.
            </p>
          </div>
        ) : (
          <form
            name="contact"
            method="POST"
            data-netlify="true"
            data-netlify-honeypot="bot-field"
            onSubmit={handleSubmit}
            className="space-y-6"
          >
            <input type="hidden" name="form-name" value="contact" />
            {/* Honeypot — hidden from real users */}
            <p className="hidden">
              <label>
                Don't fill this out:{" "}
                <input
                  name="bot-field"
                  value={form["bot-field"]}
                  onChange={handleChange}
                />
              </label>
            </p>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div>
                <label className={labelCls} htmlFor="name">
                  Nom
                </label>
                <input
                  id="name"
                  type="text"
                  name="name"
                  required
                  value={form.name}
                  onChange={handleChange}
                  className={inputCls}
                  placeholder="Votre nom"
                />
              </div>
              <div>
                <label className={labelCls} htmlFor="email">
                  Email
                </label>
                <input
                  id="email"
                  type="email"
                  name="email"
                  required
                  value={form.email}
                  onChange={handleChange}
                  className={inputCls}
                  placeholder="vous@entreprise.fr"
                />
              </div>
            </div>

            <div>
              <label className={labelCls} htmlFor="phone">
                Téléphone <span className="text-stone-300 normal-case tracking-normal">(optionnel)</span>
              </label>
              <input
                id="phone"
                type="tel"
                name="phone"
                value={form.phone}
                onChange={handleChange}
                className={inputCls}
                placeholder="06 12 34 56 78"
              />
            </div>

            <div>
              <label className={labelCls} htmlFor="message">
                Message
              </label>
              <textarea
                id="message"
                name="message"
                required
                rows={5}
                value={form.message}
                onChange={handleChange}
                className={inputCls}
                placeholder="Parlez-nous de votre projet, de votre contexte, de vos enjeux IA…"
              />
            </div>

            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pt-2">
              <p className="text-xs text-stone-400">
                Vos données restent confidentielles. <a href="/privacy.html" className="underline hover:text-stone-600">Politique de confidentialité</a>.
              </p>
              <button
                type="submit"
                disabled={status === "submitting"}
                className="px-8 py-3 bg-stone-900 text-white font-medium rounded-md hover:bg-stone-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {status === "submitting" ? "Envoi…" : "Envoyer"}
              </button>
            </div>

            {status === "error" && (
              <p className="text-sm text-red-600 text-center">
                Une erreur est survenue. Merci de réessayer dans un instant.
              </p>
            )}
          </form>
        )}

        <div className="mt-16 border-t border-stone-100 pt-8 text-center">
          <p className="text-xs text-stone-400 uppercase tracking-widest mb-2">
            GAMACA.AI © 2025
          </p>
          <p className="text-xs text-stone-300">
            Basé en France • Intervention Monde
          </p>
        </div>
      </div>
    </section>
  );
}

window.GamacaContact = ContactSection;
