// Lead magnet (download Canvas → ActiveCampaign) + Footer

function LeadMagnet() {
  const [state, setState] = useState({ name: "", email: "", consent: false, newsletter: false });
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");

  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    if (!state.name.trim()) return setError("Pon tu nombre.");
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(state.email)) return setError("Email no válido.");
    if (!state.consent) return setError("Acepta recibir el canvas para continuar.");

    setBusy(true);
    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: state.name.trim(),
          email: state.email.trim(),
          newsletter: state.newsletter,
        }),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        setSubmitted(true);
      } else {
        setError(data.error || "Ha ocurrido un error. Inténtalo de nuevo.");
      }
    } catch (err) {
      setError("Error de conexión. Inténtalo de nuevo.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <section
      id="descargar"
      style={{
        padding: "120px 0",
        background: "var(--cream-3)",
        position: "relative",
        overflow: "hidden",
      }}
    >
      <div className="container">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1.05fr) minmax(0, 1fr)",
            gap: 64,
            alignItems: "center",
          }}
          className="lead-grid"
        >
          <Reveal stagger>
            <Mono>Lead magnet · Gratis</Mono>
            <h2
              className="display"
              style={{
                fontSize: "clamp(40px, 5.6vw, 76px)",
                marginTop: 18,
                marginBottom: 28,
              }}
            >
              Descárgate el<br />
              Media Planning Canvas<br />
              <em>en PDF.</em>
            </h2>
            <p style={{ fontSize: 18, color: "var(--ink-soft)", marginBottom: 28, maxWidth: 480 }}>
              La plantilla original del método, lista para imprimir. La misma que han usado
              +10.000 profesionales para estructurar sus planes de marketing.
            </p>

            <ul style={{ listStyle: "none", padding: 0, margin: "0 0 36px", display: "flex", flexDirection: "column", gap: 10 }}>
              {[
                "PDF imprimible · A3 y A4",
                "Las 5 fases del método en una sola página",
                "Preguntas guía rellenas como ejemplo",
              ].map((t, i) => (
                <li key={i} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 15 }}>
                  <span
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: 4,
                      background: "var(--accent)",
                      color: "white",
                      display: "grid",
                      placeItems: "center",
                      fontSize: 11,
                    }}
                  >
                    ✓
                  </span>
                  {t}
                </li>
              ))}
            </ul>

            {!submitted ? (
              <form onSubmit={submit} style={{ maxWidth: 480 }} noValidate>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  <div>
                    <label style={leadLabel}>Nombre</label>
                    <input
                      type="text"
                      value={state.name}
                      onChange={(e) => setState({ ...state, name: e.target.value })}
                      placeholder="Tu nombre"
                      style={leadInput}
                    />
                  </div>
                  <div>
                    <label style={leadLabel}>Email</label>
                    <input
                      type="email"
                      value={state.email}
                      onChange={(e) => setState({ ...state, email: e.target.value })}
                      placeholder="tu@email.com"
                      style={leadInput}
                    />
                  </div>
                  <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 13, color: "var(--ink-soft)", cursor: "pointer", marginTop: 4 }}>
                    <input
                      type="checkbox"
                      checked={state.consent}
                      onChange={(e) => setState({ ...state, consent: e.target.checked })}
                      style={{ marginTop: 3, accentColor: "var(--accent)" }}
                    />
                    <span>
                      Acepto los <a href="privacidad.html" style={{color:"var(--accent-soft)",textDecoration:"underline"}}>términos de privacidad</a> y recibir el canvas.
                    </span>
                  </label>

                  <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 13, color: "var(--ink-soft)", cursor: "pointer", marginTop: 8 }}>
                    <input
                      type="checkbox"
                      checked={state.newsletter}
                      onChange={(e) => setState({ ...state, newsletter: e.target.checked })}
                      style={{ marginTop: 3, accentColor: "var(--accent)" }}
                    />
                    <span>
                      Quiero recibir novedades de la herramienta y tips de marketing. Puedo darme de baja en cualquier momento.
                    </span>
                  </label>

                  {error && (
                    <div
                      style={{
                        fontSize: 13,
                        color: "var(--accent)",
                        background: "rgba(221,90,51,0.08)",
                        padding: "8px 12px",
                        borderRadius: 6,
                      }}
                    >
                      {error}
                    </div>
                  )}

                  <button
                    type="submit"
                    className="btn btn-ink"
                    style={{ marginTop: 8, justifyContent: "center", opacity: busy ? 0.65 : 1 }}
                    disabled={busy}
                  >
                    {busy ? "Enviando..." : "Descargar Canvas gratis →"}
                  </button>

                  <p style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 4 }}>
                    Te enviamos el PDF al email. Datos almacenados en ActiveCampaign · RGPD.
                    {" "}Si has marcado la newsletter, recibirás novedades y tips de marketing.
                  </p>
                </div>
              </form>
            ) : (
              <SuccessState name={state.name} />
            )}
          </Reveal>

          <Reveal>
            <CanvasPreview />
          </Reveal>
        </div>

        <style>{`
          @media (max-width: 960px) {
            .lead-grid { grid-template-columns: 1fr !important; gap: 48px !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

const leadLabel = {
  display: "block",
  fontFamily: "var(--font-mono)",
  fontSize: 10,
  letterSpacing: "0.14em",
  textTransform: "uppercase",
  color: "var(--ink-muted)",
  marginBottom: 6,
};
const leadInput = {
  width: "100%",
  padding: "13px 16px",
  borderRadius: 10,
  border: "1px solid var(--line-strong)",
  background: "white",
  fontSize: 15,
  fontFamily: "var(--font-body)",
  color: "var(--ink)",
  outline: "none",
  transition: "border-color 0.2s ease",
};

function SuccessState({ name }) {
  return (
    <div
      style={{
        padding: "32px 28px",
        borderRadius: 14,
        background: "var(--ink)",
        color: "var(--cream)",
        maxWidth: 480,
        display: "flex",
        flexDirection: "column",
        gap: 14,
      }}
    >
      <div
        style={{
          width: 44,
          height: 44,
          borderRadius: 999,
          background: "var(--accent)",
          display: "grid",
          placeItems: "center",
          color: "white",
          fontSize: 22,
        }}
      >
        ✓
      </div>
      <h3 className="display" style={{ fontSize: 26, color: "var(--cream)" }}>
        ¡Listo, {name.split(" ")[0]}!
      </h3>
      <p style={{ fontSize: 15, color: "rgba(239,232,218,0.78)", lineHeight: 1.55 }}>
        Acabamos de enviarte el Media Planning Canvas al email. Revisa tu bandeja
        (y la de spam, por si acaso).
      </p>
      <p style={{ fontSize: 14, color: "rgba(239,232,218,0.62)" }}>
        Mientras llega, ¿quieres ver el método en acción?{" "}
        <a href="#precios" style={{ color: "var(--accent-soft)", textDecoration: "underline" }}>
          Empieza tu primer plan gratis.
        </a>
      </p>
    </div>
  );
}

function CanvasPreview() {
  // Stack two canvas previews — empty (faded) behind, filled in front
  return (
    <div style={{ position: "relative", aspectRatio: "1.4 / 1" }}>
      <div
        style={{
          position: "absolute",
          top: 0,
          right: 0,
          width: "92%",
          transform: "rotate(2.5deg)",
          borderRadius: 8,
          overflow: "hidden",
          border: "1px solid var(--line)",
          boxShadow: "0 20px 40px -20px rgba(14,34,54,0.25)",
        }}
      >
        <img src="assets/canvas-empty.jpg" alt="Canvas vacío" style={{ width: "100%", display: "block", opacity: 0.6 }} />
      </div>
      <div
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          width: "92%",
          transform: "rotate(-1.5deg)",
          borderRadius: 8,
          overflow: "hidden",
          border: "1px solid var(--line)",
          boxShadow: "0 30px 60px -25px rgba(14,34,54,0.4)",
        }}
      >
        <img src="assets/canvas-filled.jpg" alt="Canvas relleno (ejemplo)" style={{ width: "100%", display: "block" }} />
        <div
          style={{
            position: "absolute",
            top: 12,
            right: 12,
            background: "var(--accent)",
            color: "white",
            fontFamily: "var(--font-mono)",
            fontSize: 10,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            padding: "5px 10px",
            borderRadius: 4,
          }}
        >
          Ejemplo relleno
        </div>
      </div>
    </div>
  );
}

// Final CTA strip + footer
function FinalCTA() {
  return (
    <section style={{ padding: "120px 0", background: "var(--ink)", color: "var(--cream)" }}>
      <div className="container">
        <Reveal stagger>
          <div style={{ textAlign: "center", maxWidth: 980, margin: "0 auto" }}>
            <Mono style={{ color: "var(--accent-soft)" }}>Tu primer plan, hoy</Mono>
            <h2
              className="display"
              style={{
                fontSize: "clamp(48px, 7vw, 100px)",
                color: "var(--cream)",
                marginTop: 18,
                marginBottom: 28,
              }}
            >
              No necesitas un máster.<br />
              Necesitas <em style={{ color: "var(--accent-soft)" }}>el método</em>.
            </h2>
            <p style={{ fontSize: 18, color: "rgba(239,232,218,0.7)", marginBottom: 36, maxWidth: 600, margin: "0 auto 36px" }}>
              Empieza gratis. Sin tarjeta. Con 3 análisis IA y todo el método incluido.
            </p>
            <div style={{ display: "flex", justifyContent: "center", gap: 12, flexWrap: "wrap" }}>
              <a href="#precios" className="btn btn-accent">Empezar gratis →</a>
              <a href="#descargar" className="btn btn-ghost" style={{ color: "var(--cream)", borderColor: "rgba(239,232,218,0.3)" }}>
                Descargar Canvas en PDF
              </a>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer style={{ padding: "80px 0 32px", background: "var(--ink)", color: "var(--cream)" }}>
      <div className="container">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1.2fr)",
            gap: 56,
            paddingBottom: 56,
            borderBottom: "1px solid rgba(239,232,218,0.18)",
          }}
          className="footer-grid"
        >
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
              <Logo color="var(--cream)" />
              <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
                <span style={{ fontWeight: 600, fontSize: 16 }}>
                  Media Planning <span style={{ fontWeight: 400 }}>Canvas</span>
                </span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", color: "rgba(239,232,218,0.6)" }}>
                  THE MARKETING PLAN GENERATOR
                </span>
              </span>
            </div>
            <p style={{ fontSize: 14, color: "rgba(239,232,218,0.65)", maxWidth: 360, lineHeight: 1.55 }}>
              El generador de planes de marketing con IA basado en el método
              Media Planning Canvas, creado por Jaime Fernández de la Puente.
            </p>
          </div>

          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent-soft)", marginBottom: 18 }}>
              Producto
            </div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                ["Método", "#metodo"],
                ["Tour por la app", "#tour"],
                ["Precios", "#precios"],
                ["Descargar canvas", "#descargar"],
                ["FAQ", "#faq"],
              ].map(([t, h], i) => (
                <li key={i}>
                  <a href={h} style={{ color: "var(--cream)", fontSize: 14, opacity: 0.85 }}>{t}</a>
                </li>
              ))}
            </ul>
          </div>

          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent-soft)", marginBottom: 18 }}>
              Ecosistema PeopleXBrand
            </div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              {ECOSYSTEM.map((e, i) => (
                <li key={i}>
                  <a
                    href={e.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: 2,
                    }}
                  >
                    <span style={{ fontSize: 14, color: "var(--cream)" }}>
                      {e.name} <span style={{ fontSize: 10, opacity: 0.5 }}>↗</span>
                    </span>
                    <span style={{ fontSize: 12, color: "rgba(239,232,218,0.5)" }}>{e.desc}</span>
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </div>

        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginTop: 32,
            flexWrap: "wrap",
            gap: 16,
          }}
        >
          <span style={{ fontSize: 12, color: "rgba(239,232,218,0.5)", fontFamily: "var(--font-mono)", letterSpacing: "0.08em" }}>
            © 2025 MEDIA PLANNING CANVAS · CREATED BY JAIME FERNÁNDEZ DE LA PUENTE
          </span>
          <div style={{ display: "flex", gap: 18 }}>
            {[["Aviso Legal","aviso-legal.html"],["Privacidad","privacidad.html"],["Cookies","#cookies"]].map(([t,url], i) => (
              <a key={i} href={url} style={{ fontSize: 12, color: "rgba(239,232,218,0.65)" }}>{t}</a>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 880px) {
          .footer-grid { grid-template-columns: 1fr !important; gap: 40px !important; }
        }
      `}</style>
    </footer>
  );
}

Object.assign(window, { LeadMagnet, FinalCTA, Footer });
