import type { BasemapsControlsProps, MapComponentProps } from './types'
import { useMapStore } from './providers/map/provider'
import { useCallback } from 'react'

/**
 * Higher-Order Component that provides basemap management functionality through a render props pattern,
 * with seamless integration into CARTO's map state management system.
 *
 * @remarks
 * This component does not render any UI. It must be used in conjunction with a UI component
 * (like `BasemapsUI`) to provide the complete basemap selection experience. Supports CARTO basemaps,
 * Google Maps, and custom basemap providers.
 *
 * @example
 * ```tsx
 * <BasemapsControls mapId="my-map">
 *   {({ basemap, setBasemap }) => (
 *     <div>
 *       <p>Current basemap: {basemap}</p>
 *       <button onClick={() => setBasemap(CartoBasemaps.positron)}>Positron</button>
 *       <button onClick={() => setBasemap(CartoBasemaps.darkMatter)}>Dark Matter</button>
 *     </div>
 *   )}
 * </BasemapsControls>
 * ```
 */
export function BasemapsControls({ children, mapId }: BasemapsControlsProps) {
  const { basemap } = useMapStore((state) => state.maps[mapId]!)
  const setBasemap = useMapStore((state) => state.setBasemap)

  return children({
    basemap,
    setBasemap: useCallback(
      (basemap: NonNullable<MapComponentProps['basemap']>) =>
        setBasemap(mapId, basemap),
      [setBasemap, mapId],
    ),
  })
}
