"use client"; import { useState, useEffect } from "react"; import Image from "next/image"; import { Button } from "@/components/ui/button"; import { ThumbsUp, ThumbsDown } from "lucide-react"; import { Card } from "../ui/card"; import Link from "next/link"; import { listData, listArticles } from "@/service/landing/landing"; import { toggleBookmark, getBookmarkSummaryForUser } from "@/service/content"; import { getCookiesDecrypt } from "@/lib/utils"; import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; import "swiper/css/navigation"; import { Navigation } from "swiper/modules"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; // Format tanggal function formatTanggal(dateString: string) { if (!dateString) return ""; return ( new Date(dateString) .toLocaleString("id-ID", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Asia/Jakarta", }) .replace(/\./g, ":") + " WIB" ); } export default function MediaUpdate() { const [tab, setTab] = useState<"latest" | "popular">("latest"); const [dataToRender, setDataToRender] = useState([]); const [bookmarkedIds, setBookmarkedIds] = useState>(new Set()); const [loading, setLoading] = useState(true); const MySwal = withReactContent(Swal); useEffect(() => { fetchData(tab); }, [tab]); async function fetchData(section: "latest" | "popular") { try { setLoading(true); // 🔹 Ambil data artikel const response = await listArticles( 1, 20, 1, // typeId = image undefined, undefined, section === "latest" ? "createdAt" : "viewCount" ); let articlesData: any[] = []; if (response?.error) { console.error("Articles API failed, fallback ke old API"); const fallbackRes = await listData( "1", "", "", 20, 0, section === "latest" ? "createdAt" : "clickCount", "", "", "" ); articlesData = fallbackRes?.data?.data?.content || []; } else { articlesData = response?.data?.data || []; } // 🔹 Normalisasi struktur data const transformedData = articlesData.map((article: any) => ({ id: article.id, title: article.title, category: article.categoryName || (article.categories && article.categories[0]?.title) || "Tanpa Kategori", createdAt: article.createdAt, smallThumbnailLink: article.thumbnailUrl, label: article.typeId === 1 ? "Image" : article.typeId === 2 ? "Video" : article.typeId === 3 ? "Text" : article.typeId === 4 ? "Audio" : "", ...article, })); setDataToRender(transformedData); // 🔹 Sinkronisasi bookmark const roleId = Number(getCookiesDecrypt("urie")); if (roleId && !isNaN(roleId)) { const savedLocal = localStorage.getItem("bookmarkedIds"); let localSet = new Set(); if (savedLocal) { localSet = new Set(JSON.parse(savedLocal)); setBookmarkedIds(localSet); } const res = await getBookmarkSummaryForUser(); const bookmarks = res?.data?.data?.recentBookmarks || res?.data?.data?.bookmarks || res?.data?.data || []; const ids = new Set( (Array.isArray(bookmarks) ? bookmarks : []) .map((b: any) => Number(b.articleId ?? b.id ?? b.article?.id)) .filter((x) => !isNaN(x)) ); const merged = new Set([...localSet, ...ids]); setBookmarkedIds(merged); localStorage.setItem( "bookmarkedIds", JSON.stringify(Array.from(merged)) ); } } catch (err) { console.error("Gagal memuat data:", err); } finally { setLoading(false); } } // 🔹 Simpan perubahan bookmark ke localStorage useEffect(() => { if (bookmarkedIds.size > 0) { localStorage.setItem( "bookmarkedIds", JSON.stringify(Array.from(bookmarkedIds)) ); } }, [bookmarkedIds]); const handleSave = async (id: number) => { const roleId = Number(getCookiesDecrypt("urie")); if (!roleId || isNaN(roleId)) { MySwal.fire({ icon: "warning", title: "Login diperlukan", text: "Silakan login terlebih dahulu untuk menyimpan artikel.", confirmButtonText: "Login Sekarang", confirmButtonColor: "#d33", }); return; } try { const res = await toggleBookmark(id); if (res?.error) { MySwal.fire({ icon: "error", title: "Gagal", text: "Gagal menyimpan artikel.", confirmButtonColor: "#d33", }); } else { const updated = new Set(bookmarkedIds); updated.add(Number(id)); setBookmarkedIds(updated); localStorage.setItem( "bookmarkedIds", JSON.stringify(Array.from(updated)) ); MySwal.fire({ icon: "success", title: "Berhasil", text: "Artikel berhasil disimpan ke bookmark.", timer: 1500, showConfirmButton: false, }); } } catch (err) { console.error("Error saving bookmark:", err); MySwal.fire({ icon: "error", title: "Kesalahan", text: "Terjadi kesalahan saat menyimpan artikel.", }); } }; return (

