"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<Article[]>([]);
  const [articleDetail, setArticleDetail] = useState<any>(null);
  const [showData, setShowData] = useState("5");
  const [search, setSearch] = useState("-");
  const [listCategory, setListCategory] = useState<CategoryType[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<any>("-");
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });
  const [detailfiles, setDetailFiles] = useState<any>([]);
  const [mainImage, setMainImage] = useState(0);
  const [thumbnail, setThumbnail] = useState("-");
  const [diseId, setDiseId] = useState(0);
  const [thumbnailImg, setThumbnailImg] = useState<File[]>([]);
  const [selectedMainImage, setSelectedMainImage] = useState<number | null>(
    null,
  );

  const [selectedIndex, setSelectedIndex] = useState(0);

  const [tabArticles, setTabArticles] = useState<Article[]>([]);

  const [activeTab, setActiveTab] = useState<TabKey>("trending");
  const [needOtp, setNeedOtp] = useState(false);
  const [otpValue, setOtpValue] = useState("");
  const { register, handleSubmit, reset, watch } = useForm();
  const [commentList, setCommentList] = useState<any>([]);

  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<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 || [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 (
      <div className="w-full h-[400px] bg-gray-100 flex items-center justify-center rounded-lg">
        <p className="text-gray-400 text-sm">Gambar tidak tersedia</p>
      </div>
    );
  }

  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 (
    <>
      <div className="bg-white grid grid-cols-1 md:grid-cols-3 gap-6 px-8 py-8">
        <div className="md:col-span-2">
          <p className="text-sm text-gray-500 mb-2">Home {">"}Detail</p>
          <h1 className="text-3xl md:text-4xl font-bold text-[#1a1a1a] leading-tight mb-4">
            {articleDetail?.title}
          </h1>
          <div className="flex items-center space-x-2 text-sm text-gray-500 mb-4">
            <div className="text-blue-400">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
              >
                <g
                  fill="none"
                  // fill-rule="evenodd"
                >
                  <path d="m12.594 23.258l-.012.002l-.071.035l-.02.004l-.014-.004l-.071-.036q-.016-.004-.024.006l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.016-.018m.264-.113l-.014.002l-.184.093l-.01.01l-.003.011l.018.43l.005.012l.008.008l.201.092q.019.005.029-.008l.004-.014l-.034-.614q-.005-.019-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.003-.011l.018-.43l-.003-.012l-.01-.01z" />
                  <path
                    fill="currentColor"
                    d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10s10-4.477 10-10S17.523 2 12 2M8.5 9.5a3.5 3.5 0 1 1 7 0a3.5 3.5 0 0 1-7 0m9.758 7.484A7.99 7.99 0 0 1 12 20a7.99 7.99 0 0 1-6.258-3.016C7.363 15.821 9.575 15 12 15s4.637.821 6.258 1.984"
                  />
                </g>
              </svg>
            </div>

            <span className="text-blue-400 font-medium">
              {articleDetail?.customCreatorName || articleDetail?.createdByName}
            </span>
            <span>•</span>
            <span>
              {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
            </span>
            <span>•</span>
            <span>{articleDetail?.categories?.[0]?.title}</span>
          </div>

          <div className="w-full h-auto mb-6">
            {/* Gambar utama */}
            <div className="w-full">
              <Image
                src={articleDetail?.files[selectedIndex].fileUrl}
                alt={articleDetail?.files[selectedIndex].fileAlt || "Berita"}
                width={800}
                height={400}
                className="rounded-lg w-full object-cover"
              />
            </div>

            {/* Thumbnail */}
            <div className="flex gap-2 mt-3 overflow-x-auto">
              {articleDetail.files.map((file: any, index: number) => (
                <button
                  key={file.id || index}
                  onClick={() => setSelectedIndex(index)}
                  className={`border-2 rounded-lg overflow-hidden ${
                    selectedIndex === index
                      ? "border-red-500"
                      : "border-transparent"
                  }`}
                >
                  <Image
                    src={file.fileUrl}
                    alt={file.fileAlt || "Thumbnail"}
                    width={100}
                    height={80}
                    className="object-cover"
                  />
                </button>
              ))}
            </div>

            {/* Slug */}
            <p className="text-sm text-gray-500 mt-2 text-end">
              {articleDetail?.slug}
            </p>
          </div>
          <div className="flex relative">
            <div className=" flex flex-col w-fit rounded overflow-hidden  mr-5">
              <Link
                href="#"
                aria-label="Facebook"
                className="bg-[#3b5998] p-4 flex justify-center items-center"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  fill="white"
                  viewBox="0 0 24 24"
                >
                  <path d="M14 13.5h2.5l1-4H14v-2c0-1.03 0-2 2-2h1.5V2.14c-.326-.043-1.557-.14-2.857-.14C11.928 2 10 3.657 10 6.7v2.8H7v4h3V22h4z" />
                </svg>
              </Link>

              <Link
                href="#"
                aria-label="Twitter"
                className="bg-[#55acee] p-4 flex justify-center items-center"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  fill="white"
                  viewBox="0 0 24 24"
                >
                  <path d="M7.91 20.889c8.302 0 12.845-6.885 12.845-12.845c0-.193 0-.387-.009-.58A9.2 9.2 0 0 0 23 5.121a9.2 9.2 0 0 1-2.597.713a4.54 4.54 0 0 0 1.99-2.5a9 9 0 0 1-2.87 1.091A4.5 4.5 0 0 0 16.23 3a4.52 4.52 0 0 0-4.516 4.516c0 .352.044.696.114 1.03a12.82 12.82 0 0 1-9.305-4.718a4.526 4.526 0 0 0 1.4 6.03a4.6 4.6 0 0 1-2.043-.563v.061a4.524 4.524 0 0 0 3.62 4.428a4.4 4.4 0 0 1-1.189.159q-.435 0-.845-.08a4.51 4.51 0 0 0 4.217 3.135a9.05 9.05 0 0 1-5.608 1.936A9 9 0 0 1 1 18.873a12.84 12.84 0 0 0 6.91 2.016" />
                </svg>
              </Link>

              <Link
                href="#"
                aria-label="Google"
                className="bg-[#fce9e7] p-4 flex justify-center items-center text-white"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  fill="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path d="M7.796 14.333v-2.618h7.211c.066.382.12.763.12 1.265c0 4.364-2.923 7.462-7.33 7.462A7.63 7.63 0 0 1 .16 12.806a7.63 7.63 0 0 1 7.636-7.637c2.062 0 3.786.753 5.117 1.997L10.84 9.162c-.567-.546-1.56-1.178-3.044-1.178c-2.607 0-4.734 2.16-4.734 4.822s2.127 4.821 4.734 4.821c3.022 0 4.157-2.17 4.331-3.294zm13.27-2.6H23.2v2.134h-2.133V16h-2.134v-2.133H16.8v-2.134h2.133V9.6h2.134z" />
                </svg>
              </Link>

              <Link
                href="#"
                aria-label="Share"
                className="bg-[#cccccc] p-4 flex justify-center items-center text-white"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  fill="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path d="m21 12l-7-7v4C7 10 4 15 3 20c2.5-3.5 6-5.1 11-5.1V19z" />
                </svg>
              </Link>
            </div>
            <div className="flex-1 overflow-y-auto">
              <div className="text-gray-700 leading-relaxed text-justify">
                <div
                  dangerouslySetInnerHTML={removeImgTags(
                    formatTextToHtmlTag(articleDetail?.htmlDescription),
                  )}
                  className="text-sm lg:text-xl lg:leading-8 text-justify space-y-4"
                />
              </div>
              {/* <Author /> */}
              <div className="w-full bg-white   py-6">
                <p className="mx-10 text-2xl mb-4 ">AUTHOR</p>
                <div className=" border border-black p-6 flex items-center gap-6 max-w-[1200px] mx-auto">
                  {/* Foto Profil */}
                  <div className="w-20 h-20 relative ">
                    <Image
                      src="/profile.jpg"
                      alt="Author"
                      fill
                      className="rounded-full object-cover"
                    />
                  </div>

                  {/* Info Author */}
                  <div className="flex-1">
                    <h3 className="text-lg font-semibold text-gray-800">
                      {articleDetail?.customCreatorName ||
                        articleDetail?.createdByName}
                    </h3>

                    <div className="mt-2 flex items-center gap-4 flex-wrap">
                      {/* Button lihat semua post */}
                      <button className="text-sm font-medium text-white hover:underline bg-[#655997] py-1 px-5 rounded-xl">
                        Lihat Semua Pos
                      </button>

                      <div className="bg-[#655997] rounded-full p-1">
                        <MailIcon
                          size={18}
                          className="text-white hover:text-black cursor-pointer "
                        ></MailIcon>
                      </div>
                      <div className="bg-[#655997] rounded-full p-1">
                        <Link2
                          size={18}
                          className="text-white hover:text-black cursor-pointer "
                        ></Link2>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex flex-row gap-2 items-center">
                <span className="font-semibold text-sm text-gray-700">
                  Tags:
                </span>
                <div className="flex flex-wrap gap-2 mt-1">
                  {articleDetail?.tags ? (
                    articleDetail.tags
                      .split(",") // pisahkan berdasarkan koma
                      .map((tag: string, index: number) => (
                        <Badge
                          key={index}
                          variant="secondary"
                          className="text-sm"
                        >
                          {tag.trim()}
                        </Badge>
                      ))
                  ) : (
                    <span className="text-sm text-gray-500">Tidak ada tag</span>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div className="mt-10">
            <h2 className="text-2xl font-bold mb-2">Tinggalkan Balasan</h2>
            <p className="text-gray-600 mb-4 text-sm">
              Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib
              ditandai <span className="text-orange-600">*</span>
            </p>

            <div>
              <h3 className="text-lg font-semibold border-b pb-2">Komentar</h3>
              {commentList?.length === 0 ? (
                <p className="text-sm text-gray-500">Belum ada komentar.</p>
              ) : (
                commentList?.map((comment: any) => (
                  <div
                    key={comment?.id}
                    className="border rounded-lg p-3 bg-gray-50 shadow-sm"
                  >
                    <p className="text-sm text-gray-800 whitespace-pre-line">
                      {comment?.message}
                    </p>
                    <p className="text-xs text-gray-500 mt-1">
                      {comment?.commentFromName || "Anonim"} •{" "}
                      {new Date(comment?.createdAt).toLocaleString("id-ID", {
                        dateStyle: "short",
                        timeStyle: "short",
                      })}
                    </p>
                  </div>
                ))
              )}
            </div>
            <form className="space-y-6 mt-6" onSubmit={handleSubmit(onSubmit)}>
              {!needOtp ? (
                <>
                  {/* Komentar */}
                  <div>
                    <label
                      htmlFor="komentar"
                      className="block text-sm font-medium mb-1"
                    >
                      Komentar <span className="text-blue-600">*</span>
                    </label>
                    <textarea
                      id="komentar"
                      className="w-full border border-gray-300 rounded-md p-3 h-40 focus:outline-none focus:ring-2 focus:ring-blue-600"
                      {...register("comment", { required: true })}
                    />
                  </div>

                  {/* Nama */}
                  <div>
                    <label
                      htmlFor="nama"
                      className="block text-sm font-medium mb-1"
                    >
                      Nama <span className="text-blue-600">*</span>
                    </label>
                    <input
                      type="text"
                      id="nama"
                      className="w-full border border-gray-300 rounded-md p-2"
                      {...register("name", { required: true })}
                    />
                  </div>

                  {/* Email */}
                  <div>
                    <label
                      htmlFor="email"
                      className="block text-sm font-medium mb-1"
                    >
                      Email <span className="text-blue-600">*</span>
                    </label>
                    <input
                      type="email"
                      id="email"
                      className="w-full border border-gray-300 rounded-md p-2"
                      {...register("email", { required: true })}
                    />
                  </div>

                  <button
                    type="submit"
                    className="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-2 rounded-md transition mt-2 w-full"
                  >
                    KIRIM KOMENTAR
                  </button>
                </>
              ) : (
                <>
                  <p className="text-sm text-gray-600">
                    Kode verifikasi sudah dikirimkan. Silakan cek Email Anda!
                  </p>
                  <div>
                    <label className="block text-sm font-medium mb-1 mt-4">
                      OTP
                    </label>
                    <div className="flex gap-2 justify-center">
                      {[...Array(6)].map((_, i) => (
                        <input
                          key={i}
                          type="text"
                          maxLength={1}
                          className="w-10 h-10 text-center border border-gray-300 rounded-md text-lg"
                          value={otpValue[i] || ""}
                          onChange={(e) => {
                            const newValue = otpValue.split("");
                            newValue[i] = e.target.value.replace(/[^0-9]/g, "");
                            setOtpValue(newValue.join(""));
                          }}
                        />
                      ))}
                    </div>
                  </div>
                  <button
                    type="submit"
                    className="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-2 rounded-md transition mt-4 w-full"
                  >
                    Kirim
                  </button>
                </>
              )}
            </form>
          </div>
        </div>

        <div className="md:col-span-1 space-y-6">
          <div className="sticky top-0 space-y-6">
            <div className="bg-white shadow p-4 rounded-lg">
              {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="/kolom.png"
                  alt="Berita Utama"
                  width={1200}
                  height={188}
                  className="object-contain w-full h-[188px]"
                />
              )}
              <button className="mt-4 w-full bg-black text-white py-2 rounded hover:opacity-90">
                Learn More
              </button>
            </div>

            <div className="bg-white shadow p-4 rounded-lg">
              <h2 className="text-lg font-semibold mb-2">Connect with us</h2>
              <div className="flex space-x-2">
                <div className="bg-[#0057ff] text-white px-3 py-2 rounded">
                  <p className="text-sm font-bold">Bē</p>
                  <p className="text-xs">139 Followers</p>
                </div>
                <div className="bg-[#ff0000] text-white px-3 py-2 rounded">
                  <p className="text-sm font-bold">YouTube</p>
                  <p className="text-xs">205k Subscribers</p>
                </div>
                <div className="bg-[#f9a825] text-white px-3 py-2 rounded">
                  <p className="text-sm font-bold">RSS</p>
                  <p className="text-xs">23.9k Followers</p>
                </div>
              </div>
            </div>
            <div className="bg-white shadow p-4 rounded-lg">
              <div className="flex space-x-4 border-b mb-4">
                {tabs.map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id)}
                    className={`pb-2 text-sm font-medium ${
                      activeTab === tab.id
                        ? "border-b-2 border-blue-600 text-blue-600"
                        : "text-gray-600"
                    }`}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>

              <div className="space-y-4">
                {tabArticles.map((item, idx) => (
                  <div key={idx} className="flex space-x-3">
                    <Image
                      src={item.thumbnailUrl || "/default-thumb.png"}
                      alt={item.title}
                      width={70}
                      height={70}
                      className="rounded w-[70px] h-[70px] object-cover"
                    />
                    <div>
                      <p className="text-sm font-semibold leading-snug">
                        {item.title}
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        {new Date(item.createdAt).toLocaleDateString("id-ID", {
                          day: "2-digit",
                          month: "long",
                          year: "numeric",
                        })}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
              {tabArticles.length === 0 ? (
                <p className="text-sm text-gray-500">
                  Artikel tidak ditemukan.
                </p>
              ) : (
                tabArticles.map((item, idx) => (
                  <div key={idx} className="flex space-x-3">
                    <Image
                      src={item.thumbnailUrl || "/default-thumb.png"}
                      alt={item.title}
                      width={70}
                      height={70}
                      className="rounded w-[70px] h-[70px] object-cover"
                    />
                    <div>
                      <p className="text-sm font-semibold leading-snug">
                        {item.title}
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        {new Date(item.createdAt).toLocaleDateString("id-ID", {
                          day: "2-digit",
                          month: "long",
                          year: "numeric",
                        })}
                      </p>
                    </div>
                  </div>
                ))
              )}
            </div>

            <div className="mt-6">
              <h3 className="text-base font-semibold mb-2 text-gray-800 border-b pb-1 border-blue-600 inline-block">
                Recommended
              </h3>

              <div className="space-y-4">
                {/* Artikel utama (featured) */}
                {articles.length > 0 && (
                  <div className="relative">
                    <Image
                      src={articles[0]?.thumbnailUrl || "/default.jpg"}
                      alt={articles[0]?.title || "Recommended Article"}
                      width={400}
                      height={200}
                      className="rounded-lg w-full h-auto object-cover"
                    />
                    <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 text-white p-3 rounded-b-lg">
                      <p className="text-sm font-semibold leading-tight">
                        {articles[0]?.title}
                      </p>
                      <p className="text-xs text-gray-300 mt-1">
                        📅{" "}
                        {new Date(articles[0]?.createdAt).toLocaleDateString(
                          "id-ID",
                          {
                            day: "2-digit",
                            month: "long",
                            year: "numeric",
                          },
                        )}
                      </p>
                    </div>
                  </div>
                )}

                {/* List artikel lain */}
                <div className="space-y-3">
                  {articles.slice(1, 4).map((item) => (
                    <div key={item.id} className="flex space-x-3">
                      <Image
                        src={item.thumbnailUrl || "/default.jpg"}
                        alt={item.title}
                        width={80}
                        height={60}
                        className="rounded object-cover w-[80px] h-[60px]"
                      />
                      <div>
                        <p className="text-sm font-semibold leading-snug">
                          {item.title}
                        </p>
                        <p className="text-xs text-gray-500 mt-1">
                          📅{" "}
                          {new Date(item.createdAt).toLocaleDateString(
                            "id-ID",
                            {
                              day: "2-digit",
                              month: "long",
                              year: "numeric",
                            },
                          )}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
