/* CTA final — "Sumate a la experiencia" + cupos limitados + lead form + footer. */
const { useState: useCtaState, useRef: useCtaRef, useEffect: useCtaEffect } = React;

function Field({ label, type = "text", name, placeholder, ...rest }) {
  const [focus, setFocus] = useCtaState(false);
  const Tag = type === "textarea" ? "textarea" : "input";
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
      <span className="bb-eyebrow" style={{ color: "var(--text-on-dark-muted)" }}>{label}</span>
      <Tag
        type={type === "textarea" ? undefined : type}
        name={name}
        placeholder={placeholder}
        rows={type === "textarea" ? 3 : undefined}
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        style={{
          font: "var(--fw-regular) var(--fs-body)/1.4 var(--font-body)",
          color: "var(--white)",
          background: "rgba(255,255,255,0.04)",
          border: `1.5px solid ${focus ? "var(--violet)" : "var(--border-on-dark)"}`,
          borderRadius: "var(--radius-md)",
          padding: "13px 16px",
          outline: "none",
          resize: "vertical",
          transition: "border-color var(--dur-fast)",
          boxShadow: focus ? "0 0 0 4px var(--focus-ring)" : "none",
        }}
        {...rest}
      />
    </label>
  );
}

/* Número de WhatsApp destino (formato internacional, sin "+" ni espacios). */
const WHATSAPP_NUMBER = "5491171647891";

/* Web3Forms: aviso por email de cada lead. Es una notificación secundaria —
   el registro de verdad va a Firestore (saveLead), que alimenta el bot y el dashboard. */
const WEB3FORMS_ACCESS_KEY = "731cc3db-ddf6-4bd0-a2db-e10720ff6ed8";

/* Redes oficiales de Billboard Argentina (footer). Glifos de marca (Simple Icons, CC0). */
const SOCIALS = [
  { name: "Instagram", href: "https://www.instagram.com/billboardar", path: "M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z" },
  { name: "TikTok", href: "https://www.tiktok.com/@billboardar", path: "M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z" },
  { name: "YouTube", href: "https://www.youtube.com/@BIllboard-AR", path: "M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" },
  { name: "X", href: "https://x.com/BillboardArg", path: "M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z" },
];

