import { useEffect, useRef } from 'react'
import maplibregl, { type StyleSpecification } from 'maplibre-gl'
import { Protocol, PMTiles } from 'pmtiles'
import 'maplibre-gl/dist/maplibre-gl.css'

/**
 * Minimalus, BE ŠRIFTŲ (glyphs) stilius — kad žemėlapis veiktų visiškai
 * atjungtas nuo interneto. Be teksto sluoksnių, tik geometrija: žemė,
 * vanduo, žemėnauda, keliai, pastatai. Sluoksniai, kurių nėra konkrečiame
 * PMTiles faile, tiesiog nerodomi (klaidos nesukelia).
 */
const STYLE_LAYERS: StyleSpecification['layers'] = [
  { id: 'bg', type: 'background', paint: { 'background-color': '#0b0f14' } },
  { id: 'earth', type: 'fill', source: 'src', 'source-layer': 'earth', paint: { 'fill-color': '#1c2736' } },
  {
    id: 'landcover',
    type: 'fill',
    source: 'src',
    'source-layer': 'landcover',
    paint: { 'fill-color': '#1d3326', 'fill-opacity': 0.55 },
  },
  {
    id: 'landuse',
    type: 'fill',
    source: 'src',
    'source-layer': 'landuse',
    paint: { 'fill-color': '#233042', 'fill-opacity': 0.5 },
  },
  { id: 'water', type: 'fill', source: 'src', 'source-layer': 'water', paint: { 'fill-color': '#1f6091' } },
  {
    id: 'buildings',
    type: 'fill',
    source: 'src',
    'source-layer': 'buildings',
    paint: { 'fill-color': '#33404f' },
  },
  {
    id: 'roads',
    type: 'line',
    source: 'src',
    'source-layer': 'roads',
    paint: {
      'line-color': '#8499ad',
      'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.5, 12, 1.4, 16, 3],
    },
  },
  {
    id: 'boundaries',
    type: 'line',
    source: 'src',
    'source-layer': 'boundaries',
    paint: { 'line-color': '#6b5b7a', 'line-width': 0.8, 'line-dasharray': [3, 2] },
  },
]

export function MapPreview({ url }: { url: string }) {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const container = ref.current
    if (!container) return

    const protocol = new Protocol()
    maplibregl.addProtocol('pmtiles', protocol.tile)
    const archive = new PMTiles(url)
    protocol.add(archive)

    let map: maplibregl.Map | undefined
    let canceled = false

    archive
      .getHeader()
      .then((h) => {
        if (canceled) return
        const zoom = Math.min(Math.max(h.centerZoom || 12, h.minZoom), h.maxZoom)
        map = new maplibregl.Map({
          container,
          center: [h.centerLon, h.centerLat],
          zoom,
          minZoom: h.minZoom,
          maxZoom: h.maxZoom,
          attributionControl: false,
          style: {
            version: 8,
            sources: { src: { type: 'vector', url: `pmtiles://${url}` } },
            layers: STYLE_LAYERS,
          },
        })
        map.addControl(new maplibregl.NavigationControl(), 'top-right')
      })
      .catch(() => {
        /* nepavyko nuskaityti antraštės — paliekame tuščią */
      })

    return () => {
      canceled = true
      map?.remove()
      maplibregl.removeProtocol('pmtiles')
    }
  }, [url])

  return <div ref={ref} className="h-full w-full" />
}
