/* global L */

export function initEventMap() {
    const mapEl = document.getElementById('event-map')
    if (!mapEl) return

    const address = mapEl.dataset.address
    if (!address) return

    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = 'https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css'
    document.head.appendChild(link)

    const script = document.createElement('script')
    script.src = 'https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js'
    script.onload = () => geocodeAndRender(address, mapEl)
    document.head.appendChild(script)
}

function geocodeAndRender(address, mapEl) {
    const url = 'https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(address)

    globalThis.fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data.length === 0) {
                mapEl.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;background:#f3f4f6;"><p style="font-weight:700;color:#9ca3af;">Adresse introuvable sur la carte</p></div>'

                return
            }

            const lat = Number.parseFloat(data[0].lat)
            const lon = Number.parseFloat(data[0].lon)

            const map = L.map(mapEl).setView([lat, lon], 16)

            L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>',
                maxZoom: 19,
                subdomains: 'abcd',
            }).addTo(map)

            const icon = L.icon({
                iconUrl: '/marker.png',
                iconSize: [40, 40],
                iconAnchor: [20, 40],
                popupAnchor: [0, -40],
                className: 'leaflet-marker-custom',
            })

            L.marker([lat, lon], { icon }).addTo(map).bindPopup('<b>' + address + '</b>').openPopup()
        })
        .catch(() => {
            mapEl.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;background:#f3f4f6;"><p style="font-weight:700;color:#9ca3af;">Carte indisponible</p></div>'
        })
}
