import type { Metadata } from 'next';
import { API_BASE, SITE_URL } from '@/lib/config';
import { articleJsonLd, breadcrumbJsonLd, absoluteUrl } from '@/lib/seo';
import PracticeDetailClient from './client';

async function getPractice(id: string) {
  try {
    const res = await fetch(`${API_BASE}/practices/${id}`, { next: { revalidate: 3600 } });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

export function generateStaticParams() {
  const ids = Array.from({ length: 20 }, (_, i) => i + 1);
  return ids.map((id) => ({ id: String(id) }));
}

export async function generateMetadata({ params }: { params: { id: string } }): Promise<Metadata> {
  const practice = await getPractice(params.id);
  if (!practice) return { title: '练习未找到' };
  const title = practice.title;
  const description = practice.description || `${practice.title} - 宇之然 AI 练习，实战演练获得即时评分`;
  const url = absoluteUrl(`/practices/${practice.id}`);
  return {
    title,
    description,
    alternates: { canonical: `/practices/${practice.id}` },
    openGraph: { type: 'article', title, description, url },
  };
}

export default async function PracticeDetailPage({ params }: { params: { id: string } }) {
  const practice = await getPractice(params.id);
  const url = absoluteUrl(`/practices/${params.id}`);
  const jsonLd = practice
    ? [
        articleJsonLd({ headline: practice.title, description: practice.description || undefined, url }),
        breadcrumbJsonLd([
          { name: '首页', url: SITE_URL },
          { name: '练习', url: absoluteUrl('/practices') },
          { name: practice.title, url },
        ]),
      ]
    : null;

  return (
    <>
      {jsonLd && (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      )}
      <PracticeDetailClient />
    </>
  );
}
