'use client'

import { useEffect, useRef } from 'react'

interface SpotMiniMapProps {
  lat: number
  lng: number
  difficulty: string
}

const DIFF_MARKER: Record<string, string> = {
  BEGINNER:     '/brand/markers/ondevoar-marker-livre.svg',
  INTERMEDIATE: '/brand/markers/ondevoar-marker-condicionada.svg',
  ADVANCED:     '/brand/markers/ondevoar-marker-proibida.svg',
}

export function SpotMiniMap({ lat, lng, difficulty }: SpotMiniMapProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<any>(null)

  useEffect(() => {
    if (!containerRef.current || mapRef.current) return

    let destroyed = false
    ;(async () => {
      const L = (await import('leaflet')).default
      // @ts-ignore
      await import('leaflet/dist/leaflet.css')
      if (destroyed || !containerRef.current) return

      const map = L.map(containerRef.current, {
        center: [lat, lng],
        zoom: 13,
        zoomControl: false,
        scrollWheelZoom: false,
        dragging: false,
        attributionControl: false,
      })
      mapRef.current = map

      L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
        subdomains: 'abcd',
        maxZoom: 19,
      }).addTo(map)

      const iconUrl = DIFF_MARKER[difficulty] ?? '/brand/markers/ondevoar-marker-azul.svg'
      const icon = L.icon({ iconUrl, iconSize: [32, 40], iconAnchor: [16, 40] })
      L.marker([lat, lng], { icon }).addTo(map)
    })()

    return () => {
      destroyed = true
      if (mapRef.current) {
        mapRef.current.remove()
        mapRef.current = null
      }
    }
  }, [lat, lng, difficulty])

  return (
    <div
      ref={containerRef}
      style={{ width: '100%', height: 160, borderRadius: 10, overflow: 'hidden', marginBottom: 14 }}
    />
  )
}
