import { useState, useEffect } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { useCookieConsent } from "../context/CookieConsent"; // Modèle de données pour un post Facebook interface FacebookPost { id: number | string; date: string; content: string; imageSrc: string; link: string; } // Interface pour la réponse de l'API Facebook interface FacebookApiPost { id: string; created_time: string; message?: string; full_picture?: string; permalink_url: string; attachments?: { data: Array<{ title?: string; media?: { image?: { src: string }; }; }>; }; } // Composant Spinner const LoadingSpinner = () => (
); const ErrorMessage = () => (

Suivez nos dernières actions directement sur Facebook.

Voir la page Facebook
); // Affiché tant que l'utilisateur n'a pas consenti au chargement du contenu tiers const ConsentPlaceholder = ({ onAccept }: { onAccept: () => void }) => (
f

Pour afficher nos actualités Facebook, nous avons besoin de votre accord pour charger ce contenu tiers.

Voir la page Facebook
); // Utilitaire pour formater la date (ex: "Il y a 2 jours") const timeAgo = (dateString: string) => { const date = new Date(dateString); const now = new Date(); const seconds = Math.floor((now.getTime() - date.getTime()) / 1000); if (seconds < 60) return "À l'instant"; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `Il y a ${minutes} minute${minutes > 1 ? "s" : ""}`; const hours = Math.floor(minutes / 60); if (hours < 24) return `Il y a ${hours} heure${hours > 1 ? "s" : ""}`; const days = Math.floor(hours / 24); if (days < 30) return `Il y a ${days} jour${days > 1 ? "s" : ""}`; const months = Math.floor(days / 30); if (months < 12) return `Il y a ${months} mois`; return `Il y a ${Math.floor(days / 365)} an(s)`; }; export default function FacebookCarousel() { const { consent, accept } = useCookieConsent(); const [posts, setPosts] = useState([]); const [currentIndex, setCurrentIndex] = useState(0); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); const [isPaused, setIsPaused] = useState(false); // Gestion du défilement automatique useEffect(() => { // On n'active pas l'autoplay si : chargement, erreur, pas assez de posts, ou pause (souris dessus) if (loading || error || posts.length < 2 || isPaused) return; const interval = setInterval(() => { setCurrentIndex((prev) => (prev === posts.length - 1 ? 0 : prev + 1)); }, 5000); // Change toutes les 5 secondes return () => clearInterval(interval); }, [loading, error, posts.length, isPaused]); useEffect(() => { if (consent !== "accepted") return; const fetchFacebookPosts = async () => { const fields = "id,created_time,message,full_picture,permalink_url,attachments"; try { // Ni le token ni l'ID de page ne sont exposés au navigateur : // - en dev, le proxy de Vite les injecte côté serveur // - en prod, nginx les injecte côté serveur const url = `/api/facebook/posts?fields=${fields}&limit=6`; // 'credentials: omit' évite d'envoyer des cookies tiers, ce qui réduit les blocages CORS/Pistage const response = await fetch(url, { mode: "cors", credentials: "omit", }); const data = await response.json(); if (!response.ok || data.error) { console.error( "Erreur API Facebook:", data.error || response.statusText, ); throw new Error("API Error"); } if (data.data && data.data.length > 0) { const formattedPosts = (data.data as FacebookApiPost[]).map( (post) => { let imageSrc = post.full_picture || post.attachments?.data[0]?.media?.image?.src || "/logo.png"; // On passe par le proxy même origine (nginx en prod, Vite en dev) // pour éviter le blocage de pistage du navigateur, le mixed-content // et les 403 du CDN Facebook. if (imageSrc.startsWith("http")) { imageSrc = `/api/proxy-image?url=${encodeURIComponent(imageSrc)}`; } return { id: post.id, date: timeAgo(post.created_time), content: post.message || post.attachments?.data[0]?.title || "Découvrez ce contenu directement sur notre page Facebook.", imageSrc, link: post.permalink_url, }; }, ); if (formattedPosts.length > 0) { setPosts(formattedPosts); } } } catch { setError(true); } finally { setLoading(false); } }; fetchFacebookPosts(); }, [consent]); const nextPost = () => { setCurrentIndex((prev) => (prev === posts.length - 1 ? 0 : prev + 1)); }; const prevPost = () => { setCurrentIndex((prev) => (prev === 0 ? posts.length - 1 : prev - 1)); }; return (
{/* En-tête du Carrousel */}

Actualités

Suivez nos dernières actions en direct sur Facebook.

{/* Flèches de navigation */} {consent === "accepted" && posts.length > 0 && !loading && !error && (
)}
{/* Zone du Carrousel */}
setIsPaused(true)} onMouseLeave={() => setIsPaused(false)} > {consent !== "accepted" ? ( ) : loading ? ( ) : error || posts.length === 0 ? ( ) : ( {/* Image du Post */}
Illustration du post
{/* Contenu du Post */}
f

Cœur UA PAM

{posts[currentIndex].date}

"{posts[currentIndex].content}"

Voir sur Facebook
)}
); }