<!DOCTYPE html>
<html lang='<%- locals.metadata.page.language %>'>
<head>

<%- include ('partials/head.ejs') %> 

<link rel='stylesheet' href='https://unpkg.com/leaflet@1.6.0/dist/leaflet.css'
	integrity='sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=='
	crossorigin=''/>
<script src='https://unpkg.com/leaflet@1.6.0/dist/leaflet.js'
	integrity='sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=='
	crossorigin=''></script>

</head>

<body>

<%# include ('partials/navigate.ejs') %> 

<%- include ('partials/translations.ejs') %> 

<%- include ('partials/menu-languages.ejs') %> 
<%- include ('partials/menu-logo.ejs') %> 
<%- include ('partials/modals.ejs') %> 

<!-- NOT SURE THIS IS NECESSARY -->
<nav>
	<div class='inner'>
	</div>
</nav>


<main id='mobilization' class='mobilization'>
	<div class='inner'>
		<div class='head'>
			<% if (['contribute', 'edit'].includes(locals.metadata.page.activity)) { %>
				<% if (locals.metadata.page.activity === 'edit') { %>
					<a href='<%- locals.metadata.page.referer || "/en/browse/mobilizations/ongoing" %>' class='return'><%- vocabulary['back to browse'][locals.metadata.page.language] %></a>
				<% } %>
				<div class='title' data-placeholder='<%- vocabulary["untitled template"][locals.metadata.page.language] %>' onblur='partialSave("title")' contenteditable><%- locals.mobilization.title %></div>
			<% } else { %>
				<a href='<%- locals.metadata.page.referer || "/en/browse/mobilizations/ongoing" %>' class='return'><%- vocabulary['back to browse'][locals.metadata.page.language] %></a>
				<div class='title' data-placeholder='<%- vocabulary["untitled template"][locals.metadata.page.language] %>'><%- locals.mobilization.title %></div>
				<div class='contributor'><%- vocabulary['host credit'][locals.metadata.page.language](locals.mobilization.host, locals.mobilization.hostname) %></div>
			<% } %>
		</div>
		
		<div class='body'>
			

			<!-- <section class='media-layout layout <%- locals.metadata.page.activity %>'>
				<div class='input-type'>
					<label><%- vocabulary['media'][locals.metadata.page.language] %></label>
				</div>
			</section> -->

			
		</div>
		
	</div>
</main>

<footer>
	<!-- USED BY N PEOPLE IN X EXRCISES -->
</footer>


