import { useEffect } from 'react';
import { useMap } from '@vis.gl/react-maplibre';
import type { MapBounds } from '@/types/vessel';

interface MapBoundsTrackerProps {
  onBoundsChange?: (bounds: MapBounds) => void;
  onZoomChange?: (zoom: number) => void;
}

export function MapBoundsTracker({ onBoundsChange, onZoomChange }: MapBoundsTrackerProps) {
  const { current: map } = useMap();

  useEffect(() => {
    if (!map) return;

    const update = () => {
      if (onBoundsChange) {
        const b = map.getBounds();
        onBoundsChange({
          minLon: b.getWest(),
          minLat: b.getSouth(),
          maxLon: b.getEast(),
          maxLat: b.getNorth(),
        });
      }
      if (onZoomChange) {
        onZoomChange(map.getZoom());
      }
    };

    update();
    map.on('moveend', update);
    map.on('zoomend', update);

    return () => {
      map.off('moveend', update);
      map.off('zoomend', update);
    };
  }, [map, onBoundsChange, onZoomChange]);

  return null;
}
