/**
 * Map UI Context
 * Manages UI state for the map view: sidebar, view modes, refs
 * Separated from MapContexts.tsx for better SRP
 */

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

interface MapUIState {
  isSidebarOpen: boolean;
  mapViewMode: 'organizations' | 'historical';
  addOrgButtonRef: React.RefObject<HTMLButtonElement>;
}

interface MapUIActions {
  setIsSidebarOpen: (isOpen: boolean) => void;
  setMapViewMode: (mode: 'organizations' | 'historical') => void;
  toggleSidebar: () => void;
  closeSidebar: () => void;
}

interface MapUIContextType extends MapUIState, MapUIActions {}

const MapUIContext = createContext<MapUIContextType | undefined>(undefined);

export const useMapUI = () => {
  const context = useContext(MapUIContext);
  if (context === undefined) {
    throw new Error('useMapUI must be used within a MapUIProvider');
  }
  return context;
};

interface MapUIProviderProps {
  children: ReactNode;
  defaultViewMode?: 'organizations' | 'historical';
}

export const MapUIProvider = ({
  children,
  defaultViewMode = 'organizations',
}: MapUIProviderProps) => {
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [mapViewMode, setMapViewMode] = useState<'organizations' | 'historical'>(defaultViewMode);
  const addOrgButtonRef = useRef<HTMLButtonElement>(null);

  const toggleSidebar = useCallback(() => {
    setIsSidebarOpen((prev) => !prev);
  }, []);

  const closeSidebar = useCallback(() => {
    setIsSidebarOpen(false);
  }, []);

  const value: MapUIContextType = {
    // State
    isSidebarOpen,
    mapViewMode,
    addOrgButtonRef,
    // Actions
    setIsSidebarOpen,
    setMapViewMode,
    toggleSidebar,
    closeSidebar,
  };

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