(function () {
    'use strict';

    function initMapPicker(container) {
        if (!container || container.dataset.initialized === '1') {
            return;
        }

        var provider = container.dataset.provider || 'openstreetmap';
        var latInput = document.getElementById(container.dataset.latInput || 'latitude');
        var lngInput = document.getElementById(container.dataset.lngInput || 'longitude');
        var mapEl = container.querySelector('.transport-map-canvas');
        if (!mapEl || !latInput || !lngInput) {
            return;
        }

        var lat = parseFloat(latInput.value || container.dataset.defaultLat || '26.0667');
        var lng = parseFloat(lngInput.value || container.dataset.defaultLng || '50.5577');
        var zoom = parseInt(container.dataset.defaultZoom || '12', 10);

        if (provider === 'google' && window.google && window.google.maps) {
            var gMap = new google.maps.Map(mapEl, {
                center: { lat: lat, lng: lng },
                zoom: zoom,
            });
            var marker = new google.maps.Marker({
                position: { lat: lat, lng: lng },
                map: gMap,
                draggable: true,
            });
            marker.addListener('dragend', function () {
                var pos = marker.getPosition();
                latInput.value = pos.lat().toFixed(7);
                lngInput.value = pos.lng().toFixed(7);
            });
            gMap.addListener('click', function (e) {
                marker.setPosition(e.latLng);
                latInput.value = e.latLng.lat().toFixed(7);
                lngInput.value = e.latLng.lng().toFixed(7);
            });
            container.dataset.initialized = '1';
            return;
        }

        if (!window.L) {
            return;
        }

        var map = L.map(mapEl).setView([lat, lng], zoom);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; OpenStreetMap contributors',
        }).addTo(map);

        var marker = L.marker([lat, lng], { draggable: true }).addTo(map);
        marker.on('dragend', function () {
            var pos = marker.getLatLng();
            latInput.value = pos.lat.toFixed(7);
            lngInput.value = pos.lng.toFixed(7);
        });
        map.on('click', function (e) {
            marker.setLatLng(e.latlng);
            latInput.value = e.latlng.lat.toFixed(7);
            lngInput.value = e.latlng.lng.toFixed(7);
        });

        container.dataset.initialized = '1';
    }

    function initFleetMap(container) {
        if (!container || container.dataset.initialized === '1') {
            return;
        }

        var provider = container.dataset.provider || 'openstreetmap';
        var lat = parseFloat(container.dataset.defaultLat || '26.0667');
        var lng = parseFloat(container.dataset.defaultLng || '50.5577');
        var zoom = parseInt(container.dataset.defaultZoom || '12', 10);
        var mapEl = container.querySelector('.transport-map-canvas');
        if (!mapEl) {
            return;
        }

        var markers = [];
        try {
            markers = JSON.parse(container.dataset.markers || '[]');
        } catch (e) {
            markers = [];
        }

        if (provider === 'google' && window.google && window.google.maps) {
            var gMap = new google.maps.Map(mapEl, { center: { lat: lat, lng: lng }, zoom: zoom });
            var bounds = new google.maps.LatLngBounds();
            markers.forEach(function (m) {
                if (!m.lat || !m.lng) return;
                var pos = { lat: parseFloat(m.lat), lng: parseFloat(m.lng) };
                new google.maps.Marker({ position: pos, map: gMap, title: m.title || '' });
                bounds.extend(pos);
            });
            if (markers.length > 1) {
                gMap.fitBounds(bounds);
            }
            container.dataset.initialized = '1';
            return;
        }

        if (!window.L) {
            return;
        }

        var map = L.map(mapEl).setView([lat, lng], zoom);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; OpenStreetMap contributors',
        }).addTo(map);

        var group = [];
        markers.forEach(function (m) {
            if (!m.lat || !m.lng) return;
            group.push(L.marker([parseFloat(m.lat), parseFloat(m.lng)]).bindPopup(m.title || ''));
        });
        if (group.length) {
            var layer = L.featureGroup(group).addTo(map);
            map.fitBounds(layer.getBounds().pad(0.2));
        }

        container.dataset.initialized = '1';
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('[data-transport-map-picker]').forEach(initMapPicker);
        document.querySelectorAll('[data-transport-fleet-map]').forEach(initFleetMap);
    });
})();
