/* global React */

// ────────────────────────────────────────────────────────────
// HOME — вариант B: «Карта-первичная»
// Top: интерактивная Leaflet карта с маркерами всех событий
//      (preview-режим, без drag/zoom). Снизу — счётчики + лента.
// ────────────────────────────────────────────────────────────
window.HomeScreenB = ({ T, dark, onOpenEvent }) => {
  const data = window.DATA.useDataState();
  const events = data.events;
  const mapRef = React.useRef(null);
  const mapId = React.useMemo(() => "map-home-b-" + Math.random().toString(36).slice(2, 8), []);

  const last = events[0];
  const ru24 = events.filter((e) => e.isRu && e.minutesAgo < 24*60).length;
  const world24 = events.filter((e) => e.minutesAgo < 24*60).length;
  const recent24 = events.filter((e) => e.minutesAgo < 24*60);
  const maxMag = recent24.length > 0 ? Math.max(...recent24.map((e) => e.mag)) : 0;

  React.useEffect(() => {
    if (!window.L || !events.length) return;
    if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
    const m = window.L.map(mapId, {
      zoomControl: false, attributionControl: false,
      dragging: false, scrollWheelZoom: false, doubleClickZoom: false,
      touchZoom: false, boxZoom: false, keyboard: false, tap: false,
    }).setView([58, 95], 2);
    const tileUrl = dark
      ? "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
      : "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png";
    window.L.tileLayer(tileUrl, { maxZoom: 8 }).addTo(m);

    events.forEach((e) => {
      const color = window.magColor(e.mag, T);
      const r = 4 + (e.mag - 4) * 4;
      window.L.circleMarker([e.lat, e.lon], {
        radius: r, color, fillColor: color, fillOpacity: 0.5, weight: 1.5,
      }).addTo(m).on("click", () => onOpenEvent(e));
    });
    mapRef.current = m;
    return () => { if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; } };
  }, [dark, events]);

  if (!events.length) {
    return (
      <div style={{ padding: 32, textAlign: "center", color: T.textMuted, fontSize: 13 }}>
        События ещё не загружены.
      </div>
    );
  }

  return (
    <div style={{ background: T.bg, color: T.text, paddingBottom: 24 }}>
      {/* Карта-герой */}
      <div style={{ position: "relative", height: 280, background: T.surface2 }}>
        <div id={mapId} style={{ position: "absolute", inset: 0 }} />

        {/* LIVE overlay top-left */}
        <div style={{
          position: "absolute", top: 12, left: 12,
          background: dark ? "rgba(14,17,22,0.85)" : "rgba(255,255,255,0.92)",
          border: `1px solid ${T.border}`, borderRadius: 8, padding: "8px 10px",
          backdropFilter: "blur(4px)", display: "flex", alignItems: "center", gap: 8,
          fontFamily: '"JetBrains Mono", monospace', fontSize: 11, zIndex: 1000,
        }}>
          <window.LivePulse color={T.ok} />
          <span style={{ color: T.textDim, letterSpacing: 0.4 }}>LIVE</span>
          <span style={{ color: T.textMuted }}>· {events.length} событий</span>
        </div>
      </div>

      {/* Счётчики 24ч */}
      <div style={{ padding: "16px 16px 0", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
        <window.Stat T={T} label="РОССИЯ / СНГ" value={ru24} hint="за 24 ч · M≥4" />
        <window.Stat T={T} label="МИР" value={world24} hint="за 24 ч · M≥4" />
        <window.Stat T={T} label="МАКС M" value={maxMag.toFixed(1)} hint="за 24 ч" highlight />
      </div>

      {/* Лента — компактная */}
      <div style={{ padding: "16px 16px 0" }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between",
          marginBottom: 8 }}>
          <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
            fontFamily: '"JetBrains Mono", monospace' }}>
            ХРОНОЛОГИЯ · {events.length} СОБЫТИЙ
          </div>
        </div>
        <div style={{ background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 10, overflow: "hidden" }}>
          {events.map((e, i, arr) => (
            <window.EventRow key={e.id || i} ev={e} T={T}
              onClick={() => onOpenEvent(e)} last={i === arr.length - 1} />
          ))}
        </div>
      </div>
    </div>
  );
};
