if (typeof wp !== 'undefined' && wp.i18n) {
	var { __, sprintf} = wp.i18n;
}


jQuery(document).ready(function ($) {
	'use strict';

	window.addEventListener('load', () => {
		let mapElement = document.getElementById('bpchk-checkins-map');
		if (mapElement) {
			console.log( 'Map element found, initializing map.' );
			bpCheckInsMap(); // Initialize the map regardless of the slug
		} else {
			console.log( 'Map element not found ( User Profile - checkins tab ).' );
		}
	});

	$(document).on( 'click', '.activity-read-more' , function() { 
		var id         = jQuery(this).attr('id');
		var parentdiv  = ($(this).closest('div'));
		var activityId = id.split('-');
		jQuery.ajax({
			url       : bpchk_public_js_obj.ajaxurl,			
 			type      : 'POST',
			data      : {
				'action'     : 'bpchk_checkin_activity_read_more',
				'ajaxNonce'  : bpchk_public_js_obj.bpchk_ajax_nonce,
				'activity_id': activityId[3],
			},
			success: function (response) {
				console.log(response);
				parentdiv.after(response);
			},
		});
	});

	function bpCheckInsMap() {
		let mapElement = document.getElementById("bpchk-checkins-map");
		if (!mapElement) {
			console.log( 'Map element not found for initialization.' );
			return;
		}
	
		let locations = document.querySelectorAll(".bpchk-checkins-location");
		let geocoder = 'google_maps';
	
		let currentlat, currentlng;
	
		// Create bounds object to dynamically adjust zoom level
		let bounds = new google.maps.LatLngBounds() ;
	
		// Loop through the locations to find the first valid one and set bounds
		locations.forEach(location => {
			let lat = parseFloat(location.dataset.latitude);
			let lng = parseFloat(location.dataset.longitude);
	
			if (!isNaN(lat) && !isNaN(lng)) {
				if (currentlat === undefined || currentlng === undefined) {
					currentlat = lat;
					currentlng = lng;
				}
				// Extend bounds to include each location
				if (geocoder === "google_maps") {
					bounds.extend(new google.maps.LatLng(lat, lng));
				} else {
					bounds.extend([lat, lng]);
				}
			}
		});
	
		if (currentlat === undefined || currentlng === undefined) {
			console.error( 'No valid locations found. Cannot initialize the map.' );
			return;
		}
	
		console.log( 'Initializing map with:' , {
			provider: geocoder,
			lat: currentlat,
			lng: currentlng,
		});
	
		if (geocoder === "google_maps") {
			const map = new google.maps.Map(mapElement, {
				zoom: 10,
				center: { lat: currentlat, lng: currentlng },
			});
	
			const infowindow = new google.maps.InfoWindow();
			
			locations.forEach((location, index) => {
				let lat = parseFloat(location.dataset.latitude);
				let lng = parseFloat(location.dataset.longitude);
				let address = location.dataset.address;
	
				if (isNaN(lat) || isNaN(lng)) {
					console.warn( 'Skipping invalid location:', lat, lng);
					return; // Skip invalid locations
				}
	
				let marker = new google.maps.Marker({
					position: { lat, lng },
					map,
					animation: google.maps.Animation.DROP,
				});
	
				google.maps.event.addListener(marker, "click", function () {
					infowindow.setContent(address);
					infowindow.open(map, marker);
					map.setCenter(marker.getPosition());
					map.setZoom(10);
				});
	
				google.maps.event.addListener(marker, "mouseover", function () {
					marker.setAnimation(google.maps.Animation.BOUNCE);
				});
	
				// Extend the map bounds to include the marker location
				bounds.extend(marker.getPosition());
			});
	
			// Automatically adjust the zoom level based on the bounds
			map.fitBounds(bounds);
	
		}
	}

	var autocomplete1;
	var autocomplete2;
	function initialize() {
		if (navigator.geolocation) {

			var options = {
				enableHighAccuracy: true,
				timeout: 5000,
				maximumAge: 0
			};

			navigator.geolocation.getCurrentPosition(success, error, options);
		} else {
			x.innerHTML = "Geolocation is not supported by this browser.";
		}

		var loc_xprof = document.getElementById(bpchk_public_js_obj.bpchk_loc_xprof);
		if (loc_xprof) {
			var autocomplete3 = new google.maps.places.Autocomplete(loc_xprof);
			google.maps.event.addListener(
				autocomplete3, 'place_changed', function () {
					var place3 = autocomplete3.getPlace();
					var latitude3 = place3.geometry.location.lat();
					var longitude3 = place3.geometry.location.lng();
					bpchk_loc_xprof_ajax_save(latitude3, longitude3);
				}
			);
		}
	}
	function error(e) {
		jQuery('.bp-checkin-error').remove();
		jQuery('.bp-checkin-panel').prepend(
			'<div class="bp-checkin-error notice notice-error">' +
			'<p>' + wp.i18n.__('Location services error. Please try again.', 'bp-checkins') + '</p>' +
			'</div>'
		);
		console.error( "Geolocation error:", e);
	}
	function success(position) {
		var lat = position.coords.latitude;
		var lng = position.coords.longitude;

		var myLocation = new google.maps.LatLng(lat, lng);

		var mapOptions = {
			center: myLocation,
			zoom: 13,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		/*start google map api code*/
		if (document.getElementById('checkin-by-autocomplete-map')) {
			var map = new google.maps.Map(
				document.getElementById('checkin-by-autocomplete-map'),
				mapOptions
			);

			var marker = new google.maps.Marker(
				{
					position: myLocation,
					map: map,
					title: "you are here",
					draggable: true,
					
				}
			);
			map.setZoom(11);
				
			reverseGeocoder(map, marker, myLocation);

			google.maps.event.addListener(marker, 'dragend', function (evt) {
				$('#bpchk-checkin-place-lat').val(evt.latLng.lat().toFixed(6));
				$('#bpchk-checkin-place-lng').val(evt.latLng.lng().toFixed(6));
				map.panTo(evt.latLng);
				reverseGeocoder(map, marker, evt.latLng);
			});

			// Create the search box and link it to the UI element.
			var input = document.getElementById('bpchk-autocomplete-place');
			var searchBox = new google.maps.places.SearchBox(input);
			// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
			// Bias the SearchBox results towards current map's viewport.
			map.addListener(
				'bounds_changed', function () {
					searchBox.setBounds(map.getBounds());
				}
			);

			var markers = [];
			// Listen for the event fired when the user selects a prediction and retrieve
			// more details for that place.
			searchBox.addListener(
				'places_changed', function () {
					var places = searchBox.getPlaces();

					if (places.length == 0) {
						return;
					}

					// Clear out the old markers.
					markers.forEach(
						function (marker) {
							marker.setMap(null);
						}
					);
					markers = [];

					// For each place, get the icon, name and location.
					var bounds = new google.maps.LatLngBounds();
					places.forEach(
						function (place) {
							if (!place.geometry) {
								console.log( "Returned place contains no geometry" );
								return;
							}
							var icon = null;
							if (place.icon) {
								icon = {
									url: place.icon,
									size: new google.maps.Size(71, 71),
									origin: new google.maps.Point(0, 0),
									anchor: new google.maps.Point(17, 34),
									scaledSize: new google.maps.Size(25, 25)
								};
							}

							// Create a marker for each place.
							markers.push(
								new google.maps.Marker(
									{
										map: map,
										icon: icon,
										title: place.name,
										position: place.geometry.location
									}
								)
							);

							if (place.geometry.viewport) {
								// Only geocodes have viewport.
								bounds.union(place.geometry.viewport);
							} else {
								bounds.extend(place.geometry.location);
							}

							var latitude1 = place.geometry.location.lat();
							var longitude1 = place.geometry.location.lng();
							$('#bpchk-checkin-place-lat').val(latitude1);
							$('#bpchk-checkin-place-lng').val(longitude1);							
						}
					);
					map.fitBounds(bounds);
				}
			);
			/*end google map api code*/
		}
	}
	// google.maps.event.addDomListener(window, 'load', initialize);


	function reverseGeocoder(map, marker, latlng){
		let address = document.getElementById('bpchk-autocomplete-place');
		const geocoder = new google.maps.Geocoder();
		const infowindow = new google.maps.InfoWindow();

		geocoder.geocode({ location: latlng }).then((response) => {
			if (response.results[0]) {
				// centers the map on markers coords
				map.setCenter(marker.position);
				// adds the marker on the map
				marker.setMap(map);
				infowindow.close();
				infowindow.setContent(response.results[0].formatted_address);				
				infowindow.open(map, marker);
				address.value = response.results[0].formatted_address;
				jQuery('#bpchk-checkin-place-lat').val(latlng.lat());
				jQuery('#bpchk-checkin-place-lng').val(latlng.lng());

			} else {
				window.alert( "No results found" );
			}
		}).catch((e) => console.log( "Geocoder failed due to: " + e));
		
	}

	function bpchk_loc_xprof_ajax_save(latitude3, longitude3) {

		var place = $('#' + bpchk_public_js_obj.bpchk_loc_xprof).val();

		var data = {
			'action': 'bpchk_save_xprofile_location',
			'place': place,
			'latitude': latitude3,
			'longitude': longitude3,
			'nonce': bpchk_public_js_obj.bpchk_ajax_nonce
		}

		$.ajax(
			{
				dataType: "JSON",
				url: bpchk_public_js_obj.ajaxurl,
				type: 'POST',
				data: data,
				success: function (response) {

				},
			}
		);
	}

	// Open the checkin panel when clicked
	$(document).on(
		'click', '.bpchk-allow-checkin', function () {
			$('.bp-checkin-panel').slideToggle(500);
			$('.bpquotes-bg-selection-div').hide();
			$( '.bpolls-polls-option-html' ).hide();
			window.onload = initialize();
			
			if ( $('.quote-btn').length != 0 ) {
				$( '.bg-type-input' ).val( '' );
				$( '.bg-type-value' ).val( '' );
				$( '#whats-new, #bppfa-whats-new' ).removeClass( 'quotesimg-bg-selected' );
				$( '#whats-new, #bppfa-whats-new' ).removeClass( 'quotescolors-bg-selected' );
				$( "#whats-new, #bppfa-whats-new" ).css( "background-image", '' );
				$( "#whats-new, #bppfa-whats-new" ).css( "background", '' );
				$( "#whats-new, #bppfa-whats-new" ).css( "color", '' );
				$( '.bpquotes-selection' ).css( 'pointerEvents', 'auto' );
			}
			if ( $( '.bpolls-input').length != 0 ) {
				$( '.bpolls-input').each(function(){
					$(this).val('');
				});
			}
		}
	);
	
	
	// Show the places panel
	$(document).on(
		'click', '#bpchk-show-places-panel', function () {
			$('.bpchk-places-fetched').slideToggle(500);
			// $('.bpchk-places-fetched, #bpchk-add-as-place, #bpchk-add-my-place-label').show();
		}
	);

	$(
		function () {
			$("#accordion").accordion({ collapsible: true, heightStyle: "content" });
		}
	);

	$("#aw-whats-new-submit").click(
		function () {
			$('.bpchk-select-place-to-checkin').each(
				function () {
					$(this).html('Select this location');
				}
			);
			$('.bpchk-checkin-temp-location').remove();
			if ($('.bp-checkin-panel').is(':visible')) {
				$('.bp-checkin-panel').slideToggle(500);
			}
			if ($('.bpchk-places-fetched').is(':visible')) {
				$('.bpchk-places-fetched').slideToggle(500);
			}

		}
	);

	jQuery(document).on('click', '.bpchk-trash-checkin', function (e) {
		e.preventDefault();
		var checkin_id = []; 
		checkin_id.push( jQuery(this).attr('attr-key') );
		
		jQuery.ajax({
			url       : bpchk_public_js_obj.ajaxurl,			
 			type      : 'POST',
			data      : {
				'action'     : 'bpchk_delete_user_checkin_location',
				'ajaxNonce'  : bpchk_public_js_obj.bpchk_ajax_nonce,
				'checkin_id' : checkin_id,
			},
			success: function (response) {
				console.log(response);
				window.location.reload();
			},
		});
	});

	$(document).on('focus', '#whats-new, #bppfa-whats-new', function () {

		if ($(".rtmedia-plupload-container .bpchk-marker-container").length == 0 && $(".rtmedia-plupload-container").length != 0) {
			// $(".bpchk-marker-container").appendTo(".rtmedia-plupload-container");

		}
		if ($(".rtmedia-plupload-container").length != 0) {
			// $('#whats-new-options .bpchk-marker-container').hide();
		}

		jQuery('.bpchk-marker-container').click(function () {
			jQuery('.bpquotes-bg-selection-div').hide();
			jQuery('.bpolls-polls-option-html').hide();
		});
	});

	/**
	 * Manage map icon with BuddyBoss Plateform
	 */
	$(document).on('click focus', '#whats-new', function () {
		if (bpchk_public_js_obj.buddyboss) {
			$('.bpchk-marker-container').appendTo('#whats-new-toolbar');
			$('.bp-checkin-panel').appendTo('#whats-new-attachments');
			if ( $('.whats-new-form-footer #whats-new-toolbar .bpchk-marker-container').length == 0 ) {
				$('.bpchk-marker-container').appendTo($('.whats-new-form-footer #whats-new-toolbar'));
			}
		}

	});
	
	if (bpchk_public_js_obj.buddyboss  ) {
		var bb_checkins_Interval;
		function bb_checkins_icon_push() {
			bb_checkins_Interval = setInterval( function() {

				if (bpchk_public_js_obj.buddyboss && $('#whats-new-form:not(.focus-in) #whats-new-toolbar .bp-checkins-icon-placeholder').length == 0) {
					$('#whats-new-form:not(.focus-in) #whats-new-toolbar').append('<div class="post-elements-buttons-item bp-checkins-icon-placeholder"><div class="checkins-icon bp-tooltip" data-bp-tooltip-pos="up" data-bp-tooltip="' + bpchk_public_js_obj.add_checkin_text + '"><i class="wb-icons wb-icon-map-pin bpchk-allow-checkin"></i></div></div>');
				}
			}, 10);

		}
		bb_checkins_icon_push();
		
		$(document).on('click', '.bb-model-close-button, .activity-update-form-overlay', function(){
			clearInterval(bb_checkins_Interval);
			bb_checkins_icon_push();
		});

		/* jQuery Ajax prefilter*/

		$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
			try {
				if ( originalOptions.data == null || typeof ( originalOptions.data ) == 'undefined' || typeof ( originalOptions.data.action ) == 'undefined' ) {
					return true;
				}
			} catch ( e ) {
				return true;
			}
			if ( originalOptions.data.action == 'post_update' ) {
				clearInterval(bb_checkins_Interval);
				bb_checkins_icon_push();
			}

		} );
	}
	
	$( document ).on ( 'click', '#aw-whats-new-reset', function(){
		$('#bpchk-autocomplete-place').val('');
		$('#bpchk-checkin-place-lat').val('');
		$('#bpchk-checkin-place-lng').val('');
	});

	// Check Youzify
	if (bpchk_public_js_obj.youzify_enabled) {
        $(document).on('click', '.youzify-wall-post', function () {
            $(".bp-checkin-panel").hide(500);
        });
    }


	 /* Selecting/Deselecting all favourite check-ins */
	$('#bpchk-select-all-contact').on('click', function () {
		if (this.checked) {
		  $('.bpchk-all-check').each(function () {
			this.checked = true;
		  });
		} else {
		  $('.bpchk-all-check').each(function () {
			this.checked = false;
		  });
		}
	});

	// Bulk delete favourite check-ins
	$('#bpchk-bulk-manage').on('click', function(e) {
		e.preventDefault();
		var checkedCount = $('.bpchk-all-check:checked').length;
    
		if (checkedCount === 0) {
			alert( __('Please select locations to delete', 'bp-checkins') );
			return false;
		}
		if (!confirm(sprintf(
			__('Are you sure you want to delete %d location(s)?', 'bp-checkins'), 
			checkedCount
		))) {
			return false;
		}
		var checkin_ids = [];
		$('.bpchk-all-check').each(function () {
			if( this.checked ) {
				checkin_ids.push( jQuery(this).val() );
			}
		});
		jQuery.ajax({

			url    : bpchk_public_js_obj.ajaxurl,
			type   : 'POST',
			data   : {
				'action'     : 'bpchk_delete_user_checkin_location',
				'ajaxNonce'  : bpchk_public_js_obj.bpchk_ajax_nonce,
				'checkin_id' : checkin_ids,
			},
			success: function (response) {
				console.log(response);
				window.location.reload();
			},
		});
	});

});


