{{ template "base.html" . }}

{{ define "extrahead" }}
	<script src="{{ static "js/templates.js" }}"></script>
{{ end }}

{{ define "content" }}
	{{ template "showcase_templates.html" }}

	<div class="content-block">
		<div class="ph2 ph0-ns pb4">
			<div class="optionbar">
				<div class="tc tl-l w-100 pb2">
					<h2 class="di-l mr2-l">Community Showcase</h2>
					<ul class="list dib-l">
						<li class="dib-ns ma0 ph2">
							<a href="{{ .ShowcaseAtomFeedUrl }}"><span class="icon big">4</span> Showcase Feed</a>
						</li>
					</ul>
				</div>
			</div>
			<div id="showcase-container" class="mh2 mh0-ns pb4"></div>
		</div>
	</div>

	<template id="showcase-month">
		<h3 data-tmpl="dateHeader" class="mt3 f4 fw5">Unknown Date</h3>
		<div data-tmpl="itemsContainer" class="month-container"></div>
	</template>

	<script>
		const showcaseItems = JSON.parse("{{ .ShowcaseItems }}");

		const monthTemplate = makeTemplateCloner('showcase-month');
		const showcaseContainer = document.querySelector('#showcase-container');

		const itemsByMonth = []; // array of arrays

		let currentMonth = null;
		let currentYear = null;
		let currentMonthItems = [];
		for (const item of showcaseItems) {
			const date = new Date(item.date * 1000);

			if (date.getMonth() !== currentMonth || date.getFullYear() !== currentYear) {
				// rolled over to new month
				if (currentMonthItems.length > 0) {
					itemsByMonth.push(currentMonthItems);
				}

				currentMonth = date.getMonth();
				currentYear = date.getFullYear();
				currentMonthItems = [];
			}

			currentMonthItems.push(item);
		}
		if (currentMonthItems.length > 0) {
			itemsByMonth.push(currentMonthItems);
		}

		for (const monthItems of itemsByMonth) {
			const month = monthTemplate();

			const firstDate = new Date(monthItems[0].date * 1000);
			month.dateHeader.textContent = firstDate.toLocaleDateString([], { month: 'long', year: 'numeric' });

			initShowcaseContainer(month.root.querySelector('.month-container'), monthItems);
			showcaseContainer.appendChild(month.root);
		}
	</script>
{{ end }}
