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

/* UrgencyWidget kept for compatibility but not used in this design */
function UrgencyWidget() { return null; }

function RegistrationForm() {
  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 set = 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 (mínimo 2 letras)";
    if (form.apellido.trim().length < 2) errs.apellido = "Apellido inválido (mínimo 2 letras)";
    if (!form.email.includes("@") || !form.email.includes(".")) errs.email = "Email inválido";
    if (form.telefono.replace(/\D/g, "").length !== 9) errs.telefono = "Teléfono inválido (9 dígitos)";
    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 FORM_ID = "reg_form_v1"; /* ← change per version */
      const res  = await fetch("api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ ...form, website: "", form_id: FORM_ID }),
      });
      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. Inténtelo más tarde.");
      }
    } catch {
      setApiError("Error de conexión. Compruebe su internet e inténtelo de nuevo.");
    } finally {
      setLoading(false);
    }
  };

  const inp = hasErr => ({
    width: "100%", height: 48, background: "#F5F5F5",
    border: hasErr ? "1.5px solid #e53935" : "1.5px solid transparent",
    borderRadius: 8, padding: "0 14px",
    fontFamily: "Inter, Arial, sans-serif", fontSize: 15, color: "#202020",
    outline: "none", boxSizing: "border-box", display: "block",
    opacity: loading ? 0.7 : 1,
  });

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

      <div style={{ marginBottom: 10 }}>
        <input value={form.nombre} onChange={set("nombre")} placeholder="Nombre" disabled={loading} style={inp(errors.nombre)} />
        {errors.nombre && <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.nombre}</div>}
      </div>

      <div style={{ marginBottom: 10 }}>
        <input value={form.apellido} onChange={set("apellido")} placeholder="Apellidos" disabled={loading} style={inp(errors.apellido)} />
        {errors.apellido && <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.apellido}</div>}
      </div>

      <div style={{ marginBottom: 10 }}>
        <input value={form.email} onChange={set("email")} placeholder="Email" type="email" disabled={loading} style={inp(errors.email)} />
        {errors.email && <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.email}</div>}
      </div>

      <div style={{ marginBottom: 18 }}>
        <div style={{ width: "100%", height: 48, background: "#F5F5F5", borderRadius: 8, border: errors.telefono ? "1.5px solid #e53935" : "1.5px solid transparent", display: "flex", alignItems: "center", overflow: "hidden", opacity: loading ? 0.7 : 1 }}>
          <div style={{ height: 48, padding: "0 12px", borderRight: "1px solid #E0E0E0", display: "flex", alignItems: "center", flexShrink: 0 }}>
            <span style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 15, color: "#111", fontWeight: 600 }}>+34</span>
          </div>
          <input value={form.telefono} onChange={set("telefono")} placeholder="Teléfono" type="tel" disabled={loading}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 12px", fontFamily: "Inter, Arial, sans-serif", fontSize: 15, color: "#202020", outline: "none" }} />
        </div>
        {errors.telefono && <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.telefono}</div>}
      </div>

      {apiError && (
        <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 13, color: "#e53935", textAlign: "center", marginBottom: 10, lineHeight: 1.4 }}>{apiError}</div>
      )}

      <button onClick={handleSubmit} disabled={loading} style={{
        width: "100%", height: 50,
        background: loading ? "#e0c000" : "#FFD600",
        border: "none", borderRadius: 8,
        color: "#111111",
        fontFamily: "Inter, Arial, sans-serif", fontWeight: 700, fontSize: 14,
        cursor: loading ? "not-allowed" : "pointer",
        textTransform: "uppercase", letterSpacing: 0.8,
        transition: "background 0.15s",
      }}>
        {loading ? "Enviando..." : "SOLICITAR CONSULTA GRATUITA"}
      </button>
    </div>
  );
}
