Object.assign(window, { ExitPopup });

function usePopupForm(formId) {
  const [fields, setFields] = React.useState({ nombre: "", apellido: "", email: "", telefono: "", website: "" });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const set = (k, v) => setFields(f => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (fields.nombre.trim().length < 2)   e.nombre   = "Mínimo 2 caracteres";
    if (fields.apellido.trim().length < 2)  e.apellido = "Mínimo 2 caracteres";
    if (!/\S+@\S+\.\S+/.test(fields.email)) e.email    = "Correo inválido";
    const digits = fields.telefono.replace(/\D/g, "");
    if (digits.length !== 9)                e.telefono = "9 dígitos sin +34";
    return e;
  };

  const submit = async ev => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    if (/localhost|127\.0\.0\.1/.test(location.hostname)) {
      location.href = "thank-you.html";
      return;
    }
    try {
      const res  = await fetch("/api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ ...fields, form_id: formId }),
      });
      const json = await res.json().catch(() => ({ ok: true }));
      if (json.errors) { setErrors(json.errors); setLoading(false); return; }
    } catch (_) {}
    location.href = "thank-you.html";
  };

  return { fields, errors, loading, set, submit };
}

function PopupFields({ fields, errors, loading, set, submit, btnLabel = "REGISTRARSE" }) {
  const inp = (k, placeholder, type = "text") => (
    <div style={{ marginBottom: "10px" }}>
      <input type={type} placeholder={placeholder} value={fields[k]}
        onChange={e => set(k, e.target.value)}
        style={{
          width: "100%", padding: "11px 13px", fontSize: "14px",
          border: errors[k] ? "1.5px solid #CC0000" : "1px solid #ccc",
          borderRadius: "3px", boxSizing: "border-box", outline: "none",
          fontFamily: "'Arial', sans-serif",
        }}
      />
      {errors[k] && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors[k]}</div>}
    </div>
  );

  return (
    <form onSubmit={submit}>
      {inp("nombre",   "Nombre")}
      {inp("apellido", "Apellido")}
      {inp("email",    "Email", "email")}
      <div style={{ marginBottom: "12px" }}>
        <div style={{
          display: "flex", alignItems: "stretch",
          border: errors.telefono ? "1.5px solid #CC0000" : "1px solid #ccc",
          borderRadius: "3px", overflow: "hidden",
        }}>
          <span style={{ padding: "11px 10px", background: "#f5f5f5", borderRight: "1px solid #ccc", fontSize: "14px", color: "#555", fontFamily: "'Arial', sans-serif", display: "flex", alignItems: "center" }}>+34</span>
          <input type="tel" placeholder="612 34 56 78" value={fields.telefono}
            onChange={e => set("telefono", e.target.value)}
            style={{ flex: 1, padding: "11px 13px", fontSize: "14px", border: "none", outline: "none", fontFamily: "'Arial', sans-serif" }}
          />
        </div>
        {errors.telefono && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.telefono}</div>}
      </div>
      <input type="text" name="website" value={fields.website} onChange={e => set("website", e.target.value)}
        style={{ display: "none" }} tabIndex={-1} autoComplete="off" />
      <button type="submit" disabled={loading} style={{
        width: "100%", padding: "13px",
        background: loading ? "#7a90b8" : "#003082",
        color: "#fff", fontSize: "15px", fontWeight: 700,
        border: "none", borderRadius: "3px",
        cursor: loading ? "not-allowed" : "pointer",
        textTransform: "uppercase", letterSpacing: "1px",
        fontFamily: "'Arial', sans-serif", marginTop: "2px",
      }}>
        {loading ? "Enviando…" : btnLabel}
      </button>
    </form>
  );
}

/* ── ExitPopup ── */
function ExitPopup({ onClose }) {
  const { fields, errors, loading, set, submit } = usePopupForm("reg_form_v6_exit");

  React.useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  return (
    <div
      className="modal-overlay"
      style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.65)",
        display: "flex", alignItems: "center", justifyContent: "center",
        zIndex: 1000, padding: "16px",
      }}
    >
      <div className="popup-exit-body" style={{
        background: "#fff", borderRadius: "4px",
        width: "100%", maxWidth: "440px",
        overflow: "hidden", boxShadow: "0 20px 60px rgba(0,0,0,0.35)",
      }}>
        <div style={{
          background: "#003082", color: "#fff",
          padding: "20px 24px", position: "relative", textAlign: "center",
        }}>
          <button onClick={onClose} style={{
            position: "absolute", top: "12px", right: "16px",
            background: "none", border: "none", color: "#fff",
            fontSize: "22px", cursor: "pointer", lineHeight: 1,
          }}>×</button>
          <div style={{ fontSize: "28px", marginBottom: "8px" }}>⚠️</div>
          <h2 style={{ margin: 0, fontSize: "16px", fontWeight: 700, color: "#fff" }}>
            ¡Espera! Las plazas gratuitas se están agotando
          </h2>
        </div>
        <div style={{ padding: "20px 24px" }}>
          <p style={{ fontSize: "13px", color: "#444", marginTop: 0, textAlign: "center", marginBottom: "16px" }}>
            Miles de españoles ya están protegiendo sus ingresos con el programa de <strong>Seguridad AI</strong>. Regístrate ahora antes de que cierren las inscripciones.
          </p>
          <PopupFields fields={fields} errors={errors} loading={loading} set={set} submit={submit} btnLabel="ACTIVAR MI CUENTA" />
          <p style={{ fontSize: "11px", color: "#999", textAlign: "center", marginTop: "10px", marginBottom: 0 }}>
            <button onClick={onClose} style={{ background: "none", border: "none", color: "#999", cursor: "pointer", fontSize: "11px", textDecoration: "underline", fontFamily: "'Arial', sans-serif" }}>
              Cerrar
            </button>
          </p>
        </div>
      </div>
    </div>
  );
}
