"use client";
import "leaflet/dist/leaflet.css";
import { useMapStore } from "_store/mapStore";
import { MapContainer } from "react-leaflet";
import { BaseMaps } from "_components/map/BaseMaps";
import { ContextMenu } from "_components/map/ContextMenu";
import { MissionLayer } from "_components/map/MissionMarkers";
import { SearchElements } from "_components/map/SearchElements";
import { AircraftLayer } from "_components/map/AircraftMarker";
import { MarkerCluster } from "_components/map/_components/MarkerCluster";
import { useEffect, useRef } from "react";
import { Map as TMap } from "leaflet";

const Map = () => {
	const ref = useRef<TMap | null>(null);
	const { map, setMap } = useMapStore();
	useEffect(() => {
		// Sync map zoom and center with the map store
		if (ref.current) {
			ref.current.setView(map.center, map.zoom);
		}
	}, [map, setMap]);

	useEffect(() => {
		console.log("Map center or zoom changed");

		if (ref.current) {
			const center = ref.current?.getCenter();
			const zoom = ref.current?.getZoom();
			console.log("Map center or zoom changed", center.equals(map.center), zoom === map.zoom);
			if (!center.equals(map.center) || zoom !== map.zoom) {
				console.log("Updating map center and zoom");
				ref.current.setView(map.center, map.zoom);
			}
		}
	}, [map.center, map.zoom]);

	return (
		<MapContainer
			ref={ref}
			className="flex-1"
			center={map.center}
			zoom={map.zoom}
			fadeAnimation={false}
		>
			<BaseMaps />
			<SearchElements />
			<ContextMenu />
			<MarkerCluster />
			<MissionLayer />
			<AircraftLayer />
		</MapContainer>
	);
};

export default Map;
