<script lang="ts" context="module">
	export const load: Load = async ({ params }) => {
		const tagSlug = params.tag;
			const tagObj = await readTag(tagSlug);
		if (!tagObj) {
			return {
				status: 404,
				error: new Error('Tag not found')
			};
		}
		
			const posts = await browsePostWithTag(tagSlug);

			return {
				props: {
					tag: tagObj,
					posts: posts
				}
			};
	};
</script>

<script lang="ts">
	import Hero from '@damillora/plachta/components/Hero/Hero.svelte';
	import PostCard from '@damillora/plachta/components/PostCard/PostCard.svelte';
	import Index from '@damillora/plachta/components/PageTypes/Index.svelte';
	import TagHeader from '@damillora/plachta/components/Post/TagHeader.svelte';
	import Post from '@damillora/plachta/components/PageTypes/Post.svelte';
	import Container from '@damillora/plachta/components/Container/Container.svelte';
	import { browsePostWithTag, readTag } from '$lib/content/contentApi';
	import type { Load } from '@sveltejs/kit';
	import { onMount } from 'svelte';
	import { browser } from '$app/env';
	import dayjs from 'dayjs';
	import TagSeo from '$lib/components/SEO/TagSEO.svelte';

	export let tag: any;
	export let posts: any[];
	let newPosts: any[] = [];
	let page = 1;
	$: posts = [...posts, ...newPosts];

	async function loadPage() {
		const posts = await browsePostWithTag(tag.slug, page);
		newPosts = posts;
	}

	let footer: HTMLElement;

	onMount(() => {
		if (browser) {
			const handleIntersect: IntersectionObserverCallback = (entries, observer) => {
				const first = entries[0];
				if (first.isIntersecting) {
					page++;
					loadPage();
				}
			};
			const options = { threshold: 0.125, rootMargin: '-100% 0% 100%' };
			const observer = new IntersectionObserver(handleIntersect, options);
			observer.observe(footer);
		}
	});
</script>

<svelte:head>
	<title>Tag: {tag.name} - Damillora's Virtual Memoir</title>
</svelte:head>

<TagSeo {tag} />

<Hero background={tag.feature_image ?? `/images/default-feature.jpg`} />

<Container>
	<Post>
		<TagHeader accent_color={tag.accent_color} name={tag.name} description={tag.description} />
	</Post>

	<Index>
		{#each posts as post}
			<PostCard
				title={post.title}
				authors={post.authors}
				primary_tag={post.primary_tag}
				date={dayjs(post.published_at).format('DD MMM YYYY')}
				reading_time={`${post.reading_time} min read`}
				excerpt={post.excerpt}
				feature_image={post.feature_image ?? '/images/default-feature.jpg'}
				url={post.url}
			/>
		{/each}
		<div bind:this={footer} />
	</Index>
</Container>
