---
import type { ClubsPropsPages } from '@devprotocol/clubs-core'
import { ClubsSlotName } from '@devprotocol/clubs-core'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { getDefaultClient, getPaginatedPosts } from '../db/redis'
import { mask } from '../fixtures/masking'
import type { OptionsDatabase } from '../types'
dayjs.extend(relativeTime)

const { PageContentHomeBeforeContent } = ClubsSlotName

interface Props extends ClubsPropsPages {
	scope: string
	feedId: string
	slots: OptionsDatabase['slots']
}

const { scope, feedId, slots } = Astro.props

const widgetContent = slots?.[PageContentHomeBeforeContent]

const client = await getDefaultClient()
const posts = await getPaginatedPosts({
	scope,
	client,
	page: 0,
})
await client.quit()

const limitedPosts = posts
	.filter((post) => {
		return posts.indexOf(post) < (widgetContent?.items ?? 0)
	})
	.map(mask)

const getTimeAgo = (date: Date) => {
	return dayjs(date).fromNow()
}
---

{
	widgetContent?.enabled && (
		<section class="grid">
			<h2 class="mb-4 text-center text-2xl font-bold lg:text-4xl">
				{widgetContent?.title}
			</h2>
			<ul class="p-2 border rounded-md">
				{limitedPosts.map((post) => (
					<li>
						<a
							class="p-4 grid justify-around grid-cols-[1fr_auto]"
							href={`/posts/${feedId}/${post.id}`}
						>
							<span class="font-bold ">{post.title}</span>
							<span class="opacity-60">{getTimeAgo(post.created_at)}</span>
						</a>
					</li>
				))}
			</ul>
		</section>
	)
}
