"use client"; import { useState, useEffect } from "react"; import Image from "next/image"; import { Button } from "@/components/ui/button"; import { Card } from "../ui/card"; import Link from "next/link"; import { useRouter, useParams } from "next/navigation"; 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"; import { ThumbsUp, ThumbsDown } from "lucide-react"; import { useTranslations } from "next-intl"; 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 t = useTranslations("MediaUpdate"); const [tab, setTab] = useState<"latest" | "popular">("latest"); const [contentType, setContentType] = useState< "audiovisual" | "audio" | "foto" | "text" | "all" >("foto"); const [dataToRender, setDataToRender] = useState([]); const [filteredData, setFilteredData] = useState([]); const [bookmarkedIds, setBookmarkedIds] = useState>(new Set()); const [loading, setLoading] = useState(true); const [currentTypeId, setCurrentTypeId] = useState("1"); const router = useRouter(); const params = useParams(); const MySwal = withReactContent(Swal); const slug = params?.slug as string; useEffect(() => { fetchData(tab); }, [tab, slug]); useEffect(() => { // if (contentType !== "all") { // fetchData(tab); // } else { // filterDataByContentType(); // } fetchData(tab); }, [contentType]); useEffect(() => { filterDataByContentType(); }, [dataToRender]); // Function to get typeId based on content type function getTypeIdByContentType(contentType: string): string { switch (contentType) { case "audiovisual": return "2"; case "foto": return "1"; case "audio": return "4"; case "text": return "3"; default: return "1"; } } // Function to get link based on typeId (same as header.tsx) function getLink(item: any) { switch (item?.typeId) { case 1: return `/content/image/detail/${item?.id}`; case 2: return `/content/video/detail/${item?.id}`; case 3: return `/content/text/detail/${item?.id}`; case 4: return `/content/audio/detail/${item?.id}`; default: return "#"; } } // Function to get content type link for "Lihat lebih banyak" button function getContentTypeLink() { const pathname = typeof window !== "undefined" ? window.location.pathname : ""; const isTenantRoute = pathname.includes("/tenant/"); const basePath = isTenantRoute ? `/tenant/${slug}/content` : "/content"; switch (contentType) { case "audio": return `${basePath}/audio`; case "foto": return `${basePath}/image`; case "audiovisual": return `${basePath}/video`; case "text": return `${basePath}/text`; default: return `${basePath}/image`; } } // function getContentTypeLink() { // switch (contentType) { // case "audio": // return "/tenant/" + slug + "/content/audio"; // case "foto": // return "/tenant/" + slug + "/content/image"; // case "audiovisual": // return "/tenant/" + slug + "/content/video"; // case "text": // return "/tenant/" + slug + "/content/text"; // default: // return "/tenant/" + slug + "/content/image"; // } // } // if (contentType === "all") { // setFilteredData(dataToRender); // return; // } // Function to filter data by content type // function filterDataByContentType() { // const filtered = dataToRender.filter((item) => { // // Determine content type based on item properties // const hasVideo = item.videoUrl || item.videoPath; // const hasAudio = item.audioUrl || item.audioPath; // const hasImage = // item.smallThumbnailLink || item.thumbnailUrl || item.imageUrl; // const hasText = item.content || item.description; // switch (contentType) { // case "audiovisual": // return hasVideo; // case "audio": // return hasAudio && !hasVideo; // case "foto": // return hasImage && !hasVideo && !hasAudio; // case "text": // return hasText && !hasVideo && !hasAudio && !hasImage; // default: // return true; // } // }); // setFilteredData(filtered); // } function filterDataByContentType() { const filtered = dataToRender.filter((item) => { switch (contentType) { case "audiovisual": return item.typeId === 2; case "audio": return item.typeId === 4; case "foto": return item.typeId === 1; case "text": return item.typeId === 3; default: return true; } }); setFilteredData(filtered); } async function fetchData(section: "latest" | "popular") { try { setLoading(true); const typeId = parseInt(getTypeIdByContentType(contentType)); setCurrentTypeId(typeId.toString()); const response = await listArticles( 1, 10, typeId, undefined, undefined, section === "latest" ? "createdAt" : "viewCount", slug ); let hasil: any[] = []; if (response?.error) { console.error("Articles API failed, fallback ke old API"); const fallbackRes = await listData( typeId.toString(), "", "", 20, 0, "", "", "" ); hasil = fallbackRes?.data?.data?.content || []; } else { hasil = response?.data?.data || []; } const transformedData = hasil.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.categoryName, clientName: article.clientName, typeId: article.typeId, ...article, })); setDataToRender(transformedData); const roleId = Number(getCookiesDecrypt("urie")); if (roleId && !isNaN(roleId)) { const simpananLocal = localStorage.getItem("bookmarkedIds"); let localSet = new Set(); if (simpananLocal) { localSet = new Set(JSON.parse(simpananLocal)); 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 gabungan = new Set([...localSet, ...ids]); setBookmarkedIds(gabungan); localStorage.setItem( "bookmarkedIds", JSON.stringify(Array.from(gabungan)) ); } } catch (err) { console.error("Gagal memuat data:", err); } finally { setLoading(false); } } 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: "Tidak dapat 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 menyimpan bookmark:", err); MySwal.fire({ icon: "error", title: "Kesalahan", text: "Terjadi kesalahan saat menyimpan artikel.", }); } }; return (

{t("title")}

{/* Main Tab */}
{/* Content Type Filter */}
{/* */}
{/* Slider */} {loading ? (

{t("loadContent")}

) : ( {filteredData.map((item) => (
{/* ✅ Kondisi: jika typeId = 3 (text) atau 4 (audio) tampilkan ikon, lainnya tampilkan thumbnail */} {item.typeId === 3 ? ( // 📝 TEXT
) : item.typeId === 4 ? ( // 🎵 AUDIO
) : ( // 🎬 FOTO / VIDEO (default)
{item.title
)} {/* Caption / info */}
{item.clientName || "Tanpa Kategori"} {item.categories ?.map((cat: any) => cat.title) .join(", ")}

{formatTanggal(item.createdAt)}

{item.title}

))}
)} {/* Lihat lebih banyak - hanya muncul jika ada data */} {filteredData.length > 0 && (
)}
); }