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

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

export async function generateStaticParams() {
  try {
    const res = await fetch(`${API_BASE}/courses`);
    const data = await res.json();
    const items = data.items || [];
    if (items.length === 0) return [{ id: '1' }];
    return items.map((c: any) => ({ id: String(c.id) }));
  } catch {
    return [{ id: '1' }];
  }
}

export async function generateMetadata({ params }: { params: { id: string } }): Promise<Metadata> {
  const course = await getCourse(params.id);
  if (!course) return { title: '课程未找到' };
  const title = course.title;
  const description = course.description || `${course.title} - 宇之然 AI 课程，系统学习 AI 技能`;
  const url = absoluteUrl(`/courses/${course.id}`);
  return {
    title,
    description,
    alternates: { canonical: `/courses/${course.id}` },
    openGraph: {
      type: 'article',
      title,
      description,
      url,
    },
  };
}

export default async function CourseDetailPage({ params }: { params: { id: string } }) {
  const course = await getCourse(params.id);
  const url = absoluteUrl(`/courses/${params.id}`);
  const jsonLd = course
    ? [
        articleJsonLd({
          headline: course.title,
          description: course.description || undefined,
          url,
        }),
        breadcrumbJsonLd([
          { name: '首页', url: SITE_URL },
          { name: '课程', url: absoluteUrl('/courses') },
          { name: course.title, url },
        ]),
      ]
    : null;

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