import { useEffect, useRef, useState } from "react"; import maplibregl from "maplibre-gl"; import { LAST_VIEW_KEY } from "./mapConfig"; import { getViewFromMap } from "./mapGeo"; import { clearAllMarkers } from "./markerManager"; export function useMapCore() { const containerRef = useRef(null); const mapRef = useRef(null); // pour les markers (utilisé aussi par usePostsEngine + MapView) const markersRef = useRef([]); const expandedElRef = useRef(null); const [viewParams, setViewParams] = useState({ center: null, radiusKm: 250, }); const [hasLastView, setHasLastView] = useState(false); useEffect(() => { if (!containerRef.current) return; const map = new maplibregl.Map({ container: containerRef.current, style: { version: 8, sources: { "carto-dark": { type: "raster", tiles: [ "https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png", ], tileSize: 256, attribution: "© OpenStreetMap contributors © CARTO", }, }, layers: [ { id: "carto-dark-layer", type: "raster", source: "carto-dark", }, ], }, center: [-95, 40], zoom: 3.5, pitch: 0, bearing: 0, antialias: true, }); // Reprise dernière vue let hadLastView = false; try { const raw = localStorage.getItem(LAST_VIEW_KEY); if (raw) { const v = JSON.parse(raw); if ( typeof v.lat === "number" && typeof v.lon === "number" && typeof v.zoom === "number" ) { map.setCenter([v.lon, v.lat]); map.setZoom(v.zoom); hadLastView = true; } } } catch { // ignore } setHasLastView(hadLastView); map.addControl(new maplibregl.NavigationControl(), "top-right"); mapRef.current = map; map.on("load", () => { const vp = getViewFromMap(map); setViewParams(vp); }); map.on("moveend", () => { const vp = getViewFromMap(map); setViewParams(vp); try { const center = vp.center; localStorage.setItem( LAST_VIEW_KEY, JSON.stringify({ lat: center[1], lon: center[0], zoom: map.getZoom(), }) ); } catch { // ignore } }); return () => { clearAllMarkers(markersRef, expandedElRef); map.remove(); mapRef.current = null; }; }, []); return { containerRef, mapRef, markersRef, expandedElRef, viewParams, hasLastView, }; }