Files
got-gaming/components/navigation/ChallengeBadge.tsx
2025-12-16 11:19:54 +01:00

79 lines
2.3 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
interface ChallengeBadgeProps {
initialCount?: number;
onNavigate?: () => void;
}
export default function ChallengeBadge({
initialCount = 0,
onNavigate,
}: ChallengeBadgeProps) {
const [count, setCount] = useState(initialCount);
useEffect(() => {
// Si on a déjà un initialCount, l'utiliser et ne pas faire d'appel immédiat
// On rafraîchit seulement après un délai pour éviter les appels redondants
if (initialCount > 0) {
setCount(initialCount);
}
// Récupérer le nombre de défis actifs (seulement si pas d'initialCount ou pour rafraîchir)
const fetchActiveCount = async () => {
try {
const response = await fetch("/api/challenges/active-count");
const data = await response.json();
setCount(data.count || 0);
} catch (error) {
console.error("Error fetching active challenges count:", error);
}
};
// Si pas d'initialCount, charger immédiatement, sinon attendre 30s avant le premier refresh
if (initialCount === 0) {
fetchActiveCount();
}
// Rafraîchir toutes les 30 secondes
const interval = setInterval(fetchActiveCount, 30000);
return () => clearInterval(interval);
}, [initialCount]);
return (
<Link
href="/challenges"
onClick={onNavigate}
className={`inline-flex items-center gap-1.5 transition text-xs font-normal uppercase tracking-widest ${
onNavigate ? "py-2" : ""
}`}
style={{ color: "var(--foreground)" }}
onMouseEnter={(e) =>
(e.currentTarget.style.color = "var(--accent-color)")
}
onMouseLeave={(e) => (e.currentTarget.style.color = "var(--foreground)")}
title={
count > 0
? `${count} défi${count > 1 ? "s" : ""} actif${count > 1 ? "s" : ""}`
: "Défis"
}
>
<span>DÉFIS</span>
{count > 0 && (
<span
className="flex h-5 w-5 min-w-[20px] items-center justify-center rounded-full text-[10px] font-bold leading-none"
style={{
backgroundColor: "var(--accent)",
color: "var(--background)",
}}
>
{count > 9 ? "9+" : count}
</span>
)}
</Link>
);
}