/* SelectorPerfil → window. Portal obligatorio post-login para usuarios nuevos.
   Sin botón cerrar. Dos vistas: selector principal (3 cards) y sub-menú Pastor.
   Props: { uid, user, onElegido }
     - onElegido se dispara cuando ya se creó el perfil (amigo|miembro); App cierra.
     - Para Pastor, se abre IngresarCodigo o SolicitudPastor dentro del mismo portal
       y nunca se llama onElegido desde aquí — quienes navegan por ese camino salen
       por otro flujo (AceptarInvitacion para código, SolicitudPastor aparte).
*/
(function () {
  const { useState } = React;
  const { useTheme } = window;
  const getIngresarCodigo = () => window.IngresarCodigo;
  const getSolicitudPastor = () => window.SolicitudPastor;

  const TEAL = "#00796B";
  const TEAL_SHADOW = "#004D40";
  const BRAND = "#2563EB";
  const BRAND_SHADOW = "#1E4ED8";
  const PURPLE = "#7C3AED";
  const PURPLE_SHADOW = "#5B21B6";
  const INK = "#2A2A2A";
  const MUTED = "#777";
  const DANGER = "#FF4B4B";

  function Card({ emoji, titulo, descripcion, color, shadow, onClick, disabled, dark }) {
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const colorDesc = dark ? "#F0F0F0" : INK;
    return (
      <button
        type="button"
        onClick={onClick}
        disabled={!!disabled}
        style={{
          width: "100%",
          textAlign: "left",
          background: bgCard,
          border: "2px solid " + color,
          borderRadius: 18,
          padding: "16px 16px",
          cursor: disabled ? "default" : "pointer",
          opacity: disabled ? 0.7 : 1,
          boxShadow: "0 4px 0 " + shadow,
          display: "flex",
          gap: 14,
          alignItems: "center",
          transition: "transform 120ms ease, box-shadow 120ms ease",
          fontFamily: "inherit",
        }}
        onMouseDown={(e) => {
          if (disabled) return;
          e.currentTarget.style.transform = "translateY(2px)";
          e.currentTarget.style.boxShadow = "0 2px 0 " + shadow;
        }}
        onMouseUp={(e) => {
          e.currentTarget.style.transform = "";
          e.currentTarget.style.boxShadow = "0 4px 0 " + shadow;
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = "";
          e.currentTarget.style.boxShadow = "0 4px 0 " + shadow;
        }}
      >
        <div
          style={{
            width: 56, height: 56,
            borderRadius: 14,
            background: color + "1A",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 28,
            flexShrink: 0,
          }}
          aria-hidden
        >
          {emoji}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 900, color: color, marginBottom: 4 }}>
            {titulo}
          </div>
          <div style={{ fontSize: 13, fontWeight: 600, color: colorDesc, lineHeight: 1.4 }}>
            {descripcion}
          </div>
        </div>
      </button>
    );
  }

  function SelectorPerfil({ uid, user, onElegido }) {
    const { dark } = (typeof useTheme === "function" ? useTheme() : null) || { dark: false };
    const [vista, setVista] = useState("principal"); // "principal" | "pastor" | "codigo" | "solicitud"
    const [guardando, setGuardando] = useState(false);
    const [error, setError] = useState("");

    const colorTexto = dark ? "#F0F0F0" : INK;
    const colorMuted = dark ? "#9CA3AF" : MUTED;
    const bgDegradado = dark
      ? "linear-gradient(180deg, #141415 0%, #0F0F10 60%)"
      : "linear-gradient(180deg, #EEF4FF 0%, #FFFFFF 60%)";
    const bgError = dark ? "#2A0F10" : "#FFE4E6";
    const colorError = dark ? "#FCA5A5" : DANGER;

    async function elegir(tipo) {
      if (guardando) return;
      setError("");
      setGuardando(true);
      try {
        if (typeof window.crearPerfilInicial !== "function") {
          throw new Error("crearPerfilInicial no disponible");
        }
        await window.crearPerfilInicial(uid, user, tipo);
        if (typeof onElegido === "function") onElegido(tipo);
      } catch (e) {
        console.warn("[SelectorPerfil] error al guardar perfil:", e);
        setError("No pudimos guardar tu elección. Intenta de nuevo.");
        setGuardando(false);
      }
    }

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

    const overlay = (
      <div
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 95,
          background: bgDegradado,
          overflowY: "auto",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <div
          style={{
            width: "100%",
            maxWidth: 460,
            padding: "28px 18px 40px",
            display: "flex",
            flexDirection: "column",
            gap: 18,
          }}
        >
          {/* Branding */}
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <img
              src="/icon-192.svg"
              alt="CultoRD"
              width="44"
              height="44"
              style={{ borderRadius: 10, boxShadow: "0 3px 10px rgba(37,99,235,0.25)" }}
            />
            <div style={{ lineHeight: 1.1 }}>
              <div style={{ fontSize: 14, fontWeight: 900, color: BRAND }}>CultoRD</div>
              <div style={{ fontSize: 11, color: colorMuted, marginTop: 2 }}>
                República Dominicana
              </div>
            </div>
          </div>

          {vista === "principal" && renderPrincipal()}
          {vista === "pastor"    && renderPastor()}

          {error && (
            <div style={{
              fontSize: 13, color: colorError, fontWeight: 700, textAlign: "center",
              background: bgError, borderRadius: 12, padding: "10px 12px",
            }}>
              {error}
            </div>
          )}
        </div>

        {vista === "codigo" && getIngresarCodigo() && (
          React.createElement(getIngresarCodigo(), {
            onCerrar: () => setVista("pastor"),
          })
        )}
        {vista === "solicitud" && getSolicitudPastor() && (
          React.createElement(getSolicitudPastor(), {
            uid: uid,
            user: user,
            onCerrar: () => setVista("pastor"),
            onEnviada: () => { /* app.jsx cierra el selector cuando llega el perfil miembro */ },
          })
        )}

        <style>{`
          @keyframes selectorFade { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
        `}</style>
      </div>
    );

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

    function renderPrincipal() {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16, animation: "selectorFade 220ms ease-out" }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 24, fontWeight: 900, color: colorTexto, lineHeight: 1.2 }}>
              Bienvenido a CultoRD
            </h1>
            <p style={{ margin: "8px 0 0", fontSize: 14, color: colorMuted, fontWeight: 600 }}>
              ¿Cómo se une a la comunidad?
            </p>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <Card
              emoji="🤝"
              titulo="Amigo"
              descripcion="Quiero descubrir iglesias, horarios y actividades cerca de mí. Sin afiliación."
              color={TEAL}
              shadow={TEAL_SHADOW}
              onClick={() => elegir("amigo")}
              disabled={guardando}
              dark={dark}
            />
            <Card
              emoji="🏠"
              titulo="Miembro"
              descripcion="Pertenezco a una iglesia. Mi pastor me enviará un enlace para vincularme."
              color={BRAND}
              shadow={BRAND_SHADOW}
              onClick={() => elegir("miembro")}
              disabled={guardando}
              dark={dark}
            />
            <Card
              emoji="🕊️"
              titulo="Pastor"
              descripcion="Lidero una iglesia y quiero registrarla. Requiere validación del equipo CultoRD."
              color={PURPLE}
              shadow={PURPLE_SHADOW}
              onClick={() => setVista("pastor")}
              disabled={guardando}
              dark={dark}
            />
          </div>

          <div style={{ fontSize: 11, color: colorMuted, textAlign: "center", marginTop: 4 }}>
            Esta elección se puede ajustar con ayuda del equipo si fuera necesario.
          </div>
        </div>
      );
    }

    function renderPastor() {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 14, animation: "selectorFade 220ms ease-out" }}>
          <button
            type="button"
            onClick={() => setVista("principal")}
            style={{
              alignSelf: "flex-start",
              background: "transparent",
              border: "none",
              color: PURPLE,
              fontSize: 13,
              fontWeight: 800,
              cursor: "pointer",
              padding: "4px 2px",
            }}
          >
            ← Volver
          </button>

          <div>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 900, color: colorTexto, lineHeight: 1.2 }}>
              ¿Cómo ingresa como pastor?
            </h1>
            <p style={{ margin: "8px 0 0", fontSize: 14, color: colorMuted, fontWeight: 600 }}>
              Por seguridad, el registro de iglesias requiere validación. Elija una opción:
            </p>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <Card
              emoji="✉️"
              titulo="Tengo un código de invitación"
              descripcion="Si recibió un código de 6 dígitos del equipo CultoRD, úselo aquí para activar su cuenta de pastor."
              color={BRAND}
              shadow={BRAND_SHADOW}
              onClick={() => setVista("codigo")}
              dark={dark}
            />
            <Card
              emoji="📝"
              titulo="Solicitar registro como pastor"
              descripcion="Envíe una solicitud para que el equipo CultoRD revise y apruebe su registro como pastor."
              color={PURPLE}
              shadow={PURPLE_SHADOW}
              onClick={() => setVista("solicitud")}
              dark={dark}
            />
          </div>
        </div>
      );
    }
  }

  window.SelectorPerfil = SelectorPerfil;
})();
