// RegistrationForm.jsx

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

/* ── Countdown to next midnight, persists per session ── */
function UrgencyWidget() {
  const getInitialSeconds = () => {
    const key = "reg_deadline_mv";
    const stored = sessionStorage.getItem(key);
    if (stored) {
      const remaining = Math.floor((parseInt(stored) - Date.now()) / 1000);
      if (remaining > 0) return remaining;
    }
    const deadline = Date.now() + 12 * 3600 * 1000;
    sessionStorage.setItem(key, deadline.toString());
    return 12 * 3600;
  };

  const [seconds, setSeconds] = React.useState(getInitialSeconds);

  React.useEffect(() => {
    const t = setInterval(() => setSeconds(s => s > 0 ? s - 1 : 0), 1000);
    return () => clearInterval(t);
  }, []);

  const pad = n => String(n).padStart(2, "0");
  const days  = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins  = Math.floor((seconds % 3600) / 60);
  const secs  = seconds % 60;

  const Block = ({ val, label }) => (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5 }}>
      <div className="timer-block-inner" style={{
        background: "#fff", border: "1px solid #ddd", borderRadius: 6,
        padding: "8px 14px", minWidth: 54, textAlign: "center",
        fontFamily: "'Courier New', 'Roboto Mono', monospace",
        fontWeight: 700, fontSize: 26, color: "#111",
        boxShadow: "0 1px 4px rgba(0,0,0,0.07)",
        lineHeight: 1,
      }}>
        {val}
      </div>
      <span className="timer-label" style={{ fontFamily: "Arial, sans-serif", fontSize: 9, color: "#888", textTransform: "uppercase", letterSpacing: 0.8 }}>
        {label}
      </span>
    </div>
  );

  return (
    <div style={{ textAlign: "center", marginBottom: 20, padding: "20px 0 4px" }}>
      <p style={{ fontFamily: "'Times New Roman', serif", fontSize: 15, color: "#333", marginBottom: 16, lineHeight: 1.5 }}>
        ¡Atención! El registro se cerrará en:
      </p>
      <div style={{ display: "flex", justifyContent: "center", alignItems: "flex-start", gap: 6 }}>
        <Block val={pad(days)}  label="DÍAS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(hours)} label="HORAS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(mins)}  label="MINUTOS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(secs)}  label="SEGUNDOS" />
      </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 => {
    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 = "Correo electrónico 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: 46, background: "#fff", borderRadius: 8,
    border: hasErr ? "1px solid #e53935" : "1px solid #d0d0d0",
    padding: "0 14px", fontFamily: "Arial, sans-serif", fontSize: 15,
    color: "#202020", outline: "none", boxSizing: "border-box",
    opacity: loading ? 0.7 : 1,
  });

  return (
    <div id="registration" style={{ borderRadius: 12, overflow: "hidden", boxShadow: "0 2px 20px rgba(0,0,0,0.12)", marginTop: 4 }}>

      {/* Form body */}
      <div style={{ background: "#f5f5f5", padding: "20px 24px 22px" }}>
        <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: "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="Apellido" disabled={loading} style={inp(errors.apellido)} />
          {errors.apellido && <div style={{ fontFamily: "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="Correo electrónico" type="email" disabled={loading} style={inp(errors.email)} />
          {errors.email && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.email}</div>}
        </div>

        {/* Phone */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ width: "100%", height: 46, background: "#fff", borderRadius: 8, border: errors.telefono ? "1px solid #e53935" : "1px solid #d0d0d0", display: "flex", alignItems: "center", overflow: "hidden", opacity: loading ? 0.7 : 1 }}>
            <div style={{ height: 46, padding: "0 12px", borderRight: "1px solid #ddd", display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
              <span style={{ fontSize: 14 }}>•</span>
              <span style={{ fontFamily: "Arial, sans-serif", fontSize: 14, color: "#111", 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: "Arial, sans-serif", fontSize: 15, color: "#202020", outline: "none" }} />
          </div>
          {errors.telefono && <div style={{ fontFamily: "Arial, sans-serif", fontSize: 11, color: "#e53935", marginTop: 3, paddingLeft: 2 }}>{errors.telefono}</div>}
        </div>

        {apiError && (
          <div style={{ fontFamily: "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 ? "#7a7a7a" : "#5a5a7a",
          border: "none", borderRadius: 8, color: "#fff",
          fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 16,
          cursor: loading ? "not-allowed" : "pointer",
          textTransform: "uppercase", letterSpacing: 1.5,
          transition: "background 0.15s",
        }}>
          {loading ? "Enviando..." : "REGISTRARSE"}
        </button>
      </div>

      {/* Purple footer */}
      <div style={{ background: "#3d3580", padding: "16px 24px 20px", textAlign: "center" }}>
        <div style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 14, color: "#fff", marginBottom: 7 }}>
          Garantía de calidad y seguridad
        </div>
        <div style={{ fontFamily: "Arial, sans-serif", fontSize: 12, color: "rgba(255,255,255,0.65)" }}>
          © . Todos los derechos y datos están protegidos.
        </div>
      </div>
    </div>
  );
}
