// RegistrationForm.jsx
Object.assign(window, { ContactForm, UrgencyWidget, RegistrationForm });

function UrgencyWidget() { return null; }

function ContactForm({ dark, prefillData, spainOnly }) {
  const [form, setForm]     = React.useState({ email: "", phone: "" });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [apiError, setApiError] = React.useState("");

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

  const validate = () => {
    const errs = {};
    if (!form.email.includes("@") || !form.email.includes("."))
      errs.email = "Por favor, introduce un email válido";
    if (form.phone.replace(/\D/g, "").length < 6)
      errs.phone = "Por favor, introduce un teléfono válido";
    return errs;
  };

  const handleSubmit = async () => {
    const clientErrors = validate();
    if (Object.keys(clientErrors).length > 0) { setErrors(clientErrors); return; }
    setLoading(true);
    setApiError("");
    if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
      window.location.href = "thank-you.html";
      return;
    }
    try {
      const payload = {
        nombre:   prefillData?.nombre   || "Participante",
        apellido: prefillData?.apellido || "",
        ciudad:   prefillData?.ciudad   || "",
        email:    form.email.trim(),
        phone:    "+34" + form.phone.replace(/\D/g, ""),
        website:  "",
        form_id:  "reg_form_ngeu_v1",
      };
      const res  = await fetch("api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify(payload),
      });
      const json = await res.json();
      if (json.ok) {
        const dest = "thank-you.html" + (json.redirect ? "?to=" + encodeURIComponent(json.redirect) : "");
        window.location.href = dest;
      } else if (json.errors) {
        setErrors(json.errors);
      } else {
        setApiError(json.error || "Error al procesar. Por favor, inténtalo de nuevo.");
      }
    } catch {
      setApiError("Error de conexión. Por favor, comprueba tu conexión a internet.");
    } finally {
      setLoading(false);
    }
  };

  const BG  = dark ? "rgba(255,255,255,0.12)" : "#fff";
  const CLR = dark ? "#fff" : "#1a1a1a";
  const BRD = hasErr => hasErr
    ? "1.5px solid #ff4444"
    : `1px solid ${dark ? "rgba(255,255,255,0.25)" : "#dde2e8"}`;

  const baseField = hasErr => ({
    width: "100%", height: 56, background: BG,
    border: BRD(hasErr), borderRadius: 10, padding: "0 18px",
    fontFamily: "Inter, Arial, sans-serif", fontSize: 15, color: CLR,
    outline: "none", boxSizing: "border-box", display: "block",
    opacity: loading ? 0.7 : 1,
  });

  const errSt = {
    fontFamily: "Inter, sans-serif", fontSize: 12,
    color: dark ? "#ff9090" : "#cc1515",
    marginTop: 4, paddingLeft: 2,
  };

  return (
    <div id="registro">
      <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" />

      {/* Phone — Spain only */}
      <div style={{ marginBottom: 12 }}>
        <div style={{
          display: "flex", alignItems: "center",
          height: 56, background: BG, border: BRD(errors.phone),
          borderRadius: 10, opacity: loading ? 0.7 : 1,
        }}>
          <div style={{
            display: "flex", alignItems: "center", gap: 6,
            padding: "0 14px",
            borderRight: `1px solid ${dark ? "rgba(255,255,255,0.2)" : "#dde2e8"}`,
            height: "100%", flexShrink: 0,
          }}>
            <span style={{ fontSize: 20 }}>🇪🇸</span>
            <span style={{ fontFamily: "Inter, sans-serif", fontSize: 14, color: CLR, fontWeight: 600 }}>+34</span>
          </div>
          <input
            value={form.phone} onChange={set("phone")}
            placeholder="(000) 000-0000" type="tel" disabled={loading}
            className={dark ? "dark-input" : "light-input"}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 16px", fontFamily: "Inter, sans-serif", fontSize: 15, color: CLR, outline: "none" }}
          />
        </div>
        {errors.phone && <div style={errSt}>{errors.phone}</div>}
      </div>

      {/* Email */}
      <div style={{ marginBottom: 16 }}>
        <input
          value={form.email} onChange={set("email")}
          placeholder="Email" type="email" disabled={loading}
          className={dark ? "dark-input" : "light-input"}
          style={baseField(errors.email)}
        />
        {errors.email && <div style={errSt}>{errors.email}</div>}
      </div>

      {apiError && (
        <div style={{
          fontFamily: "Inter, sans-serif", fontSize: 13,
          color: dark ? "#ff9090" : "#cc1515",
          textAlign: "center", marginBottom: 12, lineHeight: 1.4,
        }}>
          {apiError}
        </div>
      )}

      <button onClick={handleSubmit} disabled={loading} style={{
        width: "100%", height: 56,
        background: loading ? "#a01010" : "#cc1515",
        border: "none", borderRadius: 10, color: "#fff",
        fontFamily: "Inter, Arial, sans-serif", fontWeight: 700, fontSize: 15,
        cursor: loading ? "not-allowed" : "pointer", transition: "background 0.15s",
      }}>
        {loading ? "Enviando..." : "Consigue una consulta gratuita"}
      </button>
    </div>
  );
}

function RegistrationForm(props) { return <ContactForm {...props} dark={false} />; }
