import type { Metadata } from 'next';
import { publicApi } from '@/lib/services';
import { Hero } from '@/components/front/Hero';
import { Section } from '@/components/front/Section';
import { ProductCard } from '@/components/front/ProductCard';
import { NewsCard } from '@/components/front/NewsCard';
import { StatsBar } from '@/components/front/StatsBar';
import { FeatureGrid } from '@/components/front/FeatureGrid';
import { SolutionShowcase } from '@/components/front/SolutionShowcase';
import { CtaSection } from '@/components/front/CtaSection';

export const metadata: Metadata = {
  title: '首页',
  description:
    '智管物业 - 让物业管理像发微信一样简单。物业缴费、在线报修、社区公告、巡检管理一站式SaaS平台。',
};

export const revalidate = 60;

async function fetchHome() {
  try {
    const [config, products, news] = await Promise.all([
      publicApi.getSiteConfig(),
      publicApi.getProducts({ page: 1, pageSize: 6 }),
      publicApi.getNews({ page: 1, pageSize: 5 }),
    ]);
    return { config, products: products.list, news: news.list };
  } catch {
    return { config: null, products: [], news: [] };
  }
}

export default async function HomePage() {
  const { config, products, news } = await fetchHome();

  return (
    <>
      <Hero />

      {/* 数据条 */}
      <StatsBar />

      {/* 核心功能 */}
      <FeatureGrid />

      {/* 解决方案 */}
      <SolutionShowcase />

      {/* 产品 */}
      <Section
        title="产品方案"
        subtitle="覆盖物业管理全场景的SaaS产品矩阵"
        moreHref="/products"
        className="bg-slate-50"
      >
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {products.map((p) => (
            <ProductCard key={p.id} product={p} />
          ))}
        </div>
        {products.length === 0 && <Empty text="暂无产品数据" />}
      </Section>

      {/* 新闻 */}
      <Section
        title="新闻资讯"
        subtitle="行业动态、产品更新、物业数字化转型洞察"
        moreHref="/news"
      >
        <div className="grid gap-4 md:grid-cols-2">
          {news.map((n) => (
            <NewsCard key={n.id} news={n} />
          ))}
        </div>
        {news.length === 0 && <Empty text="暂无新闻数据" />}
      </Section>

      {/* 转化引导 */}
      <CtaSection tel={config?.tel} />
    </>
  );
}

function Empty({ text }: { text: string }) {
  return (
    <div className="flex h-32 items-center justify-center rounded-md border border-dashed border-slate-200 text-sm text-slate-400">
      {text}
    </div>
  );
}
