/**
 * Map Viewport Context
 * Manages map viewport state: center, zoom, bounds
 * Separated from MapContexts.tsx for better SRP
 */

import { LatLngBounds } from 'leaflet';
import React, { createContext, ReactNode, useCallback, useContext, useState } from 'react';

interface MapViewportState {
  mapCenter: [number, number]; // [latitude, longitude]
  zoom: number;
  mapBounds: LatLngBounds | null;
}

interface MapViewportActions {
  setZoom: (zoom: number) => void;
  setMapCenter: (coords: [number, number]) => void;
  setMapBounds: (bounds: LatLngBounds | null) => void;
  resetView: () => void;
}

interface MapViewportContextType extends MapViewportState, MapViewportActions {}

const MapViewportContext = createContext<MapViewportContextType | undefined>(undefined);

export const useMapViewport = () => {
  const context = useContext(MapViewportContext);
  if (context === undefined) {
    throw new Error('useMapViewport must be used within a MapViewportProvider');
  }
  return context;
};

interface MapViewportProviderProps {
  children: ReactNode;
  initialCenter?: [number, number];
  initialZoom?: number;
}

export const MapViewportProvider = ({
  children,
  initialCenter = [54.53, 52.79], // Bugulma coordinates
  initialZoom = 13,
}: MapViewportProviderProps) => {
  const [mapCenter, setMapCenter] = useState<[number, number]>(initialCenter);
  const [zoom, setZoom] = useState<number>(initialZoom);
  const [mapBounds, setMapBounds] = useState<LatLngBounds | null>(null);

  const resetView = useCallback(() => {
    setMapCenter(initialCenter);
    setZoom(initialZoom);
    setMapBounds(null);
  }, [initialCenter, initialZoom]);

  const value: MapViewportContextType = {
    // State
    mapCenter,
    zoom,
    mapBounds,
    // Actions
    setZoom,
    setMapCenter,
    setMapBounds,
    resetView,
  };

  return <MapViewportContext.Provider value={value}>{children}</MapViewportContext.Provider>;
};
