/* global React, RIFA_DATA, EquipIcon, fmtMoney, pad3 */
// (useState/useMemo/useRef/useEffect ya están en scope desde components.jsx)

// ============================================================
// SELECTOR DE BOLETOS — v2
// Universo 000–999 · selección en pares · 500 lugares
// ============================================================
function Selector({ takenSet, selected, setSelected, sectionRef, onSubmit, apiBase, vendidos, payTrigger }) {
  const D = RIFA_DATA;
  const total = D.boletos.universoTotal;          // 500 (000–499 visibles)
  const offset = D.boletos.desplazamientoPar;     // 500 — N va con N+500
  const priceLugar = D.boletos.precioLugar;
  const lockHoras = D.boletos.lockHoras;

  const [search, setSearch] = useState('');
  const [error, setError] = useState('');
  const [rolling, setRolling] = useState(false);
  const [range, setRange] = useState('todos');
  const [showPay, setShowPay] = useState(false);
  const [form, setForm] = useState({ nombre: '', telefono: '', correo: '' });
  const [copiedKey, setCopiedKey] = useState(null);
  const [busy, setBusy] = useState(false);

  const gridRef = useRef(null);
  const payRef = useRef(null);
  const panelRef = useRef(null);

  // ----- Helpers de par -----
  // Cada selección visual N (0..499) implica el par automático N+500.
  // El backend recibe el array EXPANDIDO; el frontend muestra ambos.
  const pairOf = (n) => n + offset;
  const expandPair = (arr) => arr.flatMap(n => [n, pairOf(n)]).sort((a, b) => a - b);

  // ----- Selección -----
  const numbers = useMemo(() => Array.from({ length: total }, (_, i) => i), [total]);
  const lugares = selected.length;          // cada selección = 1 lugar = 1 par
  const monto = lugares * priceLugar;
  const hasSelection = lugares > 0;

  // ----- Filtros -----
  const visible = useMemo(() => {
    if (search.trim()) {
      const q = search.trim().replace(/^0+/, '') || '0';
      const qPadded = search.trim();
      return numbers.filter(n =>
        String(n).includes(q) || pad3(n).includes(qPadded)
      );
    }
    if (range !== 'todos') {
      const start = Number(range) * 100;
      return numbers.filter(n => n >= start && n < start + 100);
    }
    return numbers;
  }, [numbers, search, range]);

  // ----- Acciones -----
  function togglePick(n) {
    setError('');
    if (takenSet.has(n)) {
      setError('Ese número ya está apartado, elige otro.');
      return;
    }
    setSelected(prev => {
      if (prev.includes(n)) {
        return prev.filter(x => x !== n);
      }
      return [...prev, n];
    });
  }

  function handleRandom() {
    setError('');
    const available = numbers.filter(n => !takenSet.has(n) && !selected.includes(n));
    if (available.length < 1) {
      setError('Ya no quedan lugares libres.');
      return;
    }

    // Scroll al panel ANTES de la animación, para que el usuario vea cómo cambia.
    if (panelRef.current) {
      const top = panelRef.current.getBoundingClientRect().top + window.scrollY - 16;
      window.scrollTo({ top, behavior: 'smooth' });
    }

    // Damos tiempo al scroll smooth para llegar antes de iniciar el "ruleteo".
    setTimeout(() => {
      setRolling(true);
      const finalPick = available[Math.floor(Math.random() * available.length)];
      let i = 0;
      const initialSelected = [...selected];
      const tick = setInterval(() => {
        i++;
        const c = available[Math.floor(Math.random() * available.length)];
        setSelected([...initialSelected, c]);
        if (i >= 12) {
          clearInterval(tick);
          setSelected([...initialSelected, finalPick]);
          setRolling(false);
        }
      }, 65);
    }, 350);
  }

  function removePick(n) {
    setSelected(prev => prev.filter(x => x !== n));
  }
  function clearAll() {
    setSelected([]);
    setShowPay(false);
  }

  // ----- Pago -----
  function handlePay() {
    setError('');
    if (selected.length === 0) {
      setError('Aún no eliges ningún lugar.');
      return;
    }
    setShowPay(true);
    setTimeout(() => {
      if (payRef.current) {
        const top = payRef.current.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 80);
  }

  function copy(label, value) {
    try {
      navigator.clipboard.writeText(value);
      setCopiedKey(label);
      setTimeout(() => setCopiedKey(null), 1400);
    } catch (e) { /* ignore */ }
  }

  // ----- Submit — POST /api/reservar -----
  async function submit(forMethod) {
    if (busy) return;
    setError('');

    const nombre = form.nombre.trim();
    if (nombre.length < 3) {
      setError('Falta tu nombre (mínimo 3 caracteres).');
      return;
    }

    // Normaliza WhatsApp a 10 dígitos. Acepta espacios, guiones, +52, prefijo 1.
    const digits = form.telefono.replace(/\D/g, '');
    let tel10 = digits;
    if (digits.length === 12 && digits.startsWith('521')) tel10 = digits.slice(2);
    else if (digits.length === 11 && digits.startsWith('52')) tel10 = digits.slice(2);
    else if (digits.length === 11 && digits.startsWith('1')) tel10 = digits.slice(1);
    if (!/^\d{10}$/.test(tel10)) {
      setError('WhatsApp debe ser 10 dígitos (ej. 81 1234 5678).');
      return;
    }

    const correo = form.correo.trim();
    if (correo && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(correo)) {
      setError('Correo no válido. Déjalo vacío si prefieres.');
      return;
    }

    const numeros = expandPair(selected);
    if (numeros.length < 2 || numeros.length % 2 !== 0) {
      setError('Selecciona al menos un lugar.');
      return;
    }

    setBusy(true);
    try {
      const r = await fetch(`${apiBase}/api/reservar`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          numeros,
          nombre,
          telefono: tel10,
          correo: correo || undefined,
          metodo_pago: forMethod,
        }),
      });
      const data = await r.json().catch(() => ({}));

      if (r.status === 201) {
        onSubmit({
          method: forMethod,
          numbers: numeros,
          form: { nombre, telefono: tel10, correo },
          amount: monto,
          reservationId: data.id,
          reservadoHasta: data.reservado_hasta,
          whatsappUrl: data.whatsapp_url,
        });
        // Reset del formulario y panel de pago para el siguiente cliente
        setForm({ nombre: '', telefono: '', correo: '' });
        setShowPay(false);
        setError('');
      } else if (r.status === 409) {
        const list = (data.ocupados || []).map(n => `#${pad3(n)}`).join(', ');
        setError(list
          ? `Acaban de apartar ${list}. Quita esos y elige otros.`
          : (data.message || 'Esos números ya están apartados.'));
      } else if (r.status === 400 && Array.isArray(data.issues)) {
        setError(data.issues.map(i => i.message).join(' · '));
      } else {
        setError(data.error
          ? `Error: ${data.error}. Inténtalo otra vez.`
          : `Error ${r.status}. Inténtalo otra vez.`);
      }
    } catch (e) {
      setError('No se pudo conectar con el servidor. Revisa tu internet.');
    } finally {
      setBusy(false);
    }
  }

  // ----- Scroll al panel "Tus boletos seleccionados" cuando se AGREGA un lugar -----
  // (cuando se quita, no se mueve la página — el usuario ya está viendo el panel)
  const prevSelLength = useRef(0);
  useEffect(() => {
    const grew = selected.length > prevSelLength.current;
    prevSelLength.current = selected.length;
    if (!grew || rolling) return;
    setTimeout(() => {
      if (panelRef.current) {
        const top = panelRef.current.getBoundingClientRect().top + window.scrollY - 16;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 60);
  }, [selected.length, rolling]);

  // ----- Trigger remoto del FloatCta para abrir el flujo de pago -----
  // Cuando `payTrigger` se incrementa desde App.jsx (botón Pagar del banner flotante),
  // disparamos el mismo handlePay() que usa el botón grande del Selector.
  useEffect(() => {
    if (payTrigger > 0) handlePay();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [payTrigger]);

  // ----- Highlight animation cuando se selecciona -----
  useEffect(() => {
    if (!selected.length) return;
    const last = selected[selected.length - 1];
    const el = document.querySelector(`[data-ticket="${last}"]`);
    if (el) {
      el.classList.remove('highlight');
      void el.offsetWidth;
      el.classList.add('highlight');
    }
  }, [selected]);

  // ----- Render grid con headers de rango cuando "Todos" -----
  // Universo visible: 000–499 (5 rangos de 100)
  const gridContent = useMemo(() => {
    if (search.trim() || range !== 'todos') {
      return visible.map(n => renderCell(n, takenSet, selected, togglePick, offset));
    }
    const out = [];
    for (let r = 0; r < 5; r++) {
      out.push(
        <div className="range-header" key={`h-${r}`}>
          Rango <b>{r}00–{r}99</b> <span style={{ opacity: 0.6, fontWeight: 400 }}>(+ pares con +500)</span>
        </div>
      );
      for (let n = r * 100; n < r * 100 + 100; n++) {
        out.push(renderCell(n, takenSet, selected, togglePick, offset));
      }
    }
    return out;
    // eslint-disable-next-line
  }, [visible, takenSet, selected, search, range]);

  function jumpRange(r) {
    setRange(r);
    setSearch('');
    setTimeout(() => {
      if (gridRef.current) {
        const top = gridRef.current.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 60);
  }

  return (
    <section id="selector" ref={sectionRef} className="selector-section">
      <div className="container">
        <div className="selector-header">
          <div>
            <span className="eyebrow">Aparta tu lugar</span>
            <h2 className="section-title">Elige tu<br/>número de la suerte.</h2>
            <p className="section-sub">
              Tócale al número que te late del <b style={{ color: 'var(--y)' }}>000 al 499</b>. Tu segundo número del par sale automático: <b style={{ color: 'var(--y)' }}>tu número + 500</b>. Cada lugar son 2 oportunidades por $2,400. Los grises ya están apartados.
            </p>
          </div>
          <div className="selector-meta">
            <span className="legend"><span className="sw free"></span>Libre</span>
            <span className="legend"><span className="sw selected"></span>Tu lugar</span>
            <span className="legend"><span className="sw taken"></span>Apartado</span>
          </div>
        </div>

        {/* Contador de lugares vendidos — estilo grande como el del Hero, sin la fecha al lado */}
        <div className="dual-counter">
          <div className="label">Lugares vendidos</div>
          <div className="counter-row">
            <span className="counter-sold">{String(vendidos).padStart(3, '0')}</span>
            <span className="counter-sep">/</span>
            <span className="counter-total">{D.boletos.lugaresTotales}</span>
          </div>
          <div className="counter-bar"><div style={{ width: `${(vendidos / D.boletos.lugaresTotales) * 100}%` }}></div></div>
        </div>

        {/* Toolbar (buscador + dado al azar, prominente arriba para llamar a la acción) */}
        <div className="selector-toolbar">
          <div
            className="search-box search-box-btn"
            role="button"
            tabIndex={0}
            onClick={() => {
              if (document.activeElement && typeof document.activeElement.blur === 'function') {
                document.activeElement.blur();
              }
              if (gridRef.current) {
                const top = gridRef.current.getBoundingClientRect().top + window.scrollY - 16;
                window.scrollTo({ top, behavior: 'smooth' });
              }
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                e.currentTarget.click();
              }
            }}
          >
            <svg className="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            <div className="search-input-wrap">
              <span className="search-placeholder-fake" aria-hidden="true">
                Busca tu número<br/><span className="hint">(000–499)</span>
              </span>
            </div>
          </div>
          <button
            type="button"
            className={`btn-random ${rolling ? 'is-rolling' : ''}`}
            onClick={handleRandom}
            disabled={rolling}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="2.5" y="2.5" width="19" height="19" rx="3"/>
              <circle cx="8" cy="8" r="1.4" fill="currentColor" stroke="none"/>
              <circle cx="16" cy="8" r="1.4" fill="currentColor" stroke="none"/>
              <circle cx="8" cy="16" r="1.4" fill="currentColor" stroke="none"/>
              <circle cx="16" cy="16" r="1.4" fill="currentColor" stroke="none"/>
              <circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"/>
            </svg>
            {rolling ? 'Girando…' : 'Al azar'}
          </button>
        </div>

        {/* Panel de selección — qué llevas en el carrito */}
        <div ref={panelRef} className="selection-panel">
          <div className="sp-header">
            <h3>Tus boletos seleccionados</h3>
            {selected.length > 0 && (
              <button className="sp-clear" onClick={clearAll}>Limpiar selección</button>
            )}
          </div>

          {/* Chips — cada uno muestra el par completo #N + #(N+500) */}
          <div className="chips">
            {selected.length === 0 && (
              <span className="chips-empty">
                Tócale a un número del grid o usa <b style={{ color: 'var(--y)' }}>Al azar</b>
              </span>
            )}
            {[...selected].sort((a,b)=>a-b).map(n => (
              <span className="chip-pair" key={n}>
                <span className="chip-num">#{pad3(n)}</span>
                <span className="chip-plus">+</span>
                <span className="chip-num">#{pad3(pairOf(n))}</span>
                <button className="chip-remove" onClick={() => removePick(n)} aria-label={`Quitar lugar ${pad3(n)}`}>×</button>
              </span>
            ))}
          </div>

          {/* Status / wording dinámico */}
          {selected.length === 0 && (
            <div className="sp-status">
              Aún no eliges ningún lugar. Cada lugar incluye <b>2 números</b> (el que elijas + su par <b>+500</b>) por <b>${fmtMoney(priceLugar)}</b> — el doble de probabilidad de ganar.
            </div>
          )}
          {selected.length === 1 && (
            <div className="sp-status">
              Tu lugar <b>#{pad3(selected[0])}</b> + <b>#{pad3(pairOf(selected[0]))}</b> queda apartado a tu nombre. Completa tu pago para confirmarlo. (Si quieres más lugares, sigue eligiendo del grid.)
            </div>
          )}
          {selected.length > 1 && (
            <div className="sp-status">
              Tus <b>{selected.length} lugares</b> = <b>{selected.length * 2} números</b> quedan apartados a tu nombre. Son <b>{selected.length} oportunidades dobles</b> de ganar.
            </div>
          )}

          {/* Sumario y reservado */}
          {selected.length > 0 && (
            <>
              <div className="sp-summary">
                <div>
                  <span className="k">Lugares</span>
                  <span className="v">{selected.length}</span>
                </div>
                <div>
                  <span className="k">Números reales</span>
                  <span className="v">{selected.length * 2}</span>
                </div>
                <div>
                  <span className="k">Total a pagar</span>
                  <span className="v y">${fmtMoney(monto)}</span>
                </div>
              </div>


              <div className="pay-cta-row">
                <button
                  className="btn-gold is-lg"
                  onClick={handlePay}
                >
                  {payButtonLabel(selected, monto, pairOf)}
                  <span aria-hidden="true">→</span>
                </button>
              </div>
            </>
          )}

          {error && (
            <div className="error-inline">⚠ {error}</div>
          )}
        </div>

        {/* Range chips — 5 rangos del universo visible 000–499 */}
        <div className="range-chips" role="tablist" aria-label="Rangos de números">
          <button
            className={`range-chip ${range === 'todos' && !search ? 'active' : ''}`}
            onClick={() => jumpRange('todos')}
          >Todos</button>
          {Array.from({ length: 5 }, (_, r) => (
            <button
              key={r}
              className={`range-chip ${range === String(r) && !search ? 'active' : ''}`}
              onClick={() => jumpRange(String(r))}
            >
              {r}00–{r}99
            </button>
          ))}
        </div>

        {/* Grid */}
        <div className="tickets-grid" ref={gridRef} role="listbox" aria-label="Boletos disponibles">
          {gridContent}
          {visible.length === 0 && (
            <div style={{ gridColumn: '1 / -1', padding: 40, textAlign: 'center', color: 'var(--ink-dim)' }}>
              No encontramos ese número. Borra la búsqueda para ver todos.
            </div>
          )}
        </div>

        {/* Flujo de apartado — directo a captura de datos + transferencia.
            La elección manual de método (transferencia vs efectivo) se eliminó:
            el cliente que quiera efectivo coordina por WhatsApp directamente. */}
        {showPay && hasSelection && (
          <div className="pay-methods" ref={payRef}>
            {/* Datos del comprador */}
            <div className="pm-body" style={{ marginBottom: 14 }}>
              <p className="lead">
                <b>Tus datos.</b> Para apartar a tu nombre y mandarte tus boletos por WhatsApp en cuanto se confirme el pago.
              </p>
              <div className="form-grid">
                <div className="field">
                  <label>Nombre completo</label>
                  <input
                    type="text"
                    placeholder="Ej. Andrea Hernández"
                    value={form.nombre}
                    onChange={(e) => setForm({ ...form, nombre: e.target.value })}
                  />
                </div>
                <div className="field">
                  <label>WhatsApp</label>
                  <input
                    type="tel"
                    inputMode="tel"
                    placeholder="81 1234 5678"
                    value={form.telefono}
                    onChange={(e) => setForm({ ...form, telefono: e.target.value })}
                  />
                </div>
                <div className="field full">
                  <label>Correo (opcional)</label>
                  <input
                    type="email"
                    placeholder="tu.correo@ejemplo.com"
                    value={form.correo}
                    onChange={(e) => setForm({ ...form, correo: e.target.value })}
                  />
                </div>
              </div>
              <div className="pay-cta-row" style={{ marginTop: 18 }}>
                <button
                  className="btn-gold is-lg"
                  onClick={() => submit('transferencia')}
                  disabled={busy}
                >
                  {busy ? 'Apartando…' : 'Confirma tu orden'}
                  <span aria-hidden="true">→</span>
                </button>
              </div>
            </div>

            <PayTransferencia
              pagos={D.pagos}
              numbers={selected}
              monto={monto}
              copy={copy}
              copiedKey={copiedKey}
              onConfirm={() => submit('transferencia')}
            />

            {busy && <div className="error-inline" style={{ marginTop: 14, opacity: 0.8 }}>⏳ Apartando tu lugar…</div>}
            {!busy && error && <div className="error-inline" style={{ marginTop: 14 }}>⚠ {error}</div>}
          </div>
        )}
      </div>
    </section>
  );
}

// ----------------------------------------------------------
// Render de una celda — muestra el par +500 como hint
// ----------------------------------------------------------
function renderCell(n, takenSet, selected, togglePick, offset) {
  const taken = takenSet.has(n);
  const sel = selected.includes(n);
  const cls = `ticket ${taken ? 'taken' : ''} ${sel ? 'selected' : ''}`.trim();
  const pairLabel = `${pad3(n)} + ${pad3(n + offset)}`;
  return (
    <button
      key={n}
      type="button"
      className={cls}
      data-ticket={n}
      onClick={() => togglePick(n)}
      disabled={taken}
      aria-pressed={sel}
      aria-label={`Lugar ${pairLabel}${taken ? ' (apartado)' : sel ? ' (seleccionado)' : ''}`}
      title={taken ? `Lugar ${pairLabel} — apartado` : `Lugar ${pairLabel}`}
    >
      {pad3(n)}
    </button>
  );
}

// ----------------------------------------------------------
// Label dinámico del botón de pago
// ----------------------------------------------------------
function payButtonLabel(selected, monto, pairOf) {
  if (selected.length === 1) {
    const n = selected[0];
    return `Pagar mi lugar #${pad3(n)} + #${pad3(pairOf(n))} — $${fmtMoney(monto)}`;
  }
  return `Pagar mis ${selected.length} lugares — $${fmtMoney(monto)}`;
}

// ============================================================
// PAY: Transferencia bancaria
// ============================================================
function PayTransferencia({ pagos, numbers, monto, copy, copiedKey, onConfirm }) {
  // `numbers` viene como N base (0..499). Construimos el concepto en el formato
  // que pidió Julio: "SP <n> y <n+500>" por cada lugar elegido, separados por coma.
  // Sin pad3 (sin ceros a la izquierda) y con "y" como conector.
  const offset = RIFA_DATA.boletos.desplazamientoPar;
  const sortedBase = [...numbers].sort((a, b) => a - b);
  const concepto = 'SP ' + sortedBase.map(n => `${n} y ${n + offset}`).join(', ');
  // Para el listado visual al cliente, mostramos los pares completos.
  const sorted = [...numbers].flatMap(n => [n, n + offset]).sort((a, b) => a - b);
  const message = encodeURIComponent(
    `¡Hola! Acabo de hacer mi transferencia para Rifa San Pedro.\n\n` +
    `Mis boletos: ${sorted.map(n => '#' + pad3(n)).join(', ')}\n` +
    `Monto: $${fmtMoney(monto)} MXN\n\n` +
    `Aquí va mi comprobante 👇`
  );
  const waLink = `${RIFA_DATA.contacto.whatsappLink}?text=${message}`;

  return (
    <div className="pm-body">
      <p className="lead">
        Transfiere a esta cuenta y mándanos tu comprobante por WhatsApp. Te confirmamos en <b>menos de 24 horas</b>.
      </p>

      <div className="bank-rows">
        <div className="br">
          <span className="k">Banco</span>
          <span className="v">{pagos.banco}</span>
          <span></span>
        </div>
        <div className="br">
          <span className="k">Beneficiario</span>
          <span className="v">{pagos.beneficiario}</span>
          <span></span>
        </div>
        <div className="br">
          <span className="k">CLABE</span>
          <span className="v">{pagos.clabe}</span>
          <button className={`cp ${copiedKey === 'clabe' ? 'copied' : ''}`} onClick={() => copy('clabe', pagos.clabe)}>
            {copiedKey === 'clabe' ? '✓ Copiada' : 'Copiar'}
          </button>
        </div>
        {pagos.oxxo && (
          <div className="br">
            <span className="k">Pago en OXXO</span>
            <span className="v">{pagos.oxxo}</span>
            <button className={`cp ${copiedKey === 'oxxo' ? 'copied' : ''}`} onClick={() => copy('oxxo', pagos.oxxo)}>
              {copiedKey === 'oxxo' ? '✓ Copiada' : 'Copiar'}
            </button>
          </div>
        )}
        {pagos.cuenta && (
          <div className="br">
            <span className="k">Cuenta</span>
            <span className="v">{pagos.cuenta}</span>
            <button className={`cp ${copiedKey === 'cuenta' ? 'copied' : ''}`} onClick={() => copy('cuenta', pagos.cuenta)}>
              {copiedKey === 'cuenta' ? '✓ Copiada' : 'Copiar'}
            </button>
          </div>
        )}
        <div className="br">
          <span className="k">Monto</span>
          <span className="v y">${fmtMoney(monto)} MXN</span>
          <span></span>
        </div>
        <div className="br">
          <span className="k">Concepto</span>
          <span className="v">{concepto}</span>
          <button className={`cp ${copiedKey === 'concepto' ? 'copied' : ''}`} onClick={() => copy('concepto', concepto)}>
            {copiedKey === 'concepto' ? '✓ Copiado' : 'Copiar'}
          </button>
        </div>
      </div>

      <div className="pm-tagline">
        <b>Sube tu comprobante por WhatsApp</b> para que validemos tu pago. Tus números quedan apartados a tu nombre hasta que confirmemos el pago.
      </div>
    </div>
  );
}

// ============================================================
// PAY: Efectivo
// ============================================================
function PayEfectivo({ numbers, monto, onConfirm }) {
  // Expandir al par +500 para mostrar el listado completo al organizador
  const offset = RIFA_DATA.boletos.desplazamientoPar;
  const sorted = [...numbers].flatMap(n => [n, n + offset]).sort((a, b) => a - b);
  const message = encodeURIComponent(
    `¡Hola! Quiero pagar en efectivo para Rifa San Pedro.\n\n` +
    `Mis boletos: ${sorted.map(n => '#' + pad3(n)).join(', ')}\n` +
    `Monto: $${fmtMoney(monto)} MXN\n\n` +
    `¿Cuándo y dónde nos vemos?`
  );
  const waLink = `${RIFA_DATA.contacto.whatsappLink}?text=${message}`;

  return (
    <div className="pm-body">
      <p className="lead">
        Coordinamos el pago en efectivo por WhatsApp — nos vemos en San Pedro Garza García, N.L. o área metropolitana. Te confirmamos los boletos en cuanto recibimos el pago.
      </p>
      <div className="pm-tagline">
        <b>El pago en efectivo se valida en persona.</b> Recibirás confirmación por WhatsApp el mismo día de la entrega del efectivo. Tus números quedan apartados a tu nombre hasta que confirmemos.
      </div>
      <div className="pm-actions">
        <a className="btn-wa" href={waLink} target="_blank" rel="noreferrer" onClick={() => setTimeout(onConfirm, 100)}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M20.5 3.5A11 11 0 0 0 3.6 17.3L2 22l4.8-1.5A11 11 0 1 0 20.5 3.5ZM12 20.2c-1.7 0-3.4-.4-4.8-1.3l-.3-.2-2.9.9.9-2.8-.2-.3A8.9 8.9 0 1 1 12 20.2Z"/></svg>
          Coordinar pago en efectivo
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { Selector });
