import Link from "next/link";
import Image from "next/image";
import { fetchPortfolioPosts } from "../utils/useWordpress";

export default async function PortfolioGridServerSide() {
	let posts = [];
	let error = null;

	try {
		// fetchPortfolioPosts récupère automatiquement les images de couverture
		const result = await fetchPortfolioPosts({
			perPage: 10,
			fetchOptions: {
				next: { revalidate: 3600 }, // Revalide toutes les heures
			},
		});
		posts = result.posts;
	} catch (err) {
		error = err.message;
	}

	if (error) {
		return (
			<div className='flex justify-center items-center py-12'>
				<p className='text-red-500 text-lg'>Erreur: {error}</p>
			</div>
		);
	}

	return (
		<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 px-8 py-8'>
			{posts.map((post) => {
				return (
					<Link href={`/projects/${post.slug}`} key={post.id}>
						<article className='bg-white dark:bg-neutral-800 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow'>
							{post.featuredImageUrl && (
								<div className='relative w-full h-48 overflow-hidden'>
									<Image
										src={post.featuredImageUrl}
										alt={post.title.rendered || "Image du projet"}
										fill
										className='object-cover'
										sizes='(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw'
									/>
								</div>
							)}
							<div className='p-6'>
								<h3 className='text-xl font-bold mb-2 text-neutral-800 dark:text-white'>
									{post.title.rendered}
								</h3>
								<div
									className='text-neutral-600 dark:text-neutral-300 line-clamp-3'
									dangerouslySetInnerHTML={{
										__html:
											post.excerpt?.rendered ||
											post.content.rendered?.substring(0, 150) + "...",
									}}
								/>
							</div>
						</article>
					</Link>
				);
			})}
		</div>
	);
}
