import Link from "next/link";
import { notFound } from "next/navigation";
import PageShell from "@/components/page-shell";
import GuaFooter from "@/components/learn/gua-footer";
import MarkdownContent from "@/components/learn/markdown-content";
import {
  getGuaName,
  getGuaNumber,
  guaNumFromMark,
  listGuaMarks,
  markFromNum,
  readLearnMarkdown,
  stripFrontmatter,
} from "@/lib/content/zhouyi";

async function resolveGuaMark(slug: string): Promise<string | null> {
  const decoded = decodeURIComponent(slug);
  if (/^\d{1,2}$/.test(decoded)) {
    return markFromNum(decoded, "simplified");
  }
  const marks = await listGuaMarks("simplified");
  if (marks.includes(decoded)) {
    return decoded;
  }
  return null;
}

export async function generateStaticParams() {
  return Array.from({ length: 64 }, (_, i) => ({
    slug: String(i + 1).padStart(2, "0"),
  }));
}

export const dynamicParams = true;

export default async function GuaOtherDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const guaMark = await resolveGuaMark(slug);
  if (!guaMark) {
    notFound();
  }

  const raw = await readLearnMarkdown(guaMark, "simplified");
  const content = stripFrontmatter(raw);

  return (
    <PageShell width="narrow" className="py-8">
      <div className="mb-6 text-sm text-muted-foreground">
        <Link href="/learn/other" className="hover:text-foreground">
          ← 返回简体总览
        </Link>
      </div>
      <div className="mb-4 text-sm text-muted-foreground">
        第 {getGuaNumber(guaMark)} 卦 · {getGuaName(guaMark)}
      </div>
      <MarkdownContent content={content} variant="simplified" guaMark={guaMark} />
      <GuaFooter guaMark={guaMark} guaNum={guaNumFromMark(guaMark)} />
    </PageShell>
  );
}
