// =====================================================================
// V5 Contact — section shows title + tagline + button.
// Clicking the button opens the contact form as a modal popup.
// Submits to our own backend (Firebase Function `crearLead`, exposed at
// /api/crear-lead via firebase.json rewrites), which forwards the lead
// to monday.com via Resend.
// The backend URL is read from window.__INTELIK_API__ (set in <head>).
// Empty string = same-origin (relative URL), which is the production setup.
// =====================================================================

const API_BASE = (typeof window !== "undefined" && window.__INTELIK_API__ != null)
  ? window.__INTELIK_API__
  : "";
const LEAD_ENDPOINT = API_BASE.replace(/\/$/, "") + "/api/crear-lead";

window.V5Contact = function V5Contact() {
  const { t } = window.useV4();
  const c = (t.contact || {});
  const { useState, useEffect, useRef, useCallback } = React;

  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({
    nombreCompleto: "", email: "", telefono: "",
    empresa: "", mensaje: "",
    // Honeypot — bots fill it, humans don't see it.
    website: "",
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [apiError, setApiError] = useState("");

  const dialogRef = useRef(null);
  const firstFieldRef = useRef(null);
  const openerRef = useRef(null);

  const closeModal = useCallback(() => {
    setOpen(false);
    // Return focus to the opener
    setTimeout(() => openerRef.current?.focus(), 0);
  }, []);

  // Open: lock scroll + focus first field + listen to Esc
  useEffect(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const t = setTimeout(() => firstFieldRef.current?.focus(), 60);
    const onKey = (e) => { if (e.key === "Escape") closeModal(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
      clearTimeout(t);
    };
  }, [open, closeModal]);

  // Reset form when closing (only if it wasn't a successful submit — let the
  // user see the success state if they reopen during the same session, fresh).
  useEffect(() => {
    if (open) {
      setApiError("");
      setErrors({});
    }
  }, [open]);

  const set = (k) => (e) => {
    setForm((f) => ({ ...f, [k]: e.target.value }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: "" }));
  };

  // Parse a full-name string into first / last. The first token is the first
  // name; everything after is the last name (handles compound surnames like
  // "García López" or "de la Vega").
  const splitName = (full) => {
    const parts = full.trim().split(/\s+/);
    return {
      nombre: parts[0] || "",
      apellido: parts.slice(1).join(" "),
    };
  };

  const validate = () => {
    const e = {};
    const { nombre, apellido } = splitName(form.nombreCompleto);
    if (!form.nombreCompleto.trim()) {
      e.nombreCompleto = c.err_required || "Campo obligatorio";
    } else if (!nombre || nombre.length < 2 || !apellido || apellido.length < 2) {
      e.nombreCompleto = c.err_fullname || "Escribe tu nombre y apellido";
    }
    if (!form.email.trim())    e.email    = c.err_required || "Campo obligatorio";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      e.email = c.err_email || "Correo no válido";
    if (!form.telefono.trim()) e.telefono = c.err_required || "Campo obligatorio";
    if (!form.empresa.trim())  e.empresa  = c.err_required || "Campo obligatorio";
    if (!form.mensaje.trim())  e.mensaje  = c.err_required || "Campo obligatorio";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    setApiError("");
    if (!validate()) return;

    // Silent bot block — pretend success but don't send.
    if (form.website) { setSubmitted(true); return; }

    setSubmitting(true);
    try {
      const payload = {
        nombreCompleto: form.nombreCompleto.trim(),
        correo:        form.email.trim(),
        telefono:      form.telefono.trim(),
        empresa:       form.empresa.trim(),
        descripcion:   (form.mensaje || "").trim(),
        // Honeypot mirrored — backend also ignores when present.
        website:       form.website,
        // Optional context for the lead record.
        idioma:        (window.location.pathname || "").includes("/en") ? "EN" : "ES",
        origen_url:    window.location.href,
      };

      const res = await fetch(LEAD_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      let data = {};
      try { data = await res.json(); } catch (_) { /* ignore */ }

      if (!res.ok || !data.success) {
        throw new Error(data.error || ("HTTP " + res.status));
      }
      setSubmitted(true);
    } catch (err) {
      setApiError(err.message || String(err));
    } finally {
      setSubmitting(false);
    }
  };

  // ---------- Reusable bits ----------
  const labelEl = (label, required) => (
    <span className="v5-contact__label">
      {label}{required && <span className="v5-contact__req"> *</span>}
    </span>
  );

  const inputCls = (key) =>
    "v5-contact__input" + (errors[key] ? " is-invalid" : "");

  const onBackdrop = (ev) => {
    if (ev.target === ev.currentTarget) closeModal();
  };

  return (
    <React.Fragment>
      {/* ---------- Trigger section ---------- */}
      <section className="v5-contact" id="contacto">
        <div className="v5-contact__accent-bar" aria-hidden="true"></div>
        <div className="v5-contact__deco v5-contact__deco--tr" aria-hidden="true"></div>
        <div className="v5-contact__deco v5-contact__deco--br" aria-hidden="true"></div>

        <div className="v5-contact__inner v5-contact__inner--cta" data-reveal>
          <header className="v5-contact__head">
            <h2 className="v5-contact__title">{c.title || "Contáctanos"}</h2>
            <p className="v5-contact__sub">
              {c.sub || "Déjanos tus detalles y un experto se comunicará contigo"}
            </p>
          </header>
          <button
            ref={openerRef}
            type="button"
            className="v5-contact__btn v5-contact__btn--open"
            onClick={() => setOpen(true)}
          >
            {c.open_cta || c.send || "Contáctanos"}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M3.5 12h17M14 5l7 7-7 7" stroke="currentColor" strokeWidth="2"
                    strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </section>

      {/* ---------- Modal ---------- */}
      {open && (
        <div className="v5-contact-modal" role="dialog" aria-modal="true"
             aria-labelledby="v5-contact-modal-title"
             onMouseDown={onBackdrop}>
          <div className="v5-contact-modal__panel" ref={dialogRef} onMouseDown={(e) => e.stopPropagation()}>
            <button
              type="button"
              className="v5-contact-modal__close"
              onClick={closeModal}
              aria-label={c.close || "Cerrar"}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2"
                      strokeLinecap="round"/>
              </svg>
            </button>

            {submitted ? (
              <div className="v5-contact__success">
                <div className="v5-contact__success-icon" aria-hidden="true">
                  <svg viewBox="0 0 24 24" width="28" height="28" fill="none">
                    <path d="M5 12.5l4.5 4.5L19 7.5" stroke="#00C8C8" strokeWidth="2.4"
                          strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
                <h3 id="v5-contact-modal-title" className="v5-contact__title">
                  {c.ok_title || "¡Mensaje enviado!"}
                </h3>
                <p className="v5-contact__sub">{c.ok_sub || "Tu información ya está en nuestro equipo. Te contactaremos pronto."}</p>
                <button type="button"
                        className="v5-contact__btn v5-contact-modal__done"
                        onClick={closeModal}>
                  {c.close || "Cerrar"}
                </button>
              </div>
            ) : (
              <React.Fragment>
                <header className="v5-contact__head v5-contact-modal__head">
                  <h3 id="v5-contact-modal-title" className="v5-contact__title">
                    {c.modal_title || c.title || "Contáctanos"}
                  </h3>
                  <p className="v5-contact__sub">
                    {c.sub || "Déjanos tus detalles y un experto se comunicará contigo"}
                  </p>
                </header>

                <form className="v5-contact__form" onSubmit={onSubmit} noValidate>
                  <div className="v5-contact__grid">
                    <div className="v5-contact__field v5-contact__field--full">
                      {labelEl(c.f_fullname || "Nombre completo y Apellido", true)}
                      <input ref={firstFieldRef} className={inputCls("nombreCompleto")} type="text"
                             autoComplete="name"
                             placeholder={c.ph_fullname || "Ej. María García López"}
                             value={form.nombreCompleto} onChange={set("nombreCompleto")} />
                      {errors.nombreCompleto && <span className="v5-contact__err">{errors.nombreCompleto}</span>}
                    </div>
                    <div className="v5-contact__field">
                      {labelEl(c.f_email || "Correo electrónico", true)}
                      <input className={inputCls("email")} type="email" autoComplete="email"
                             placeholder="nombre@empresa.com"
                             value={form.email} onChange={set("email")} />
                      {errors.email && <span className="v5-contact__err">{errors.email}</span>}
                    </div>
                    <div className="v5-contact__field">
                      {labelEl(c.f_phone || "Teléfono", true)}
                      <input className={inputCls("telefono")} type="tel" autoComplete="tel"
                             placeholder="+52 55 0000 0000"
                             value={form.telefono} onChange={set("telefono")} />
                      {errors.telefono && <span className="v5-contact__err">{errors.telefono}</span>}
                    </div>

                    <div className="v5-contact__field v5-contact__field--full">
                      {labelEl(c.f_company || "Empresa", true)}
                      <input className={inputCls("empresa")} type="text" autoComplete="organization"
                             placeholder={c.ph_company || "Nombre de tu empresa"}
                             value={form.empresa} onChange={set("empresa")} />
                      {errors.empresa && <span className="v5-contact__err">{errors.empresa}</span>}
                    </div>

                    <div className="v5-contact__field v5-contact__field--full">
                      {labelEl(c.f_msg || "¿En qué te podemos ayudar?", true)}
                      <textarea className={`${inputCls("mensaje")} v5-contact__textarea`} rows="4"
                                placeholder={c.ph_msg || "Cuéntanos un poco sobre tu proyecto…"}
                                value={form.mensaje} onChange={set("mensaje")} />
                      {errors.mensaje && <span className="v5-contact__err">{errors.mensaje}</span>}
                    </div>

                    {/* Honeypot — hidden from real users, attractive to bots. */}
                    <div aria-hidden="true"
                         style={{ position: "absolute", left: "-9999px", top: "auto",
                                  width: "1px", height: "1px", overflow: "hidden" }}>
                      <label>
                        Website (no rellenar)
                        <input type="text" name="website" tabIndex="-1" autoComplete="off"
                               value={form.website} onChange={set("website")} />
                      </label>
                    </div>
                  </div>

                  <div className="v5-contact__foot">
                    <p className="v5-contact__privacy">
                      {c.privacy_pre || "Al enviar aceptas nuestra"}{" "}
                      <a href="privacy.html" className="v5-contact__privacy-link">{c.privacy_link || "política de privacidad"}</a>.
                    </p>
                    <button type="submit" className="v5-contact__btn" disabled={submitting}>
                      {submitting ? (
                        <React.Fragment>
                          <span className="v5-contact__spinner" aria-hidden="true"></span>
                          {c.sending || "Enviando…"}
                        </React.Fragment>
                      ) : (
                        <React.Fragment>
                          {c.send || "Enviar mensaje"}
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                            <path d="M3.5 12h17M14 5l7 7-7 7" stroke="currentColor" strokeWidth="2"
                                  strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                        </React.Fragment>
                      )}
                    </button>
                  </div>

                  {apiError && (
                    <p className="v5-contact__api-error" aria-live="polite">
                      {c.api_err || "No se pudo enviar. Intenta nuevamente en unos momentos."}
                    </p>
                  )}
                </form>
              </React.Fragment>
            )}
          </div>
        </div>
      )}
    </React.Fragment>
  );
};
