web-kabar-harapan/components/landing-page/news.tsx

269 lines
8.1 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import Image from "next/image";
import { getListArticle } from "@/service/article";
import Link from "next/link";
import { getAdvertise } from "@/service/advertisement";
// Type dari API
type Article = {
id: number;
title: string;
description: string;
categoryName: string;
createdAt: string;
slug: string;
createdByName: string;
thumbnailUrl: string;
categories: { title: string }[];
files: { fileUrl: string; file_alt: string }[];
};
type Advertise = {
id: number;
title: string;
description: string;
placement: string;
contentFileUrl: string;
redirectLink: string;
};
export default function News() {
const [articlesByCategory, setArticlesByCategory] = useState<
Record<string, Article[]>
>({});
const [loading, setLoading] = useState(true);
const [visiblePosts, setVisiblePosts] = useState<Record<string, number>>({});
const [bannerAd, setBannerAd] = useState<Advertise | null>(null);
useEffect(() => {
initStateAdver();
}, []);
async function initStateAdver() {
const req = {
limit: 100,
page: 1,
sort: "desc",
sortBy: "created_at",
isPublish: true,
};
try {
const res = await getAdvertise(req);
const data: Advertise[] = res?.data?.data || [];
// filter iklan dengan placement = "banner"
const banner = data.find((ad) => ad.placement === "banner");
if (banner) {
setBannerAd(banner);
}
} catch (err) {
console.error("Error fetching advertisement:", err);
}
}
useEffect(() => {
fetchArticles();
}, []);
async function fetchArticles() {
try {
const req = {
limit: "20", // ambil lebih banyak, nanti dibagi per kategori
page: 1,
search: "",
categorySlug: "",
sort: "desc",
isPublish: true,
sortBy: "created_at",
};
const res = await getListArticle(req);
const allArticles: Article[] = res?.data?.data || [];
// Group by category
const grouped: Record<string, Article[]> = {};
allArticles.forEach((a) => {
const cat = a.categoryName || a.categories?.[0]?.title || "Lainnya";
if (!grouped[cat]) grouped[cat] = [];
grouped[cat].push(a);
});
setArticlesByCategory(grouped);
// Set default visiblePosts untuk setiap kategori
const initialVisible: Record<string, number> = {};
Object.keys(grouped).forEach((cat) => {
initialVisible[cat] = 2; // awal 2 post bawah
});
setVisiblePosts(initialVisible);
} catch (error) {
console.error("Gagal ambil artikel:", error);
} finally {
setLoading(false);
}
}
return (
<>
<div className="max-w-7xl mx-auto relative mb-2 h-[120px] overflow-hidden flex items-center border my-8">
{bannerAd ? (
<a
href={bannerAd.redirectLink}
target="_blank"
rel="noopener noreferrer"
className="block w-full"
>
<div className="relative w-full h-[350px] flex justify-center">
<Image
src={bannerAd.contentFileUrl}
alt={bannerAd.title || "Iklan Banner"}
width={1200} // ukuran dasar untuk responsive
height={350}
className="object-cover w-full h-full"
/>
</div>
</a>
) : (
<Image
src="/image-kolom.png"
alt="Berita Utama"
width={1200}
height={188}
className="object-contain w-full h-[188px]"
/>
)}
</div>
<div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
{loading && <p className="text-center">Memuat data...</p>}
{!loading &&
Object.keys(articlesByCategory).map((category) => {
const posts = articlesByCategory[category];
if (!posts?.length) return null;
const postsTop = posts.slice(0, 2); // 2 atas
const postsBottom = posts.slice(2); // sisanya
return (
<div key={category} className="border p-4 bg-white">
{/* Header kategori */}
<div className="bg-[#3677A8] text-white px-3 py-1 text-sm font-bold inline-block mb-4">
{category}
</div>
{/* Posts atas */}
{postsTop.map((post) => (
<PostItem key={post.id} post={post} />
))}
{/* Banner Kolom PPS */}
<div className="relative mb-2 h-[120px] overflow-hidden flex items-center border my-8">
{bannerAd ? (
<a
href={bannerAd.redirectLink}
target="_blank"
rel="noopener noreferrer"
className="block w-full"
>
<div className="relative w-full h-[350px] flex justify-center">
<Image
src={bannerAd.contentFileUrl}
alt={bannerAd.title || "Iklan Banner"}
width={1200} // ukuran dasar untuk responsive
height={350}
className="object-cover w-full h-full"
/>
</div>
</a>
) : (
<Image
src="/image-kolom.png"
alt="Berita Utama"
width={1200}
height={188}
className="object-contain w-full h-[188px]"
/>
)}
</div>
{/* Posts bawah (pakai visiblePosts[category]) */}
{postsBottom
.slice(0, visiblePosts[category] || 2)
.map((post) => (
<PostItem key={post.id} post={post} />
))}
{/* Tombol Load More */}
{(visiblePosts[category] || 2) < postsBottom.length && (
<div className="flex justify-center">
<button
onClick={() =>
setVisiblePosts((prev) => ({
...prev,
[category]: (prev[category] || 2) + 2,
}))
}
className="bg-black text-white text-xs px-4 py-2 hover:bg-gray-800 mt-4"
>
LOAD MORE POSTS
</button>
</div>
)}
</div>
);
})}
</div>
</>
);
}
function PostItem({ post }: { post: Article }) {
return (
<div className="flex gap-4 mb-6 pb-4">
<Link
className="flex items-center gap-4 "
href={`/details/${post?.slug}`}
>
<div className="relative w-40 h-28 flex-shrink-0">
<Image
src={
post.thumbnailUrl ||
post.files?.[0]?.fileUrl ||
"/placeholder.jpg"
}
alt={post.files?.[0]?.file_alt || post.title}
fill
className="object-cover"
/>
</div>
{/* Konten */}
<div className="flex flex-col justify-between">
<div>
<h2 className="font-semibold text-lg mb-1 hover:text-[#3677A8] cursor-pointer">
{post.title}
</h2>
<p className="text-xs text-gray-500 mb-1">
by {post.createdByName} {" "}
{new Date(post.createdAt).toLocaleDateString("id-ID", {
day: "numeric",
month: "long",
year: "numeric",
})}{" "}
💬 0
</p>
<p className="text-sm text-gray-600 mb-2 line-clamp-2">
{post.description}
</p>
</div>
<button className="bg-black text-white text-xs px-3 py-1 hover:bg-gray-800 w-fit">
Read more
</button>
</div>
</Link>
</div>
);
}