import { MapContainer, TileLayer, CircleMarker, useMap } from 'react-leaflet'
import { useEffect } from 'react'
import type L from 'leaflet'
import { getTileUrl } from './types'
import type { MovingPointInfo } from './types'

function UpdateCenter({ latlng }: { latlng: L.LatLng }) {
  const map = useMap()
  useEffect(() => { map.setView(latlng) }, [latlng, map])
  return null
}

interface Props {
  pointPosition: MovingPointInfo
}

export default function MiniMap({ pointPosition }: Props) {
  return (
    <div
      className="absolute w-[240px] h-[180px] border border-az-border rounded shadow-lg z-[1000] overflow-hidden pointer-events-none"
      style={{ top: pointPosition.y, left: pointPosition.x }}
    >
      <MapContainer center={pointPosition.latlng} zoom={18} zoomControl={false}
        className="w-full h-full" attributionControl={false}>
        <TileLayer url={getTileUrl()} crossOrigin="use-credentials" />
        <CircleMarker center={pointPosition.latlng} radius={3} color="#fa5252" />
        <UpdateCenter latlng={pointPosition.latlng} />
      </MapContainer>
    </div>
  )
}
