<script lang="ts" context="module">
	export const load: Load = async ({ params }) => {
		const authorSlug = params.author;
		const authorObj = await readAuthor(authorSlug);

		if (!authorObj) {
			return {
				status: 404,
				error: new Error('Author not found')
			};
		}
		
		const posts = await browsePostWithAuthor(authorSlug);

		return {
			props: {
				author: authorObj,
				posts: posts
			}
		};
	};
</script>

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

	export let author: any;

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

	async function loadPage() {
		const posts = await browsePostWithAuthor(author.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>Author: {author.name} - Damillora's Virtual Memoir</title>
</svelte:head>

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

<AuthorSeo {author} />

<Container>
	<Post>
		<AuthorHeader
			profile_image={author.profile_image}
			name={author.name}
			bio={author.bio}
			website={author.website}
			facebook={author.facebook}
			twitter={author.twitter}
		/>
	</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>
