import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getNewsroomDetail } from "@/api/newsroom";
import { PageContainer } from "@/components/layout/PageContainer";
import { SiteFooter } from "@/components/layout/SiteFooter";
import { formatHeroDate, formatNewsroomDate } from "@/lib/formatDate";
import { ROUTES } from "@/lib/routes";
import {
  FacebookIcon,
  InstagramIcon,
  LinkedInIcon,
  MailIcon,
  XIcon,
} from "@/components/ui/Icons";
import { NewsroomHeader } from "@/components/newsroom/NewsroomHeader";
import { env } from "@/config/env";
import type { NewsroomItem } from "@/types/newsroom";

interface NewsroomDetailPageProps {
  params: Promise<{ slug: string }>;
  searchParams?: Promise<{ [key: string]: string | string[] | undefined }>;
}

/**
 * Generate SEO Metadata using mt (meta title) and md (meta description).
 */
export const instant = false;
export async function generateMetadata(
  props: NewsroomDetailPageProps
): Promise<Metadata> {
  const resolvedParams = await props?.params;
  const slug = resolvedParams?.slug;

  if (!slug) {
    return {
      title: "Article Not Found | Sterling Protection Partners",
      description: "The requested newsroom article could not be found.",
    };
  }

  const article = await getNewsroomDetail(slug);

  if (!article) {
    return {
      title: "Article Not Found | Sterling Protection Partners",
      description: "The requested newsroom article could not be found.",
    };
  }

  const metaTitle = article.mt || article.t || "Newsroom Article";
  const metaDescription =
    article.md ||
    "Explore the latest insights and updates from Sterling Protection Partners.";

  const metaKeywords = (() => {
    if (Array.isArray(article.kw)) {
      return article.kw.map((k) => String(k).trim()).filter(Boolean);
    }
    if (typeof article.kw === "string" && article.kw.trim()) {
      try {
        const parsed = JSON.parse(article.kw);
        if (Array.isArray(parsed)) {
          return parsed.map((k) => String(k).trim()).filter(Boolean);
        }
      } catch {
        const stripped = article.kw.replace(/^\[|\]$/g, "").trim();
        if (stripped) {
          return stripped
            .split(",")
            .map((s) => s.replace(/["']/g, "").trim())
            .filter(Boolean);
        }
      }
    }
    return undefined;
  })();

  return {
    title: `${metaTitle} | Sterling Protection Partners`,
    description: metaDescription,
    keywords: metaKeywords,
    openGraph: {
      title: metaTitle,
      description: metaDescription,
      url: `/newsroom/${slug}`,
      type: "article",
      publishedTime: article.createdAt,
      images: article.bi ? [{ url: article.bi }] : undefined,
      
      siteName: "Sterling Protection Partners",
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description: metaDescription,
      images: article.bi ? [article.bi] : undefined,
    },
    metadataBase: new URL(env.siteUrl),
    alternates: {
      canonical: `/newsroom/${slug}`,
    },
    publisher: "https://sterlingprotection.co/",

  };
}

export default async function NewsroomDetailPage(
  props: NewsroomDetailPageProps
) {
  const resolvedParams = await props?.params;
  const slug = resolvedParams?.slug;

  if (!slug) {
    notFound();
  }

  const article = await getNewsroomDetail(slug);

  if (!article) {
    notFound();
  }

  const formattedDate = formatNewsroomDate(article.d);
  const heroDate = formatHeroDate(article.d || article.createdAt).toUpperCase();
  const authorName = article.author || article.cat_name || "Sterling Protection";
  const articleUrl = `${env.siteUrl}/newsroom/${article.sl || article._id}`;

  // Parse categories array or string
  const categories: string[] = (() => {
    if (Array.isArray(article.cat)) {
      return article.cat
        .map((c) =>
          typeof c === "object" && c !== null
            ? (c as any).n || (c as any).name || (c as any).title
            : String(c)
        )
        .filter(Boolean);
    }
    if (article.cat_name) {
      return [article.cat_name];
    }
    if (typeof article.cat === "string" && article.cat.trim()) {
      const stripped = article.cat.replace(/^\[|\]$/g, "").trim();
      if (stripped) {
        return stripped
          .split(",")
          .map((s) => s.replace(/["']/g, "").trim())
          .filter(Boolean);
      }
    }
    return ["Newsroom"];
  })();

  // Parse keywords array or string
  const keywords: string[] = (() => {
    if (Array.isArray(article.kw)) {
      return article.kw.map((k) => String(k).trim()).filter(Boolean);
    }
    if (typeof article.kw === "string" && article.kw.trim()) {
      try {
        const parsed = JSON.parse(article.kw);
        if (Array.isArray(parsed)) {
          return parsed.map((k) => String(k).trim()).filter(Boolean);
        }
      } catch {
        const stripped = article.kw.replace(/^\[|\]$/g, "").trim();
        if (stripped) {
          return stripped
            .split(",")
            .map((s) => s.replace(/["']/g, "").trim())
            .filter(Boolean);
        }
      }
    }
    return [];
  })();

  // Parse related news articles
  const relatedNews: NewsroomItem[] = Array.isArray(article.related_news)
    ? article.related_news
    : [];
  const sidebarRelated = relatedNews.slice(0, 3);
  const readNextRelated = relatedNews.length > 3 ? relatedNews.slice(3, 5) : [];

  // Calculate estimated reading time
  const readingTime = (() => {
    if (!article.c) return 3;
    const words = article.c.replace(/<[^>]*>/g, " ").trim().split(/\s+/).length;
    return Math.max(1, Math.ceil(words / 200));
  })();

  // Structured Data (JSON-LD) for SEO
  const blogPostingSchema = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: article.t,
    description: article.md || article.st || "",
    image: article.bi ? [article.bi] : undefined,
    datePublished: article.d,
    dateModified: article.d,
    author: {
      "@type": "Person",
      name: authorName,
    },
    publisher: {
      "@type": "Organization",
      name: "Sterling Protection Partners",
      url: env.siteUrl,
      logo: {
        "@type": "ImageObject",
        url: `${env.siteUrl}/icon.svg`,
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": articleUrl,
    },
    articleSection: categories[0] || undefined,
    keywords: keywords.join(", "),
  };

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Home",
        item: `${env.siteUrl}/`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: "Blog",
        item: `${env.siteUrl}/newsroom`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: article.t,
        item: articleUrl,
      },
    ],
  };

  return (
    <PageContainer>
      {/* Schema.org Structured Data */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(blogPostingSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      <NewsroomHeader />

      {/* Hero Section with newsroom.jpg Background - full width like footer */}
      <section className="relative right-1/2 left-1/2 -mr-[50vw] -ml-[50vw] flex min-h-[350px] w-screen flex-col justify-center overflow-hidden bg-[#0a1e36] bg-[url('/images/newsroom/newsroom.jpg')] bg-cover bg-center bg-no-repeat pt-10 pb-28 text-white shadow-sm sm:min-h-[520px] sm:pt-12 sm:pb-36 md:min-h-[350px] md:pt-10 md:pb-27">
        {/* Subtle dark gradient overlay for optimal text contrast while preserving image texture */}
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-r from-[#0a1e36]/60 via-[#0a1e36]/40 to-[#0a1e36]/60" />

        <div className="relative mx-auto w-full max-w-[1280px] px-[60px] max-[769px]:px-5">
          {/* Subtle wolf crest watermark on right - anchored to container, visible and half-cut on tablet/mobile */}
          <div className="pointer-events-none absolute right-0 top-[65%] md:top-[70%] translate-x-[48%] -translate-y-1/2 select-none opacity-[0.08]">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="/images/brand/footer-logo.png"
              alt=""
              className="h-[180px] w-auto object-contain sm:h-[240px] md:h-[300px] lg:h-[300px]"
            />
          </div>
          {/* Top Row: Categories & Hero Date - Moved up with tighter spacing */}
          <div className="flex flex-wrap items-center justify-between gap-4 text-xs font-semibold tracking-wider text-white/90 uppercase sm:text-sm w-[95%]">
            <div className="flex flex-wrap items-center gap-2">
              {categories.map((cat, idx) => (
                <span key={`${cat}-${idx}`} className="flex items-center gap-2">
                  <span>{cat}</span>
                  {idx < categories.length - 1 && (
                    <span className="text-white/40">•</span>
                  )}
                </span>
              ))}
            </div>
            {heroDate && (
              <div className="tracking-wider text-white/90">{heroDate}</div>
            )}
          </div>

          {/* Title - Reduced width on tablet/mobile so text does not overlap the half-cut logo */}
          <h1 className="mt-14.5 mb-5 max-w-[70%] text-2xl leading-[1.25] tracking-tight text-white sm:mt-14 sm:mb-6 sm:max-w-[72%] sm:text-3xl md:max-w-[75%] md:text-4xl lg:max-w-[82%] lg:text-[34px] xl:max-w-[1050px]">
            {article.t}
          </h1>

          {/* Social Share Icons */}
          <div className="flex items-center gap-2.5">
            <a
              href={`https://www.facebook.com/sharer.php?u=${encodeURIComponent(articleUrl)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Share on Facebook"
              className="flex size-9 items-center justify-center rounded-[4px] bg-[#2E5E99] text-white transition-colors duration-200 hover:bg-[#1E4E89]"
            >
              <FacebookIcon className="size-4" />
            </a>
            <a
              href="https://www.instagram.com/sterling_protection_partners?mdxt=MWd6Y2dpY2lxYzFxdg=="
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Instagram"
              className="flex size-9 items-center justify-center rounded-[4px] bg-[#2E5E99] text-white transition-colors duration-200 hover:bg-[#1E4E89]"
            >
              <InstagramIcon className="size-4" />
            </a>
            <a
              href={`https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(articleUrl)}&title=${encodeURIComponent(article.t)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Share on LinkedIn"
              className="flex size-9 items-center justify-center rounded-[4px] bg-[#2E5E99] text-white transition-colors duration-200 hover:bg-[#1E4E89]"
            >
              <LinkedInIcon className="size-4" />
            </a>
            <a
              href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(articleUrl)}&text=${encodeURIComponent(article.t)}`}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Share on X"
              className="flex size-9 items-center justify-center rounded-[4px] bg-[#2E5E99] text-white transition-colors duration-200 hover:bg-[#1E4E89]"
            >
              <XIcon className="size-4" />
            </a>
            <a
              href={`mailto:?subject=${encodeURIComponent(article.t)}&body=${encodeURIComponent(articleUrl)}`}
              aria-label="Share via Email"
              className="flex size-9 items-center justify-center rounded-[4px] bg-[#2E5E99] text-white transition-colors duration-200 hover:bg-[#1E4E89]"
            >
              <MailIcon className="size-4" />
            </a>
          </div>
        </div>
      </section>

      {/* Main Content Area */}
      <main className="w-full pb-20 sm:pb-28">
        <div className="mx-auto w-full max-w-[1280px] px-[60px] max-[769px]:px-5">
          {/* 2-Column Grid: Left (Article) & Right (Sidebar) */}
          <div className="grid grid-cols-1 items-start gap-10 lg:grid-cols-12 lg:gap-12 xl:gap-14">
            {/* Left Content Area */}
            <div
              className={
                sidebarRelated.length > 0 ? "lg:col-span-8" : "lg:col-span-12"
              }
            >
              {/* Banner Image with crisp white border slightly overlapping hero */}
              {article.bi && (
                <div className="relative z-10 mt-12 overflow-hidden border-[12px] border-white bg-white  sm:-mt-16 sm:border-12 md:-mt-20">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={article.bi}
                    alt={article.t}
                    className="h-auto max-h-[580px] w-full  object-cover"
                    loading="eager"
                  />
                </div>
              )}

              {/* Meta row below image */}
              {/* <div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-b border-gray-100 pb-3 text-xs text-gray-500">
                <div>
                  <span>
                    Cover image: © {article.author || "Sterling Protection Partners"}
                  </span>
                </div>
                <div className="flex items-center gap-4">
                  <span>Issued on: {formattedDate}</span>
                  <span className="text-gray-300">|</span>
                  <span>{readingTime} min read</span>
                </div>
              </div> */}

              {/* Subtitle below image */}
              {article.st && (
                <p className="mt-6 text-base font-medium leading-relaxed text-gray-800 sm:text-lg">
                  {article.st}
                </p>
              )}

              {/* HTML Content */}
              {article.c ? (
                <article
                  className="newsroom-article-content mt-6 py-2"
                  dangerouslySetInnerHTML={{ __html: article.c }}
                />
              ) : (
                <p className="py-12 text-center text-gray-500">
                  No content available for this article yet.
                </p>
              )}
            </div>

            {/* Right Column: ON THE SAME TOPIC - Sharp square card with clean border */}
            {sidebarRelated.length > 0 && (
              <aside className="pt-6 sm:pt-8 lg:sticky lg:top-24 lg:col-span-4 lg:pt-10">
                <div className="border border-gray-300 bg-white p-5 sm:p-6">
                  {/* Card Title */}
                  <div className="mb-4 flex items-center gap-2 text-base font-bold tracking-wide text-[#0d2440] uppercase sm:text-lg">
                    <span className="inline-block size-3 rounded-none bg-[#0088cc]" />
                    <span>ON THE SAME TOPIC</span>
                  </div>

                  <div className="divide-y divide-gray-200">
                    {sidebarRelated.map((item, idx) => {
                      const itemCat =
                        item.cat_name ||
                        (Array.isArray(item.cat) ? item.cat[0] : item.cat) ||
                        "Newsroom";
                      return (
                        <div
                          key={item._id || item.sl || idx}
                          className="py-4 first:pt-0 last:pb-0"
                        >
                          {idx === 0 && (
                            <div className="mb-1 text-[11px] font-medium tracking-wide text-gray-500">
                              Spotlight
                            </div>
                          )}
                          <Link
                            href={`/newsroom/${item.sl || item._id}`}
                            className="block font-bold text-sm leading-snug text-gray-900 transition-colors hover:text-accent sm:text-base line-clamp-3"
                          >
                            {item.t}
                          </Link>
                          {/* <div className="mt-2.5 flex items-center gap-1.5 text-[11px] font-bold tracking-wider text-gray-700 uppercase">
                            <span className="inline-block size-2 rounded-none bg-[#0088cc]" />
                            <span>{itemCat}</span>
                          </div> */}
                        </div>
                      );
                    })}
                  </div>
                </div>
              </aside>
            )}
          </div>

          {/* READ NEXT Section - Shown if related_news.length > 3 */}
          {readNextRelated.length > 0 && (
            <div className="mt-14 border-t border-gray-200 pt-10">
              <div className="mb-6 flex items-center gap-2">
                <span className="inline-block size-3.5 rounded-[2px] bg-[#0088cc]" />
                <h2 className="text-xl font-bold tracking-tight text-[#0d2440] uppercase sm:text-2xl">
                  READ NEXT
                </h2>
              </div>

              <div className="grid grid-cols-1 gap-6 sm:grid-cols-3 md:grid-cols-4">
                {readNextRelated.map((item, idx) => {
                  const itemCat =
                    item.cat_name ||
                    (Array.isArray(item.cat) ? item.cat[0] : item.cat) ||
                    "Newsroom";
                  return (
                    <Link
                      key={item._id || item.sl || idx}
                      href={`/newsroom/${item.sl || item._id}`}
                      className="group flex flex-col"
                    >
                      {item.bi && (
                        <div className="relative aspect-[16/9] w-full overflow-hidden  bg-gray-100">
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={item.bi}
                            alt={item.t}
                            className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                          />
                        </div>
                      )}
                      <h3 className="mt-3 font-bold text-sm leading-snug text-gray-900 transition-colors group-hover:text-accent sm:text-base line-clamp-2">
                        {item.t}
                      </h3>
                      {/* <div className="mt-2 flex items-center gap-1.5 text-[11px] font-bold tracking-wider text-gray-600 uppercase">
                        <span className="inline-block size-2 rounded-[1px] bg-[#0088cc]" />
                        <span>{itemCat}</span>
                      </div> */}
                    </Link>
                  );
                })}
              </div>
            </div>
          )}

          {/* KEYWORDS FOR THIS ARTICLE Section */}
          {keywords.length > 0 && (
            <div className="mt-12 border-t border-gray-200 pt-8">
              <h3 className="mb-4 text-sm font-bold tracking-wider text-[#0d2440] uppercase sm:text-base">
                KEYWORDS FOR THIS ARTICLE
              </h3>
              <div className="flex flex-wrap gap-2.5">
                {keywords.map((kw, i) => (
                  <span
                    key={`${kw}-${i}`}
                    className="inline-flex items-center rounded-md border border-gray-300 bg-white px-3.5 py-1.5 text-xs font-medium text-gray-700 shadow-sm transition-colors hover:border-gray-400 hover:bg-gray-50 sm:text-sm"
                  >
                    {kw}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Navigation Back */}
          <div className="mt-12 border-t border-gray-100 pt-8">
            <Link
              href={ROUTES.newsroom}
              className="group inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-5 py-3 text-sm font-semibold text-gray-700 shadow-sm transition-all hover:border-accent hover:bg-gray-50 hover:text-accent"
            >
              <svg
                className="h-4 w-4 transition-transform group-hover:-translate-x-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2.5"
                  d="M10 19l-7-7m0 0l7-7m-7 7h18"
                />
              </svg>
              <span>Back to All Articles</span>
            </Link>
          </div>
        </div>
      </main>

      <SiteFooter />
    </PageContainer>
  );
}
