// Popup.jsx — HorizonPopup (by link click) + ExitPopup (exit intent)

Object.assign(window, { HorizonPopup, ExitPopup });

/* ── Shared submit hook ── */
function usePopupForm() {
  const [form, setForm]         = React.useState({ nombre: "", apellido: "", email: "", telefono: "" });
  const [errors, setErrors]     = React.useState({});
  const [loading, setLoading]   = React.useState(false);
  const [apiError, setApiError] = React.useState("");

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

  const validate = () => {
    const errs = {};
    if (form.nombre.trim().length < 2)   errs.nombre   = "Nombre inválido";
    if (form.apellido.trim().length < 2) errs.apellido = "Apellido inválido";
    if (!form.email.includes("@") || !form.email.includes(".")) errs.email = "Email inválido";
    if (form.telefono.replace(/\D/g, "").length !== 9) errs.telefono = "9 dígitos requeridos";
    return errs;
  };

  const submit = async () => {
    const errs = validate();
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }
    setLoading(true);
    if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
      window.location.href = "thank-you.html";
      return;
    }
    try {
      const res  = await fetch("api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ ...form, website: "", form_id: "reg_form_v1" }),
      });
      const json = await res.json();
      if (json.ok) {
        window.location.href = "thank-you.html";
      } else if (json.errors) {
        setErrors(json.errors);
      } else {
        setApiError(json.error || "Error al procesar.");
      }
    } catch {
      setApiError("Error de conexión.");
    } finally {
      setLoading(false);
    }
  };

  return { form, errors, loading, apiError, onChange, submit };
}

/* ── Shared form fields ── */
function PopupFields({ form, errors, loading, onChange }) {
  const inp = hasErr => ({
    width: "100%", height: 44, background: "#fff", borderRadius: 6,
    border: hasErr ? "1px solid #e53935" : "1px solid #d0d0d0",
    padding: "0 13px", fontFamily: "Arial, sans-serif", fontSize: 14,
    color: "#202020", outline: "none", boxSizing: "border-box", display: "block",
    opacity: loading ? 0.7 : 1,
  });

  return (
    <>
      <div style={{ marginBottom: 8 }}>
        <input value={form.nombre} onChange={onChange("nombre")} placeholder="Nombre" disabled={loading} style={inp(errors.nombre)} />
        {errors.nombre && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 2 }}>{errors.nombre}</div>}
      </div>
      <div style={{ marginBottom: 8 }}>
        <input value={form.apellido} onChange={onChange("apellido")} placeholder="Apellido" disabled={loading} style={inp(errors.apellido)} />
        {errors.apellido && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 2 }}>{errors.apellido}</div>}
      </div>
      <div style={{ marginBottom: 8 }}>
        <input value={form.email} onChange={onChange("email")} placeholder="Correo electrónico" type="email" disabled={loading} style={inp(errors.email)} />
        {errors.email && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 2 }}>{errors.email}</div>}
      </div>
      <div style={{ marginBottom: 14 }}>
        <div style={{ width: "100%", height: 44, background: "#fff", borderRadius: 6, border: errors.telefono ? "1px solid #e53935" : "1px solid #d0d0d0", display: "flex", alignItems: "center", overflow: "hidden", opacity: loading ? 0.7 : 1 }}>
          <div style={{ height: 44, padding: "0 10px", borderRight: "1px solid #ddd", display: "flex", alignItems: "center", gap: 5, flexShrink: 0 }}>
            <span style={{ fontSize: 12 }}>•</span>
            <span style={{ fontFamily: "Arial, sans-serif", fontSize: 13, fontWeight: 600, color: "#111" }}>+34</span>
          </div>
          <input value={form.telefono} onChange={onChange("telefono")} placeholder="612 34 56 78" type="tel" disabled={loading}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 10px", fontFamily: "Arial, sans-serif", fontSize: 14, color: "#202020", outline: "none" }} />
        </div>
        {errors.telefono && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 2 }}>{errors.telefono}</div>}
      </div>
    </>
  );
}

