"use client";

import Link from "next/link";
import ArticleThumbnail from "@/components/landing-page/article-thumbnail";
import type { PublicArticle } from "@/lib/articles-public";

const BADGE_COLORS = [
  "bg-red-600",
  "bg-yellow-500",
  "bg-yellow-600",
  "bg-[#0f3b63]",
];

function firstTag(tags: string | undefined): string {
  if (!tags?.trim()) return "";
  const t = tags
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean)[0];
  return t ?? "";
}

export function articleDetailHref(a: PublicArticle) {
  return `/news/detail/${a.id}-${a.slug}`;
}

type Props = {
  article: PublicArticle;
};

export default function PublicArticleCard({ article }: Props) {
  const badgeClass = BADGE_COLORS[article.id % BADGE_COLORS.length];
  const category = article.categoryName?.trim() || "Berita";
  const tag = firstTag(article.tags);
  const dateSrc = article.publishedAt || article.createdAt;
  const dateLabel =
    typeof dateSrc === "string"
      ? new Date(dateSrc).toLocaleDateString("id-ID", {
          day: "2-digit",
          month: "long",
          year: "numeric",
        })
      : "";

  return (
    <Link
      href={articleDetailHref(article)}
      className="block overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm transition duration-300 hover:shadow-md"
    >
      <div className="relative h-[200px] w-full">
        <ArticleThumbnail
          src={article.thumbnailUrl}
          alt={article.title}
          sizes="(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 33vw"
        />
      </div>

      <div className="space-y-3 p-5">
        <div className="flex flex-wrap items-center gap-2 text-xs">
          <span
            className={`rounded-md px-2 py-[3px] font-medium text-white ${badgeClass}`}
          >
            {category}
          </span>
          {tag ? (
            <span className="uppercase tracking-wide text-gray-500">{tag}</span>
          ) : null}
        </div>

        <p className="text-xs text-gray-400">{dateLabel}</p>

        <h3 className="line-clamp-2 text-[15px] font-semibold leading-snug transition hover:text-[#966314]">
          {article.title}
        </h3>

        <p className="line-clamp-2 text-sm leading-relaxed text-gray-500">
          {article.description}
        </p>
      </div>
    </Link>
  );
}