function FinalCTA() {
  const [sent, setSent] = useCtaState(false);
  const [sending, setSending] = useCtaState(false);
  const [waLink, setWaLink] = useCtaState(null);

  /* ---- Analytics: funnel del formulario --------------------------------- */
  const formCardRef = useCtaRef(null);
  const started = useCtaRef(false);
  const startTime = useCtaRef(0);
  const submittedRef = useCtaRef(false);
  const abandonRef = useCtaRef(false);
  const lastField = useCtaRef("");
  const fieldsSeen = useCtaRef({});

  // form_view — cuando el formulario entra en viewport (una vez)
  useCtaEffect(function () {
    const el = formCardRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    let done = false;
    const io = new IntersectionObserver(function (entries) {
      if (!done && entries.some(function (e) { return e.isIntersecting; })) {
        done = true; bbTrack("form_view", { form: "lead" }); io.disconnect();
      }
    }, { threshold: 0.4 });
    io.observe(el);
    return function () { io.disconnect(); };
  }, []);

  // form_abandon — se va tras empezar y sin enviar
  useCtaEffect(function () {
    const onLeave = function () {
      if (started.current && !submittedRef.current && !abandonRef.current) {
        abandonRef.current = true;
        bbTrack("form_abandon", {
          last_field: lastField.current,
          seconds_elapsed: Math.round((Date.now() - startTime.current) / 1000),
          fields_filled: Object.keys(fieldsSeen.current).length,
        });
      }
    };
    const onVis = function () { if (document.visibilityState === "hidden") onLeave(); };
    window.addEventListener("pagehide", onLeave);
    document.addEventListener("visibilitychange", onVis);
    return function () {
      window.removeEventListener("pagehide", onLeave);
      document.removeEventListener("visibilitychange", onVis);
    };
  }, []);

  const onFormFocus = function (e) {
    const name = e.target && e.target.name;
    if (!name) return;
    lastField.current = name;
    if (!started.current) {
      started.current = true;
      startTime.current = Date.now();
      bbTrack("form_start", { form: "lead" });
    }
  };
  const onFormBlur = function (e) {
    const t = e.target;
    if (!t || !t.name || t.name === "botcheck") return;
    const val = (t.value || "").trim();
    if (val && !fieldsSeen.current[t.name]) {
      fieldsSeen.current[t.name] = true;
      bbTrack("form_field_complete", { field: t.name });
    }
  };

  const submit = (e) => {
    e.preventDefault();
    if (sending) return;

    // Analytics: métricas de submit (antes de la lógica de envío)
    submittedRef.current = true;
    const secs = started.current ? Math.round((Date.now() - startTime.current) / 1000) : 0;
    const filled = Object.keys(fieldsSeen.current).length;
    bbTrack("form_submit", { seconds_to_complete: secs, fields_filled: filled });
    bbTrack("generate_lead", { seconds_to_complete: secs, fields_filled: filled });
    const data = new FormData(e.target);
    const get = (n) => (data.get(n) || "").toString().trim();

    // 1) Armar el mensaje de WhatsApp con los datos del formulario
    const lines = [
      "¡Hola! Quiero sumarme a Billboard Experience: Latin Music Week Edition.",
      "",
      "Nombre: " + get("name"),
      "Email: " + get("email"),
      get("Teléfono") && "Teléfono: " + get("Teléfono"),
      get("¿Qué estudia?") && "¿Qué estudia?: " + get("¿Qué estudia?"),
      get("Universidad") && "Universidad: " + get("Universidad"),
      get("Mensaje") && "Mensaje: " + get("Mensaje"),
    ].filter(Boolean);
    const url = "https://wa.me/" + WHATSAPP_NUMBER + "?text=" + encodeURIComponent(lines.join("\n"));
    setWaLink(url);

    // 2) Registrar el lead ANTES de abrir WhatsApp. En mobile, abrir WhatsApp
    //    cambia de app y SUSPENDE la página, cortando escrituras fire-and-forget
    //    disparadas después. Por eso disparamos primero: Firestore (alimenta el
    //    bot + dashboard) y el email con keepalive (sobrevive a que la página
    //    pase a segundo plano, así el lead nunca se pierde).
    saveLead({
      nombre: get("name"),
      email: get("email"),
      telefono: get("Teléfono"),
      estudias: get("¿Qué estudia?"),
      universidad: get("Universidad"),
      mensaje: get("Mensaje"),
    }).catch(function () { /* best-effort; el email con keepalive es el respaldo */ });

    data.append("access_key", WEB3FORMS_ACCESS_KEY);
    data.append("subject", "Nuevo lead — Billboard Experience");
    data.append("from_name", "Billboard Experience");
    fetch("https://api.web3forms.com/submit", {
      method: "POST",
      headers: { Accept: "application/json" },
      body: data,
      keepalive: true,
    }).catch(function () {});

    // 3) Recién ahora abrir WhatsApp (sigue siendo síncrono dentro del gesto del
    //    usuario, así que el navegador no lo bloquea como popup).
    window.open(url, "_blank", "noopener");
    bbTrack("whatsapp_open", { source: "form_submit" });
    setSent(true);
  };

  return (
    <section id="sumate" style={{ position: "relative", background: "var(--black)", overflow: "hidden", paddingTop: "var(--section-y)", paddingBottom: "calc(var(--section-y) / 1.4)" }}>
      <div className="bb-grad-anim" style={{ position: "absolute", inset: 0, background: "var(--grad-hero-bloom)", opacity: 0.55, mixBlendMode: "screen", pointerEvents: "none" }} />
      <div style={{ position: "relative", width: "min(100% - calc(var(--gutter) * 2), var(--maxw))", marginInline: "auto" }}>
        <div className="kit-cta" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "clamp(2rem, 6vw, 5rem)", alignItems: "center" }}>
          <Reveal>
            <div>
              <h2 className="bb-display" style={{ fontSize: "var(--fs-display-lg)", maxWidth: "12ch" }}>
                Inscribite a la <span className="bb-gradient-text">experiencia</span>
              </h2>
              <p style={{ font: "var(--text-lead)", color: "var(--text-on-dark-muted)", marginTop: "22px", maxWidth: "38ch" }}>
                Cupos limitados en esta primera edición. Completá el formulario y descubrí todo lo
                que incluye Billboard Experience: Latin Music Week Edition.
              </p>
              <p style={{ font: "var(--fw-semibold) var(--fs-body)/1.5 var(--font-body)", color: "var(--white)", marginTop: "18px", maxWidth: "38ch" }}>
                Hay experiencias que se ven. Y otras que se viven.
              </p>
              <div style={{ marginTop: "30px", display: "flex", flexDirection: "column", gap: "12px" }}>
                <a href="mailto:experience@billboard.ar" style={{ font: "var(--fw-semibold) var(--fs-body)/1 var(--font-body)", color: "var(--white)" }}>experience@billboard.ar</a>
                <a href="https://www.billboard.ar" style={{ font: "var(--fw-medium) var(--fs-body)/1 var(--font-body)", color: "var(--coral)" }}>www.billboard.ar</a>
              </div>
              <div style={{ marginTop: "28px" }}>
                <Button
                  variant="outline"
                  size="md"
                  href="assets/media/billboard-ar-experience-media-kit.pdf"
                  download="Billboard AR Experience - Media Kit.pdf"
                  icon={Icons.download}
                  iconPosition="left"
                  onClick={() => bbTrack("media_kit_download")}
                >
                  Descargar media kit (PDF)
                </Button>
              </div>
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div style={{ position: "relative", borderRadius: "var(--radius-xl)", padding: "1.5px", background: "var(--grad-accent)" }}>
              <div ref={formCardRef} style={{ borderRadius: "calc(var(--radius-xl) - 1.5px)", background: "var(--surface-card-dark)", padding: "clamp(26px, 3vw, 38px)" }}>
                {sent ? (
                  <div style={{ textAlign: "center", padding: "26px 6px" }}>
                    <div style={{ width: 52, height: 52, margin: "0 auto 18px", color: "var(--positive)" }}>{Icons.sparkles}</div>
                    <h3 className="bb-display" style={{ fontSize: "1.8rem", marginBottom: "10px" }}>¡Casi listo!</h3>
                    <p style={{ font: "var(--text-body)", color: "var(--text-on-dark-muted)", marginBottom: "22px" }}>
                      Te abrimos <strong style={{ color: "var(--white)" }}>WhatsApp</strong> con tu mensaje. Tocá <strong style={{ color: "var(--white)" }}>enviar</strong> para confirmar tu lugar.
                    </p>
                    {waLink ? (
                      <a href={waLink} target="_blank" rel="noopener noreferrer"
                         style={{ display: "inline-flex", alignItems: "center", gap: "10px", padding: "13px 24px", borderRadius: "var(--radius-pill)", background: "#25D366", color: "#06231A", font: "var(--fw-semibold) var(--fs-body)/1 var(--font-body)" }}>
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M19.05 4.91A9.82 9.82 0 0 0 12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.75.46 3.46 1.32 4.97L2 22l5.25-1.38a9.86 9.86 0 0 0 4.78 1.22h.01c5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.91-7.02zm-7.01 15.22a8.2 8.2 0 0 1-4.18-1.15l-.3-.18-3.12.82.83-3.04-.2-.31a8.18 8.18 0 0 1-1.26-4.37c0-4.54 3.7-8.23 8.24-8.23a8.2 8.2 0 0 1 8.23 8.24c0 4.54-3.7 8.23-8.23 8.23zm4.52-6.16c-.25-.12-1.47-.72-1.69-.81-.23-.08-.39-.12-.56.12-.17.25-.64.81-.79.97-.14.17-.29.19-.54.06-.25-.12-1.05-.39-1.99-1.23-.74-.66-1.23-1.47-1.38-1.72-.14-.25-.02-.38.11-.51.11-.11.25-.29.37-.43.12-.14.17-.25.25-.41.08-.17.04-.31-.02-.43-.06-.12-.56-1.34-.76-1.84-.2-.48-.4-.42-.56-.43h-.48c-.17 0-.43.06-.66.31-.23.25-.86.85-.86 2.07 0 1.22.89 2.4 1.01 2.56.12.17 1.75 2.67 4.23 3.74.59.26 1.05.41 1.41.52.59.19 1.13.16 1.56.1.48-.07 1.47-.6 1.68-1.18.21-.58.21-1.07.14-1.18-.06-.1-.22-.16-.47-.28z" /></svg>
                        Abrir WhatsApp
                      </a>
                    ) : null}
                  </div>
                ) : (
                  <form onSubmit={submit} onFocus={onFormFocus} onBlur={onFormBlur} style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                    <Field label="Nombre y apellido" name="name" placeholder="Tu nombre" required />
                    <Field label="Email" type="email" name="email" placeholder="vos@email.com" required />
                    <Field label="Teléfono" type="tel" name="Teléfono" placeholder="+54 9 11 1234 5678" />
                    <Field label="¿Qué estudias?" name="¿Qué estudia?" placeholder="Comunicación, marketing, producción…" />
                    <Field label="¿En qué universidad?" name="Universidad" placeholder="Nombre de tu universidad" />
                    <Field label="Contanos por qué querés sumarte" type="textarea" name="Mensaje" placeholder="En una línea…" />
                    {/* honeypot anti-spam (Web3Forms) — oculto a humanos */}
                    <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" style={{ display: "none" }} aria-hidden="true" />
                    <Button type="submit" variant="primary" size="lg" block icon={Icons.arrow} disabled={sending}>
                      {sending ? "Abriendo WhatsApp…" : "Quiero mi lugar"}
                    </Button>
                    <p style={{ font: "var(--fw-regular) var(--fs-caption)/1.4 var(--font-body)", color: "var(--text-on-dark-faint)", textAlign: "center", margin: 0 }}>
                      Te abrimos WhatsApp para confirmar tu lugar · Cupos limitados.
                    </p>
                  </form>
                )}
              </div>
            </div>
          </Reveal>
        </div>

        <footer style={{ marginTop: "clamp(3.5rem, 7vw, 6rem)", paddingTop: "clamp(2rem, 4vw, 3rem)", borderTop: "1px solid var(--border-on-dark)" }}>
          {/* Bloque de marcas */}
          <div className="kit-cta" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: "clamp(1rem, 3vw, 2.5rem)", alignItems: "center", padding: "clamp(20px, 3vw, 30px)", borderRadius: "var(--radius-xl)", border: "1px solid var(--border-on-dark)", background: "rgba(255,255,255,0.03)" }}>
            <div style={{ maxWidth: "46ch" }}>
              <h3 className="bb-display" style={{ fontSize: "clamp(1.4rem, 2.6vw, 2.1rem)", color: "var(--white)" }}>
                ¿Querés que tu marca sea parte de esta <span className="bb-gradient-text">experiencia</span>?
              </h3>
              <p style={{ font: "var(--text-body)", color: "var(--text-on-dark-muted)", margin: "10px 0 0" }}>
                Sumate como partner de Billboard Experience · Latin Music Week Edition.
              </p>
            </div>
            <a href="mailto:brandpartnerships@billboard.ar" style={{ display: "inline-flex", alignItems: "center", gap: "10px", padding: "13px 22px", borderRadius: "var(--radius-pill)", border: "1px solid var(--border-on-dark)", background: "rgba(255,255,255,0.05)", font: "var(--fw-semibold) var(--fs-body)/1 var(--font-body)", color: "var(--white)", whiteSpace: "nowrap" }}>
              brandpartnerships@billboard.ar
            </a>
          </div>

          {/* Logo + web + redes */}
          <div style={{ marginTop: "clamp(2rem, 4vw, 3rem)", display: "flex", flexWrap: "wrap", gap: "20px", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", flexDirection: "column", gap: "10px", alignItems: "flex-start" }}>
              <img src="assets/logos/billboard-ar-wordmark-white.png" alt="billboard AR" style={{ height: "22px", width: "auto", display: "block" }} />
              <a href="https://www.billboard.ar" target="_blank" rel="noopener noreferrer" style={{ font: "var(--fw-medium) var(--fs-caption)/1 var(--font-body)", color: "var(--coral)" }}>billboard.ar</a>
            </div>
            <div style={{ display: "flex", gap: "12px", alignItems: "center" }}>
              {SOCIALS.map((soc) => (
                <a key={soc.name} href={soc.href} target="_blank" rel="noopener noreferrer" aria-label={"Billboard AR en " + soc.name} onClick={() => bbTrack("social_click", { network: soc.name })}
                   style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 40, height: 40, borderRadius: "999px", border: "1px solid var(--border-on-dark)", background: "rgba(255,255,255,0.03)", color: "var(--text-on-dark-muted)" }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style={{ display: "block" }}><path d={soc.path} /></svg>
                </a>
              ))}
            </div>
          </div>

          {/* Agencia de viajes */}
          <div style={{ marginTop: "clamp(1.75rem, 3.5vw, 2.5rem)", paddingTop: "22px", borderTop: "1px solid var(--border-on-dark)", display: "flex", flexWrap: "wrap", alignItems: "center", gap: "18px" }}>
            <span className="bb-eyebrow" style={{ color: "var(--text-on-dark-faint)", letterSpacing: "0.16em" }}>Partner oficial</span>
            <img src="assets/logos/travel-services-white.png" alt="Travel Services" style={{ height: "clamp(22px, 3vw, 28px)", width: "auto", display: "block" }} />
          </div>

          <p style={{ marginTop: "clamp(1.25rem, 2.5vw, 1.75rem)", paddingBottom: "8px", font: "var(--fw-regular) var(--fs-caption)/1.4 var(--font-body)", color: "var(--text-on-dark-faint)" }}>
            © Billboard Argentina · Billboard Experience · Latin Music Week Edition
          </p>
        </footer>
      </div>
    </section>
  );
}

window.FinalCTA = FinalCTA;
