import type { Metadata } from "next";
import JsonLd from "@/app/components/JsonLd";
import { absoluteSiteUrl } from "@/app/lib/seo";
import AutumnLeaves from "@/app/components/AutumnLeaves";
import { getPortfolioPage, getPortfolioTaxonomy, type PortfolioFilter } from "@/app/lib/portfolio";
import PortfolioBrowser from "./PortfolioBrowser";
import PortfolioHeader from "./PortfolioHeader";
import styles from "./portfolio.module.css";

export const dynamic = "force-dynamic";

const portfolioTitle = "Portfolio thiết kế đồ họa";
const portfolioDescription = "Xem các tác phẩm ảnh bìa, banner website và thiết kế quảng cáo của JUNX DESIGN. Lọc thư viện theo danh mục và loại thiết kế.";
const portfolioUrl = absoluteSiteUrl("/portfolio");
const brandImage = absoluteSiteUrl("/og");

export const metadata: Metadata = {
  title: portfolioTitle,
  description: portfolioDescription,
  ...(portfolioUrl ? { alternates: { canonical: portfolioUrl } } : {}),
  openGraph: { type: "website", locale: "vi_VN", siteName: "JUNX DESIGN", title: portfolioTitle, description: portfolioDescription, ...(portfolioUrl ? { url: portfolioUrl } : {}), images: brandImage ? [{ url: brandImage, width: 1200, height: 630, alt: "Thư viện thiết kế JUNX DESIGN" }] : [] },
  twitter: { card: "summary_large_image", title: portfolioTitle, description: portfolioDescription, images: brandImage ? [brandImage] : [] },
};

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

function one(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

export default async function PortfolioPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const filters: PortfolioFilter = {
    category: one(params.category)?.slice(0, 80),
    theme: one(params.theme)?.slice(0, 80),
    type: one(params.type)?.slice(0, 80),
    q: one(params.q)?.slice(0, 100),
    page: Number(one(params.page) ?? 1),
    pageSize: 12,
  };
  const [result, taxonomy] = await Promise.all([getPortfolioPage(filters), getPortfolioTaxonomy()]);
  const activeFilters = {
    category: filters.category ?? "",
    theme: filters.theme ?? "",
    type: filters.type ?? "",
    q: filters.q ?? "",
    page: result.page,
  };
  const schema = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: portfolioTitle,
    description: portfolioDescription,
    inLanguage: "vi-VN",
    ...(portfolioUrl ? { url: portfolioUrl } : {}),
    mainEntity: {
      "@type": "ItemList",
      itemListElement: result.items.map((item, index) => ({
        "@type": "ListItem", position: index + 1,
        item: { "@type": "CreativeWork", name: item.title, image: item.coverUrl },
      })),
    },
    breadcrumb: {
      "@type": "BreadcrumbList",
      itemListElement: [
        { "@type": "ListItem", position: 1, name: "Trang chủ", item: absoluteSiteUrl("/") },
        { "@type": "ListItem", position: 2, name: "Portfolio", item: portfolioUrl },
      ],
    },
  };

  return (
    <main className={styles.portfolioPage}>
      <JsonLd data={schema} />
      <AutumnLeaves />
      <PortfolioHeader />
      <section className="portfolio-library section-wrap" aria-label="Thư viện thiết kế">
        <PortfolioBrowser
          initialItems={result.items}
          initialPagination={{ page: result.page, pageSize: result.pageSize, total: result.total, totalPages: Math.ceil(result.total / result.pageSize) }}
          initialFilters={activeFilters}
          initialError={result.error}
          taxonomy={taxonomy}
        />
      </section>
      <footer className="footer portfolio-footer">
        <div className="footer__main"><a className="footer__wordmark" href="/">JUNX DESIGN</a><p>Thiết kế hình ảnh nổi bật cho thương hiệu của bạn.</p><a href="/#contact">Liên hệ ↗</a></div>
        <div className="footer__meta"><span>© JUNX DESIGN</span><span>VIỆT NAM</span></div>
      </footer>
    </main>
  );
}
