<%
	// CREATE ALIASES
	const object = locals.metadata.page.object
	const space = locals.metadata.page.space
	const query = locals.metadata.page.query
	const language = locals.metadata.page.language
	const filter = [
		{ country : locals.data?.[2]?.['countries'] },
		{ 'type': locals.data?.[2]?.['articleType']  },
	]

	const display_content = Object.keys(query)?.filter(key => !['status', 'source', 'mapscale']?.includes(key)).length > 0
%>

<nav id='search-and-filter' class='lg'>
	<form autocomplete='off'>
		<!-- ADD ALL EXISTING HEADER QUERIES THAT ARE NOT IN THE MENU (THIS IS FOR PERSISTENCE OF VIEW PARAMETERS) -->
		<% 
			const menu_keys = locals?.global_info?.filters_menu?.map(d => Object.keys(d)).flat()
			const view_params = Object.keys(query)?.filter(key => !menu_keys?.includes(key) && !['search', 'status', 'source']?.includes(key)) 

			view_params.forEach(d => {
				query[d].forEach(c => {
		%>
			<input type='hidden' name='<%- d %>' value='<%- c %>'>
		<% 
				}) 
			})	
		%>
		
		<% if (display_content) { %>
			<div class='sources'>
				<menu>
					<li class='label'>
						Datasource: 
						<!-- TO DO: TRANSLATE -->
					</li>
						<li class='active'>
							<input type='radio' name='source'  value='blog' checked  onchange='this.form.submit()'>
							<label for='blog'>Articles</label>
						</li>
				</menu>
			</div>
		<% } %>

		<div class='search'>
			<% if (query?.search?.length) { %>
				<input type='text' name='search' id='search-field' class='has-value' value='<%- query?.search %>' onblur='fixLabel(this)'>
			<% } else { %>
				<input type='text' name='search' id='search-field' onblur='fixLabel(this)'>
			<% } %>
			<label for='search-field'><%- vocabulary['search'][language](object === 'contributors') %></label>
			<button id='search' type='submit'><img src='/imgs/icons/i-search.svg'></button>
		</div>

		<% if (filter.length) { %>
			<div class='filters'>
				<% filter?.forEach(d => { %>
					<section>
						<% for (let key in d) { %>
							<div class='filter'>
								<input type='text' id='<%- key %>' onblur='fixLabel(this)'>
								<label for='<%- key %>'><%- vocabulary[key.slice(0, -1).replace(/_/g, ' ')]?.[language](true).capitalize() || vocabulary[key.replace(/_/g, ' ')]?.[language].capitalize() || key.capitalize() %></label>
								<div class='dropdown'>
									<menu>
										<% d[key]?.forEach(c => { %>
											<li>
												<input type='checkbox' value='<%- c.country || c.article_type %>' id='<%- key %>-<%- c.country || c.article_type %>' name='<%- key %>' <% if (query?.[key]?.includes(c?.country?.toString()) ||  query?.[key]?.includes(c?.article_type?.toString()) ) { %>checked<% } %> onchange='addequivalents(this)'>
												<label for='<%- key %>-<%- c.country || c.article_type %>'><%- Number.isInteger(c.country || c.article_type) ? c.country || c.article_type : (c.country?.capitalize() || c.article_type?.capitalize() || vocabulary['unknown'][language]) %><span class='count'><%- c.recordcount %></span></label>
											</li>
										<% }) %>
									</menu>
								</div>
							</div>
						<% } %>
					</section>
				<% }) %>
				<div class='break'></div>
				<button type='submit' class='submit-filters'>
					<%- vocabulary['apply filters'][language] %>
				</button>
			</div>
		<% } %>

		<% if (locals?.stats?.persistent_breakdown?.length > 1) { %>
			<div class='status'>
				<menu>
					<% locals?.stats?.persistent_breakdown?.forEach(d => { %>
						<li>
							<input type='checkbox' class='toggle' id='status-<%- d.status %>' value='<%- d.status %>' name='status' onchange='this.form.requestSubmit[this.form.querySelector("button#search")] || this.form.submit()' <% if (!query?.status || query?.status?.map(d => +d).includes(d.status)) { %>checked<% } %>>
							<label for='status-<%- d.status %>' data-content='<%- d.count %>'></label>
							<p>
								<%- vocabulary['status'][language](object, d.status, d.count) %>
							</p>
						</li>
					<% }) %>
				</menu>
			</div>
		<% } %>


		<div class='global-actions'></div>
		
		<% if (filter?.length) { %>
			<button type='button' class='expand-filters' onclick='expandfilters(this)'>
				<div class='line l1'></div><div class='line l2'></div><div class='line l3'></div>
			</button>
		<% } %>
	</form>
</nav>


<script type='text/javascript'>
	function expandfilters (node) {
		d3.select(node).toggleClass('close')
		const filters = node.form.querySelector('.filters')
		const padding = filters.querySelector('section').getBoundingClientRect().height / 2
		// WE NEED TO MANUALLY ADD THE BOTTOM PADDING BECAUSE IT IS NOT COMPUTED IN THE scrollHeight
		if (filters.style.maxHeight) {
			filters.style.maxHeight = null
			filters.style.overflow = 'hidden'
		} else filters.style.maxHeight = `${filters.scrollHeight + padding}px`
	}
	function addequivalents (node, equivalents) {
		const parent = d3.select(node.parentNode)
		parent.selectAll('input[type=hidden]')
			.attr('disabled', node.checked ? null : true)
	}
	
	// MAIN SEARCH BAR
	d3.selectAll('.filter input[type=text]')
	.on('keyup', function () {
		const node = this
		const dropdown = d3.select(node).findAncestor('filter').select('.dropdown')
		dropdown.selectAll('menu li')
			.classed('hide', function () {
				return !this.textContent.trim().toLowerCase()
				.includes(node.value.trim().toLowerCase())
			})
	}).on('focus', function () {
		const dropdown = d3.select(this).findAncestor('filter').select('.dropdown')
		const filters = d3.select(this).findAncestor('filters')
		if (dropdown.node()) dropdown.node().style.maxHeight = `${Math.min(dropdown.node().scrollHeight, 300)}px`
		if (filters) filters.node().style.overflow = 'visible'

		dropdown.selectAll('label, a').on('mousedown', function () { 
			d3.event.preventDefault()
			// this.previousElementSibling.setAttribute('checked', '')
		})
	}).on('blur', function () {
		const dropdown = d3.select(this).findAncestor('filter').select('.dropdown')
		if (dropdown.node()) dropdown.node().style.maxHeight = null
	})
</script>