/* RegistrarIglesia → window. Wizard de 3 pasos para crear o editar una iglesia en RTDB.
   Props: { abierto, onClose, onCreado, iglesiaInicial }
   - Si iglesiaInicial está presente → modo edición (actualizarIglesia).
   - Si no → modo creación (crearIglesia).
   - Portal a document.body, overlay full-screen. */
(function () {
  const { useState, useEffect, useMemo } = React;
  const { useAuth, BackIcon, TIPOS_CULTO } = window;

  const BRAND = "#2563EB";
  const DANGER = "#DC2626";

  const DIAS_NOMBRE = ["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"];
  const DIAS_LETRA = ["D","L","M","M","J","V","S"];
  const ORDEN_ADMIN = [1, 2, 3, 4, 5, 6, 0];

  function hhmmGreater(a, b) {
    return String(a || "").localeCompare(String(b || "")) > 0;
  }
  function fmtHora12(hhmm) {
    if (!hhmm) return "";
    const [hStr, mStr] = hhmm.split(":");
    const h = Number(hStr), m = Number(mStr);
    if (isNaN(h) || isNaN(m)) return hhmm;
    const period = h >= 12 ? "PM" : "AM";
    const hr = h % 12 || 12;
    return hr + ":" + String(m).padStart(2, "0") + " " + period;
  }

  function soloDigitos(s) {
    return (s || "").toString().replace(/\D/g, "");
  }

  function esWhatsappValido(s) {
    const d = soloDigitos(s);
    if (!d) return true; // opcional
    return d.length >= 8 && d.length <= 15;
  }

  function RegistrarIglesia({ abierto, onClose, onCreado, iglesiaInicial }) {
    const { user } = useAuth();
    const editMode = !!(iglesiaInicial && iglesiaInicial.id);

    // Create: 4 pasos (incluye horarios). Edit: 3 pasos (horarios se manejan en Gestionar).
    const TOTAL_PASOS = editMode ? 3 : 4;
    const PASO_HORARIOS = 3;
    const PASO_REVIEW = editMode ? 3 : 4;

    const [paso, setPaso] = useState(1);
    const [nombre, setNombre] = useState("");
    const [descripcion, setDescripcion] = useState("");
    const [direccion, setDireccion] = useState("");
    const [coords, setCoords] = useState(null);
    const [geoCargando, setGeoCargando] = useState(false);
    const [geoError, setGeoError] = useState("");
    const [whatsapp, setWhatsapp] = useState("");
    const [guardando, setGuardando] = useState(false);
    const [errorGuardar, setErrorGuardar] = useState("");

    // Horarios sólo en create mode (array local, se guarda tras crearIglesia).
    const [slots, setSlots] = useState([]);
    const [slotDraft, setSlotDraft] = useState({
      titulo: "", tipo: "culto", dia: 1, hora_inicio: "08:00", hora_fin: "09:00",
    });
    const [slotError, setSlotError] = useState("");

    // Imagen de portada (archivo local + preview data URL). Se sube tras crearIglesia.
    const [imagenFile, setImagenFile] = useState(null);
    const [imagenPreview, setImagenPreview] = useState("");
    const [imagenError, setImagenError] = useState("");
    const [subiendoImagen, setSubiendoImagen] = useState(false);
    const [progresoImagen, setProgresoImagen] = useState(0);

    const dark =
      typeof document !== "undefined" &&
      document.querySelector(".app-frame")?.classList.contains("dark");

    const reset = () => {
      setPaso(1);
      setNombre("");
      setDescripcion("");
      setDireccion("");
      setCoords(null);
      setGeoCargando(false);
      setGeoError("");
      setWhatsapp("");
      setGuardando(false);
      setErrorGuardar("");
      setSlots([]);
      setSlotDraft({ titulo: "", tipo: "culto", dia: 1, hora_inicio: "08:00", hora_fin: "09:00" });
      setSlotError("");
      setImagenFile(null);
      setImagenPreview("");
      setImagenError("");
      setSubiendoImagen(false);
      setProgresoImagen(0);
    };

    const cargarDesdeIglesia = (ig) => {
      setPaso(1);
      setNombre(ig.nombre || "");
      setDescripcion(ig.descripcion || "");
      setDireccion(ig.direccion_texto || "");
      setCoords(
        typeof ig.lat === "number" && typeof ig.lng === "number"
          ? { lat: ig.lat, lng: ig.lng }
          : null
      );
      setWhatsapp(ig.whatsapp || "");
      setGeoCargando(false);
      setGeoError("");
      setGuardando(false);
      setErrorGuardar("");
    };

    useEffect(() => {
      if (!abierto) return;
      const onKey = (e) => { if (e.key === "Escape" && !guardando) cerrar(); };
      document.addEventListener("keydown", onKey);
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {
        document.removeEventListener("keydown", onKey);
        document.body.style.overflow = prev;
      };
    }, [abierto, guardando]);

    useEffect(() => {
      if (!abierto) {
        reset();
        return;
      }
      if (editMode) cargarDesdeIglesia(iglesiaInicial);
      else reset();
      // eslint-disable-next-line
    }, [abierto, iglesiaInicial && iglesiaInicial.id]);

    const cerrar = () => {
      if (guardando) return;
      if (onClose) onClose();
    };

    const capturarUbicacion = () => {
      if (!("geolocation" in navigator)) {
        setGeoError("Tu dispositivo no soporta geolocalización.");
        return;
      }
      setGeoCargando(true);
      setGeoError("");
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          setCoords({
            lat: Number(pos.coords.latitude.toFixed(6)),
            lng: Number(pos.coords.longitude.toFixed(6)),
          });
          setGeoCargando(false);
        },
        (err) => {
          setGeoCargando(false);
          setGeoError(
            err && err.code === 1
              ? "Permiso denegado. Habilita la ubicación en tu navegador."
              : "No pudimos obtener tu ubicación. Intenta de nuevo."
          );
        },
        { enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }
      );
    };

    const puedeAvanzarPaso1 = nombre.trim().length >= 3;
    // Coords ahora son OPCIONALES para no bloquear cuando el navegador niega permiso.
    const puedeAvanzarPaso2 =
      direccion.trim().length >= 3 && esWhatsappValido(whatsapp);

    const siguiente = () => {
      if (paso === 1 && puedeAvanzarPaso1) setPaso(2);
      else if (paso === 2 && puedeAvanzarPaso2) setPaso(3);
      else if (paso === 3 && !editMode) setPaso(4); // horarios → review
    };

    const atras = () => {
      if (paso > 1) setPaso(paso - 1);
      else cerrar();
    };

    // --- horarios helpers (paso 3 en create mode) ---
    const slotDraftValido =
      slotDraft.titulo.trim().length > 0 &&
      !!slotDraft.tipo &&
      typeof slotDraft.dia === "number" && slotDraft.dia >= 0 && slotDraft.dia <= 6 &&
      !!slotDraft.hora_inicio && !!slotDraft.hora_fin &&
      hhmmGreater(slotDraft.hora_fin, slotDraft.hora_inicio);

    const agregarSlotLocal = () => {
      if (!slotDraftValido) {
        setSlotError(
          hhmmGreater(slotDraft.hora_fin, slotDraft.hora_inicio)
            ? "Completa todos los campos."
            : "La hora de fin debe ser posterior a la de inicio."
        );
        return;
      }
      setSlotError("");
      setSlots((arr) => arr.concat([{
        titulo: slotDraft.titulo.trim(),
        tipo: slotDraft.tipo,
        dia: slotDraft.dia,
        hora_inicio: slotDraft.hora_inicio,
        hora_fin: slotDraft.hora_fin,
        activo: true,
      }]));
      setSlotDraft({ titulo: "", tipo: "culto", dia: 1, hora_inicio: "08:00", hora_fin: "09:00" });
    };

    const quitarSlot = (idx) => {
      setSlots((arr) => arr.filter((_, i) => i !== idx));
    };

    // --- imagen helpers ---
    const onSeleccionarImagen = (e) => {
      const file = e.target.files && e.target.files[0];
      e.target.value = ""; // permite re-seleccionar el mismo archivo.
      if (!file) return;
      if (!/^image\//.test(file.type)) {
        setImagenError("Debe ser una imagen (jpg, png, webp).");
        return;
      }
      if (file.size > 10 * 1024 * 1024) {
        setImagenError("Imagen muy grande (máx 10 MB).");
        return;
      }
      setImagenError("");
      setImagenFile(file);
      const reader = new FileReader();
      reader.onload = () => setImagenPreview(String(reader.result || ""));
      reader.readAsDataURL(file);
    };

    const quitarImagen = () => {
      setImagenFile(null);
      setImagenPreview("");
      setImagenError("");
    };

    const publicar = async () => {
      if (!user || !user.uid) {
        setErrorGuardar("Debes iniciar sesión.");
        return;
      }
      const fnCrear = window.crearIglesia;
      const fnActualizar = window.actualizarIglesia;
      if (editMode ? typeof fnActualizar !== "function" : typeof fnCrear !== "function") {
        setErrorGuardar("Módulo no disponible.");
        return;
      }
      setGuardando(true);
      setErrorGuardar("");
      try {
        const datosBase = {
          nombre: nombre.trim(),
          descripcion: descripcion.trim(),
          direccion_texto: direccion.trim(),
          lat: coords ? coords.lat : null,
          lng: coords ? coords.lng : null,
          whatsapp: soloDigitos(whatsapp) ? "+" + soloDigitos(whatsapp) : "",
        };
        let idFinal;
        if (editMode) {
          await fnActualizar(iglesiaInicial.id, datosBase);
          idFinal = iglesiaInicial.id;
        } else {
          const datos = Object.assign({}, datosBase, {
            creado_por_nombre: (user.displayName || user.email || "").trim(),
            creado_por_photo: user.photoURL || "",
          });
          idFinal = await fnCrear(user.uid, datos);
          // Guardar horarios que el usuario agregó en el paso 3.
          if (slots.length > 0 && typeof window.agregarSlotHorario === "function") {
            for (let i = 0; i < slots.length; i++) {
              try {
                await window.agregarSlotHorario(idFinal, slots[i]);
              } catch (slotErr) {
                console.warn("[RegistrarIglesia] no pudimos guardar slot:", slotErr);
              }
            }
          }
        }

        // Subir imagen de portada (si el usuario seleccionó una).
        if (imagenFile && typeof window.subirImagenIglesia === "function") {
          setSubiendoImagen(true);
          setProgresoImagen(0);
          try {
            await window.subirImagenIglesia(idFinal, imagenFile, (pct) => setProgresoImagen(pct));
          } catch (imgErr) {
            console.warn("[RegistrarIglesia] no pudimos subir la imagen:", imgErr);
            // No abortamos: la iglesia ya quedó creada. Sólo avisamos.
            setErrorGuardar("Iglesia publicada, pero no pudimos subir la imagen: " + (imgErr && imgErr.message ? imgErr.message : "error desconocido"));
          }
          setSubiendoImagen(false);
        }

        setGuardando(false);
        if (onCreado) onCreado(idFinal);
        if (onClose) onClose();
      } catch (err) {
        console.error("[RegistrarIglesia] error:", err);
        setGuardando(false);
        setErrorGuardar(err && err.message ? err.message : "No pudimos guardar la iglesia.");
      }
    };

    // --- estilos reutilizables ---
    const colorTexto = dark ? "#F0F0F0" : "#111827";
    const colorSecundario = dark ? "#9CA3AF" : "#6B7280";
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const bgInput = dark ? "#1A1A1A" : "#FFFFFF";
    const bgPanel = dark ? "#0F0F10" : "#FFFFFF";

    const inputBase = {
      width: "100%",
      padding: "12px 14px",
      borderRadius: 12,
      border: "1.5px solid " + colorBorde,
      background: bgInput,
      color: colorTexto,
      fontSize: 15,
      fontWeight: 600,
      outline: "none",
      boxSizing: "border-box",
    };

    const labelStyle = {
      display: "block",
      fontSize: 12,
      fontWeight: 800,
      textTransform: "uppercase",
      letterSpacing: 0.4,
      color: colorSecundario,
      marginBottom: 6,
    };

    const btnPrimario = (habil) => ({
      width: "100%",
      padding: "14px 16px",
      borderRadius: 14,
      border: "none",
      background: habil ? BRAND : dark ? "#1F2937" : "#D1D5DB",
      color: habil ? "#FFFFFF" : dark ? "#6B7280" : "#9CA3AF",
      fontSize: 15,
      fontWeight: 800,
      cursor: habil ? "pointer" : "not-allowed",
      transition: "opacity 120ms ease",
    });

    const btnSecundario = {
      width: "100%",
      padding: "12px 16px",
      borderRadius: 14,
      border: "1.5px solid " + colorBorde,
      background: "transparent",
      color: colorTexto,
      fontSize: 14,
      fontWeight: 700,
      cursor: "pointer",
    };

    // --- render ---
    if (!abierto) return null;
    if (typeof document === "undefined") return null;

    const progreso = Math.max(0, Math.min(1, paso / TOTAL_PASOS));

    return (
      <div className="fade-in" style={{ paddingBottom: 96 }}>
        {/* Encabezado inline (sin barra fullwidth): atrás + título + paso */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "12px 16px 8px",
          }}
        >
            <button
              type="button"
              onClick={atras}
              disabled={guardando}
              aria-label="Atrás"
              style={{
                width: 32,
                height: 32,
                borderRadius: 999,
                border: "none",
                background: "transparent",
                color: colorTexto,
                cursor: guardando ? "default" : "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexShrink: 0,
                marginLeft: -6,
              }}
            >
              {BackIcon ? <BackIcon /> : <span style={{ fontSize: 20 }}>←</span>}
            </button>
            <h2
              style={{
                flex: 1,
                margin: 0,
                fontSize: 16,
                fontWeight: 800,
                color: colorTexto,
              }}
            >
              {editMode ? "Editar iglesia" : "Registrar iglesia"}
            </h2>
            <span
              style={{
                fontSize: 11,
                fontWeight: 800,
                color: colorSecundario,
                textTransform: "uppercase",
                letterSpacing: 0.4,
              }}
            >
              {paso}/{TOTAL_PASOS}
            </span>
          </div>

          {/* Barra progreso */}
          <div
            style={{
              height: 3,
              background: dark ? "#1F2937" : "#F3F4F6",
              width: "100%",
            }}
          >
            <div
              style={{
                height: "100%",
                width: (progreso * 100).toFixed(2) + "%",
                background: BRAND,
                transition: "width 200ms ease",
              }}
            />
          </div>

          {/* Cuerpo */}
          <div
            style={{
              flex: 1,
              padding: "20px 20px 24px",
              overflowY: "auto",
              WebkitOverflowScrolling: "touch",
            }}
          >
            {paso === 1 && (
              <div>
                <h3 style={{ margin: 0, fontSize: 20, fontWeight: 900, color: colorTexto }}>
                  ¿Cómo se llama tu iglesia?
                </h3>
                <p
                  style={{
                    margin: "6px 0 18px",
                    fontSize: 13,
                    fontWeight: 500,
                    color: colorSecundario,
                  }}
                >
                  Datos básicos que verán las personas al encontrarte.
                </p>

                <label style={labelStyle}>Foto de portada</label>
                <div
                  style={{
                    position: "relative",
                    width: "100%",
                    aspectRatio: "16 / 9",
                    borderRadius: 12,
                    border: "1.5px dashed " + colorBorde,
                    background: imagenPreview ? "#000" : (dark ? "#141415" : "#F3F4F6"),
                    overflow: "hidden",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    marginBottom: 8,
                  }}
                >
                  {imagenPreview ? (
                    <>
                      <img
                        src={imagenPreview}
                        alt="Portada"
                        style={{ width: "100%", height: "100%", objectFit: "cover" }}
                      />
                      <button
                        type="button"
                        onClick={quitarImagen}
                        aria-label="Quitar imagen"
                        style={{
                          position: "absolute",
                          top: 8,
                          right: 8,
                          width: 32,
                          height: 32,
                          borderRadius: 999,
                          border: "none",
                          background: "rgba(0,0,0,0.65)",
                          color: "#fff",
                          fontSize: 16,
                          fontWeight: 800,
                          cursor: "pointer",
                        }}
                      >
                        ×
                      </button>
                    </>
                  ) : (
                    <div style={{ textAlign: "center", padding: 12 }}>
                      <div style={{ fontSize: 32, marginBottom: 4 }}>📷</div>
                      <div style={{ fontSize: 12, fontWeight: 700, color: colorSecundario }}>
                        Opcional — 16:9, máx 10 MB
                      </div>
                    </div>
                  )}
                </div>
                <label
                  htmlFor="ig-img"
                  style={{
                    ...btnSecundario,
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: 6,
                    cursor: "pointer",
                    marginBottom: 6,
                  }}
                >
                  {imagenPreview ? "Cambiar imagen" : "Elegir imagen"}
                </label>
                <input
                  id="ig-img"
                  type="file"
                  accept="image/*"
                  onChange={onSeleccionarImagen}
                  style={{ display: "none" }}
                />
                {imagenError && (
                  <div
                    style={{
                      padding: "8px 12px",
                      borderRadius: 10,
                      background: dark ? "#2A0F10" : "#FEF2F2",
                      color: DANGER,
                      fontSize: 12,
                      fontWeight: 700,
                      marginBottom: 8,
                    }}
                  >
                    {imagenError}
                  </div>
                )}
                <div style={{ height: 10 }} />

                <label style={labelStyle} htmlFor="ig-nombre">Nombre *</label>
                <input
                  id="ig-nombre"
                  type="text"
                  value={nombre}
                  onChange={(e) => setNombre(e.target.value)}
                  placeholder="Nombre de tu iglesia"
                  maxLength={80}
                  style={inputBase}
                />
                <p style={{ fontSize: 11, color: colorSecundario, marginTop: 4, marginBottom: 18 }}>
                  {nombre.length}/80 — mínimo 3 caracteres
                </p>

                <label style={labelStyle} htmlFor="ig-desc">Descripción</label>
                <textarea
                  id="ig-desc"
                  value={descripcion}
                  onChange={(e) => setDescripcion(e.target.value)}
                  placeholder="Breve descripción de tu iglesia"
                  maxLength={240}
                  rows={4}
                  style={{ ...inputBase, resize: "vertical", minHeight: 90 }}
                />
                <p style={{ fontSize: 11, color: colorSecundario, marginTop: 4 }}>
                  {descripcion.length}/240 — opcional
                </p>
              </div>
            )}

            {paso === 2 && (
              <div>
                <h3 style={{ margin: 0, fontSize: 20, fontWeight: 900, color: colorTexto }}>
                  ¿Dónde queda?
                </h3>
                <p
                  style={{
                    margin: "6px 0 18px",
                    fontSize: 13,
                    fontWeight: 500,
                    color: colorSecundario,
                  }}
                >
                  Usamos tu ubicación para mostrarte en el radar.
                </p>

                <label style={labelStyle} htmlFor="ig-dir">Dirección *</label>
                <input
                  id="ig-dir"
                  type="text"
                  value={direccion}
                  onChange={(e) => setDireccion(e.target.value)}
                  placeholder="Dirección completa"
                  maxLength={120}
                  style={inputBase}
                />
                <p style={{ fontSize: 11, color: colorSecundario, marginTop: 4, marginBottom: 18 }}>
                  {direccion.length}/120
                </p>

                <label style={labelStyle}>Coordenadas *</label>
                <button
                  type="button"
                  onClick={capturarUbicacion}
                  disabled={geoCargando}
                  style={{
                    ...btnSecundario,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: 8,
                    marginBottom: 8,
                  }}
                >
                  {geoCargando ? (
                    <>
                      <span
                        style={{
                          width: 14,
                          height: 14,
                          borderRadius: "50%",
                          border: "2px solid " + colorBorde,
                          borderTopColor: BRAND,
                          display: "inline-block",
                          animation: "spin 0.8s linear infinite",
                        }}
                      />
                      Obteniendo ubicación...
                    </>
                  ) : coords ? (
                    <>📍 Ubicación capturada — tocar para repetir</>
                  ) : (
                    <>📍 Usar mi ubicación actual</>
                  )}
                </button>
                {coords && (
                  <div
                    style={{
                      padding: "10px 12px",
                      borderRadius: 10,
                      background: dark ? "#0F2A18" : "#ECFDF5",
                      color: dark ? "#6EE7B7" : "#047857",
                      fontSize: 12,
                      fontWeight: 700,
                      marginBottom: 8,
                    }}
                  >
                    ✓ Lat {coords.lat}, Lng {coords.lng}
                  </div>
                )}
                {geoError && (
                  <div
                    style={{
                      padding: "10px 12px",
                      borderRadius: 10,
                      background: dark ? "#2A0F10" : "#FEF2F2",
                      color: DANGER,
                      fontSize: 12,
                      fontWeight: 700,
                      marginBottom: 8,
                    }}
                  >
                    {geoError}
                  </div>
                )}

                <div style={{ height: 14 }} />

                <label style={labelStyle} htmlFor="ig-wa">WhatsApp</label>
                <input
                  id="ig-wa"
                  type="tel"
                  value={whatsapp}
                  onChange={(e) => setWhatsapp(e.target.value)}
                  placeholder="Número de WhatsApp"
                  inputMode="tel"
                  style={inputBase}
                />
                <p style={{ fontSize: 11, color: colorSecundario, marginTop: 4 }}>
                  {esWhatsappValido(whatsapp)
                    ? "Opcional — solo dígitos, 8 a 15"
                    : "Número inválido (8 a 15 dígitos)"}
                </p>
              </div>
            )}

            {paso === PASO_HORARIOS && !editMode && (
              <div>
                <h3 style={{ margin: 0, fontSize: 20, fontWeight: 900, color: colorTexto }}>
                  ¿Cuándo son tus cultos?
                </h3>
                <p
                  style={{
                    margin: "6px 0 18px",
                    fontSize: 13,
                    fontWeight: 500,
                    color: colorSecundario,
                  }}
                >
                  Opcional. Puedes agregarlos después desde Gestionar.
                </p>

                <label style={labelStyle} htmlFor="slot-titulo">Nombre del culto *</label>
                <input
                  id="slot-titulo"
                  type="text"
                  value={slotDraft.titulo}
                  onChange={(e) => setSlotDraft((d) => ({ ...d, titulo: e.target.value }))}
                  placeholder="Nombre del culto"
                  maxLength={60}
                  style={inputBase}
                />
                <div style={{ height: 14 }} />

                <label style={labelStyle}>Tipo</label>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
                  {Object.keys(TIPOS_CULTO || { culto: { label: "Culto" } }).map((t) => {
                    const activo = slotDraft.tipo === t;
                    const meta = (TIPOS_CULTO && TIPOS_CULTO[t]) || { label: t };
                    return (
                      <button
                        key={t}
                        type="button"
                        onClick={() => setSlotDraft((d) => ({ ...d, tipo: t }))}
                        style={{
                          padding: "6px 12px",
                          borderRadius: 999,
                          border: "1.5px solid " + (activo ? BRAND : colorBorde),
                          background: activo ? BRAND : "transparent",
                          color: activo ? "#FFFFFF" : colorTexto,
                          fontSize: 12,
                          fontWeight: 800,
                          cursor: "pointer",
                        }}
                      >
                        {meta.label}
                      </button>
                    );
                  })}
                </div>

                <label style={labelStyle}>Día</label>
                <div style={{ display: "flex", gap: 6, marginBottom: 14 }}>
                  {ORDEN_ADMIN.map((d) => {
                    const activo = slotDraft.dia === d;
                    return (
                      <button
                        key={d}
                        type="button"
                        onClick={() => setSlotDraft((dd) => ({ ...dd, dia: d }))}
                        style={{
                          flex: 1,
                          padding: "10px 0",
                          borderRadius: 10,
                          border: "1.5px solid " + (activo ? BRAND : colorBorde),
                          background: activo ? BRAND : "transparent",
                          color: activo ? "#FFFFFF" : colorTexto,
                          fontSize: 13,
                          fontWeight: 800,
                          cursor: "pointer",
                        }}
                        aria-label={DIAS_NOMBRE[d]}
                      >
                        {DIAS_LETRA[d]}
                      </button>
                    );
                  })}
                </div>

                <div style={{ display: "flex", gap: 10, marginBottom: 10 }}>
                  <div style={{ flex: 1 }}>
                    <label style={labelStyle} htmlFor="slot-ini">Inicio</label>
                    <input
                      id="slot-ini"
                      type="time"
                      value={slotDraft.hora_inicio}
                      onChange={(e) => setSlotDraft((d) => ({ ...d, hora_inicio: e.target.value }))}
                      style={inputBase}
                    />
                  </div>
                  <div style={{ flex: 1 }}>
                    <label style={labelStyle} htmlFor="slot-fin">Fin</label>
                    <input
                      id="slot-fin"
                      type="time"
                      value={slotDraft.hora_fin}
                      onChange={(e) => setSlotDraft((d) => ({ ...d, hora_fin: e.target.value }))}
                      style={inputBase}
                    />
                  </div>
                </div>

                {slotError && (
                  <div
                    style={{
                      padding: "8px 12px",
                      borderRadius: 10,
                      background: dark ? "#2A0F10" : "#FEF2F2",
                      color: DANGER,
                      fontSize: 12,
                      fontWeight: 700,
                      marginBottom: 10,
                    }}
                  >
                    {slotError}
                  </div>
                )}

                <button
                  type="button"
                  onClick={agregarSlotLocal}
                  disabled={!slotDraftValido}
                  style={{
                    ...btnSecundario,
                    borderColor: slotDraftValido ? BRAND : colorBorde,
                    color: slotDraftValido ? BRAND : colorSecundario,
                    cursor: slotDraftValido ? "pointer" : "not-allowed",
                  }}
                >
                  + Agregar horario
                </button>

                {slots.length > 0 && (
                  <div style={{ marginTop: 18 }}>
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 800,
                        textTransform: "uppercase",
                        letterSpacing: 0.4,
                        color: colorSecundario,
                        marginBottom: 8,
                      }}
                    >
                      Horarios agregados ({slots.length})
                    </div>
                    <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
                      {slots.map((s, idx) => (
                        <li
                          key={idx}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 10,
                            padding: "10px 12px",
                            border: "1px solid " + colorBorde,
                            borderRadius: 12,
                            background: dark ? "#141415" : "#F9FAFB",
                            marginBottom: 6,
                          }}
                        >
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div
                              style={{
                                fontSize: 13,
                                fontWeight: 800,
                                color: colorTexto,
                                whiteSpace: "nowrap",
                                overflow: "hidden",
                                textOverflow: "ellipsis",
                              }}
                            >
                              {s.titulo}
                            </div>
                            <div
                              style={{
                                fontSize: 11,
                                fontWeight: 700,
                                color: colorSecundario,
                                marginTop: 2,
                              }}
                            >
                              {DIAS_NOMBRE[s.dia]} · {fmtHora12(s.hora_inicio)} – {fmtHora12(s.hora_fin)}
                            </div>
                          </div>
                          <button
                            type="button"
                            onClick={() => quitarSlot(idx)}
                            aria-label="Quitar"
                            style={{
                              width: 32,
                              height: 32,
                              borderRadius: 999,
                              border: "none",
                              background: "transparent",
                              color: DANGER,
                              cursor: "pointer",
                              fontSize: 18,
                              fontWeight: 800,
                            }}
                          >
                            ×
                          </button>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            )}

            {paso === PASO_REVIEW && (
              <div>
                <h3 style={{ margin: 0, fontSize: 20, fontWeight: 900, color: colorTexto }}>
                  Revisa antes de publicar
                </h3>
                <p
                  style={{
                    margin: "6px 0 18px",
                    fontSize: 13,
                    fontWeight: 500,
                    color: colorSecundario,
                  }}
                >
                  Podrás editar estos datos más tarde.
                </p>

                {imagenPreview && (
                  <div
                    style={{
                      width: "100%",
                      aspectRatio: "16 / 9",
                      borderRadius: 12,
                      overflow: "hidden",
                      background: "#000",
                      marginBottom: 14,
                    }}
                  >
                    <img
                      src={imagenPreview}
                      alt="Portada"
                      style={{ width: "100%", height: "100%", objectFit: "cover" }}
                    />
                  </div>
                )}

                <div
                  style={{
                    border: "1.5px solid " + colorBorde,
                    borderRadius: 14,
                    padding: "14px 16px",
                    background: dark ? "#141415" : "#F9FAFB",
                  }}
                >
                  <Row label="Nombre" value={nombre || "—"} dark={dark} />
                  {descripcion && <Row label="Descripción" value={descripcion} dark={dark} multiline />}
                  <Row label="Dirección" value={direccion || "—"} dark={dark} />
                  <Row
                    label="Coordenadas"
                    value={coords ? `${coords.lat}, ${coords.lng}` : "—"}
                    dark={dark}
                  />
                  {whatsapp && (
                    <Row
                      label="WhatsApp"
                      value={"+" + soloDigitos(whatsapp)}
                      dark={dark}
                    />
                  )}
                  {!editMode && (
                    <Row
                      label="Horarios"
                      value={
                        slots.length === 0
                          ? "Ninguno (puedes agregarlos luego)"
                          : slots.length + (slots.length === 1 ? " horario" : " horarios")
                      }
                      dark={dark}
                    />
                  )}
                </div>

                {errorGuardar && (
                  <div
                    style={{
                      marginTop: 14,
                      padding: "10px 12px",
                      borderRadius: 10,
                      background: dark ? "#2A0F10" : "#FEF2F2",
                      color: DANGER,
                      fontSize: 12,
                      fontWeight: 700,
                    }}
                  >
                    {errorGuardar}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Footer fijo */}
          <div
            style={{
              padding: "12px 20px calc(12px + env(safe-area-inset-bottom, 0px))",
              borderTop: "1px solid " + colorBorde,
              background: bgPanel,
              display: "flex",
              flexDirection: "column",
              gap: 8,
            }}
          >
            {paso < PASO_REVIEW && (
              <button
                type="button"
                onClick={siguiente}
                disabled={
                  paso === 1
                    ? !puedeAvanzarPaso1
                    : paso === 2
                    ? !puedeAvanzarPaso2
                    : false
                }
                style={btnPrimario(
                  paso === 1 ? puedeAvanzarPaso1 : paso === 2 ? puedeAvanzarPaso2 : true
                )}
              >
                {paso === PASO_HORARIOS && !editMode && slots.length === 0
                  ? "Saltar"
                  : "Continuar"}
              </button>
            )}
            {paso === PASO_REVIEW && (
              <button
                type="button"
                onClick={publicar}
                disabled={guardando}
                style={btnPrimario(!guardando)}
              >
                {subiendoImagen
                  ? "Subiendo imagen " + progresoImagen + "%"
                  : guardando
                    ? (editMode ? "Guardando..." : "Publicando...")
                    : (editMode ? "Guardar cambios" : "Publicar iglesia")}
              </button>
            )}
          </div>

        {/* spinner keyframes inline */}
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  function Row({ label, value, dark, multiline }) {
    return (
      <div
        style={{
          padding: "8px 0",
          borderBottom: "1px solid " + (dark ? "#1F1F1F" : "#E5E7EB"),
        }}
      >
        <div
          style={{
            fontSize: 10,
            fontWeight: 800,
            textTransform: "uppercase",
            letterSpacing: 0.4,
            color: dark ? "#6B7280" : "#6B7280",
          }}
        >
          {label}
        </div>
        <div
          style={{
            fontSize: 14,
            fontWeight: 700,
            marginTop: 2,
            color: dark ? "#F0F0F0" : "#111827",
            wordBreak: "break-word",
            whiteSpace: multiline ? "pre-wrap" : "normal",
          }}
        >
          {value}
        </div>
      </div>
    );
  }

  window.RegistrarIglesia = RegistrarIglesia;
})();
