@props([
	'id' => null,                //random if not supplied
	'instanceUid' => null,       //random suffix - auto generated if not provided
	'mapsApiKey' => '',
	'dataRole' => null,          //autogenerated if you supply a locations array of objects
    'locations' =>[],            //optional if you already have the data in elements on the page that can be matched with data-role
	'mapZoom' => 6,
	'homeLatitude' => 52.4767812,
	'homeLongitude' =>  -1.9104241,
	'markerUrl' => '/images/map-marker.svg',
    'markerSizeWidth' => 32,
    'markerSizeHeight' => 32,
	'clusterMarker' => '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-100 -100 200 200"><defs><g id="a" transform="rotate(45)"><path d="M0 47A47 47 0 0 0 47 0L62 0A62 62 0 0 1 0 62Z" fill-opacity="0.7"/><path d="M0 67A67 67 0 0 0 67 0L81 0A81 81 0 0 1 0 81Z" fill-opacity="0.5"/><path d="M0 86A86 86 0 0 0 86 0L100 0A100 100 0 0 1 0 100Z" fill-opacity="0.3"/></g></defs><g fill="$$color"><circle r="42"/><use xlink:href="#a"/><g transform="rotate(120)"><use xlink:href="#a"/></g><g transform="rotate(240)"><use xlink:href="#a"/></g></g></svg>',
	'libraries' => 'places',
	//style and class is passed through as $attributes on the container div
	]
)
@php
	if(empty($instanceUid))
        $instanceUid=Clevercherry\Backslash4\Backslash4::generateShortUuid();
    if(empty($id))
        $id="locationMap_". $instanceUid;

    if(empty($dataRole))
        $dataRole='map-locations-'.$instanceUid;
	
@endphp
<div {{ $attributes }}> {{-- containing block make sure it has some size --}}
	@if(!empty($locations)) {{-- if the datalist is provied in the array build it as elements for the JS to query --}}
    <datalist id="maplocations_{{ $instanceUid }}" style="display:none">
        @foreach($locations as $place)
            <option 
                data-role="{{ $dataRole }}" {{-- used to find all in document --}}
                data-name="{{ @$place->name }}" {{-- this data should be in tiles or something is data is not provided in an array --}}
                data-latitude="{{ $place->latitude }}" 
                data-longitude="{{ $place->longitude }}" 
                data-uid="{{ @$place->uid ?? 'location_'.Clevercherry\Backslash4\Backslash4::generateShortUuid() }}"
				data-icon="{{ @$place->icon }}"
				data-iconbackgroundcolor="{{ @$place->icon_background_color }}"
				data-iconmaskbaseuri="{{ @$place->icon_mask_base_uri }}"
				data-placeid="{{ @$place->place_id }}"
				data-type="{{ @$place->type }}"
				>
                {!! @$place->html !!}
            </option>
        @endforeach
	</datalist>
    @endif
	<div data-role="google-map-container" id="{{ $id }}" style="width: 100%; height: 100%;"></div>
	@if(!empty($clusterMarker))
	<script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>
	@endif
	<script type="text/javascript">
	function initMap() {
		//save the map variable into a global
		if(!('bs4data' in window))
        	window.bs4data={};
    	if(!('maps' in window.bs4data))
        	window.bs4data.maps=[];
		if(!('markers' in window.bs4data))
        	window.bs4data.markers=[];
		if(!('lastInfoWindow' in window.bs4data))
        	window.bs4data.lastInfoWIndow = null;
		
		var markers = [];
		var location = new google.maps.LatLng({{ $homeLatitude }}, {{ $homeLongitude }} );
		var gmTarget = document.getElementById('{{ $id }}');
		var gmTargetId = gmTarget.getAttribute('id'); //or '{{ $id }}'
		
		
		var mapZoom = {{ $mapZoom }};
		var initMapZoom = mapZoom;
		if(mapZoom<1)
			initMapZoom=6;
		
		var map = new google.maps.Map( gmTarget, {center: location, zoom: initMapZoom});
		var latlngbounds = new google.maps.LatLngBounds();

		window.bs4data.maps[gmTargetId] = map;
		window.bs4data.markers[gmTargetId] = markers;

		document.querySelectorAll('[data-role={{ $dataRole }}]').forEach((element) => {
			var long = element.dataset.longitude;
			var lat  = element.dataset.latitude;
			var defaultUrl = '{{ $markerUrl }}';

			if((long!='') && (lat!=''))
			{
				try {
					//inside a try incase the parseFloats error
					lat  = parseFloat(lat);
					long = parseFloat(long);
					let img = element.dataset.icon;
					
                    if (img == null || img == '') {
						img = defaultUrl;
                    }
                    
                    infoHTML = element.innerHTML.trim(); //remove whitespace \n layout

                    if (infoHTML == '') {
                        infoHTML = element.dataset.name;
                    }

					var marker = new google.maps.Marker({
						map: map,
						icon: new google.maps.MarkerImage(
							img,
							null,
							null,
							null,
							new google.maps.Size({{ $markerSizeWidth}},{{$markerSizeHeight}})
						),
						name:  element.dataset.name,
						id: element.dataset.uid, 
						distance: null,
						position: {'lat' : lat , 'lng': long },
						animation: google.maps.Animation.DROP,
						bsType: element.dataset.type
					});

                    const infowindow = new google.maps.InfoWindow({
                        content: infoHTML,
                    });

                    marker.addListener("click", () => {
                        if (window.bs4data.lastInfoWIndow != null) {
                            window.bs4data.lastInfoWIndow.close();
                        }

                        window.bs4data.lastInfoWIndow = infowindow;

                        infowindow.open({
                            anchor: marker,
                            map,
                        });
                    });
                    

					latlngbounds.extend(marker.position);

					markers.push(marker);
				} catch (error) {
					console.log('ccdev map error 53,', [long,lat, error]);								
				}
			}
		});

		var getGoogleClusterInlineSvg = function (color) {
			var encoded = window.btoa('{!! $clusterMarker !!}'.replace('$$color', color));
			return ('data:image/svg+xml;base64,' + encoded);
		};

		@if(!empty($clusterMarker))
		markerCluster = new markerClusterer.MarkerClusterer({ map, markers });
		@endif

		if(mapZoom<1)
		{   map.setCenter(latlngbounds.getCenter());
			map.fitBounds(latlngbounds);
		}
		google.maps.event.trigger(map, 'resize');
	}
	</script>
	<script type="text/javascript" src="https://maps.google.com/maps/api/js?libraries={{ $libraries }}&key={{ $mapsApiKey }}&ver=1.11.1&callback=initMap" async defer></script>
</div>