/* IngresarCodigo → window. Portal sobre SelectorPerfil (zIndex 96).
   Props: { onCerrar }
   Input numérico de 6 dígitos. Al validar, redirige a /i/XXXXXX para que
   AceptarInvitacion haga su trabajo (lee RTDB, muestra carta, marca usada). */
(function () {
  const { useState, useRef, useEffect } = React;
  const { useTheme } = window;

  const BRAND = "#2563EB";
  const BRAND_SHADOW = "#1E4ED8";
  const INK = "#2A2A2A";
  const MUTED = "#777";
  const DANGER = "#FF4B4B";

  function soloDigitos(s) { return String(s || "").replace(/\D+/g, "").slice(0, 6); }
  function formateado(digits) {
    if (digits.length <= 3) return digits;
    return digits.slice(0, 3) + " " + digits.slice(3);
  }

  function IngresarCodigo({ onCerrar }) {
    const { dark } = (typeof useTheme === "function" ? useTheme() : null) || { dark: false };
    const [raw, setRaw] = useState("");
    const [err, setErr] = useState("");
    const inputRef = useRef(null);

    const bgOverlay = dark ? "rgba(0, 0, 0, 0.7)" : "rgba(15, 23, 42, 0.55)";
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const colorTitulo = dark ? "#F0F0F0" : INK;
    const colorMuted = dark ? "#9CA3AF" : MUTED;
    const bgInput = dark ? "#141415" : "#F3F4F6";
    const colorInput = dark ? "#F0F0F0" : INK;
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const colorError = dark ? "#FCA5A5" : DANGER;
    const bgDisabled = dark ? "#374151" : "#CBD5E1";

    useEffect(() => {
      if (inputRef.current) {
        try { inputRef.current.focus(); } catch (_) { /* noop */ }
      }
      const onKey = (e) => { if (e.key === "Escape") onCerrar && onCerrar(); };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, [onCerrar]);

    const valido = /^\d{6}$/.test(raw);

    const validar = () => {
      if (!valido) {
        setErr("El código debe tener 6 dígitos.");
        return;
      }
      try {
        window.location.href = "/i/" + raw;
      } catch (_) {
        setErr("No se pudo abrir el enlace. Intenta de nuevo.");
      }
    };

    if (typeof document === "undefined") return null;

    const overlay = (
      <div
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 96,
          background: bgOverlay,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          padding: 16,
        }}
      >
        <div
          style={{
            width: "100%",
            maxWidth: 380,
            background: bgCard,
            borderRadius: 20,
            padding: "22px 20px",
            boxShadow: dark ? "0 20px 60px rgba(0,0,0,0.6)" : "0 20px 60px rgba(0,0,0,0.25)",
            animation: "ingcodFade 180ms ease-out",
          }}
        >
          <button
            type="button"
            onClick={onCerrar}
            aria-label="Volver"
            style={{
              background: "transparent",
              border: "none",
              color: colorMuted,
              fontSize: 13,
              fontWeight: 800,
              cursor: "pointer",
              padding: 0,
              marginBottom: 10,
            }}
          >
            ← Volver
          </button>

          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 900, color: colorTitulo, lineHeight: 1.2 }}>
            Ingrese su código
          </h2>
          <p style={{ margin: "8px 0 16px", fontSize: 13, fontWeight: 600, color: colorMuted, lineHeight: 1.4 }}>
            Digite los 6 dígitos del código de invitación que le enviamos.
          </p>

          <div style={{ position: "relative", marginBottom: 14 }}>
            <input
              ref={inputRef}
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              pattern="[0-9]*"
              value={formateado(raw)}
              onChange={(e) => {
                setErr("");
                setRaw(soloDigitos(e.target.value));
              }}
              onKeyDown={(e) => { if (e.key === "Enter") validar(); }}
              placeholder="000 000"
              style={{
                width: "100%",
                textAlign: "center",
                fontSize: 28,
                fontWeight: 900,
                letterSpacing: 8,
                color: colorInput,
                background: bgInput,
                border: "2px solid " + (err ? colorError : colorBorde),
                borderRadius: 14,
                padding: "14px 8px",
                outline: "none",
                fontFamily: "inherit",
              }}
            />
          </div>

          {err && (
            <div style={{
              fontSize: 13, color: colorError, fontWeight: 700, textAlign: "center", marginBottom: 10,
            }}>
              {err}
            </div>
          )}

          <button
            type="button"
            onClick={validar}
            disabled={!valido}
            style={{
              width: "100%",
              minHeight: 50,
              border: "none",
              borderRadius: 13,
              background: valido ? BRAND : bgDisabled,
              color: "#FFFFFF",
              fontSize: 15,
              fontWeight: 900,
              cursor: valido ? "pointer" : "not-allowed",
              boxShadow: valido ? "0 4px 0 " + BRAND_SHADOW : "none",
              letterSpacing: 0.2,
            }}
          >
            Validar código
          </button>

          <div style={{ fontSize: 11, color: colorMuted, textAlign: "center", marginTop: 10, lineHeight: 1.4 }}>
            ¿No tiene código? Vuelva y elija <strong>Solicitar registro como pastor</strong>.
          </div>
        </div>

        <style>{`
          @keyframes ingcodFade {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
          }
        `}</style>
      </div>
    );

    return ReactDOM.createPortal(overlay, document.body);
  }

  window.IngresarCodigo = IngresarCodigo;
})();
