"use client";
import { useState, useEffect } from "react";

export default function PostGridClientSide({ apiUrl = "https://deligraph.com/wp-json/wp/v2/portfolio" }) {
	const [posts, setPosts] = useState([]);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState(null);

	useEffect(() => {
		const fetchPosts = async () => {
			try {
				setLoading(true);
				setError(null);
				const response = await fetch(apiUrl);

				if (!response.ok) {
					throw new Error(`Erreur HTTP: ${response.status}`);
				}

				const data = await response.json();
				setPosts(data);
			} catch (err) {
				setError(err.message);
				console.error("Erreur lors du fetch:", err);
			} finally {
				setLoading(false);
			}
		};

		fetchPosts();
	}, [apiUrl]);

	if (loading) {
		return (
			<div className='flex justify-center items-center py-12'>
				<p className='text-lg'>Chargement des posts...</p>
			</div>
		);
	}

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

	return (
		<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 px-8 py-8'>
			{posts.map((post) => (
				<article
					key={post.id}
					className='bg-white dark:bg-neutral-800 rounded-lg p-6 shadow-md hover:shadow-lg transition-shadow'>
					<h3 className='text-xl font-bold mb-2 text-neutral-800 dark:text-white'>
						{post.title.rendered}
					</h3>
					<p className='text-neutral-600 dark:text-neutral-300 line-clamp-3'>
						{post.content.rendered}
					</p>
				</article>
			))}
		</div>
	);
}
