export default function () {
    const apiKey = window.googleMapsApiKey?.[0];
    if (!apiKey) {
        console.error('Google Maps API key is missing');
        return;
    }

    if (typeof google === 'object' && typeof google.maps === 'object') {
        console.log('Google Maps API already loaded');
        window.initialiseGoogleMaps();
        return;
    }

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://maps.googleapis.com/maps/api/js?loading=async&callback=window.initialiseGoogleMaps&key=${apiKey}`;
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
}

export function initialiseGoogleMaps() {
    const mapCollection = document.querySelectorAll('.wdg_google_init');
    mapCollection.forEach((element) => {
        const googleMarker = element.dataset.gmarker;
        const googleStyle = element.dataset.gstyle;
        const googleType = element.dataset.gtype;
        const styleIsJson = googleStyle === 'json';
        const addMarker = googleMarker === '1';
        const zoom = parseInt(element.dataset.zoom) || 8;
        const longitude = parseFloat(element.dataset.lan) || 0; // Note: 'lan' might be 'lng'
        const latitude = parseFloat(element.dataset.lat) || 0;
        const myLatlng = new google.maps.LatLng(latitude, longitude);

        const map = new google.maps.Map(element, buildMapOptions({
            zoom,
            center: myLatlng,
            googleStyle,
            googleType
        }));

        if (styleIsJson) {
            setCustomEdooboxMapType(map);
        }

        if (addMarker) {
            setMapMarker({ map, position: myLatlng });
        }
    });
}

function buildMapOptions({ zoom, center, googleStyle, googleType }) {
    const edooboxStyle = 'edooboxstyle';
    return {
        zoom,
        center,
        streetViewControl: true,
        ...(googleStyle === 'json' ? {
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId[googleType], edooboxStyle]
            },
            mapTypeId: edooboxStyle
        } : {
            mapTypeId: (googleType || 'ROADMAP').toLowerCase()
        })
    };
}

function setCustomEdooboxMapType(map) {
    map.mapTypes.set('edooboxstyle', new google.maps.StyledMapType(window.googlemapstyle, {
        name: 'Event Style'
    }));
}

function setMapMarker({ map, position }) {
    return new google.maps.Marker({
        position,
        map,
        animation: google.maps.Animation.DROP,
        title: 'Location' // Replace with tg('N1669') if using a translation function
    });
}