<script lang="ts" context="module">
	import { browsePost } from '$lib/content/contentApi';

	export async function load() {
		const posts = await browsePost();

		return {
			props: {
				posts: posts
			}
		};
	}
</script>

<script lang="ts">
	import { browser } from '$app/env';
	import dayjs from 'dayjs';

	import Container from '@damillora/plachta/components/Container/Container.svelte';
	import Hero from '@damillora/plachta/components/Hero/Hero.svelte';
	import Index from '@damillora/plachta/components/PageTypes/Index.svelte';
	import PostCard from '@damillora/plachta/components/PostCard/PostCard.svelte';
	import { onMount } from 'svelte';
import IndexSeo from '$lib/components/SEO/IndexSEO.svelte';

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

	async function loadPage() {
		const posts = await browsePost(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>Damillora's Virtual Memoir</title>
</svelte:head>
<IndexSeo />

<Hero background="/images/default-feature.jpg" />

<Container>
	<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}
	</Index>
	<div bind:this={footer} />
</Container>
