import Banner from "@/components/banner/Banner";
import Category from "@/components/sidebar/Category";
import Gallery from "@/components/common/Gallery";
import Pagination1 from "@/components/common/Pagination1";
import { getSiteSettings } from "@/utils/siteSettings";
import ListPageTemplate from "@/components/common/ListPageTemplate";
import { notFound } from 'next/navigation';

const baseSlug = 'applications';

export const revalidate = 3600;

export async function generateMetadata() {
  // 频道首页只需要基础 meta 信息
  return {
    title: 'Applications',
    description: 'Applications Channel Home',
  };
}

export default async function Page({ searchParams }) {
  const currentPage = Number(searchParams?.page) || 1;
  const siteSettings = await getSiteSettings(process.env.SITE_URL);
  const pageSize = Number(siteSettings.page_size) || 12;
  // 频道首页只查根 slug
  const res = await fetch(`${process.env.SITE_URL}/api/get-page-data`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ slug_list: [baseSlug], page: currentPage, page_size: pageSize })
  });
  const result = await res.json();
  const { data, error, total } = result;
  if (error) notFound();
  const bannerComponentName = 'Banner-' + baseSlug;
  const categoryComponentName = 'Category-' + baseSlug;
  const galleryComponentName = 'Gallery-' + baseSlug;
  const currentPath = '/' + baseSlug;
  const totalPages = Math.ceil((total || 0) / pageSize);
  const listItems = Array.isArray(data) ? data.map(item => ({
    slug: item.slug,
    title: item.title,
    image: item.image || item.cover || item.img || '',
    content: item.content || item.description || '',
  })) : [];

  return (
    <>
      <Banner componentName={bannerComponentName} />
      <div className="wrapper !bg-[#ffffff]">
        <div className="container py-[4.5rem] xl:!py-24 lg:!py-24 md:!py-24">
          <div className="flex flex-col md:flex-row mx-[-15px] xl:mx-[-35px] lg:mx-[-20px]">
            <Category componentName={categoryComponentName} />
            <div className="flex-1 min-w-0 !px-[15px] max-w-full md:!px-[20px] lg:!px-[20px] xl:!px-[35px]">
              <Gallery componentName={galleryComponentName} />
              <ListPageTemplate items={listItems} basePath={currentPath} />
              <div className="mt-8">
                <Pagination1
                  currentPage={currentPage}
                  totalPages={totalPages}
                  basePath={currentPath}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
