<script lang="ts">
	import { page } from '$app/state';
	import Icon from '@iconify/svelte';
	import SocialHyperlink from '$src/lib/components/SocialHyperlink.svelte';
	import InfoBlock from '$src/lib/components/InfoBlock.svelte';

	function groupPostsByMonthYear(posts: App.BlogPost[]) {
		const groupedPosts = new Map<string, App.BlogPost[]>();

		posts.forEach((post) => {
			const key = new Date(post.date!).toLocaleString('default', {
				month: 'long',
				year: 'numeric'
			});
			if (!groupedPosts.has(key)) groupedPosts.set(key, []);
			groupedPosts.get(key)?.push(post);
		});

		return groupedPosts;
	}

	const groupedPosts = groupPostsByMonthYear(page.data.posts);
</script>

<section class="hero flex shrink-0 flex-col items-center justify-center gap-5 overflow-hidden p-4">
	<div
		class="flex flex-col flex-nowrap items-center justify-center gap-3 lg:flex-row lg:flex-nowrap"
	>
		<div
			class="font-disket text-center text-4xl font-bold text-slate-50 [text-shadow:_0_0_15px_rgba(0,0,0,0.25)] sm:text-6xl md:text-8xl"
		>
			<h1>БЛОГ</h1>
		</div>
	</div>
</section>

<InfoBlock>
	Подпишитесь на нашу <SocialHyperlink href="/blog/rss.xml">RSS ленту</SocialHyperlink>, чтобы не
	пропускать новые посты!
</InfoBlock>

<section class="flex flex-col items-stretch p-2 pb-8 md:p-4">
	{#each groupedPosts.entries() as [monthYear, postsInMonthYear]}
		<h1
			class="mt-10 mb-4 text-left text-2xl font-bold underline decoration-4 md:text-center md:text-4xl md:decoration-8"
		>
			{monthYear}
		</h1>
		<div class="flex flex-col flex-wrap items-stretch gap-4">
			{#each postsInMonthYear as post, i}
				<a
					href="/blog/{post.slug}"
					class="flex flex-col justify-baseline overflow-hidden rounded-lg bg-slate-100 text-slate-950 drop-shadow-xl transition-all hover:drop-shadow-2xl sm:flex-row sm:justify-stretch"
				>
					<div class="relative h-32 w-full basis-auto sm:h-auto sm:basis-1/3">
						{#if post.thumbnail}
							<img
								class="absolute h-full w-full object-cover"
								src={`/blog/${post.slug}/${post.thumbnail}`}
								alt="thumbnail"
							/>
						{/if}
					</div>
					<div class="flex w-full flex-col justify-center p-4 break-words md:p-8">
						<div class="flex flex-row flex-wrap justify-between gap-4 pb-4">
							<div class="flex items-center text-lg font-bold">
								<Icon
									icon="material-symbols:calendar-today"
									class="mr-3"
									style="transform: scale( 1.3 )"
								/>
								<p>
									{new Date(post.date!).toLocaleString('default', {
										month: 'short',
										day: 'numeric',
										year: 'numeric'
									})}
								</p>
							</div>
						</div>

						<h2 class="text-3xl font-bold">{post.title}</h2>

						{#if post.description}
							<p>{post.description}</p>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	{/each}
</section>

<style>
	@import '$src/app.css';
</style>