<script type='text/javascript'>
	// ADD ALL INTERACTION WITH MEDIA AND META INPUT BUTTONS
	var lang = '<%- locals.metadata.page.language %>'; // THIS NEEDS TO BE A GLOBAL VARIABLE
	
	let activity = '<%- locals.metadata.page.activity %>';
	const editing = ['contribute', 'edit'].includes(activity)

	const contributing_countries = (<%- JSON.stringify(locals.cohort) %>).nest('country')
	contributing_countries.forEach(d => {
		d.contributions = (<%- JSON.stringify(locals.contributors) %>).nest('country')?.find(c => c.key === d.key)?.count || 0
	})
	// TO DO: PRETIFY THE TABLE
	const overview = d3.select('main#mobilization div.inner div.body')
		.addElems('table')
	const rows = overview.addElems('tr', 'row', contributing_countries.sort((a, b) => b.contributions - a.contributions))
	rows.addElems('td', 'cell name')
			.html(d => d.key)
	rows.addElems('td', 'cell count')
			.html(d => d.contributions)

	const sections = d3.select('main#mobilization div.inner div.body')
		.addElems('section', `chart-layout layout ${activity}`, <%- JSON.stringify(locals.data) %>)
		.addElems('div', `results-container bar-container`)
		.addElems('div', 'chart chart-bar')
	
	sections.addElems('h1', 'instruction')
		.html(d => d.key)
	// .on('click.focus', function () { d3.select(this).classed('focus', editing && !templated) })

	sections.addElems('svg')
		.each(drawBarchart)

	function drawBarchart (d, i) {
		// console.log(transition)
		const sel = d3.select(this)
		const section = sel.findAncestor('layout')
		const w = section.node().clientWidth || section.node().offsetWidth
		const h = w / 2 //section.node().clientHeight || section.node().offsetHeight
		const p = .1

		// GET THE FILTERS
		const url = new URL(window.location)
		const queryparams = new URLSearchParams(url.search)
		const pads = queryparams.getAll('pad').map(c => +c)
		// TRANSFORM THE DATA
		const values = d.values.filter(c => pads.length ? pads.includes(c.id) : true)
		d.options = values.map(c => c.options).flat().unique('name', true)
		d.counts = values.map(c => c.options.filter(b => b.checked)
			.map(b => { return { name: b.name, pad: c.id } })).flat().group('name', 'pad')
		d.options.forEach(c => {
			if (!d.counts.map(b => b.key).includes(c)) d.counts.push({ key: c, count: 0, p: 0 })
		})

		const xscale = d3.scaleBand()
			.rangeRound([w * p, w * (1 - p)])
			.domain(d.options)
			.padding(p)
		const yscale = d3.scaleLinear()
			.rangeRound([h * (1 - p), h * p])
			.domain([0, d3.max(d.counts, c => c.count)])

		sel.attrs({ 'width': w, 'height': h })

		sel.addElems('g', 'x axis')
			.attr('transform', `translate(${[0, h * (1 - p)]})`)
			.transition()
			.duration(500)
			.call(d3.axisBottom(xscale).tickPadding(10))
		sel.addElems('g', 'y axis')
			.attr('transform', `translate(${[w * p, 0]})`)
			.transition()
			.duration(500)
			.call(d3.axisLeft(yscale).tickPadding(10))

		const bars = sel.addElems('rect', 'bar', c => c.counts, c => c.key)
			.attrs({ 
				'x': c => xscale(c.key), 
				'y': function (c) {
					if (d3.select(this).attr('y')) return d3.select(this).attr('y')
					else return yscale(0)
				},
				'width': xscale.bandwidth(),
				'height': function (c) {
					if (d3.select(this).attr('height')) return d3.select(this).attr('height')
					else h * (1 - p) - yscale(0) >= 0 ? h * (1 - p) - yscale(0) : 0
				}
			})
		.on('click', c => {
			queryparams.delete('pad')

			d.values.filter(b => b.options.filter(a => {
				return a.name === c.key && a.checked
			}).length).map(b => b.id)
			.forEach(b => {
				// console.log(b)
				queryparams.append('pad', b)
			})
			window.history.pushState({}, '<%- locals.metadata.page.title %>', `${window.location.pathname}?${queryparams}`)
			d3.selectAll('.results-container .chart svg').each(drawBarchart)
		})
		.on('dblclick', c => {
			window.location.href = `../browse/pads/public?${c.pad.map(b => `pads=${b}`).join('&')}`
		})

		bars.transition()
			.duration(500)
			.delay((c, j) => i * 250 + j * 25)
			.attrs({ 
				'x': c => xscale(c.key), 
				'y': c => yscale(c.count),
				'width': xscale.bandwidth(),
				'height': c => h * (1 - p) - yscale(c.count) >= 0 ? h * (1 - p) - yscale(c.count) : 0
			})
	}

	// POPULATE THE PAGE
	if (['edit', 'view'].includes(activity)) {
		// const data = <%- JSON.stringify(locals.data || {}) %>;

		// head.select('.title').html(data.title)
		// descriptionLayout.select('.media-container .media-txt').text(data.description)
		// if (data.sections) {
		// 	data.sections.forEach(d => {
		// 		addSection({ data: d, lang: '<%- locals.metadata.page.language %>' })
		// 	})
		// }
		//// CLEAR CHANGES
		// window.sessionStorage.removeItem('changed-content')
	} else {
		// addSection({ lang: '<%- locals.metadata.page.language %>' })
		// addTitle({ lang: '<%- locals.metadata.page.language %>' })
		//// CLEAR CHANGES
		// window.sessionStorage.removeItem('changed-content')
	}

</script>
</body>
</html>