import { BlogCard, BlogProps } from ':components/BlogBlocks.tsx'
import CardList from ':islands/CardList.tsx'
import type { Ref } from 'preact'

export default function BlogCardList(
	{ limit, usePlaceholder, useObserver }: {
		limit?: number
		usePlaceholder?: boolean
		useObserver?: boolean
	},
) {
	if (usePlaceholder) {
		return (
			<CardList
				apiRoute='news/fetchAll'
				builder={builder}
				limit={limit}
				placeholder={Placeholder}
				fallback={Fallback}
				useObserver={useObserver}
			/>
		)
	}

	return (
		<CardList
			apiRoute='news/fetchAll'
			builder={builder}
			limit={limit}
		/>
	)
}

function builder(news: BlogProps) {
	return BlogCard({ ...news, lastUpdate: new Date(news.lastUpdate) })
}

function Placeholder({ ref }: { ref?: Ref<HTMLDivElement> | undefined }) {
	return (
		<div
			class='components__blog_block components__blog_block--card components__blog_block--placeholder'
			ref={ref}
		>
			<h3>Chargement ...</h3>
		</div>
	)
}

function Fallback() {
	return (
		<div
			class='components__blog_block components__blog_block--card components__blog_block--fallback'
			inert
		>
			<h3>Pas de news disponible</h3>
		</div>
	)
}
