/* Mapa (tab) → Radar SVG custom. Centrado en la ubicación efectiva del
   usuario (GPS o provincia manual). Muestra sólo iglesias dentro del
   alcance configurado globalmente.

   Props:
     onSelect                  → abre DetalleIglesia.
     iglesias                  → lista completa (fallback para legacy).
     iglesiasEnRango           → lista ya filtrada por alcance global.
     ubicacionEfectiva         → { estado, lat?, lng?, provincia?, ... }
     alcanceKm                 → number (preferencia del user).
     onCambiarAlcance(km)      → persiste el nuevo alcance en RTDB.
     onConfigurarUbicacion     → abre Perfil → Descubrimiento.
*/
(function () {
  const { useEffect, useState, useMemo } = React;
  const { Radar, haversineKm, bearingRad, direccionCardinal, enriquecerIglesias } = window;

  // Radios alineados con el sistema global (Perfil → Descubrimiento).
  const RADIOS = [2, 5, 10, 15, 25];

  function pinEmoji(ig) {
    const m = ig.proximo_culto && ig.proximo_culto.minutos_para_empezar;
    if (m != null && m >= -60 && m <= 0) return "🔴";
    if (m != null && m > 0 && m < 60) return "🟠";
    return "🔵";
  }

  function Mapa({ onSelect, iglesias: iglesiasProp, iglesiasEnRango, ubicacionEfectiva, alcanceKm, onCambiarAlcance, onConfigurarUbicacion }) {
    const [ahora, setAhora] = useState(() => new Date());

    // Refresh cada 60s → colores de blips y pills de tiempo.
    useEffect(() => {
      const id = setInterval(() => setAhora(new Date()), 60000);
      return () => clearInterval(id);
    }, []);

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

    const estadoUbic = (ubicacionEfectiva && ubicacionEfectiva.estado) || "sin_config";
    const ubicacionResuelta = (estadoUbic === "gps_activo" || estadoUbic === "manual_activo");
    const centro = ubicacionResuelta
      ? { lat: ubicacionEfectiva.lat, lng: ubicacionEfectiva.lng }
      : null;

    const radioKm = (typeof alcanceKm === "number" && alcanceKm > 0) ? alcanceKm : 5;

    // iglesiasEnRango ya viene filtrado desde app.jsx con distancia_km.
    // Enriquecemos para añadir proximo_culto/score y ordenar.
    const iglesiasEnriquecidas = useMemo(() => {
      const base = Array.isArray(iglesiasEnRango) ? iglesiasEnRango : [];
      if (!centro || typeof enriquecerIglesias !== "function") return base;
      return enriquecerIglesias(base, centro, ahora);
    }, [iglesiasEnRango, centro, ahora]);

    // Lista inferior con bearing/cardinal.
    const enriched = useMemo(() => {
      if (!centro) return [];
      return iglesiasEnriquecidas
        .map((ig) => {
          const d = ig.distancia_km != null
            ? ig.distancia_km
            : haversineKm(centro.lat, centro.lng, ig.lat, ig.lng);
          const θ = bearingRad(centro.lat, centro.lng, ig.lat, ig.lng);
          return { ig, d, cardinal: direccionCardinal(θ) };
        })
        .filter((x) => x.d != null)
        .sort((a, b) => a.d - b.d);
    }, [centro, iglesiasEnriquecidas]);

    // Chip click: persiste el alcance global (no sólo visual).
    const handleRadio = (km) => {
      if (typeof onCambiarAlcance === "function") onCambiarAlcance(km);
    };

    return (
      <div className="fade-in pb-24 bg-gradient-to-b from-gray-50 to-white dark:from-gray-900 dark:to-gray-950 min-h-[calc(100vh-64px)]">
        <div className="px-5 pt-4 pb-2">
          <h2 className="text-xl font-black text-[#3C3C3C] dark:text-gray-100">
            Radar de Iglesias
          </h2>
          <p className="text-xs font-semibold text-[#777] dark:text-gray-400 mt-0.5">
            {centro
              ? enriched.length + (enriched.length === 1 ? " iglesia" : " iglesias") + " en " + radioKm + " km"
              : "Activa tu ubicación o elige una provincia"}
          </p>
        </div>

        {/* Chips de radio — persisten el alcance global */}
        <div className="px-5 flex gap-2 mb-4 flex-wrap">
          {RADIOS.map((r) => {
            const activo = r === radioKm;
            return (
              <button
                key={r}
                onClick={() => handleRadio(r)}
                disabled={!centro}
                className={
                  "px-3 py-1.5 rounded-full text-xs font-black transition " +
                  (activo
                    ? "bg-[#2563EB] text-white shadow"
                    : "bg-white dark:bg-gray-800 text-[#2563EB] dark:text-blue-300 border border-[#E5E7EB] dark:border-gray-700")
                }
                style={{ opacity: centro ? 1 : 0.5, cursor: centro ? "pointer" : "default" }}
              >
                {r} km
              </button>
            );
          })}
        </div>

        {/* Sin centro resuelto: empty-state con CTA para configurar. */}
        {!centro && estadoUbic === "detectando" && (
          <div className="px-5 mt-6 text-center">
            <div className="text-sm font-semibold text-[#9AA0A6] dark:text-gray-500">
              Detectando tu ubicación…
            </div>
          </div>
        )}

        {!centro && estadoUbic !== "detectando" && (
          <div className="px-5 mt-4">
            <div className="card-soft p-6 text-center">
              <div className="text-5xl mb-2">📍</div>
              <div className="font-black text-[#3C3C3C] dark:text-gray-100">
                {estadoUbic === "gps_denegado"
                  ? "Permiso de ubicación denegado"
                  : estadoUbic === "gps_no_disponible"
                    ? "No pudimos obtener tu ubicación"
                    : "Necesitamos tu ubicación"}
              </div>
              <div className="text-sm font-semibold text-[#777] dark:text-gray-400 mt-1">
                {estadoUbic === "gps_denegado"
                  ? "Actívala en tu navegador o elige una provincia para ver el radar."
                  : "Activa tu ubicación o elige una provincia para ver el radar."}
              </div>
              <button
                type="button"
                onClick={onConfigurarUbicacion}
                className="mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#2563EB] text-white text-sm font-black active:opacity-80 transition"
              >
                <span aria-hidden>⚙️</span>
                <span>Configurar ubicación</span>
              </button>
            </div>
          </div>
        )}

        {/* Radar SVG — solo si hay centro. */}
        {centro && (
          <div className="px-4">
            <div className="mx-auto max-w-md aspect-square">
              <Radar
                iglesias={iglesiasEnriquecidas}
                centroLat={centro.lat}
                centroLng={centro.lng}
                radioKm={radioKm}
                onSelectIglesia={onSelect}
                dark={dark}
              />
            </div>
          </div>
        )}

        {/* Lista inferior */}
        {centro && (
          <div className="mt-6 px-5">
            <h3 className="text-sm font-black text-[#3C3C3C] dark:text-gray-200 mb-2 uppercase tracking-wide">
              Dentro del radio
            </h3>
            {enriched.length === 0 ? (
              <div className="card-soft p-5 text-center">
                <div className="font-black text-[#3C3C3C] dark:text-gray-100">
                  {estadoUbic === "manual_activo"
                    ? "No hay iglesias a " + radioKm + " km de " + (ubicacionEfectiva.provincia || "esta provincia")
                    : "No hay iglesias a " + radioKm + " km de ti"}
                </div>
                <div className="text-sm font-semibold text-[#777] dark:text-gray-400 mt-1">
                  Amplía el alcance para ver más resultados.
                </div>
                <button
                  type="button"
                  onClick={onConfigurarUbicacion}
                  className="mt-3 inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-[#2563EB] text-white text-xs font-black active:opacity-80 transition"
                >
                  <span aria-hidden>📏</span>
                  <span>Ampliar alcance</span>
                </button>
              </div>
            ) : (
              <ul className="divide-y divide-[#EEE] dark:divide-gray-800 bg-white dark:bg-gray-800 rounded-xl overflow-hidden card-soft">
                {enriched.map(({ ig, d, cardinal }) => (
                  <li key={ig.id}>
                    <button
                      onClick={() => onSelect && onSelect(ig)}
                      className="w-full px-4 py-3 flex items-center gap-3 text-left active:bg-[#F0F0F0] dark:active:bg-gray-700 transition"
                    >
                      <span className="text-lg flex-shrink-0" aria-hidden>{pinEmoji(ig)}</span>
                      <div className="flex-1 min-w-0">
                        <p className="font-black text-sm text-[#3C3C3C] dark:text-gray-100 truncate">
                          <span>{ig.nombre}</span>
                          {ig.reclamada === false && (
                            <span className="ml-1.5 inline-block align-middle text-[9px] font-black uppercase tracking-wider px-1.5 py-0.5 rounded bg-[#FEF3C7] text-[#92400E] dark:bg-amber-900/50 dark:text-amber-300">
                              No reclamada
                            </span>
                          )}
                        </p>
                        <p className="text-xs font-semibold text-[#777] dark:text-gray-400 mt-0.5">
                          {d < 1 ? Math.round(d * 1000) + " m" : d.toFixed(1) + " km"} · {cardinal}
                        </p>
                      </div>
                      <span className="text-[#9AA0A6]" aria-hidden>›</span>
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}
      </div>
    );
  }

  window.Mapa = Mapa;
})();
