Object.assign(window, { RegistrationForm });

const FORM_ID   = "reg_form_v6";
const TIMER_KEY = "reg_deadline_min";

function RegistrationForm({ formId, compact }) {
  const id = formId || FORM_ID;
  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 electrónico 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: id }),
      });
      const json = await res.json().catch(() => ({ ok: true }));
      if (json.errors) { setErrors(json.errors); setLoading(false); return; }
    } catch (_) {}
    location.href = "thank-you.html";
  };

  const inputStyle = hasError => ({
    width: "100%",
    padding: "12px 14px",
    fontSize: "14px",
    border: hasError ? "1.5px solid #CC0000" : "1px solid #ccc",
    borderRadius: "3px",
    boxSizing: "border-box",
    outline: "none",
    fontFamily: "'Arial', sans-serif",
    color: "#333",
  });

  return (
    <form id="registration" onSubmit={submit} style={{ maxWidth: compact ? "100%" : "420px", margin: "0 auto" }}>
      {/* Nombre */}
      <div style={{ marginBottom: "10px" }}>
        <input type="text" placeholder="Nombre" value={fields.nombre}
          onChange={e => { set("nombre", e.target.value); setErrors(er => ({ ...er, nombre: undefined })); }}
          style={inputStyle(errors.nombre)} />
        {errors.nombre && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.nombre}</div>}
      </div>

      {/* Apellido */}
      <div style={{ marginBottom: "10px" }}>
        <input type="text" placeholder="Apellido" value={fields.apellido}
          onChange={e => { set("apellido", e.target.value); setErrors(er => ({ ...er, apellido: undefined })); }}
          style={inputStyle(errors.apellido)} />
        {errors.apellido && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.apellido}</div>}
      </div>

      {/* Email */}
      <div style={{ marginBottom: "10px" }}>
        <input type="email" placeholder="Email" value={fields.email}
          onChange={e => { set("email", e.target.value); setErrors(er => ({ ...er, email: undefined })); }}
          style={inputStyle(errors.email)} />
        {errors.email && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.email}</div>}
      </div>

      {/* Phone with +34 prefix */}
      <div style={{ marginBottom: "14px" }}>
        <div style={{
          display: "flex", alignItems: "stretch",
          border: errors.telefono ? "1.5px solid #CC0000" : "1px solid #ccc",
          borderRadius: "3px", overflow: "hidden",
        }}>
          <span style={{
            padding: "12px 10px", background: "#f5f5f5",
            borderRight: "1px solid #ccc", fontSize: "14px",
            color: "#555", fontFamily: "'Arial', sans-serif",
            whiteSpace: "nowrap", display: "flex", alignItems: "center",
          }}>+34</span>
          <input type="tel" placeholder="612 34 56 78" value={fields.telefono}
            onChange={e => { set("telefono", e.target.value); setErrors(er => ({ ...er, telefono: undefined })); }}
            style={{
              flex: 1, padding: "12px 14px", fontSize: "14px",
              border: "none", outline: "none",
              fontFamily: "'Arial', sans-serif", color: "#333",
            }} />
        </div>
        {errors.telefono && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.telefono}</div>}
      </div>

      {/* Honeypot */}
      <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: "14px",
          background: loading ? "#7a90b8" : "#003082",
          color: "#fff", fontSize: "15px", fontWeight: 700,
          border: "none", borderRadius: "3px",
          cursor: loading ? "not-allowed" : "pointer",
          textTransform: "uppercase", letterSpacing: "1.5px",
          fontFamily: "'Arial', sans-serif",
        }}
      >
        {loading ? "Enviando…" : "REGISTRARSE"}
      </button>
    </form>
  );
}
