/* global React */

// ────────────────────────────────────────────────────────────
// MAP — полный экран карты с фильтрами
// ────────────────────────────────────────────────────────────
window.MapScreen = ({ T, dark, onBack, onOpenEvent }) => {
  const data = window.DATA.useDataState();
  const events = data.events;
  const mapRef = React.useRef(null);
  const mapId = React.useMemo(() => "map-full-" + Math.random().toString(36).slice(2,8), []);
  const [minMag, setMinMag] = React.useState(4.0);
  const [region, setRegion] = React.useState("all");

  React.useEffect(() => {
    if (!window.L) return;
    if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
    const m = window.L.map(mapId, { zoomControl: false, attributionControl: false }).setView([60, 100], 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: 9 }).addTo(m);

    events.forEach(e => {
      if (e.mag < minMag) return;
      if (region === "ru" && !e.isRu) return;
      const color = window.magColor(e.mag, T);
      const r = 5 + (e.mag - 4) * 4;
      if (e.mag >= 5.0 && e.minutesAgo < 180) {
        const pulseHtml = `
          <div class="eq-pulse-wrap">
            <span class="eq-pulse-ring" style="background:${color}"></span>
            <span class="eq-pulse-ring eq-pulse-ring-2" style="background:${color}"></span>
            <span class="eq-pulse-dot" style="background:${color}; box-shadow: 0 0 8px ${color}"></span>
          </div>`;
        const icon = window.L.divIcon({
          html: pulseHtml, className: "eq-pulse-icon",
          iconSize: [40, 40], iconAnchor: [20, 20],
        });
        window.L.marker([e.lat, e.lon], { icon }).addTo(m).on("click", () => onOpenEvent(e));
      } else {
        window.L.circleMarker([e.lat, e.lon], {
          radius: r, color, fillColor: color, fillOpacity: 0.45, weight: 1.5,
        }).addTo(m).on("click", () => onOpenEvent(e));
      }
    });
    mapRef.current = m;
    return () => { if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; } };
  }, [dark, minMag, region, events]);

  const filtered = events.filter(e => e.mag >= minMag && (region === "all" || e.isRu));

  return (
    <div style={{ background: T.bg, color: T.text, height: "100%", display: "flex", flexDirection: "column" }}>
      <window.ScreenHeader title="Карта эпицентров" subtitle={`${filtered.length} событий`} onBack={onBack} T={T} />

      <div style={{
        padding: "10px 12px", display: "flex", gap: 6, background: T.surface,
        borderBottom: `1px solid ${T.borderSoft}`, overflowX: "auto",
      }}>
        {[
          { id: "all", label: "Все" },
          { id: "ru", label: "🇷🇺 Россия / СНГ" },
        ].map(r => (
          <Chip key={r.id} T={T} active={region === r.id} onClick={() => setRegion(r.id)}>{r.label}</Chip>
        ))}
        <div style={{ width: 1, background: T.borderSoft, margin: "0 4px" }} />
        {[4.0, 4.5, 5.0, 6.0].map(m => (
          <Chip key={m} T={T} active={minMag === m} onClick={() => setMinMag(m)}>M≥{m.toFixed(1)}</Chip>
        ))}
      </div>

      <div style={{ flex: 1, position: "relative", minHeight: 320, background: T.surface2 }}>
        <div id={mapId} style={{ position: "absolute", inset: 0 }} />
        {/* Compact legend in the top-right (less marker density there since
            most events cluster around Russia/SE Asia in the lower half). One
            row of dots; tap to expand a labelled view. Solid background and
            high z-index to never get visually obscured by Leaflet markers. */}
        <CompactLegend T={T} dark={dark} />
      </div>

      <div style={{ padding: "12px 16px", background: T.surface, borderTop: `1px solid ${T.borderSoft}` }}>
        <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
          fontFamily: '"JetBrains Mono", monospace', marginBottom: 8 }}>
          ВИДИМЫЕ НА КАРТЕ
        </div>
        <div style={{ display: "flex", gap: 8, overflowX: "auto", margin: "0 -16px", padding: "0 16px 4px" }}>
          {filtered.slice(0, 6).map(e => (
            <div key={e.id} onClick={() => onOpenEvent(e)} style={{
              minWidth: 160, padding: 10, borderRadius: 8, border: `1px solid ${T.border}`,
              background: T.bg, cursor: "pointer", flexShrink: 0,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <window.MagBadge mag={e.mag} T={T} size={36} />
                <div style={{ fontSize: 10, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace' }}>
                  {e.timeMsk} МСК
                </div>
              </div>
              <div style={{ fontSize: 11.5, marginTop: 6, lineHeight: 1.3,
                display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
                {e.place}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const Chip = ({ T, active, onClick, children }) => (
  <button onClick={onClick} style={{
    padding: "6px 12px", borderRadius: 14,
    border: `1px solid ${active ? T.accent : T.border}`,
    background: active ? T.accentSoft : "transparent",
    color: active ? T.accent : T.text,
    fontSize: 11.5, cursor: "pointer", whiteSpace: "nowrap",
    fontFamily: '"JetBrains Mono", monospace', fontWeight: active ? 600 : 400,
  }}>{children}</button>
);

const Legend = ({ T, c, s, v }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 3 }}>
    <span style={{ width: s, height: s, borderRadius: "50%", background: c, display: "inline-block",
      flexShrink: 0 }} />
    <span style={{ minWidth: 36 }}>{v}</span>
  </div>
);

// Compact, solid-background legend. Bottom-left of the map (less marker
// density there typically — most events cluster around Russia/SE Asia which
// is in the right half). Collapsed = colored dots + "M". Tap → full key.
const CompactLegend = ({ T, dark }) => {
  const [open, setOpen] = React.useState(false);
  const bg = dark ? "#161A21" : "#FFFFFF";
  const border = `1px solid ${T.border}`;
  const baseStyle = {
    position: "absolute", bottom: 10, left: 10,
    background: bg, border, borderRadius: 8,
    fontFamily: '"JetBrains Mono", monospace', color: T.textDim,
    cursor: "pointer", userSelect: "none",
    zIndex: 1000,  // above all Leaflet panes
    boxShadow: dark ? "0 1px 4px rgba(0,0,0,0.4)" : "0 1px 4px rgba(0,0,0,0.1)",
  };

  if (!open) {
    return (
      <div onClick={() => setOpen(true)} style={{
        ...baseStyle,
        padding: "6px 9px", display: "flex", alignItems: "center", gap: 6,
        fontSize: 10.5,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: T.textDim }} />
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: T.accent }} />
        <span style={{ width: 10, height: 10, borderRadius: "50%", background: T.warning }} />
        <span style={{ width: 12, height: 12, borderRadius: "50%", background: T.danger }} />
        <span style={{ marginLeft: 4, color: T.textMuted, fontSize: 10 }}>M</span>
      </div>
    );
  }
  return (
    <div onClick={() => setOpen(false)} style={{
      ...baseStyle,
      padding: "10px 12px", fontSize: 10.5,
    }}>
      <div style={{ fontSize: 9.5, letterSpacing: 1, color: T.textMuted, marginBottom: 6 }}>
        МАГНИТУДА · нажмите чтобы свернуть
      </div>
      <Legend T={T} c={T.textDim} s={6} v="<4.5" />
      <Legend T={T} c={T.accent} s={8} v="4.5–5" />
      <Legend T={T} c={T.warning} s={10} v="5–6" />
      <Legend T={T} c={T.danger} s={12} v="6+" />
    </div>
  );
};
