// Contacto — form en .ct (dark) que postea a /api/taller/leads (Supabase + Telegram).
// LEADS_ENDPOINT: ajustar al deploy real del colo-dashboard.
const LEADS_ENDPOINT = "https://colo-dashboard.vercel.app/api/taller/leads";

function Contacto() {
  const [lang] = window.useLang();
  const isEn = lang === "en";
  const [form, setForm] = React.useState({ nombre: "", email: "", whatsapp: "", mensaje: "" });
  const [status, setStatus] = React.useState("idle"); // idle | sending | ok | err

  const onChange = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.nombre || !form.email || !form.mensaje || status === "sending") return;
    setStatus("sending");
    try {
      const res = await fetch(LEADS_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nombre: form.nombre.trim(),
          contacto_email: form.email.trim(),
          contacto_whatsapp: form.whatsapp.trim() || null,
          fuente: "organico",
          estado: "nuevo",
          notas_call: {
            mensaje: form.mensaje.trim(),
            origen: "form-landing-celtis",
            idioma: lang,
            recibido_en: new Date().toISOString(),
          },
        }),
      });
      if (!res.ok) throw new Error("bad status");
      setStatus("ok");
      setForm({ nombre: "", email: "", whatsapp: "", mensaje: "" });
    } catch {
      setStatus("err");
    }
  };

  const labels = isEn
    ? {
        eyebrow: "CONTACT",
        title: "Let's talk.",
        name: "NAME",
        namePh: "Your name",
        email: "EMAIL",
        emailPh: "you@company.com",
        wa: "NUMBER",
        waOpt: "",
        msg: "WHAT YOU NEED",
        msgPh: "Tell us briefly what you'd like to solve.",
        send: "Send message",
        sending: "Sending…",
        sent: "Sent",
        ok: "Got it. I'll write you back in under 24 hours.",
        err: "Something failed. Try WhatsApp or write to celtis.ai@gmail.com.",
      }
    : {
        eyebrow: "CONTACTO",
        title: "Hablemos.",
        name: "NOMBRE",
        namePh: "Tu nombre",
        email: "EMAIL",
        emailPh: "vos@empresa.com",
        wa: "NÚMERO",
        waOpt: "",
        msg: "QUÉ NECESITÁS",
        msgPh: "Contame brevemente qué problema querés resolver.",
        send: "Enviar mensaje",
        sending: "Enviando…",
        sent: "Enviado",
        ok: "Recibido. Te escribo en menos de 24 horas.",
        err: "Algo falló. Probá WhatsApp o escribime a celtis.ai@gmail.com.",
      };

  return (
    <section className="ct" id="contacto">
      <div className="container ct-grid">
        <div className="ct-head">
          <Reveal className="rv-up">
            <span className="eyebrow on-dark">{labels.eyebrow}</span>
          </Reveal>
          <Reveal as="h2" className="section-title on-dark rv-up" delay={120}>
            {labels.title}
          </Reveal>
        </div>

        <div className="ct-body">
          <Reveal as="form" className="ct-form rv-up" delay={180} onSubmit={onSubmit} noValidate>
            <div className="ct-row two">
              <div className="ct-field">
                <label htmlFor="ct-nombre">{labels.name}</label>
                <input
                  id="ct-nombre"
                  type="text"
                  required
                  autoComplete="name"
                  value={form.nombre}
                  onChange={onChange("nombre")}
                  placeholder={labels.namePh}
                />
              </div>
              <div className="ct-field">
                <label htmlFor="ct-email">{labels.email}</label>
                <input
                  id="ct-email"
                  type="email"
                  required
                  autoComplete="email"
                  value={form.email}
                  onChange={onChange("email")}
                  placeholder={labels.emailPh}
                />
              </div>
            </div>

            <div className="ct-field">
              <label htmlFor="ct-whatsapp">{labels.wa} <span className="ct-opt">{labels.waOpt}</span></label>
              <input
                id="ct-whatsapp"
                type="tel"
                autoComplete="tel"
                value={form.whatsapp}
                onChange={onChange("whatsapp")}
                placeholder="+54 9 11 ..."
              />
            </div>

            <div className="ct-field">
              <label htmlFor="ct-mensaje">{labels.msg}</label>
              <textarea
                id="ct-mensaje"
                rows={4}
                required
                value={form.mensaje}
                onChange={onChange("mensaje")}
                placeholder={labels.msgPh}
              />
            </div>

            <div className="ct-submit">
              <button type="submit" className="btn primary big" disabled={status === "sending"}>
                {status === "sending" ? labels.sending : status === "ok" ? labels.sent : labels.send}
                <span className="btn-arrow">{status === "ok" ? "✓" : "→"}</span>
              </button>
              {status === "ok" && (
                <p className="ct-msg ok">{labels.ok}</p>
              )}
              {status === "err" && (
                <p className="ct-msg err">{labels.err}</p>
              )}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}
window.Contacto = Contacto;
