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

const FORM_ID = "reg_form_v6";

/* ── 3-step quiz → registration form ── */
function QuizForm() {
  const [step, setStep] = React.useState(1);

  const questions = [
    {
      n: 1,
      text: "¿Trabaja actualmente?",
      opts: ["Sí", "No"],
      row: true,
    },
    {
      n: 2,
      text: "¿Le parece adecuado su ingreso mensual actual?",
      opts: ["Sí, totalmente", "Más bien no", "No"],
      row: false,
    },
    {
      n: 3,
      text: "¿Le gustaría recibir cada mes un ingreso adicional del Estado?",
      opts: ["Sí, me interesa", "No"],
      row: false,
    },
  ];

  if (step > 3) {
    return (
      <div id="registration">
        <RegistrationForm />
      </div>
    );
  }

  const q = questions[step - 1];

  return (
    <div id="registration" className="quiz-box" style={{
      maxWidth: "380px", margin: "0 auto",
      background: "#fff", border: "1px solid #d0dae6",
      borderRadius: "8px", padding: "28px 28px 32px",
    }}>
      {/* Step indicator */}
      <div style={{ marginBottom: "20px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "7px", marginBottom: "8px" }}>
          <svg width="17" height="17" viewBox="0 0 17 17" fill="none">
            <circle cx="8.5" cy="8.5" r="7.5" stroke="#003082" strokeWidth="1.5"/>
            <path d="M5 8.5L7.5 11L12 6.5" stroke="#003082" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span style={{ fontSize: "13px", color: "#555", fontFamily: "Arial, sans-serif" }}>
            Paso {step} de 3
          </span>
        </div>
        <div style={{ width: "48px", height: "2px", background: "#003082" }} />
      </div>

      {/* Question */}
      <p style={{
        fontSize: "21px", fontWeight: 700, color: "#003082",
        fontFamily: "Arial, sans-serif", textAlign: "center",
        lineHeight: "1.3", marginBottom: "28px",
      }}>
        {q.text}
      </p>

      {/* Answer buttons */}
      <div style={{
        display: "flex",
        flexDirection: q.row ? "row" : "column",
        gap: "10px",
        justifyContent: "center",
      }}>
        {q.opts.map(opt => (
          <button
            key={opt}
            onClick={() => setStep(s => s + 1)}
            style={{
              flex: q.row ? 1 : "unset",
              padding: "12px 24px",
              fontSize: "15px",
              fontFamily: "Arial, sans-serif",
              background: "#fff",
              border: "1px solid #b5c4d3",
              borderRadius: "4px",
              cursor: "pointer",
              color: "#1a1a1a",
              textAlign: "center",
            }}
            onMouseEnter={e => { e.currentTarget.style.background = "#f0f5fb"; e.currentTarget.style.borderColor = "#003082"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.style.borderColor = "#b5c4d3"; }}
          >
            {opt}
          </button>
        ))}
      </div>
    </div>
  );
}

/* ── Registration form (shown after quiz completes) ── */
function RegistrationForm({ formId }) {
  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 inp = err => ({
    width: "100%", padding: "12px 14px", fontSize: "14px",
    border: err ? "1.5px solid #CC0000" : "1px solid #ccc",
    borderRadius: "4px", boxSizing: "border-box",
    outline: "none", fontFamily: "Arial, sans-serif", color: "#333",
    background: "#fff",
  });

  return (
    <div className="quiz-box" style={{
      maxWidth: "380px", margin: "0 auto",
      background: "#fff", border: "1px solid #d0dae6",
      borderRadius: "8px", padding: "24px 28px 28px",
    }}>
      <h3 style={{
        fontSize: "17px", fontWeight: 700, color: "#1a1a1a",
        fontFamily: "Arial, sans-serif", textAlign: "center", marginBottom: "20px",
      }}>
        Solicitar consulta sobre el programa
      </h3>
      <form onSubmit={submit}>
        <div style={{ marginBottom: "10px" }}>
          <input type="text" placeholder="Tu Nombre" value={fields.nombre}
            onChange={e => { set("nombre", e.target.value); setErrors(er => ({ ...er, nombre: undefined })); }}
            style={inp(errors.nombre)} />
          {errors.nombre && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.nombre}</div>}
        </div>
        <div style={{ marginBottom: "10px" }}>
          <input type="text" placeholder="Apellidos" value={fields.apellido}
            onChange={e => { set("apellido", e.target.value); setErrors(er => ({ ...er, apellido: undefined })); }}
            style={inp(errors.apellido)} />
          {errors.apellido && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.apellido}</div>}
        </div>
        <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={inp(errors.email)} />
          {errors.email && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.email}</div>}
        </div>
        <div style={{ marginBottom: "18px" }}>
          <input type="tel" placeholder="Teléfono" value={fields.telefono}
            onChange={e => { set("telefono", e.target.value); setErrors(er => ({ ...er, telefono: undefined })); }}
            style={inp(errors.telefono)} />
          {errors.telefono && <div style={{ color: "#CC0000", fontSize: "11px", marginTop: "3px" }}>{errors.telefono}</div>}
        </div>
        <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: "4px",
          cursor: loading ? "not-allowed" : "pointer",
          fontFamily: "Arial, sans-serif",
        }}>
          {loading ? "Enviando…" : "Obtener detalles"}
        </button>
      </form>
    </div>
  );
}
