<% 
	// CREATE ALIASES
	const activity = locals.metadata.page.activity
	const publicpage = locals.metadata.page.public || activity === 'preview'
	const space = locals.metadata.page.space
	const object = locals.metadata.page.object
	const language = locals.metadata.page.language
	const page_content_limit = locals.metadata.page.page_content_limit

	let mapscale = locals.metadata.page.mscale
	// THIS IS FOR PUBLIC PINBOARDS: TO ENSURE THAT THE DEFINED MAP SCALE IS PRESERVED
	if (space === 'pinned' && (!locals.pinboard?.editable || activity === 'preview') && locals.pinboard?.display_map) {
		if (locals.pinboard?.display_fullscreen) mapscale = 'full-screen'
		else mapscale = 'contain'
	}
%>

<div class='map-container<% if (mapscale !== "full-screen") { %> lg<% } %> <%- mapscale %>'>
	<div id='map'>
	</div>
	<!-- <% if (locals.session_data?.logged) { %>
		<div class='btn-group'>
			<a class='mtype <% if (locals.mtype === "locations") { %>active<% } %>' data-type='locations'><%- capitalize(vocabulary['location'][language](true)) %></a>
			<a class='mtype <% if (locals.mtype === "labs") { %>active<% } %>' data-type='labs'><%- capitalize(vocabulary['lab'][language](true)) %></a>
		</div>
	<% } %> -->
	<% if (
		!(space === 'pinned' 
		&& (!locals.pinboard?.editable || activity === 'preview'))
	) { %>
		<div class='btn-group map-scale lg'>
			<a class='mscale'>
				<i class='material-icons'>
					<% if (mapscale === 'contain') { %>
						open_in_full
					<% } else { %>
						close_fullscreen
					<% } %>
				</i>
			</a>
		</div>
	<% } %>
</div>

<script type='text/javascript'>

const centerpoint = <%- JSON.stringify(locals.metadata.user?.country?.lnglat || null) %>;
const clusters = <%- JSON.stringify(locals.clusters || []) %>;

// THE LEAFLET CODE
// const drawMap = window.matchMedia("(min-width: 576px)").matches || clusters.length || data.map(d => d.location).filter(d => d).length
// const drawMap = window.matchMedia("(min-width: 576px)").matches
const drawMap = true

