/* ReclamarIglesiaForm → window. Pantalla inline (mismo patrón que
   GestionarActividades / MisIglesias) que el pastor abre desde
   DetalleIglesia cuando quiere reclamar una iglesia no reclamada.

   Props:
     iglesia: objeto de iglesia con { id, nombre, lat, lng, ... }.
     onCerrar: () => void. El padre cierra el formulario.

   Submit: crea un reclamo en /reclamos/{reclamoId} con estado=pendiente.
   El superadmin lo revisa desde el Panel Superadmin → tab Reclamos.
*/
(function () {
  const { useState } = React;
  const { useAuth } = window;

  function Field({ label, children, hint }) {
    return (
      <div style={{ marginBottom: 14 }}>
        <label style={{
          display: "block",
          fontSize: 11, fontWeight: 900,
          letterSpacing: "0.15em", textTransform: "uppercase",
          color: "#6B7280",
          marginBottom: 6,
        }}>
          {label}
        </label>
        {children}
        {hint && (
          <div style={{
            fontSize: 11, fontWeight: 500,
            color: "#9CA3AF", marginTop: 4,
          }}>
            {hint}
          </div>
        )}
      </div>
    );
  }

  function ReclamarIglesiaForm({ iglesia, onCerrar }) {
    const { user } = (typeof useAuth === "function" ? useAuth() : {}) || {};

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

    const [descripcion, setDescripcion] = useState("");
    const [direccion, setDireccion] = useState("");
    const [whatsapp, setWhatsapp] = useState("");
    const [telefono, setTelefono] = useState("");
    const [notas, setNotas] = useState("");
    const [enviando, setEnviando] = useState(false);
    const [error, setError] = useState("");
    const [ok, setOk] = useState(false);

    const fieldStyle = {
      width: "100%",
      padding: "10px 12px",
      borderRadius: 10,
      border: "1px solid " + (dark ? "#2A2A2A" : "#E5E7EB"),
      background: dark ? "#1A1A1A" : "#FFFFFF",
      color: dark ? "#F0F0F0" : "#111827",
      fontFamily: "inherit",
      fontSize: 14,
      fontWeight: 600,
      outline: "none",
    };

    async function handleSubmit(e) {
      if (e && typeof e.preventDefault === "function") e.preventDefault();
      setError("");
      if (!user || !user.uid) {
        setError("Debes iniciar sesión.");
        return;
      }
      if (typeof window.crearReclamo !== "function") {
        setError("El servicio de reclamos no está disponible.");
        return;
      }
      if (descripcion.trim().length < 20) {
        setError("Describe la iglesia (mínimo 20 caracteres) para ayudarnos a validar.");
        return;
      }
      setEnviando(true);
      try {
        await window.crearReclamo(user.uid, iglesia.id, {
          iglesia_nombre: iglesia.nombre || "",
          nombre_pastor: user.displayName || "",
          email_pastor: user.email || "",
          photo_pastor: user.photoURL || "",
          whatsapp: whatsapp.trim(),
          descripcion: descripcion.trim(),
          direccion_texto: direccion.trim(),
          telefono_contacto: telefono.trim(),
          notas: notas.trim(),
        });
        setOk(true);
      } catch (err) {
        console.warn("[ReclamarIglesiaForm] error:", err);
        setError("No pudimos enviar el reclamo. Intenta más tarde.");
      } finally {
        setEnviando(false);
      }
    }

    if (ok) {
      return (
        <div className="fade-in" style={{
          padding: "32px 20px", background: dark ? "#0F0F10" : "#F9F9F9",
          minHeight: "calc(100vh - 140px)",
        }}>
          <div className="card-soft" style={{ padding: 24, textAlign: "center" }}>
            <div style={{ fontSize: 48, marginBottom: 8 }}>📨</div>
            <div style={{
              fontSize: 18, fontWeight: 900,
              color: dark ? "#F0F0F0" : "#111827",
              marginBottom: 6,
            }}>
              Reclamo enviado
            </div>
            <div style={{
              fontSize: 14, fontWeight: 600,
              color: dark ? "#9CA3AF" : "#6B7280",
              lineHeight: 1.5, marginBottom: 16,
            }}>
              Nuestro equipo revisará tu solicitud para reclamar
              <br />
              <strong>{iglesia.nombre}</strong>.
              <br />
              Te avisaremos cuando sea aprobada.
            </div>
            <button
              type="button"
              onClick={onCerrar}
              style={{
                padding: "10px 20px",
                borderRadius: 999,
                border: "none",
                background: "#2563EB",
                color: "#FFFFFF",
                fontWeight: 900,
                fontSize: 14,
                cursor: "pointer",
                fontFamily: "inherit",
              }}
            >
              Volver
            </button>
          </div>
        </div>
      );
    }

    return (
      <div className="fade-in" style={{
        padding: "16px 20px 120px",
        background: dark ? "#0F0F10" : "#F9F9F9",
        minHeight: "calc(100vh - 140px)",
      }}>
        <button
          type="button"
          onClick={onCerrar}
          style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            background: "transparent", border: "none",
            color: dark ? "#93C5FD" : "#2563EB",
            fontSize: 13, fontWeight: 800,
            cursor: "pointer", padding: 0, marginBottom: 12,
            fontFamily: "inherit",
          }}
        >
          ← Cancelar
        </button>

        <h1 style={{
          fontSize: 22, fontWeight: 900,
          color: dark ? "#F0F0F0" : "#111827",
          marginBottom: 4,
        }}>
          Reclamar iglesia
        </h1>
        <div style={{
          fontSize: 14, fontWeight: 700,
          color: dark ? "#D1D5DB" : "#374151",
          marginBottom: 4,
        }}>
          {iglesia.nombre}
        </div>
        <p style={{
          fontSize: 12, fontWeight: 500,
          color: dark ? "#9CA3AF" : "#6B7280",
          lineHeight: 1.5, marginBottom: 20,
        }}>
          Al enviar este reclamo confirmas que eres el pastor o representante
          autorizado de esta iglesia. Nuestro equipo verificará la información
          antes de aprobar.
        </p>

        <form onSubmit={handleSubmit}>
          <Field
            label="Descripción de la iglesia"
            hint="Cuéntanos sobre el ministerio, año de fundación, denominación, etc. (mínimo 20 caracteres)."
          >
            <textarea
              rows={4}
              value={descripcion}
              onChange={(e) => setDescripcion(e.target.value)}
              placeholder="Ej: Iglesia Evangélica fundada en 1998, denominación Pentecostal..."
              style={{ ...fieldStyle, resize: "vertical", minHeight: 90 }}
              maxLength={2000}
            />
          </Field>

          <Field label="Dirección completa" hint="Calle, número, sector/barrio, ciudad.">
            <input
              type="text"
              value={direccion}
              onChange={(e) => setDireccion(e.target.value)}
              placeholder="Ej: Calle Duarte #12, Sector Pantoja, Los Alcarrizos"
              style={fieldStyle}
              maxLength={400}
            />
          </Field>

          <Field label="WhatsApp de la iglesia" hint="Con código de país (ej: 18091234567).">
            <input
              type="tel"
              value={whatsapp}
              onChange={(e) => setWhatsapp(e.target.value)}
              placeholder="18091234567"
              style={fieldStyle}
              maxLength={32}
              inputMode="tel"
            />
          </Field>

          <Field label="Teléfono de contacto del pastor" hint="Nuestro equipo lo usará solo para verificar tu reclamo.">
            <input
              type="tel"
              value={telefono}
              onChange={(e) => setTelefono(e.target.value)}
              placeholder="18091234567"
              style={fieldStyle}
              maxLength={32}
              inputMode="tel"
            />
          </Field>

          <Field label="Notas adicionales" hint="Cualquier información que nos ayude a verificar (opcional).">
            <textarea
              rows={3}
              value={notas}
              onChange={(e) => setNotas(e.target.value)}
              placeholder="Ej: Sitio web, redes sociales, referencia de otra iglesia hermana..."
              style={{ ...fieldStyle, resize: "vertical", minHeight: 70 }}
              maxLength={500}
            />
          </Field>

          {error && (
            <div style={{
              padding: "10px 12px",
              borderRadius: 10,
              background: dark ? "#3F1D1D" : "#FEE2E2",
              color: dark ? "#FCA5A5" : "#B91C1C",
              fontSize: 13, fontWeight: 700,
              marginBottom: 14,
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={enviando}
            style={{
              width: "100%",
              padding: "14px 16px",
              borderRadius: 999,
              border: "none",
              background: enviando ? "#93C5FD" : "#2563EB",
              color: "#FFFFFF",
              fontWeight: 900,
              fontSize: 15,
              cursor: enviando ? "default" : "pointer",
              fontFamily: "inherit",
              letterSpacing: 0.2,
            }}
          >
            {enviando ? "Enviando..." : "Enviar reclamo"}
          </button>
        </form>
      </div>
    );
  }

  window.ReclamarIglesiaForm = ReclamarIglesiaForm;
})();