Media Update

{/* Tab */}
{/* Slider */} {loading ? (

Loading...

) : ( {dataToRender.map((item) => (
{item.title
{item.category || "Tanpa Kategori"} {item.label || ""}

{formatTanggal(item.createdAt)}

{item.title}

))}
)} {/* Lihat lebih banyak */}
); } // "use client"; // import { useState, useEffect } from "react"; // import Image from "next/image"; // import { Button } from "@/components/ui/button"; // import { ThumbsUp, ThumbsDown } from "lucide-react"; // import { Card } from "../ui/card"; // import Link from "next/link"; // import { listData, listArticles } from "@/service/landing/landing"; // import { Swiper, SwiperSlide } from "swiper/react"; // import "swiper/css"; // import "swiper/css/navigation"; // import { Navigation } from "swiper/modules"; // // Format tanggal // function formatTanggal(dateString: string) { // if (!dateString) return ""; // return ( // new Date(dateString) // .toLocaleString("id-ID", { // day: "2-digit", // month: "short", // year: "numeric", // hour: "2-digit", // minute: "2-digit", // hour12: false, // timeZone: "Asia/Jakarta", // }) // .replace(/\./g, ":") + " WIB" // ); // } // export default function MediaUpdate() { // const [tab, setTab] = useState<"latest" | "popular">("latest"); // const [dataToRender, setDataToRender] = useState([]); // const [loading, setLoading] = useState(true); // useEffect(() => { // fetchData(tab); // }, [tab]); // async function fetchData(section: "latest" | "popular") { // try { // setLoading(true); // // Use new Articles API // const response = await listArticles( // 1, // 20, // 1, // typeId for images // undefined, // undefined, // section === "latest" ? "createdAt" : "viewCount" // ); // console.log("Media Update Articles API response:", response); // if (response?.error) { // console.error("Articles API failed, falling back to old API"); // // Fallback to old API // const fallbackRes = await listData( // "1", // "", // "", // 20, // 0, // section === "latest" ? "createdAt" : "clickCount", // "", // "", // "" // ); // setDataToRender(fallbackRes?.data?.data?.content || []); // return; // } // // Handle new API response structure // const articlesData = response?.data?.data || []; // // Transform articles data to match old structure for backward compatibility // const transformedData = articlesData.map((article: any) => ({ // id: article.id, // title: article.title, // category: article.categoryName || (article.categories && article.categories[0]?.title) || "Tanpa Kategori", // createdAt: article.createdAt, // smallThumbnailLink: article.thumbnailUrl, // label: article.typeId === 1 ? "Image" : article.typeId === 2 ? "Video" : article.typeId === 3 ? "Text" : article.typeId === 4 ? "Audio" : "", // ...article // })); // setDataToRender(transformedData); // } catch (err) { // console.error("Gagal memuat data:", err); // // Try fallback to old API if new API fails // try { // const fallbackRes = await listData( // "1", // "", // "", // 20, // 0, // section === "latest" ? "createdAt" : "clickCount", // "", // "", // "" // ); // setDataToRender(fallbackRes?.data?.data?.content || []); // } catch (fallbackError) { // console.error("Fallback API also failed:", fallbackError); // } // } finally { // setLoading(false); // } // } // return ( //
//
//

// Media Update //

// {/* Tab */} //
// // // // //
// {/* Slider */} // {loading ? ( //

Loading...

// ) : ( // // {dataToRender.map((item) => ( // //
//
// {item.title //
//
//
// // {item.category || "Tanpa Kategori"} // // // {item.label || ""} // //
//

// {formatTanggal(item.createdAt)} //

//

// {item.title} //

//
//
// // //
// //
//
//
//
// ))} //
// )} // {/* Lihat lebih banyak */} //
// // // //
//
//
// ); // }