import { notFound } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import Nav from "../../components/Nav";
import { fetchPortfolioPostBySlug, fetchMedia } from "../../utils/useWordpress";

export default async function ProjectDetail({ params }) {
	const { slug } = params;

	if (!slug) {
		notFound();
	}

	let post = null;
	let featuredImageUrl = null;

	try {
		// Récupérer le post par son slug
		post = await fetchPortfolioPostBySlug(slug, {
			next: { revalidate: 3600 }, // Revalide toutes les heures
		});

		if (!post) {
			notFound();
		}

		// Récupérer l'image featured si elle existe
		if (post.featured_media) {
			featuredImageUrl = await fetchMedia(post.featured_media, {
				next: { revalidate: 3600 },
			});
		}
	} catch (error) {
		console.error("Erreur lors de la récupération du projet:", error);
		notFound();
	}

	return (
		<main>
			<Nav />
			<article className='max-w-4xl mx-auto px-8 py-8'>
				<Link
					href='/projects'
					className='inline-block mb-6 text-blue-600 dark:text-blue-400 hover:underline'>
					← Retour aux projets
				</Link>

				{featuredImageUrl && (
					<div className='relative w-full h-96 mb-8 rounded-lg overflow-hidden'>
						<Image
							src={featuredImageUrl}
							alt={post.title?.rendered || "Image du projet"}
							fill
							className='object-cover'
							priority
							sizes='(max-width: 768px) 100vw, 896px'
						/>
					</div>
				)}

				<h1 className='text-4xl font-bold mb-6 text-neutral-800 dark:text-white'>
					{post.title?.rendered || "Sans titre"}
				</h1>

				<div
					className='prose prose-lg dark:prose-invert max-w-none text-neutral-700 dark:text-neutral-300'
					dangerouslySetInnerHTML={{
						__html: post.content?.rendered || "",
					}}
				/>
			</article>
		</main>
	);
}
