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 ArticleDetailView({ item }: { item: BlogArticle }) {
  const image = resolveMediaUrl(item.image);
  const contentHtml = (item.contentHtml || "").replace(
    /\bsrc=["']([^"']+)["']/gi,
    (_full, src: string) => `src="${resolveMediaUrl(src)}"`,
  );

  return (
    <section className="section">
      <div className="container-page max-w-4xl">
        {item.date ? (
          <p className="mb-4 text-sm text-[#999]">{formatDate(item.date)}</p>
        ) : null}

        {image ? (
          <div className="mb-8 overflow-hidden bg-[#f3f3f3]">
            <Image
              src={image}
              alt={item.title}
              width={1200}
              height={800}
              unoptimized
              priority
              className="h-auto w-full object-contain"
              sizes="(max-width: 896px) 100vw, 896px"
            />
          </div>
        ) : null}

        {contentHtml ? (
          <div
            className="article-body"
            dangerouslySetInnerHTML={{ __html: contentHtml }}
          />
        ) : item.excerpt ? (
          <p className="text-justify text-base leading-8 text-[#555]">
            {item.excerpt}
          </p>
        ) : null}
      </div>
    </section>
  );
}