if (drawMap) {
	const map = L.map('map', { boxZoom: false, minZoom: 2 })

	L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		attribution: '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>',
		maxZoom: 19,
	}).addTo(map)

	if (!clusters.length) {
		if (!centerpoint) map.fitWorld()
		else map.setView([centerpoint.lat, centerpoint.lng], 2)
	} else {
		d3.select('.map-container').classed('hide', false)

		const singlepin = L.divIcon({
			className: 'single-pin',
			iconAnchor: [0, 24],
			labelAnchor: [-6, 0],
			popupAnchor: [0, -36],
			html: '<i class="material-icons">place</i>'
		})

		clusters.forEach(d => {
			const markerScale = d3.scaleLinear()
				.domain([1, d3.max(d, c => c.properties.count)])
				.range([10, 50])
			
			d.markers = d.map(c => {
				const clusterpin = L.divIcon({
					className: 'cluster-pin',
					iconSize: markerScale(c.properties.count),
					popupAnchor: [0, -markerScale(c.properties.count)],
					html: `${c.properties.count}`
				})
				const marker = L.marker([c.geometry.coordinates[1], c.geometry.coordinates[0]], { icon: clusterpin })
					.on('click', function () {
						return loadPopup(this._popup, c.properties.pads)
					})
				marker.bindPopup()
				return marker
			})
		})

		async function loadPopup (popup, pads, page = 1) {
			let { data } = await POST('/<%- language %>/browse/pads/<%- space %>', { pads, page })

			const max_pages = Math.ceil(pads.length / <%- page_content_limit %>)

			const section = document.createElement('section')
			section.classList.add('container')
			section.classList.add('<%- object %>')
			const body = d3.select(section)
				.addElems('div', 'layout columns', [data])
			.each(function (d) {
				const section = d3.select(this)

				d.forEach(c => {
					const entry = new Entry({ 
						parent: section, 
						data: c,
						display: 'columns',
						language: '<%- language %>'
					})
					// CREATE ALIAS FOR render
					const render = entry.render
					render.img(entry.head)
					render.actions(entry.head)
					render.title(entry.body)
					render.owner(entry.body)
					if (c.img?.length === 0) render.txt(entry.body)
					<% if (!publicpage) { %>
						render.metainfo(entry.body)
						render.followup(entry.body)
					<% } %>
					render.tags(entry.body)
					// if (mediaSize !== 'xs') render.stats(entry.foot)
					render.engagement(entry.foot)
					render.pin(entry.foot)
					render.delete(entry.outer)
				})

				const pagination = section.addElems('nav', 'pagination')
					.addElems('div', 'inner')
				pagination.addElems('div', 'caroussel')
					.addElems('div', 'dots')
					.addElems('div', 'dot', new Array(d.length).fill(0).map((c, i) => i + 1))

				pagination.addElems('ul')
				.addElems('li', null, new Array(max_pages).fill(0).map((c, i) => i + 1))
				.addElems('a', 'page-link')
					.classed('active', c => c === page)
					.attr('data-page', c => c)
					.html(c => c)
				.on('click', c => {
					return loadPopup (popup, pads, c)
				})
			})

			function animateCarousel (idx) {
				const deck = d3.select('.layout.columns')
				const slides = deck.selectAll('article.pad')
				const delay = 3000

				if (idx === slides.size()) idx = 0
				deck.node().scrollTo({
					top: 0,
					left: idx * (slides.node().clientWidth || slides.node().offsetWidth || slides.node().scrollWidth),
					behavior: 'smooth'
				})
				d3.selectAll('.caroussel .dots .dot')
					.classed('highlight', (d, i) => i === idx)
				.on('click', function (d, i) {
					idx = i
					animateCarousel(idx)
				})
			}

			popup.setContent(section)
			animateCarousel(0)
		}

		// const locations = clusters.last().markers
		// (<%- JSON.stringify(locals.locations || []) %>).map(d => {
		// 	let centerpoints = d.location?.centerpoints || [d.location?.centerpoint] || []
		// 	centerpoints = centerpoints.filter(c => c?.lat && c?.lng)
		// 	return centerpoints.map(c => {
		// 		return L.marker([c.lat, c.lng], { icon: singlepin })
		// 			// .on('click', _ => window.location = `?pads=${c.id}`)
		// 			.on('click', function () { loadPopup(this._popup, c.id) })
		// 			.bindPopup()
		// 	})
		// }).flat()

		let group
		let bounds = L.featureGroup(clusters.last().markers)

		if (Math.max(...clusters.map(d => d.length)) > 1) map.fitBounds(bounds.getBounds(), { padding: [15, 15] })
		else map.setView([centerpoint.lat, centerpoint.lng], 2)
		
		function setZoomLayer (map, group, clusters) {
			const currentZoom = map.getZoom()
			if (group) map.removeLayer(group)
			
			if (currentZoom < 4) group = L.featureGroup(clusters[0].markers)
			// else if (currentZoom < 6) group = L.featureGroup(clusters[1].markers)
			else group = L.featureGroup(clusters.last().markers)
			
			group.addTo(map)

			return group
		}
		group = setZoomLayer(map, group, clusters)

		// ONLY CHANGE CLUSTERS IF THERE ARE DIFFERENT CLUSTER LEVELS IN THE DATA
		if (clusters.length > 1) {
			map.on('zoomend', _ => { group = setZoomLayer(map, group, clusters) })
		}
		
		d3.select('.map-container')
			.call(multiSelection, { class: '.leaflet-marker-icon', constraint: evt => evt.ctrlKey || evt.metaKey })
		.on('mousedown', _ => {
			const evt = d3.event
			if (evt.ctrlKey || evt.metaKey) map.dragging.disable()
		})
		.on('mouseup', _ => {
			map.dragging.enable()
		})

		// SWITCH MAP TYPE: THIS IS NOT USED FOR NOW // TO DO
		d3.selectAll('.map-container a.mtype').each(function () {
			const sel = d3.select(this)
			const url = new URL(window.location)
			const queryparams = new URLSearchParams(url.search)
			queryparams.set('mtype', sel.attr('data-type'))
			sel.attr('href', `?${queryparams.toString()}`)
		})
		// SWITCH MAP SIZE
		d3.select('.map-container a.mscale')
		.attr('href', function () {
			const url = new URL(window.location)
			const queryparams = new URLSearchParams(url.search)
			<% if (mapscale === 'contain') { %>queryparams.set('mscale', 'full-screen')
			<% } else { %>queryparams.set('mscale', 'contain')<% } %>
			return `?${queryparams.toString()}`
		})
	}
}
</script>