"use client"; import Link from "next/link"; import { useEffect, useState } from "react"; import { PostType, Categorie, PaginatedResponse } from "@/Type/post"; import { getBlogPosts, getBlogCategories, extractPageNumber } from "@/lib/blogApi"; export default function BlogSection() { const [mounted, setMounted] = useState(false); const [posts, setPosts] = useState([]); const [recentPosts, setRecentPosts] = useState([]); const [categories, setCategories] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [totalPages, setTotalPages] = useState(1); const [nextPage, setNextPage] = useState(null); const [prevPage, setPrevPage] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { setMounted(true); // Initialize WOW.js after mount if (typeof window !== "undefined" && window.WOW) { new window.WOW().init(); } }, []); useEffect(() => { const fetchData = async () => { setIsLoading(true); setError(null); try { // Fetch posts, recent posts (from different page) and categories in parallel const [postsData, recentPostsData, categoriesData] = await Promise.all([ getBlogPosts(currentPage), getBlogPosts(currentPage === 1 ? 2 : 1), // Get from different page getBlogCategories() ]); setPosts(postsData.results); setNextPage(postsData.next); setPrevPage(postsData.previous); // Calculate total pages (assuming 10 items per page, adjust if needed) const itemsPerPage = postsData.results.length || 10; setTotalPages(Math.ceil(postsData.count / itemsPerPage)); // Set recent posts (exclude current page posts) const currentPostSlugs = new Set(postsData.results.map(p => p.slug)); const filteredRecentPosts = recentPostsData.results .filter(post => !currentPostSlugs.has(post.slug)) .slice(0, 3); // If we don't have enough recent posts, try to get more from page 3 if (filteredRecentPosts.length < 3 && currentPage !== 3) { try { const additionalPostsData = await getBlogPosts(3); const additionalFiltered = additionalPostsData.results .filter(post => !currentPostSlugs.has(post.slug)) .slice(0, 3 - filteredRecentPosts.length); setRecentPosts([...filteredRecentPosts, ...additionalFiltered]); } catch { setRecentPosts(filteredRecentPosts); } } else { setRecentPosts(filteredRecentPosts); } setCategories(categoriesData); } catch (err) { console.error("Error fetching blog data:", err); setError("Blog yazıları yüklenirken bir hata oluştu."); } finally { setIsLoading(false); } }; fetchData(); }, [currentPage]); const handlePageChange = (page: number) => { if (page >= 1 && page <= totalPages) { setCurrentPage(page); window.scrollTo({ top: 0, behavior: "smooth" }); } }; const formatDate = (dateString: string) => { const date = new Date(dateString); return date.toLocaleDateString("tr-TR", { year: "numeric", month: "long", day: "numeric" }); }; const getPageNumbers = () => { const pages: (number | string)[] = []; const maxVisible = 5; if (totalPages <= maxVisible) { for (let i = 1; i <= totalPages; i++) { pages.push(i); } } else { if (currentPage <= 3) { for (let i = 1; i <= 4; i++) { pages.push(i); } pages.push("..."); pages.push(totalPages); } else if (currentPage >= totalPages - 2) { pages.push(1); pages.push("..."); for (let i = totalPages - 3; i <= totalPages; i++) { pages.push(i); } } else { pages.push(1); pages.push("..."); for (let i = currentPage - 1; i <= currentPage + 1; i++) { pages.push(i); } pages.push("..."); pages.push(totalPages); } } return pages; }; // Get unique tags from all posts const allTags = Array.from( new Set( posts.flatMap(post => post.tags.map(tag => tag.tag)) ) ); // Get category count from API data const getCategoryCount = (category: Categorie): number => { if (category.posts && category.posts.length > 0) { return category.posts.length; } return 0; }; // Flatten categories to show both parent and child categories const flattenCategories = (categories: Categorie[]): Categorie[] => { const result: Categorie[] = []; categories.forEach(category => { if (category.is_active) { // Add parent category result.push(category); // Add child categories if they exist if (category.child && category.child.length > 0) { category.child.forEach(child => { if (child.is_active) { result.push(child); } }); } } }); return result; }; return (
{/* Divider */}
{/* Blog List Wrapper */}
{isLoading ? (

Yükleniyor...

) : error ? (

{error}

) : posts.length === 0 ? (

Henüz blog yazısı bulunmamaktadır.

) : ( <> {posts.map((post, index) => (
{/* Post Image */} {post.image && (
{post.title}
)} {/* Post Body */}
{post.title}

{post.content.length > 200 ? `${post.content.substring(0, 200)}...` : post.content}

Read More
))} {/* Pagination */} {totalPages > 1 && ( )} )}
{/* Widget */}
Search Here
{/* Form */}
{/* Widget - Categories */}
Categories
    {categories.map((category) => { if (!category.is_active) return null; return (
  • {category.title} {getCategoryCount(category)} {/* Child Categories */} {category.child && category.child.length > 0 && (
      {category.child .filter(child => child.is_active) .map((child) => (
    • {child.title} {getCategoryCount(child)}
    • ))}
    )}
  • ); })}
{/* Widget - Recent Posts */}
Recent Posts
{recentPosts.length > 0 ? ( recentPosts.map((post) => (
{post.thumb && (
{post.title}
)}

{formatDate(post.created_at)}

{post.title}
)) ) : (

Henüz yazı bulunmamaktadır.

)}
{/* Widget - Tags */} {allTags.length > 0 && (
Tags
    {allTags.slice(0, 8).map((tag, index) => (
  • {tag}
  • ))}
)}
{/* Divider */}
); } // Extend Window interface declare global { interface Window { WOW: any; } }