// leaflet-map-init.js
// This script reads window._leaflet_map_init_queue and initializes each map.
// Depends on Leaflet (L) being available.

(function () {
    'use strict';

    function initSingleMap(cfg) {
        try {
            var mapEl = document.getElementById(cfg.id);
            if (!mapEl) return;

            // Avoid double-init
            if (mapEl.dataset.leafletInitialized) return;
            mapEl.dataset.leafletInitialized = '1';

            var map = L.map(cfg.id).setView([cfg.lat, cfg.lng], cfg.zoom);

            var tileUrl = (typeof LeafletMapPluginData !== 'undefined' && LeafletMapPluginData.tileUrl) ? LeafletMapPluginData.tileUrl : 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
            var tileAttr = (typeof LeafletMapPluginData !== 'undefined' && LeafletMapPluginData.tileAttr) ? LeafletMapPluginData.tileAttr : '';

            L.tileLayer(tileUrl, {
                attribution: tileAttr,
                maxZoom: 19
            }).addTo(map);

            if (cfg.marker) {
                var marker = L.marker([cfg.lat, cfg.lng]).addTo(map);
                if (cfg.popup && cfg.popup.length) {
                    marker.bindPopup(cfg.popup);
                }
            }

            // optional: resize handling
            setTimeout(function () {
                map.invalidateSize();
            }, 200);

        } catch (e) {
            // graceful failure
            // console.error('Leaflet Map Init error:', e);
        }
    }

    function initAllQueued() {
        var q = window._leaflet_map_init_queue || [];
        for (var i = 0; i < q.length; i++) {
            initSingleMap(q[i]);
        }
        // clear queue so subsequent pushes still work (we'll process them on DOM ready)
        window._leaflet_map_init_queue = [];
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initAllQueued);
    } else {
        initAllQueued();
    }

    // If shortcode adds more maps after DOMContentLoaded, process newly pushed items periodically for a short while
    // (useful for some Ajax/Builder environments)
    (function watchQueue() {
        var checks = 0;
        var maxChecks = 20; // ~10 seconds (500ms intervals)
        var interval = setInterval(function () {
            if ((window._leaflet_map_init_queue && window._leaflet_map_init_queue.length > 0) && checks < maxChecks) {
                initAllQueued();
            }
            checks++;
            if (checks >= maxChecks) {
                clearInterval(interval);
            }
        }, 500);
    })();

})();