function initialize_edit_map() {
	if (navigator.geolocation) {
		var options = {
			enableHighAccuracy: true,
			timeout: 5000,
			maximumAge: 0
		};

		navigator.geolocation.getCurrentPosition(edit_activity_success, edit_activity_error, options);
	} else {
		x.innerHTML = "Geolocation is not supported by this browser.";
	}

	var loc_xprof = document.getElementById(bpchk_public_js_obj.bpchk_loc_xprof);
	if (loc_xprof) {
		var autocomplete3 = new google.maps.places.Autocomplete(loc_xprof);
		google.maps.event.addListener(
			autocomplete3, 'place_changed', function () {
				var place3 = autocomplete3.getPlace();
				var latitude3 = place3.geometry.location.lat();
				var longitude3 = place3.geometry.location.lng();
				bpchk_loc_xprof_ajax_save(latitude3, longitude3);
			}
		);
	}
}

function edit_activity_error(e) {
	alert( e.message );
	console.log( "error code:"  + e.code + 'message: ' + e.message);
}
function edit_activity_success( position ) {
	
	var lat 		= jQuery("#bpchk-checkin-edit-place-lat").val();	
	var lng 		= jQuery("#bpchk-checkin-edit-place-lng").val();
	var myLocation 	= new google.maps.LatLng(lat, lng);

	var mapOptions = {
		center: myLocation,
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	/*start google map api code*/
	if (document.getElementById('checkin-by-autocomplete-edit-map')) {
		var map = new google.maps.Map(
			document.getElementById('checkin-by-autocomplete-edit-map'),
			mapOptions
		);

		var marker = new google.maps.Marker({
				position: myLocation,
				map: map,
				title: "you are here",
				draggable: true,					
			});
		map.setZoom(11);				
		edit_activity_reverseGeocoder(map, marker, myLocation);
		google.maps.event.addListener(marker, 'dragend', function (evt) {
			jQuery("#bpchk-checkin-edit-place-lat").val(evt.latLng.lat().toFixed(6));
			jQuery("#bpchk-checkin-edit-place-lng").val(evt.latLng.lng().toFixed(6));
			map.panTo(evt.latLng);
			edit_activity_reverseGeocoder(map, marker, evt.latLng);
		});

		// Create the search box and link it to the UI element.
		var input 		= document.getElementById('bpchk-autocomplete-edit-place');
		var searchBox 	= new google.maps.places.SearchBox(input);
		// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
		// Bias the SearchBox results towards current map's viewport.
		map.addListener(
			'bounds_changed', function () {
				searchBox.setBounds(map.getBounds());
			}
		);

		var markers = [];
		// Listen for the event fired when the user selects a prediction and retrieve
		// more details for that place.
		searchBox.addListener(
			'places_changed', function () {
				var places = searchBox.getPlaces();
				if (places.length == 0) {
					return;
				}
				// Clear out the old markers.
				markers.forEach(
					function (marker) {
						marker.setMap(null);
					}
				);
				markers = [];

				// For each place, get the icon, name and location.
				var bounds = new google.maps.LatLngBounds();
				places.forEach(
					function (place) {
						if (!place.geometry) {
							console.log( "Returned place contains no geometry" );
							return;
						}
						var icon = null;
						if (place.icon) {
							icon = {
								url: place.icon,
								size: new google.maps.Size(71, 71),
								origin: new google.maps.Point(0, 0),
								anchor: new google.maps.Point(17, 34),
								scaledSize: new google.maps.Size(25, 25)
							};
						}

						// Create a marker for each place.
						markers.push(
							new google.maps.Marker({
									map: map,
									icon: icon,
									title: place.name,
									position: place.geometry.location
								})
						);

						if (place.geometry.viewport) {
							// Only geocodes have viewport.
							bounds.union(place.geometry.viewport);
						} else {
							bounds.extend(place.geometry.location);
						}

						var latitude1 	= place.geometry.location.lat();
						var longitude1 	= place.geometry.location.lng();
						jQuery('#bpchk-checkin-edit-place-lat').val(latitude1);
						jQuery('#bpchk-checkin-edit-place-lng').val(longitude1);							
					}
				);
				map.fitBounds(bounds);
			}
		);
		/*end google map api code*/
	}
}


function edit_activity_reverseGeocoder(map, marker, latlng){
	let address 		= document.getElementById('bpchk-autocomplete-edit-place');
	const geocoder 		= new google.maps.Geocoder();
	const infowindow 	= new google.maps.InfoWindow();

	geocoder.geocode({ location: latlng }).then((response) => {
		if (response.results[0]) {
			// centers the map on markers coords
			map.setCenter(marker.position);
			// adds the marker on the map
			marker.setMap(map);
			infowindow.close();
			infowindow.setContent(response.results[0].formatted_address);				
			infowindow.open(map, marker);
			if( address.value == '' ) {
				address.value = response.results[0].formatted_address;
			}
			jQuery('#bpchk-checkin-edit-place-lat').val(latlng.lat());
			jQuery('#bpchk-checkin-edit-place-lng').val(latlng.lng());

		} else {
			window.alert( "No results found" );
		}
	}).catch((e) => console.log( "Geocoder failed due to: " )  + e );
	
}