/* WizardMinisterio → window. Portal (zIndex 90). 3 pasos + review.
   Guarda en /users/{uid}/ministerio.

   Props:
     uid                     string (requerido)
     ministerioActual        objeto | null (para edición)
     onCerrar                () => void   — botón "Ahora no" o ✕ (solo si !forzado)
     onGuardado              (datosGuardados) => void
     forzado                 bool (default false). true = no permite cerrar sin guardar.

   Flujo:
     paso 1: ¿Tiene ministerio? Sí (avanza) / No (cierra).
     paso 2: tipos (multi).
     paso 3: alcance, disponible_para (multi), descripción, provincia, toggles
             acepta_invitaciones + visible_en_busqueda.
     paso 4 (review): resumen + botón Guardar.

   En edición se entra directamente a paso 2.
*/
(function () {
  const { useState } = React;
  const { useTheme } = window;

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

  const ALCANCE_LABEL = {
    provincial: "Provincial",
    nacional: "Nacional",
    internacional: "Internacional",
  };

  function Chip({ activo, onClick, label, color, dark }) {
    const bgOff = dark ? "#1B1B1B" : "#FFFFFF";
    const txtOff = dark ? "#E5E7EB" : INK;
    return (
      <button
        type="button"
        onClick={onClick}
        style={{
          padding: "10px 14px",
          borderRadius: 999,
          border: "2px solid " + color,
          background: activo ? color : bgOff,
          color: activo ? "#FFFFFF" : txtOff,
          fontWeight: 800,
          fontSize: 13,
          fontFamily: "inherit",
          cursor: "pointer",
          transition: "all 120ms ease",
        }}
      >
        {label}
      </button>
    );
  }

  function Toggle({ activo, onClick }) {
    return (
      <button
        type="button"
        onClick={onClick}
        aria-pressed={activo}
        style={{
          width: 44, height: 26,
          borderRadius: 999,
          background: activo ? BRAND : "#CCCCCC",
          border: "none",
          position: "relative",
          cursor: "pointer",
          transition: "background 120ms ease",
          flexShrink: 0,
        }}
      >
        <span
          style={{
            position: "absolute",
            top: 3,
            left: activo ? 21 : 3,
            width: 20, height: 20,
            borderRadius: "50%",
            background: "#FFFFFF",
            boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
            transition: "left 120ms ease",
          }}
        />
      </button>
    );
  }

  function FilaToggle({ label, descripcion, activo, onChange, dark }) {
    const txt = dark ? "#E5E7EB" : INK;
    const muted = dark ? "#9CA3AF" : MUTED;
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 800, color: txt }}>{label}</div>
          {descripcion && (
            <div style={{ fontSize: 12, color: muted, marginTop: 2, lineHeight: 1.4 }}>{descripcion}</div>
          )}
        </div>
        <Toggle activo={activo} onClick={() => onChange(!activo)} />
      </div>
    );
  }

  function WizardMinisterio({ uid, ministerioActual, onCerrar, onGuardado, forzado }) {
    const { dark } = (typeof useTheme === "function" ? useTheme() : null) || { dark: false };
    const editMode = !!(ministerioActual && typeof ministerioActual === "object");
    const base = editMode
      ? Object.assign(window.ministerioVacio(), ministerioActual)
      : window.ministerioVacio();

    // Paso inicial: en edición saltamos paso 1.
    const [paso, setPaso] = useState(editMode ? 2 : 1);
    const [tipos, setTipos] = useState(base.tipos || {});
    const [alcance, setAlcance] = useState(base.alcance || "provincial");
    const [disp, setDisp] = useState(base.disponible_para || {});
    const [descripcion, setDescripcion] = useState(base.descripcion || "");
    const [provincia, setProvincia] = useState(base.provincia || "");
    const [aceptaInv, setAceptaInv] = useState(base.acepta_invitaciones !== false);
    const [visible, setVisible] = useState(base.visible_en_busqueda !== false);
    const [guardando, setGuardando] = useState(false);
    const [error, setError] = useState("");

    const colorTexto = dark ? "#F0F0F0" : INK;
    const colorMuted = dark ? "#9CA3AF" : MUTED;
    const bgPanel = dark ? "#1F1F1F" : "#FFFFFF";
    const bgInput = dark ? "#1B1B1B" : "#FFFFFF";
    const borderInput = dark ? "#333333" : "#E5E7EB";
    const bgDegradado = dark
      ? "linear-gradient(180deg, #141415 0%, #0F0F10 60%)"
      : "linear-gradient(180deg, #F5F0FF 0%, #FFFFFF 60%)";
    const bgError = dark ? "#2A0F10" : "#FFE4E6";
    const colorError = dark ? "#FCA5A5" : DANGER;

    function alMenosUnTipo() {
      return Object.keys(tipos).some((k) => !!tipos[k]);
    }

    function toggleTipo(k) {
      setTipos(Object.assign({}, tipos, { [k]: !tipos[k] }));
    }

    function toggleDisp(k) {
      setDisp(Object.assign({}, disp, { [k]: !disp[k] }));
    }

    async function guardar() {
      if (guardando) return;
      setError("");
      if (!alMenosUnTipo()) {
        setError("Seleccione al menos un tipo de ministerio.");
        setPaso(2);
        return;
      }
      setGuardando(true);
      try {
        const datos = {
          activo: true,
          acepta_invitaciones: aceptaInv,
          visible_en_busqueda: visible,
          tipos: tipos,
          descripcion: descripcion,
          alcance: alcance,
          disponible_para: disp,
          provincia: provincia,
        };
        const fn = editMode ? window.actualizarMinisterio : window.crearMinisterio;
        if (typeof fn !== "function") throw new Error("API ministerios no disponible");
        await fn(uid, datos);
        if (typeof onGuardado === "function") onGuardado(datos);
      } catch (e) {
        console.warn("[WizardMinisterio] error al guardar:", e);
        setError("No pudimos guardar su ministerio. Intente de nuevo.");
        setGuardando(false);
      }
    }

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

    const overlay = (
      <div
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 90,
          background: bgDegradado,
          overflowY: "auto",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <div
          style={{
            width: "100%",
            maxWidth: 460,
            padding: "24px 18px 40px",
            display: "flex",
            flexDirection: "column",
            gap: 18,
          }}
        >
          {/* Header */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div
                style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: PURPLE + "1A",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 20,
                }}
                aria-hidden
              >🕊️</div>
              <div style={{ lineHeight: 1.1 }}>
                <div style={{ fontSize: 14, fontWeight: 900, color: PURPLE }}>Mi ministerio</div>
                <div style={{ fontSize: 11, color: colorMuted, marginTop: 2 }}>
                  {editMode ? "Editar perfil ministerial" : "Configuración inicial"}
                </div>
              </div>
            </div>

            {!forzado && typeof onCerrar === "function" && (
              <button
                type="button"
                onClick={onCerrar}
                aria-label="Cerrar"
                style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: "transparent", border: "none",
                  color: colorMuted, fontSize: 22, cursor: "pointer",
                  fontWeight: 700,
                }}
              >✕</button>
            )}
          </div>

          {/* Pasos */}
          {paso === 1 && renderPaso1()}
          {paso === 2 && renderPaso2()}
          {paso === 3 && renderPaso3()}
          {paso === 4 && renderReview()}

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

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

    function renderPaso1() {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 900, color: colorTexto, lineHeight: 1.25 }}>
            ¿Tiene un ministerio?
          </h1>
          <p style={{ margin: 0, fontSize: 14, color: colorMuted, fontWeight: 600, lineHeight: 1.5 }}>
            Si predica, ministra música, evangeliza o tiene un llamado activo, configure
            su perfil para que las iglesias puedan invitarlo.
          </p>

          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 6 }}>
            <button
              type="button"
              onClick={() => setPaso(2)}
              style={{
                background: PURPLE, color: "#FFFFFF",
                border: "2px solid " + PURPLE,
                borderRadius: 16, padding: "14px 16px",
                fontWeight: 900, fontSize: 15,
                fontFamily: "inherit", cursor: "pointer",
                boxShadow: "0 4px 0 " + PURPLE_SHADOW,
                textAlign: "left",
              }}
            >
              Sí, tengo un ministerio
            </button>
            <button
              type="button"
              onClick={() => { if (typeof onCerrar === "function") onCerrar(); }}
              style={{
                background: bgPanel, color: colorTexto,
                border: "2px solid " + borderInput,
                borderRadius: 16, padding: "14px 16px",
                fontWeight: 800, fontSize: 14,
                fontFamily: "inherit", cursor: "pointer",
                textAlign: "left",
              }}
            >
              Ahora no
            </button>
          </div>

          <div style={{ fontSize: 11, color: colorMuted, textAlign: "center", marginTop: 4 }}>
            Puede activarlo más tarde desde su perfil.
          </div>
        </div>
      );
    }

    function renderPaso2() {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: PURPLE, letterSpacing: 0.4 }}>
              PASO 2 DE 3
            </div>
            <h1 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 900, color: colorTexto, lineHeight: 1.25 }}>
              ¿Qué tipo de ministerio?
            </h1>
            <p style={{ margin: "6px 0 0", fontSize: 13, color: colorMuted, fontWeight: 600 }}>
              Puede seleccionar más de uno.
            </p>
          </div>

          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {Object.keys(window.TIPOS_MINISTERIO).map((k) => (
              <Chip
                key={k}
                activo={!!tipos[k]}
                onClick={() => toggleTipo(k)}
                label={window.TIPOS_MINISTERIO[k]}
                color={PURPLE}
                dark={dark}
              />
            ))}
          </div>

          <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
            {!editMode && (
              <button type="button" onClick={() => setPaso(1)} style={btnSecundario(borderInput, colorTexto, bgPanel)}>
                ← Atrás
              </button>
            )}
            <button
              type="button"
              onClick={() => {
                if (!alMenosUnTipo()) { setError("Seleccione al menos un tipo."); return; }
                setError("");
                setPaso(3);
              }}
              style={btnPrimario(PURPLE, PURPLE_SHADOW)}
            >
              Continuar →
            </button>
          </div>
        </div>
      );
    }

    function renderPaso3() {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: PURPLE, letterSpacing: 0.4 }}>
              PASO 3 DE 3
            </div>
            <h1 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 900, color: colorTexto, lineHeight: 1.25 }}>
              Detalles del ministerio
            </h1>
          </div>

          {/* Alcance */}
          <div>
            <div style={labelStyle(colorTexto)}>Alcance</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {window.ALCANCES_MINISTERIO.map((a) => (
                <Chip
                  key={a}
                  activo={alcance === a}
                  onClick={() => setAlcance(a)}
                  label={ALCANCE_LABEL[a]}
                  color={BRAND}
                  dark={dark}
                />
              ))}
            </div>
          </div>

          {/* Disponible para */}
          <div>
            <div style={labelStyle(colorTexto)}>Disponible para</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {Object.keys(window.DISPONIBILIDADES_MINISTERIO).map((k) => (
                <Chip
                  key={k}
                  activo={!!disp[k]}
                  onClick={() => toggleDisp(k)}
                  label={window.DISPONIBILIDADES_MINISTERIO[k]}
                  color={TEAL}
                  dark={dark}
                />
              ))}
            </div>
          </div>

          {/* Descripción corta */}
          <div>
            <div style={labelStyle(colorTexto)}>Breve descripción (opcional)</div>
            <textarea
              value={descripcion}
              onChange={(e) => setDescripcion(e.target.value.slice(0, 500))}
              placeholder="Ej: Predicador con énfasis en avivamiento, disponible para campañas en provincias del Cibao."
              rows={3}
              style={Object.assign({}, inputStyle(borderInput, bgInput, colorTexto), {
                resize: "vertical", minHeight: 80, fontFamily: "inherit",
              })}
              maxLength={500}
            />
            <div style={{ fontSize: 11, color: colorMuted, marginTop: 4, textAlign: "right" }}>
              {descripcion.length}/500
            </div>
          </div>

          {/* Provincia base */}
          <div>
            <div style={labelStyle(colorTexto)}>Provincia base (opcional)</div>
            <input
              type="text"
              value={provincia}
              onChange={(e) => setProvincia(e.target.value.slice(0, 80))}
              placeholder="Ej: Santo Domingo"
              style={inputStyle(borderInput, bgInput, colorTexto)}
              maxLength={80}
            />
          </div>

          {/* Toggles */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 4 }}>
            <FilaToggle
              label="Aceptar invitaciones"
              descripcion="Las iglesias pueden enviarle solicitudes para ministrar."
              activo={aceptaInv}
              onChange={setAceptaInv}
              dark={dark}
            />
            <FilaToggle
              label="Visible en búsquedas"
              descripcion="Su ministerio aparecerá en el directorio de la app."
              activo={visible}
              onChange={setVisible}
              dark={dark}
            />
          </div>

          <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
            <button type="button" onClick={() => setPaso(2)} style={btnSecundario(borderInput, colorTexto, bgPanel)}>
              ← Atrás
            </button>
            <button type="button" onClick={() => setPaso(4)} style={btnPrimario(PURPLE, PURPLE_SHADOW)}>
              Revisar →
            </button>
          </div>
        </div>
      );
    }

    function renderReview() {
      const tiposActivos = Object.keys(tipos).filter((k) => tipos[k]).map((k) => window.TIPOS_MINISTERIO[k]);
      const dispActivos = Object.keys(disp).filter((k) => disp[k]).map((k) => window.DISPONIBILIDADES_MINISTERIO[k]);

      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: PURPLE, letterSpacing: 0.4 }}>
              REVISAR Y GUARDAR
            </div>
            <h1 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 900, color: colorTexto, lineHeight: 1.25 }}>
              Confirme su ministerio
            </h1>
          </div>

          <div
            style={{
              background: bgPanel,
              border: "2px solid " + borderInput,
              borderRadius: 16,
              padding: 16,
              display: "flex", flexDirection: "column", gap: 12,
            }}
          >
            <FilaResumen titulo="Tipos" valor={tiposActivos.join(", ") || "—"} dark={dark} />
            <FilaResumen titulo="Alcance" valor={ALCANCE_LABEL[alcance] || "—"} dark={dark} />
            <FilaResumen titulo="Disponible para" valor={dispActivos.join(", ") || "—"} dark={dark} />
            {provincia && <FilaResumen titulo="Provincia" valor={provincia} dark={dark} />}
            {descripcion && <FilaResumen titulo="Descripción" valor={descripcion} dark={dark} />}
            <FilaResumen
              titulo="Acepta invitaciones"
              valor={aceptaInv ? "Sí" : "No"}
              dark={dark}
            />
            <FilaResumen
              titulo="Visible en búsquedas"
              valor={visible ? "Sí" : "No"}
              dark={dark}
            />
          </div>

          <div style={{ display: "flex", gap: 10 }}>
            <button type="button" onClick={() => setPaso(3)} style={btnSecundario(borderInput, colorTexto, bgPanel)}>
              ← Editar
            </button>
            <button
              type="button"
              onClick={guardar}
              disabled={guardando}
              style={Object.assign({}, btnPrimario(PURPLE, PURPLE_SHADOW), {
                opacity: guardando ? 0.7 : 1, cursor: guardando ? "default" : "pointer",
              })}
            >
              {guardando ? "Guardando..." : (editMode ? "Guardar cambios" : "Activar ministerio")}
            </button>
          </div>
        </div>
      );
    }
  }

  function FilaResumen({ titulo, valor, dark }) {
    const muted = dark ? "#9CA3AF" : MUTED;
    const txt = dark ? "#E5E7EB" : INK;
    return (
      <div>
        <div style={{ fontSize: 11, fontWeight: 800, color: muted, letterSpacing: 0.3, textTransform: "uppercase" }}>
          {titulo}
        </div>
        <div style={{ fontSize: 14, fontWeight: 700, color: txt, marginTop: 2, lineHeight: 1.4 }}>
          {valor}
        </div>
      </div>
    );
  }

  function labelStyle(color) {
    return { fontSize: 13, fontWeight: 800, color: color, marginBottom: 8 };
  }

  function inputStyle(border, bg, color) {
    return {
      width: "100%",
      padding: "12px 14px",
      borderRadius: 12,
      border: "2px solid " + border,
      background: bg,
      color: color,
      fontSize: 14,
      fontFamily: "inherit",
      outline: "none",
      boxSizing: "border-box",
    };
  }

  function btnPrimario(color, shadow) {
    return {
      flex: 1,
      background: color,
      color: "#FFFFFF",
      border: "2px solid " + color,
      borderRadius: 14,
      padding: "12px 14px",
      fontWeight: 900,
      fontSize: 14,
      fontFamily: "inherit",
      cursor: "pointer",
      boxShadow: "0 4px 0 " + shadow,
    };
  }

  function btnSecundario(border, color, bg) {
    return {
      background: bg,
      color: color,
      border: "2px solid " + border,
      borderRadius: 14,
      padding: "12px 14px",
      fontWeight: 800,
      fontSize: 14,
      fontFamily: "inherit",
      cursor: "pointer",
      minWidth: 88,
    };
  }

  window.WizardMinisterio = WizardMinisterio;
})();
