import type { Metadata } from "next";
import { notFound } from "next/navigation";

import { ProjectGalleryLightbox } from "@/components/portfolios/ProjectGalleryLightbox";
import { ProjectVideo } from "@/components/portfolios/ProjectVideo";
import { Reveal } from "@/components/Reveal";
import { PageCta } from "@/components/shared/PageCta";
import { PageHero } from "@/components/shared/PageHero";
import { SiteFooter } from "@/components/SiteFooter";
import { SiteHeader } from "@/components/SiteHeader";
import { portfoliosPage, projectVideos } from "@/data/site";
import { getPortfolioBySlug, getPortfolios, toDisplayProject } from "@/lib/api";

export const revalidate = 3600;

export async function generateStaticParams() {
  const portfolios = await getPortfolios();
  return portfolios.map((item) => ({ slug: item.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const item = await getPortfolioBySlug(slug);
  if (!item) return {};

  return {
    title: item.titleFa,
    description: item.abstract || item.titleFa,
  };
}

const publishedDateFormatter = new Intl.DateTimeFormat("fa-IR", {
  year: "numeric",
  month: "long",
  day: "numeric",
});

/**
 * Structurally inspired by binghatti.com's project pages (hero, in-page jump
 * nav, gallery grid, closing CTA) — but scoped strictly to what the meshkee
 * API actually returns for a portfolio item. Binghatti's page also carries
 * location/map, floor plans, a brochure download and priced unit listings;
 * none of those exist as data here, so none of those sections are built.
 */
export default async function PortfolioDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const item = await getPortfolioBySlug(slug);
  if (!item) notFound();

  const project = toDisplayProject(item);
  const hasGallery = project.gallery.length > 0;
  const videoUrl = projectVideos[project.slug];
  const publishedLabel = publishedDateFormatter.format(new Date(project.publishedAt));

  const navItems = [
    { id: "overview", label: "معرفی پروژه" },
    ...(videoUrl ? [{ id: "video", label: "ویدیو" }] : []),
    ...(hasGallery ? [{ id: "gallery", label: "گالری تصاویر" }] : []),
  ];

  // Backgrounds alternate by what actually renders, not by fixed section
  // name — otherwise skipping the video section (no link set) could leave
  // two sections the same colour back to back.
  const videoBg = "bg-sand";
  const galleryBg = videoUrl ? "bg-paper" : "bg-sand";

  return (
    <>
      <SiteHeader />

      <main>
        <PageHero
          image={project.image}
          caption={project.type}
          title={project.name}
          breadcrumb={[
            { label: "صفحه اصلی", href: "/" },
            { label: "نمونه کارها", href: "/portfolios" },
            { label: project.name, href: `/portfolios/${project.slug}` },
          ]}
        />

        {/* Jump nav — only rendered when there is a second section to jump to. */}
        {navItems.length > 1 && (
          <nav aria-label="بخش‌های صفحه" className="border-b border-line bg-paper">
            <ul className="no-scrollbar mx-auto flex max-w-[1400px] items-center gap-8 overflow-x-auto px-6 lg:px-12">
              {navItems.map((navItem) => (
                <li key={navItem.id}>
                  <a
                    href={`#${navItem.id}`}
                    className="block scroll-mt-24 py-5 text-sm whitespace-nowrap text-muted transition-colors duration-300 hover:text-gold"
                  >
                    {navItem.label}
                  </a>
                </li>
              ))}
            </ul>
          </nav>
        )}

        <section id="overview" className="scroll-mt-20 bg-paper py-16 lg:py-24">
          <div className="mx-auto max-w-[1400px] px-6 lg:px-12">
            <Reveal>
              <div className="mx-auto mb-14 flex max-w-[738px] flex-col items-center gap-3 text-center">
                <p className="kicker justify-center">معرفی پروژه</p>
                <time dateTime={project.publishedAt} className="text-xs text-muted">
                  {publishedLabel}
                </time>
              </div>
            </Reveal>

            {project.bodyHtml && (
              <Reveal delay={90}>
                <div className="cms-body" dangerouslySetInnerHTML={{ __html: project.bodyHtml }} />
              </Reveal>
            )}
          </div>
        </section>

        {videoUrl && (
          <section id="video" className={`scroll-mt-20 ${videoBg} py-16 lg:py-24`}>
            <div className="mx-auto max-w-[1400px] px-6 lg:px-12">
              <Reveal>
                <p className="kicker mb-14 justify-center">ویدیو</p>
              </Reveal>

              <Reveal delay={90}>
                <ProjectVideo url={videoUrl} />
              </Reveal>
            </div>
          </section>
        )}

        {hasGallery && (
          <section id="gallery" className={`scroll-mt-20 ${galleryBg} py-16 lg:py-24`}>
            <div className="mx-auto max-w-[1400px] px-6 lg:px-12">
              <Reveal>
                <p className="kicker mb-14 justify-center">گالری تصاویر</p>
              </Reveal>

              <ProjectGalleryLightbox images={project.gallery} alt={project.name} />
            </div>
          </section>
        )}

        <PageCta
          caption={portfoliosPage.cta.caption}
          title={portfoliosPage.cta.title}
          action={portfoliosPage.cta.action}
        />
      </main>

      <SiteFooter />
    </>
  );
}
