import { notFound } from "next/navigation";
import { getAllGames, getGame, getChapter, getAdjacentChapters } from "@/lib/content";
import ChapterReader from "@/components/ChapterReader";

interface PageProps {
  params: { game: string; chapter: string };
}

export function generateStaticParams() {
  const games = getAllGames();
  const paths: { game: string; chapter: string }[] = [];

  for (const gameMeta of games) {
    const game = getGame(gameMeta.slug);
    for (const chapter of game.chapters) {
      paths.push({ game: gameMeta.slug, chapter: chapter.slug });
    }
  }

  return paths;
}

export function generateMetadata({ params }: PageProps) {
  try {
    const game = getGame(params.game);
    const chapter = getChapter(params.game, params.chapter);
    return {
      title: `${chapter.title} - ${game.title} | Cronicas de los Reinos`,
      description: `Capitulo ${chapter.number} de ${game.title}`,
    };
  } catch {
    return { title: "No encontrado" };
  }
}

export default function ChapterPage({ params }: PageProps) {
  try {
    const game = getGame(params.game);
    const chapter = getChapter(params.game, params.chapter);
    const { prev, next } = getAdjacentChapters(params.game, params.chapter);

    return (
      <ChapterReader
        game={game}
        chapter={chapter}
        totalChapters={game.chapters.length}
        prevChapter={prev}
        nextChapter={next}
      />
    );
  } catch {
    notFound();
  }
}
