// RegistrationForm.jsx

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

function UrgencyWidget() {
  const getInitialSeconds = () => {
    const key = "reg_deadline_ship";
    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: 6 }}>
      <div className="timer-block-inner" style={{
        background: "#fff",
        border: "1px solid #d0d0d0",
        borderRadius: 8,
        minWidth: 58,
        padding: "10px 10px",
        textAlign: "center",
        fontFamily: "'Courier New', monospace",
        fontWeight: 700,
        fontSize: 28,
        color: "#111",
        lineHeight: 1,
        boxShadow: "0 1px 3px rgba(0,0,0,0.06)",
      }}>
        {val}
      </div>
      <span className="timer-label" style={{
        fontFamily: "Arial, sans-serif",
        fontSize: 9,
        color: "#999",
        textTransform: "uppercase",
        letterSpacing: 0.8,
      }}>
        {label}
      </span>
    </div>
  );

  return (
    <div style={{ textAlign: "center", marginBottom: 24, padding: "16px 0 8px" }}>
      <p style={{
        fontFamily: "'Times New Roman', serif",
        fontSize: 15,
        color: "#333",
        marginBottom: 18,
        lineHeight: 1.5,
      }}>
        ¡Atención! El registro se cerrará en:
      </p>
      <div style={{ display: "flex", justifyContent: "center", alignItems: "flex-start", gap: 8 }}>
        <Block val={pad(days)}  label="DÍAS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 28, color: "#999", paddingTop: 10, lineHeight: 1 }}>:</span>
        <Block val={pad(hours)} label="HORAS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 28, color: "#999", paddingTop: 10, lineHeight: 1 }}>:</span>
        <Block val={pad(mins)}  label="MINUTOS" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 28, color: "#999", paddingTop: 10, lineHeight: 1 }}>:</span>
        <Block val={pad(secs)}  label="SEGUNDOS" />
      </div>
    </div>
  );
}

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";
      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 fieldStyle = hasErr => ({
    width: "100%",
    height: 48,
    background: "#fff",
    borderRadius: 10,
    border: hasErr ? "1px solid #e53935" : "1px solid #d8d8d8",
    padding: "0 16px",
    fontFamily: "Arial, sans-serif",
    fontSize: 15,
    color: "#202020",
    outline: "none",
    boxSizing: "border-box",
    opacity: loading ? 0.7 : 1,
    display: "block",
  });

  return (
    <div id="registration" className="reg-card" style={{ width: "100%", maxWidth: 480, margin: "0 auto" }}>
      <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" readOnly />

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

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

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

      {/* Teléfono */}
      <div style={{ marginBottom: 20 }}>
        <div style={{
          width: "100%", height: 48,
          background: "#fff",
          borderRadius: 10,
          border: errors.telefono ? "1px solid #e53935" : "1px solid #d8d8d8",
          display: "flex", alignItems: "center",
          overflow: "hidden",
          opacity: loading ? 0.7 : 1,
          boxSizing: "border-box",
        }}>
          {/* Flag + arrow */}
          <div style={{
            height: 48, padding: "0 10px",
            borderRight: "1px solid #e0e0e0",
            display: "flex", alignItems: "center", gap: 4,
            flexShrink: 0, cursor: "pointer",
          }}>
            <div style={{
              width: 22, height: 14,
              background: "#e0e0e0",
              borderRadius: 2,
              flexShrink: 0,
            }} />
            <svg width="10" height="10" viewBox="0 0 10 6" fill="none">
              <path d="M1 1l4 4 4-4" stroke="#999" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            <span style={{ fontFamily: "Arial, sans-serif", fontSize: 14, color: "#111", fontWeight: 500 }}>+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 14px", 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: 12, lineHeight: 1.4 }}>{apiError}</div>
      )}

      {/* Submit */}
      <button onClick={handleSubmit} disabled={loading} style={{
        width: "100%", height: 52,
        background: loading ? "#aaa" : "#6b6b6b",
        border: "none", borderRadius: 10, color: "#fff",
        fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 15,
        cursor: loading ? "not-allowed" : "pointer",
        textTransform: "uppercase", letterSpacing: 1.5,
        transition: "background 0.15s",
      }}>
        {loading ? "Enviando..." : "REGISTRARSE"}
      </button>
    </div>
  );
}