/* ── Horizon AI link popup (with registration form) ── */
function HorizonPopup({ onClose }) {
  const { form, errors, loading, apiError, onChange, submit } = usePopupForm();

  return (
    <div className="modal-overlay" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ background: "#fff", borderRadius: 12, width: "100%", maxWidth: 460, overflow: "hidden", position: "relative", boxShadow: "0 8px 40px rgba(0,0,0,0.28)", margin: "16px" }}>

        {/* Close */}
        <button onClick={onClose} style={{ position: "absolute", top: 10, right: 14, background: "none", border: "none", fontSize: 22, color: "#aaa", cursor: "pointer", lineHeight: 1, zIndex: 1 }}>
          ×
        </button>

        {/* Title */}
        <div className="popup-title" style={{ padding: "28px 28px 0", textAlign: "center" }}>
          <p style={{ fontFamily: "'Times New Roman', serif", fontSize: 17, color: "#111", lineHeight: 1.55 }}>
            Registro gratuito. Si no ganás dinero en dos semanas, te devolvemos todo tu depósito. Sin riesgos
          </p>
        </div>

        {/* Form */}
        <div className="popup-form-body" style={{ padding: "20px 28px 20px" }}>
          <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" readOnly />
          <PopupFields form={form} errors={errors} loading={loading} onChange={onChange} />
          {apiError && (
            <div style={{ fontFamily: "Arial, sans-serif", fontSize: 12, color: "#e53935", textAlign: "center", marginBottom: 8 }}>{apiError}</div>
          )}
          <button onClick={submit} disabled={loading} style={{
            width: "100%", minHeight: 50, background: loading ? "#888" : "#5a5a7a",
            border: "none", borderRadius: 8, color: "#fff",
            fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 15,
            cursor: loading ? "not-allowed" : "pointer",
            textTransform: "uppercase", letterSpacing: 1.5,
            padding: "12px 16px",
          }}>
            {loading ? "Enviando..." : "REGISTRARSE"}
          </button>
        </div>

        {/* Purple footer */}
        <div className="popup-footer" style={{ background: "#3d3580", padding: "14px 28px 18px", textAlign: "center" }}>
          <div style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 13, color: "#fff", marginBottom: 5 }}>
            Garantía de calidad y seguridad
          </div>
          <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "rgba(255,255,255,0.65)" }}>
            © . Todos los derechos y datos están protegidos.
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Exit intent popup ── */
function ExitPopup({ onClose }) {
  const scrollToReg = () => {
    onClose();
    setTimeout(() => {
      const reg = document.getElementById("registration");
      if (reg) {
        reg.scrollIntoView({ behavior: "smooth", block: "center" });
      } else {
        const btn = document.querySelector(".cta-btn");
        if (btn) {
          btn.click();
          setTimeout(() => {
            const reg2 = document.getElementById("registration");
            if (reg2) reg2.scrollIntoView({ behavior: "smooth", block: "center" });
          }, 350);
        }
      }
    }, 120);
  };

  return (
    <div className="modal-overlay" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="popup-exit-body" style={{ background: "#fff", borderRadius: 8, width: "100%", maxWidth: 380, padding: "32px 28px 24px", position: "relative", boxShadow: "0 8px 40px rgba(0,0,0,0.28)", textAlign: "center", margin: "16px" }}>

        {/* Close */}
        <button onClick={onClose} style={{ position: "absolute", top: 10, right: 14, background: "none", border: "none", fontSize: 22, color: "#aaa", cursor: "pointer", lineHeight: 1 }}>
          ×
        </button>

        <h2 style={{ fontFamily: "'Times New Roman', serif", fontWeight: 700, fontSize: 24, color: "#111", marginBottom: 14, lineHeight: 1.3 }}>
          No te vayas todavía…
        </h2>

        <p style={{ fontFamily: "'Times New Roman', serif", fontSize: 15, color: "#333", lineHeight: 1.65, marginBottom: 20, textAlign: "center" }}>
          <strong>La esposa del primer ministro Pedro Sánchez</strong> entró en pánico, gritó y salió corriendo del plató para que nadie se enterara de la existencia de esa plataforma. Y <strong>Andrés Moreno</strong>, conductor de autobús de Madrid, ya había empezado a contar cómo la gente corriente gana dinero gracias a esa misma plataforma.
        </p>

        <button onClick={scrollToReg} style={{
          width: "100%", minHeight: 50, background: "#cc0000",
          border: "none", borderRadius: 6, color: "#fff",
          fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 13,
          cursor: "pointer", textTransform: "uppercase", letterSpacing: 0.5,
          marginBottom: 14, padding: "12px 16px",
        }}>
          REGISTRARME ANTES DE QUE SE AGOTEN
        </button>

        <a href="#" onClick={e => { e.preventDefault(); scrollToReg(); }}
          style={{ fontFamily: "Arial, sans-serif", fontSize: 13, color: "#1a73e8", textDecoration: "underline", cursor: "pointer" }}>
          Ver más información
        </a>
      </div>
    </div>
  );
}
