"use client"; import Image from "next/image"; import { useEffect, useState } from "react"; import Link from "next/link"; import { getArticleById, getArticleBySlug, getListArticle, } from "@/service/article"; import { close, error, loading } from "@/config/swal"; import { useParams, usePathname } from "next/navigation"; import Author from "../landing-page/author"; import { Link2, MailIcon } from "lucide-react"; import { getAdvertise } from "@/service/advertisement"; import { useForm } from "react-hook-form"; import { getArticleComment, otpRequest, otpValidation, postArticleComment, } from "@/service/master-user"; import { saveActivity } from "@/service/activity-log"; import { Badge } from "../ui/badge"; import { formatTextToHtmlTag } from "@/utils/global"; type TabKey = "trending" | "comments" | "latest"; type Article = { id: number; title: string; description: string; categoryName: string; createdAt: string; createdByName: string; customCreatorName: 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; }; interface CategoryType { id: number; label: string; value: number; } export default function DetailContent() { const params = useParams(); const id = params?.id; const slug = params?.slug; const pathname = usePathname(); const [page, setPage] = useState(1); const [totalPage, setTotalPage] = useState(1); const [articles, setArticles] = useState([]); const [articleDetail, setArticleDetail] = useState(null); const [showData, setShowData] = useState("5"); const [search, setSearch] = useState("-"); const [listCategory, setListCategory] = useState([]); const [selectedCategories, setSelectedCategories] = useState("-"); const [startDateValue, setStartDateValue] = useState({ startDate: null, endDate: null, }); const [detailfiles, setDetailFiles] = useState([]); const [mainImage, setMainImage] = useState(0); const [thumbnail, setThumbnail] = useState("-"); const [diseId, setDiseId] = useState(0); const [thumbnailImg, setThumbnailImg] = useState([]); const [selectedMainImage, setSelectedMainImage] = useState( null, ); const [selectedIndex, setSelectedIndex] = useState(0); const [tabArticles, setTabArticles] = useState([]); const [activeTab, setActiveTab] = useState("trending"); const [needOtp, setNeedOtp] = useState(false); const [otpValue, setOtpValue] = useState(""); const { register, handleSubmit, reset, watch } = useForm(); const [commentList, setCommentList] = useState([]); useEffect(() => { fetchData(); }, [id]); const fetchData = async () => { try { const res = await getArticleComment(String(id)); const data = res?.data?.data; setCommentList(data); console.log("komen", data); } catch (err) { console.error("❌ Gagal memuat komentar:", err); setCommentList([]); } }; const onSubmit = async (values: any) => { if (!needOtp) { const res = await otpRequest(values.email, values?.name); if (res?.error) { error(res.message); return false; } setNeedOtp(true); } else { const validation = await otpValidation(values.email, otpValue); if (validation?.error) { error("OTP Tidak Sesuai"); return false; } const data = { commentFromName: values.name, commentFromEmail: values.email, articleId: Number(id), isPublic: false, message: values.comment, parentId: 0, }; const res = await postArticleComment(data); if (res?.error) { error(res?.message); return false; } const req: any = { activityTypeId: 5, url: "https://dev.mikulnews/" + pathname, articleId: Number(id), }; const resActivity = await saveActivity(req); reset(); fetchData(); setNeedOtp(false); } }; const tabs: { id: TabKey; label: string }[] = [ { id: "trending", label: "Trending" }, { id: "comments", label: "Comments" }, { id: "latest", label: "Latest" }, ]; const [bannerAd, setBannerAd] = useState(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 || [1]; // filter iklan dengan placement = "banner" const banner = data.find((ad) => ad.placement === "jumbotron"); if (banner) { setBannerAd(banner); } } catch (err) { console.error("Error fetching advertisement:", err); } } useEffect(() => { fetchTabArticles(); }, [activeTab]); async function fetchTabArticles() { const req: any = { limit: showData, page, search, categorySlug: Array.from(selectedCategories).join(","), sort: "desc", sortBy: "created_at", }; // Sesuaikan sortBy berdasarkan tab if (activeTab === "trending") { req.sortBy = "view_count"; } else if (activeTab === "comments") { req.sortBy = "comment_count"; } else { req.sortBy = "created_at"; } // Hanya kirimkan search jika valid if (search && search !== "-" && search !== "") { req.search = search; } if (selectedCategories && selectedCategories !== "-") { req.categorySlug = selectedCategories; } try { const res = await getListArticle(req); setTabArticles(res?.data?.data || []); } catch (error) { console.error("Failed fetching tab articles:", error); setTabArticles([]); // Optional fallback } } const content: Record< TabKey, { image: string; title: string; date: string }[] > = { trending: [ { image: "/thumb1.png", title: "#StopBullyDiSekolah: Peran Positif Media Sosial dalam Mengatasi Bullying", date: "22 FEBRUARI 2024", }, { image: "/thumb2.png", title: "Polri Gelar Lomba Orasi Unjuk Rasa dalam Rangka Hari HAM Sedunia Berhadiah Total Lebih dari Rp 150 juta!", date: "29 NOVEMBER 2021", }, { image: "/thumb3.png", title: "Tingkatkan Ibadah Sambut #RamadhanPenuhDamai", date: "7 MARET 2024", }, { image: "/thumb4.png", title: "Exploring the Charm of Papua’s Traditional Clothing: A Captivating and Meaningful Cultural Heritage", date: "1 AGUSTUS 2024", }, ], comments: [ { image: "/thumb-comment.png", title: "Pengunjung Komentar Positif tentang Fitur Baru", date: "3 JUNI 2024", }, ], latest: [ { image: "/thumb-latest.png", title: "Update Terbaru dari Redaksi Hari Ini", date: "2 JULI 2025", }, ], }; useEffect(() => { initState(); }, [page, showData]); async function initState() { // loading(); const req = { limit: showData, page: 1, search: "", categorySlug: "", sort: "desc", isPublish: true, sortBy: "created_at", }; try { const res = await getListArticle(req); setArticles(res?.data?.data || []); setTotalPage(res?.data?.meta?.totalPage || 1); } finally { // close(); } } useEffect(() => { initStateData(); }, [listCategory]); async function initStateData() { loading(); const res = await getArticleBySlug(slug); const data = res?.data?.data; setThumbnail(data?.thumbnailUrl); setDiseId(data?.aiArticleId); setDetailFiles(data?.files); setArticleDetail(data); // <-- Add this close(); } if (!articleDetail?.files || articleDetail?.files.length === 0) { return (

Gambar tidak tersedia

); } function removeImgTags(htmlString?: { __html: string }) { const parser = new DOMParser(); const doc = parser.parseFromString(String(htmlString?.__html), "text/html"); const images = doc.querySelectorAll("img"); images.forEach((img) => img.remove()); return { __html: doc.body.innerHTML }; } return ( <>

Home {">"}Detail

{articleDetail?.title}

{articleDetail?.customCreatorName || articleDetail?.createdByName} {new Date(articleDetail?.publishedAt ?? articleDetail?.createdAt) .toLocaleString("id-ID", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Asia/Jakarta", }) .replace("pukul ", "")}{" "} WIB {articleDetail?.categories?.[0]?.title}
{/* Gambar utama */}
{articleDetail?.files[selectedIndex].fileAlt
{/* Thumbnail */}
{articleDetail.files.map((file: any, index: number) => ( ))}
{/* Slug */}

{articleDetail?.slug}

{/* */}

AUTHOR

{/* Foto Profil */}
Author
{/* Info Author */}

{articleDetail?.customCreatorName || articleDetail?.createdByName}

{/* Button lihat semua post */}
Tags:
{articleDetail?.tags ? ( articleDetail.tags .split(",") // pisahkan berdasarkan koma .map((tag: string, index: number) => ( {tag.trim()} )) ) : ( Tidak ada tag )}

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *

Komentar

{commentList?.length === 0 ? (

Belum ada komentar.

) : ( commentList?.map((comment: any) => (

{comment?.message}

{comment?.commentFromName || "Anonim"} •{" "} {new Date(comment?.createdAt).toLocaleString("id-ID", { dateStyle: "short", timeStyle: "short", })}

)) )}
{!needOtp ? ( <> {/* Komentar */}