import { useEffect, useRef } from 'react';
import { useMap } from '@vis.gl/react-maplibre';
import type { IncidentCompat } from '@interfaces/incidents/IncidentsInterface';

export function FlyToController({ incident }: { incident: IncidentCompat | null }) {
  const { current: map } = useMap();
  const prevIdRef = useRef<string | null>(null);

  useEffect(() => {
    if (!map || !incident) return;
    if (prevIdRef.current === incident.id) return;
    prevIdRef.current = incident.id;
    map.flyTo({
      center: [incident.location.lon, incident.location.lat],
      zoom: 10,
      duration: 800,
    });
  }, [map, incident]);

  return null;
}
