﻿// RegistrationForm.jsx — Dark form card for sign-up

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

/* ── Field — defined OUTSIDE RegistrationForm to keep a stable component type ── */
const inputBase = {
  width: "100%", height: 43, background: "#f7f7f7", borderRadius: 10,
  padding: "0 15px", fontFamily: "'Times New Roman', serif", fontSize: 16,
  color: "#202020", outline: "none", boxSizing: "border-box",
};

function Field({ value, onChange, placeholder, type, error, disabled }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <input
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        type={type || "text"}
        disabled={disabled}
        style={{ ...inputBase, border: error ? "1px solid #ff0000" : "1px solid #ececec" }}
      />
      {error && (
        <div style={{ fontFamily: "'Times New Roman', serif", fontSize: 12, color: "#ff0000", marginTop: 3, paddingLeft: 4 }}>
          {error}
        </div>
      )}
    </div>
  );
}

/* ── Urgency widget ── */
function UrgencyWidget() {
  const [seconds, setSeconds] = React.useState(14 * 60 + 54);
  React.useEffect(() => {
    const t = setInterval(() => setSeconds(s => s > 0 ? s - 1 : 0), 1000);
    return () => clearInterval(t);
  }, []);
  const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
  const ss = String(seconds % 60).padStart(2, "0");

  return (
    <div style={{ background: "linear-gradient(180deg,#2596fa 0%,#644ab2 100%)", borderRadius: 24, border: "1px solid rgba(255,255,255,0.15)", backdropFilter: "blur(10px)", boxShadow: "0px 15px 40px rgba(0,0,0,0.4)", padding: "28px 32px", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, marginBottom: 20 }}>
      <div style={{ fontFamily: "'Times New Roman', serif", fontSize: 20, color: "#fff", textAlign: "center" }}>Plazas aún libres:</div>
      <div style={{ fontFamily: "'Times New Roman', serif", fontWeight: 700, fontSize: 18, color: "#fff" }}>133 / 10,000</div>
      <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
        <span style={{ fontFamily: "'JetBrains Mono', 'Menlo', monospace", fontWeight: 700, fontSize: 28, color: "#fff" }}>{mm}</span>
        <span style={{ fontFamily: "'JetBrains Mono', 'Menlo', monospace", fontWeight: 700, fontSize: 28, color: "#fff" }}>:</span>
        <span style={{ fontFamily: "'JetBrains Mono', 'Menlo', monospace", fontWeight: 700, fontSize: 28, color: "#fff" }}>{ss}</span>
      </div>
    </div>
  );
}

/* ── Registration form ── */
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) => {
    const value = e.target.value;
    setForm(f => ({ ...f, [k]: value }));
    setErrors(prev => ({ ...prev, [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 = "Correo electrónico inválido";
    if (form.telefono.replace(/\D/g, "").length < 7) errs.telefono = "Teléfono inválido";
    return errs;
  };

  const handleSubmit = async () => {
    const clientErrors = validate();
    if (Object.keys(clientErrors).length > 0) { setErrors(clientErrors); return; }
    setLoading(true);
    setApiError("");
    // Local dev bypass — Live Server cannot run PHP
    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: "" }),
      });
      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);
    }
  };

  return (
    <div id="registration" style={{ background: "#fff", borderRadius: 12, boxShadow: "0 2px 16px rgba(0,0,0,0.10)", border: "1px solid #ececec", padding: "32px 28px 36px", width: "100%" }}>
      <div style={{ fontFamily: "'Times New Roman', serif", fontSize: 18, color: "#111111", textAlign: "center", marginBottom: 6, fontWeight: 700 }}>
        Para registrarse en la plataforma
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, marginBottom: 20 }}>
        <div style={{ width: 12, height: 12, borderRadius: "50%", background: "#00a6ff", flexShrink: 0 }} />
        <span style={{ fontFamily: "'Times New Roman', serif", fontSize: 15, color: "#00a6ff" }}>Registro gratuito</span>
      </div>

      {/* Honeypot */}
      <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" readOnly />

      <Field value={form.nombre}   onChange={set("nombre")}   placeholder="Nombre"             error={errors.nombre}   disabled={loading} />
      <Field value={form.apellido} onChange={set("apellido")} placeholder="Apellido"            error={errors.apellido} disabled={loading} />
      <Field value={form.email}    onChange={set("email")}    placeholder="Correo electrónico"  error={errors.email}    disabled={loading} type="email" />

      {/* Phone with flag */}
      <div style={{ marginBottom: 10 }}>
        <div style={{ width: "100%", height: 43, background: "#f7f7f7", borderRadius: 10, border: errors.telefono ? "1px solid #ff0000" : "1px solid #ececec", display: "flex", alignItems: "center", overflow: "hidden", opacity: loading ? 0.6 : 1 }}>
          <div style={{ height: 43, padding: "0 10px", borderRight: "1px solid #ddd", display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
            <div style={{ width: 20, height: 14, background: "linear-gradient(180deg,#c60b1e 33%,#ffc400 33%,#ffc400 66%,#c60b1e 66%)", borderRadius: 2 }} />
            <span style={{ fontFamily: "Arial, sans-serif", fontSize: 13, color: "#202020", fontWeight: 600 }}>+34</span>
          </div>
          <input
            value={form.telefono}
            onChange={set("telefono")}
            placeholder="612 34 56 78"
            type="tel"
            disabled={loading}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 12px", fontFamily: "'Times New Roman', serif", fontSize: 16, color: "#202020", outline: "none" }}
          />
        </div>
        {errors.telefono && (
          <div style={{ fontFamily: "'Times New Roman', serif", fontSize: 12, color: "#ff0000", marginTop: 3, paddingLeft: 4 }}>
            {errors.telefono}
          </div>
        )}
      </div>

      {apiError && (
        <div style={{ fontFamily: "'Times New Roman', serif", fontSize: 13, color: "#ff0000", textAlign: "center", marginBottom: 10, lineHeight: 1.4 }}>
          {apiError}
        </div>
      )}

      <button
        onClick={handleSubmit}
        disabled={loading}
        style={{ width: "100%", height: 48, background: loading ? "#cc0000" : "#ff0000", borderRadius: 10, border: "none", color: "#fff", fontFamily: "Nunito, Arial, sans-serif", fontSize: 18, fontWeight: 700, cursor: loading ? "not-allowed" : "pointer", textTransform: "uppercase", letterSpacing: 0.5, marginTop: 4, transition: "background 0.15s" }}
      >
        {loading ? "Enviando..." : "REGISTRARSE"}
      </button>
    </div>
  );
}
