<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/environment';
	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 data;
    let { posts } = data;
	let newPosts: any[] = [];
	let page = 1;
	$: posts = [...posts, ...newPosts];

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

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

<AuthorSeo author={data.author} />

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