import Image from "next/image";
import type { BlogArticle } from "@/data/articles";
import { resolveMediaUrl } from "@/lib/meshkee";

function formatDate(date: string) {
  if (!date) return "";
  try {
    return new Intl.DateTimeFormat("fa-IR", {
      year: "numeric",
      month: "long",
      day: "numeric",
    }).format(new Date(date));
  } catch {
    return date;
  }
}

export function ArticlesGrid({ items }: { items: BlogArticle[] }) {
  if (!items.length) {
    return (
      <p className="py-16 text-center text-[#777]">
        در حال حاضر مقاله‌ای برای نمایش وجود ندارد.
      </p>
    );
  }

  return (
    <div className="grid gap-7 sm:grid-cols-2 xl:grid-cols-3">
      {items.map((item) => {
        const image = resolveMediaUrl(item.image);
        return (
          <article
            key={item.id}
            className="article-card flex h-full flex-col overflow-hidden bg-white shadow-[0_0_10px_rgba(0,0,0,0.05)]"
          >
            <a
              href={`/articles/${item.slug}`}
              className="block overflow-hidden bg-[#f3f3f3]"
            >
              {image ? (
                <Image
                  src={image}
                  alt={item.title}
                  width={800}
                  height={600}
                  unoptimized
                  className="h-auto w-full object-contain transition duration-500 hover:opacity-95"
                  sizes="(max-width: 640px) 100vw, (max-width: 1280px) 50vw, 33vw"
                />
              ) : null}
            </a>

            <div className="flex flex-1 flex-col p-4">
              {item.date ? (
                <p className="mb-2 text-[13px] text-[#999]">
                  {formatDate(item.date)}
                </p>
              ) : null}
              <h2 className="mb-3 text-[15px] font-bold leading-7 text-[#232323]">
                <a href={`/articles/${item.slug}`} className="hover:text-brand">
                  {item.title}
                </a>
              </h2>
              <p className="mb-4 line-clamp-3 flex-1 text-sm leading-7 text-[#777]">
                {item.excerpt}
              </p>
              <div className="mt-auto border-t border-[#eee] pt-3">
                <a
                  href={`/articles/${item.slug}`}
                  className="inline-flex items-center gap-1 text-[13px] font-medium text-[#232323] hover:text-brand"
                >
                  بیشتر بخوانید
                  <span aria-hidden>›</span>
                </a>
              </div>
            </div>
          </article>
        );
      })}
    </div>
  );
}
