"use client" import { useEffect, useState } from "react" import { formatDistanceToNow, format } from "date-fns" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import Link from "next/link" import strings from "@/strings.json" interface Category { id: number name: string description: string slug: string } interface Post { category: string date: number } export default function Home() { const [posts, setPosts] = useState([]) const [categories, setCategories] = useState([]) const [error, setError] = useState("") const [loading, setLoading] = useState(true) useEffect(() => { Promise.all([ fetch("http://localhost:3001/api/categories/fetchList").then((res) => res.json()), fetch("http://localhost:3001/api/posts/fetchList").then((res) => res.json()), ]) .then(([categoriesData, postsData]) => { setCategories(categoriesData.categories) setPosts(postsData.posts) setLoading(false) }) .catch((error) => { console.error("[!] Error fetching data:", error) setError("Failed to fetch data") setLoading(false) }) }, []) const formatDate = (timestamp: number) => { const date = new Date(timestamp * 1000) const now = new Date() if (date.getFullYear() !== now.getFullYear()) { return format(date, "d MMMM, yyyy") } else { return formatDistanceToNow(date, { addSuffix: true }) } } const getCategoryPostCount = (categoryName: string) => { return posts.filter((post) => post.category === categoryName).length } const getLastUpdatedDate = (categoryName: string) => { const categoryPosts = posts.filter((post) => post.category === categoryName) if (categoryPosts.length === 0) return null return Math.max(...categoryPosts.map((post) => post.date)) } return (

{strings.categoriesHeader}

{loading ? (
) : error ? (
{error}
) : (
{categories.map((category) => { const postCount = getCategoryPostCount(category.name) const lastUpdated = getLastUpdatedDate(category.name) return (
{category.name} {postCount}{" "} {postCount === 1 ? strings.categoriesPostUnitSingle : strings.categoriesPostUnitPlural}
{category.description}
{lastUpdated && (

{strings.categoriesLastUpdatedLabel} {formatDate(lastUpdated)}

)}
{strings.categoriesViewPostsFromLinkText}
) })}
)}
) }