---
import type { CollectionEntry } from 'astro:content';
import { getCollection } from 'astro:content';
import FormattedDate from './FormattedDate.astro';

export interface Props {
	headingLevel?: 1 | 2 | 3 | 4 | 5 | 6,
	hideAuthor?: boolean,
	maxEntries?: number,
};

const { headingLevel = 2, hideAuthor = false, maxEntries } = Astro.props;

const allPosts = (await getCollection('blog')).filter((post) => !post.data.hidden);

const posts = maxEntries === undefined
	? allPosts
	: allPosts.sort(sortByPubDateDescending).slice(0, maxEntries);

const distinctYears: number[] = posts
	.map(post => post.data.pubDate.getFullYear())
	.reduce<number[]>((acc, curr) => acc.includes(curr) ? acc : [...acc, curr], [])
	.sort((a, b) => b - a);

function matchesYear(year: number) {
	return (post: CollectionEntry<'blog'>) => post.data.pubDate.getFullYear() === year;
}

function sortByPubDateDescending(post1: CollectionEntry<'blog'>, post2: CollectionEntry<'blog'>) {
	const date1 = post1.data.pubDate.getTime();
	const date2 = post2.data.pubDate.getTime();
	return date2 - date1;
}

const headingElem = `h${headingLevel}`;
const subHeadingElem = `h${headingLevel + 1}`

const canonicalBlogUrl = new URL('blog', Astro.site)
---

<section class="h-feed">
	<Fragment set:html={`
		<${headingElem} class="p-name">
			My blog
		</${headingElem}>
	`} />

	<aside>
		<p hidden={hideAuthor}>
			This blog is written by <a class="p-author h-card" href="/">Joe Carstairs</a>
		</p>

		<p hidden>
			<a class="u-url" href={canonicalBlogUrl}>Permalink</a>
		</p>
	</aside>

	{ distinctYears.map(year => (
		<Fragment set:html={`
			<${subHeadingElem}>
				${year}
			</${subHeadingElem}>
		`} />
		<ul>
			{ posts.filter(matchesYear(year)).sort(sortByPubDateDescending).map(post => (
				<li class="h-entry">
					<a class="u-url p-name" href={`/blog/${post.slug}`}>{post.data.title}</a>.
					<Fragment set:html={post.data.description} />
					Added: <FormattedDate date={post.data.pubDate} />
				</li>
			)) }
		</ul>
	)) }

	{ (maxEntries !== undefined && maxEntries < allPosts.length)
		? <p class="full-feed-link"><a href="/blog">All blog posts</a></p>
		: <></>
	}
</section>
