import { notFound } from "next/navigation";

import { CodexPage } from "@/components/codex/CodexPage";
import {
  fetchCharacters,
  fetchProject,
  fetchWorldEntities,
} from "@/lib/api/server";

interface PageProps {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ gen?: string }>;
}

// 设定库 Codex 页（UX §6.5）。Server Component 取项目 + 跨会话全量人物/世界观真源；
// CodexPage（Client）承载生成/管理 + 本会话新入库回显。
// ?gen=character|world 由命令面板动作跳转，进页直开对应生成器 tab。
export default async function CodexRoutePage({
  params,
  searchParams,
}: PageProps) {
  const { id } = await params;
  const { gen } = await searchParams;
  const initialTab = gen === "world" ? "world" : "characters";
  try {
    const [project, characters, worldEntities] = await Promise.all([
      fetchProject(id),
      fetchCharacters(id),
      fetchWorldEntities(id),
    ]);
    return (
      <CodexPage
        project={project}
        initialCharacters={characters.characters ?? []}
        initialWorldEntities={worldEntities.world_entities ?? []}
        initialTab={initialTab}
      />
    );
  } catch {
    notFound();
  }
}
