"use client";

import Image from "next/image";
import Link from "next/link";
import { ThumbsUp, ThumbsDown } from "lucide-react";
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { listData, listArticles } from "@/service/landing/landing";
import { getCookiesDecrypt } from "@/lib/utils";
import { toggleBookmark, getBookmarkSummaryForUser } from "@/service/content";

import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import ImageBlurry from "../ui/image-blurry";
import { useTranslations } from "next-intl";
import { Reveal } from "../ui/Reveal";
import { RevealL } from "../ui/RevealL";
import { RevealR } from "../ui/RevealR";

const images = ["/PPS.png", "/PPS2.jpeg", "/PPS3.jpg", "/PPS4.png"];

export default function Header() {
  const t = useTranslations("MediaUpdate");
  const [data, setData] = useState<any[]>([]);
  const [bookmarkedIds, setBookmarkedIds] = useState<Set<number>>(new Set());
  const router = useRouter();
  const params = useParams();
  const MySwal = withReactContent(Swal);

  const slug = params?.slug as string;

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await listArticles(
          1,
          5,
          1,
          undefined,
          undefined,
          "createdAt",
          slug,
        );

        let articlesData: any[] = [];

        if (response?.error) {
          const fallbackResponse = await listData(
            "",
            "",
            "",
            5,
            0,
            "createdAt",
            "",
            "",
            "",
          );
          articlesData = (fallbackResponse?.data?.data?.content || []).filter(
            (item: any) => item.typeId === 1,
          );
        } else {
          articlesData = (response?.data?.data || []).filter(
            (item: any) => item.typeId === 1,
          );
        }

        const transformed = articlesData.map((article: any) => ({
          id: article.id,
          title: article.title,
          categoryName:
            article.categoryName ||
            (article.categories && article.categories[0]?.title) ||
            "",
          createdAt: article.createdAt,
          smallThumbnailLink: article.thumbnailUrl,
          fileTypeId: article.typeId,
          clientName: article.clientName,
          categories: article.categories,
          label: "Image",
        }));

        setData(transformed);

        const roleId = Number(getCookiesDecrypt("urie"));
        if (roleId && !isNaN(roleId)) {
          const userId = getCookiesDecrypt("uie");
          const localKey = `bookmarkedIds_${userId || "guest"}`;
          const saved = localStorage.getItem(localKey);

          let localSet = new Set<number>();
          if (saved) {
            localSet = new Set(JSON.parse(saved));
            setBookmarkedIds(localSet);
          }

          const res = await getBookmarkSummaryForUser();
          const bookmarks =
            res?.data?.data?.recentBookmarks ||
            res?.data?.data?.bookmarks ||
            res?.data?.data ||
            [];

          const ids = new Set<number>(
            (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 (error) {
        console.error("Gagal memuat data:", error);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    if (bookmarkedIds.size > 0) {
      localStorage.setItem(
        "bookmarkedIds",
        JSON.stringify(Array.from(bookmarkedIds)),
      );
    }
  }, [bookmarkedIds]);

  return (
    <section className="max-w-[1350px] mx-auto px-4">
      <RevealR>
        <div className="flex flex-col lg:flex-row gap-6 py-6">
          {data.length > 0 && (
            <Card
              item={data[0]}
              isBig
              isInitiallyBookmarked={bookmarkedIds.has(Number(data[0].id))}
              onSaved={(id) =>
                setBookmarkedIds((prev) => new Set([...prev, Number(id)]))
              }
            />
          )}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 w-full">
            {data.slice(1, 5).map((item) => (
              <Card
                key={item.id}
                item={item}
                isInitiallyBookmarked={bookmarkedIds.has(Number(item.id))}
                onSaved={(id) =>
                  setBookmarkedIds((prev) => new Set([...prev, Number(id)]))
                }
              />
            ))}
          </div>
        </div>
      </RevealR>

      <div className="relative w-full h-48 sm:h-64 md:h-80 lg:h-[460px] mt-4 rounded-xl overflow-hidden">
        <Swiper
          modules={[Navigation, Pagination]}
          navigation
          pagination={{ clickable: true }}
          spaceBetween={10}
          slidesPerView={1}
          loop={true}
          className="w-full h-full"
        >
          {images.map((img, index) => (
            <SwiperSlide key={index}>
              <div className="relative w-full h-48 sm:h-64 md:h-80 lg:h-[460px]">
                {/* <Image
                  src={img}
                  alt={`slide-${index}`}
                  fill
                  className="object-cover rounded-xl"
                  priority={index === 0}
                /> */}
                <ImageBlurry
                  priority
                  src={img}
                  alt="gambar"
                  style={{
                    objectFit: "contain",
                    width: "100%",
                    height: "100%",
                  }}
                />
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
    </section>
  );
}

function Card({
  item,
  isBig = false,
  isInitiallyBookmarked = false,
  onSaved,
}: {
  item: any;
  isBig?: boolean;
  isInitiallyBookmarked?: boolean;
  onSaved?: (id: number) => void;
}) {
  const router = useRouter();
  const t = useTranslations("MediaUpdate");
  const MySwal = withReactContent(Swal);
  const [isSaving, setIsSaving] = useState(false);
  const [isBookmarked, setIsBookmarked] = useState(isInitiallyBookmarked);
  const DEFAULT_IMAGE = "/assets/logo1.png";

  const [imageSrc, setImageSrc] = useState(DEFAULT_IMAGE);

  useEffect(() => {
    const src = item?.smallThumbnailLink;

    if (!src) {
      setImageSrc(DEFAULT_IMAGE);
      return;
    }

    const img = new window.Image();
    img.src = src;

    img.onload = () => {
      setImageSrc(src);
    };

    img.onerror = () => {
      setImageSrc(DEFAULT_IMAGE);
    };
  }, [item?.smallThumbnailLink]);

  useEffect(() => {
    setIsBookmarked(isInitiallyBookmarked);
  }, [isInitiallyBookmarked]);

  const getLink = () => `/content/image/detail/${item?.id}`;

  const handleSave = async () => {
    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",
      }).then(() => router.push("/auth"));
      return;
    }

    try {
      setIsSaving(true);
      const res = await toggleBookmark(item.id);

      if (res?.error) {
        MySwal.fire({
          icon: "error",
          title: "Gagal",
          text: "Gagal menyimpan artikel.",
          confirmButtonColor: "#d33",
        });
      } else {
        setIsBookmarked(true);
        onSaved?.(item.id);

        const saved = localStorage.getItem("bookmarkedIds");
        const newSet = new Set<number>(saved ? JSON.parse(saved) : []);
        newSet.add(Number(item.id));
        localStorage.setItem(
          "bookmarkedIds",
          JSON.stringify(Array.from(newSet)),
        );

        MySwal.fire({
          icon: "success",
          title: "Berhasil",
          text: "Artikel berhasil disimpan ke bookmark.",
          confirmButtonColor: "#3085d6",
          timer: 1500,
          showConfirmButton: false,
        });
      }
    } catch (err) {
      console.error("Toggle bookmark error:", err);
      MySwal.fire({
        icon: "error",
        title: "Kesalahan",
        text: "Terjadi kesalahan saat menyimpan artikel.",
        confirmButtonColor: "#d33",
      });
    } finally {
      setIsSaving(false);
    }
  };

  return (
    // <RevealL>
    <div
      className={`rounded-xl overflow-hidden shadow hover:shadow-lg transition-all bg-white dark:bg-black dark:border dark:border-slate-50 ${
        isBig
          ? "w-full lg:max-w-[670px] lg:min-h-[680px]"
          : "w-full h-[350px] md:h-[330px]"
      }`}
    >
      <div
        className={`relative ${
          isBig ? "aspect-[3/2] lg:h-[525px]" : "aspect-video"
        } w-full`}
      >
        <Link href={getLink()}>
          {/* <Image
              src={item.smallThumbnailLink || "/contributor.png"}
              alt={item.title}
              fill
              className="object-cover"
            /> */}
          <ImageBlurry
            src={imageSrc}
            alt={item.title}
            className="w-full h-full object-contain"
          />
        </Link>
      </div>

      <div className="py-[26px] px-4 space-y-2">
        <div className="flex justify-between items-center gap-2 text-xs font-semibold flex-row">
          <span className="bg-emerald-600 text-white px-2 py-0.5 rounded">
            {item.clientName}
          </span>
          <span className="text-orange-600">
            {item.categories?.map((cat: any) => cat.title).join(", ")}
          </span>
        </div>

        <div className="text-xs text-gray-500">
          {new Date(item.createdAt)
            .toLocaleString("id-ID", {
              day: "2-digit",
              month: "short",
              year: "numeric",
              hour: "2-digit",
              minute: "2-digit",
              hour12: false,
              timeZone: "Asia/Jakarta",
            })
            .replace(".", ":")}{" "}
          WIB
        </div>

        <Link href={getLink()}>
          <h3 className="text-sm font-semibold leading-snug line-clamp-2">
            {item.title}
          </h3>
        </Link>

        <div className="flex justify-between items-center pt-2">
          <div className="flex gap-2 text-gray-500">
            <ThumbsUp
              size={18}
              className="cursor-pointer hover:text-[#F60100]"
            />
            <ThumbsDown
              size={18}
              className="cursor-pointer hover:text-red-600"
            />
          </div>

          <button
            onClick={handleSave}
            disabled={isSaving || isBookmarked}
            className={`text-sm px-3 py-1 rounded-md transition-all duration-200 ${
              isBookmarked
                ? "bg-gray-400 text-white cursor-not-allowed"
                : "bg-[#F60100] text-white hover:bg-[#c90000]"
            }`}
          >
            {isSaving ? t("saving") : isBookmarked ? t("saved") : t("save")}
          </button>
        </div>
      </div>
    </div>
    // </RevealL>
  );
}

// "use client";

// import Image from "next/image";
// import Link from "next/link";
// import { ThumbsUp, ThumbsDown } from "lucide-react";
// import { useEffect, useState } from "react";
// import { useParams, useRouter } from "next/navigation";
// import Swal from "sweetalert2";
// import withReactContent from "sweetalert2-react-content";
// import { listData, listArticles } from "@/service/landing/landing";
// import { getCookiesDecrypt } from "@/lib/utils";
// import { toggleBookmark, getBookmarkSummaryForUser } from "@/service/content";

// export default function Header() {
//   const [data, setData] = useState<any[]>([]);
//   const [bookmarkedIds, setBookmarkedIds] = useState<Set<number>>(new Set());
//   const router = useRouter();
//   const params = useParams();
//   const MySwal = withReactContent(Swal);
//   const slug = params?.slug as string;

//   // ✅ Ambil data artikel (khusus typeId = 1 -> Image)
//   useEffect(() => {
//     const fetchData = async () => {
//       try {
//         const response = await listArticles(
//           1,
//           5,
//           1, // hanya typeId = 1 (image)
//           undefined,
//           undefined,
//           "createdAt",
//           slug
//         );

//         let articlesData: any[] = [];

//         if (response?.error) {
//           const fallback = await listData(
//             "",
//             "",
//             "",
//             5,
//             0,
//             "createdAt",
//             "",
//             "",
//             "1"
//           );
//           articlesData = fallback?.data?.data?.content || [];
//         } else {
//           articlesData = response?.data?.data || [];
//         }

//         const transformed = articlesData.map((article: any) =>
//           itemTransform(article)
//         );

//         setData(transformed);
//       } catch (error) {
//         console.error("Gagal memuat data:", error);
//       }
//     };

//     fetchData();
//   }, [slug]);

//   // ✅ Sinkronisasi bookmark: dari localStorage + backend user login
//   useEffect(() => {
//     const syncBookmarks = async () => {
//       try {
//         const roleId = Number(getCookiesDecrypt("urie"));
//         let localSet = new Set<number>();

//         const simpananLocal = localStorage.getItem("bookmarkedIds");
//         if (simpananLocal) {
//           localSet = new Set(JSON.parse(simpananLocal));
//         }

//         // Jika user login, gabungkan dengan data dari backend
//         if (roleId && !isNaN(roleId)) {
//           const res = await getBookmarkSummaryForUser();
//           const bookmarks =
//             res?.data?.data?.recentBookmarks ||
//             res?.data?.data?.bookmarks ||
//             res?.data?.data ||
//             [];

//           const ids = new Set<number>(
//             (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))
//           );
//         } else {
//           // Jika belum login, pakai local saja
//           setBookmarkedIds(localSet);
//         }
//       } catch (err) {
//         console.error("Gagal sinkronisasi bookmark:", err);
//       }
//     };

//     syncBookmarks();
//   }, []);

//   return (
//     <section className="max-w-[1350px] mx-auto px-4">
//       <div className="flex flex-col lg:flex-row gap-6 py-6">
//         {data.length > 0 && (
//           <Card
//             key={data[0].id}
//             item={data[0]}
//             isBig
//             bookmarkedIds={bookmarkedIds}
//             setBookmarkedIds={setBookmarkedIds}
//           />
//         )}

//         <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 w-full">
//           {data.slice(1, 5).map((item) => (
//             <Card
//               key={item.id}
//               item={item}
//               bookmarkedIds={bookmarkedIds}
//               setBookmarkedIds={setBookmarkedIds}
//             />
//           ))}
//         </div>
//       </div>

//       <div className="relative w-full h-48 sm:h-64 md:h-80 lg:h-[460px] mt-4 rounded-xl">
//         <Image
//           src={"/PPS.png"}
//           alt={"pps"}
//           fill
//           className="object-cover rounded-xl"
//         />
//       </div>
//     </section>
//   );
// }

// // 🔹 Helper function
// function itemTransform(article: any) {
//   return {
//     id: article.id,
//     title: article.title,
//     categoryName:
//       article.categoryName ||
//       (article.categories && article.categories[0]?.title) ||
//       "",
//     createdAt: article.createdAt,
//     smallThumbnailLink: article.thumbnailUrl,
//     fileTypeId: article.typeId,
//     clientName: article.clientName,
//     categories: article.categories,
//     label:
//       article.typeId === 1
//         ? "Image"
//         : article.typeId === 2
//         ? "Video"
//         : article.typeId === 3
//         ? "Text"
//         : article.typeId === 4
//         ? "Audio"
//         : "",
//   };
// }

// // 🔹 Komponen Card
// function Card({
//   item,
//   isBig = false,
//   bookmarkedIds,
//   setBookmarkedIds,
// }: {
//   item: any;
//   isBig?: boolean;
//   bookmarkedIds: Set<number>;
//   setBookmarkedIds: React.Dispatch<React.SetStateAction<Set<number>>>;
// }) {
//   const router = useRouter();
//   const MySwal = withReactContent(Swal);
//   const [isSaving, setIsSaving] = useState(false);

//   const isBookmarked = bookmarkedIds.has(Number(item.id));

//   const getLink = () => `/content/image/detail/${item?.id}`;

//   const handleToggleBookmark = async () => {
//     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",
//       }).then(() => router.push("/auth"));
//       return;
//     }

//     try {
//       setIsSaving(true);
//       const res = await toggleBookmark(item.id);

//       if (res?.error) {
//         MySwal.fire({
//           icon: "error",
//           title: "Gagal",
//           text: "Gagal memperbarui bookmark.",
//           confirmButtonColor: "#d33",
//         });
//       } else {
//         const updated = new Set(bookmarkedIds);
//         let pesan = "";

//         if (isBookmarked) {
//           updated.delete(Number(item.id));
//           pesan = "Dihapus dari bookmark.";
//         } else {
//           updated.add(Number(item.id));
//           pesan = "Artikel disimpan ke bookmark.";
//         }

//         setBookmarkedIds(updated);
//         localStorage.setItem(
//           "bookmarkedIds",
//           JSON.stringify(Array.from(updated))
//         );

//         MySwal.fire({
//           icon: "success",
//           title: isBookmarked ? "Dihapus!" : "Disimpan!",
//           text: pesan,
//           timer: 1500,
//           showConfirmButton: false,
//         });
//       }
//     } catch (err) {
//       console.error("Toggle bookmark error:", err);
//       MySwal.fire({
//         icon: "error",
//         title: "Kesalahan",
//         text: "Terjadi kesalahan saat menyimpan artikel.",
//         confirmButtonColor: "#d33",
//       });
//     } finally {
//       setIsSaving(false);
//     }
//   };

//   return (
//     <div
//       className={`rounded-xl overflow-hidden shadow hover:shadow-lg transition-all bg-white flex flex-col ${
//         isBig
//           ? "w-full lg:max-w-[670px] h-[680px]"
//           : "w-full h-[360px] md:h-[340px]"
//       }`}
//     >
//       <div className={`relative ${isBig ? "h-[420px]" : "h-[180px]"} w-full`}>
//         <Link href={getLink()}>
//           <Image
//             src={item.smallThumbnailLink || "/contributor.png"}
//             alt={item.title}
//             fill
//             className="object-cover"
//           />
//         </Link>
//       </div>

//       <div className="p-4 flex flex-col justify-between flex-1">
//         <div className="space-y-2">
//           <div className="flex items-center gap-2 text-xs font-semibold flex-wrap">
//             <span className="bg-emerald-600 text-white px-2 py-0.5 rounded">
//               {item.clientName}
//             </span>
//             <span className="text-orange-600">
//               {item.categories?.map((cat: any) => cat.title).join(", ")}
//             </span>
//           </div>

//           <div className="text-xs text-gray-500">
//             {new Date(item.createdAt)
//               .toLocaleString("id-ID", {
//                 day: "2-digit",
//                 month: "short",
//                 year: "numeric",
//                 hour: "2-digit",
//                 minute: "2-digit",
//                 hour12: false,
//                 timeZone: "Asia/Jakarta",
//               })
//               .replace(".", ":")}{" "}
//             WIB
//           </div>

//           <Link href={getLink()}>
//             <h3 className="text-sm font-semibold leading-snug line-clamp-2">
//               {item.title}
//             </h3>
//           </Link>
//         </div>

//         <div className="flex justify-between items-center pt-4">
//           <div className="flex gap-2 text-gray-500">
//             <ThumbsUp
//               size={18}
//               className="cursor-pointer hover:text-[#F60100]"
//             />
//             <ThumbsDown
//               size={18}
//               className="cursor-pointer hover:text-red-600"
//             />
//           </div>

//           <button
//             onClick={handleToggleBookmark}
//             disabled={isSaving || isBookmarked}
//             className={`text-sm px-3 py-1 rounded-md transition-all duration-200 ${
//               isBookmarked
//                 ? "bg-gray-400 text-white cursor-not-allowed"
//                 : "bg-[#F60100] text-white hover:bg-[#c90000]"
//             }`}
//           >
//             {isSaving ? "Menyimpan" : isBookmarked ? "Tersimpan" : "Simpan"}
//           </button>
//         </div>
//       </div>
//     </div>
//   );
// }
