
export class LeafletMap extends HTMLElement {
    connectedCallback() {
        if (this.map) return;

        // Ensure Leaflet is loaded
        if (typeof L === 'undefined') {
            const checkLeaflet = setInterval(() => {
                if (typeof L !== 'undefined') {
                    clearInterval(checkLeaflet);
                    this.initMap();
                }
            }, 100);
            return;
        }

        this.initMap();
    }

    initMap() {
        if (!this.dataset.geometry) return;

        try {
            const geometry = JSON.parse(this.dataset.geometry);
            
            // 'this' refers to the custom element itself. 
            // Leaflet can attach to it if it has dimensions.
            this.map = L.map(this);

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(this.map);

            const layer = L.geoJSON(geometry).addTo(this.map);
            this.map.fitBounds(layer.getBounds(), {padding: [50, 50]});
            
            // Fix for map not rendering correctly sometimes when container size changes or initial load
            setTimeout(() => {
                this.map.invalidateSize();
            }, 100);

        } catch (e) {
            console.error('Error initializing Leaflet map:', e);
        }
    }

    disconnectedCallback() {
        if (this.map) {
            this.map.remove();
            this.map = null;
        }
    }
}
