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, "traditional");
  }
  const marks = await listGuaMarks("traditional");
  if (marks.includes(decoded)) {
    return decoded;
  }
  if (/^\d{2}\./.test(decoded)) {
    return marks.find((m) => m === decoded || m.startsWith(decoded.split(".")[0] + ".")) ?? null;
  }
  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 GuaDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const guaMark = await resolveGuaMark(slug);
  if (!guaMark) {
    notFound();
  }

  const raw = await readLearnMarkdown(guaMark, "traditional");
  const content = stripFrontmatter(raw);
  const num = guaNumFromMark(guaMark);

  return (
    <PageShell className="max-w-3xl px-4 py-8">
      <div className="mb-6 text-sm text-muted-foreground">
        <Link href="/learn" className="hover:text-foreground">
          ← 返回总览
        </Link>
      </div>
      <div className="mb-4 text-sm text-muted-foreground">
        第 {getGuaNumber(guaMark)} 卦 · {getGuaName(guaMark)}
      </div>
      <MarkdownContent content={content} variant="traditional" guaMark={guaMark} />
      <GuaFooter guaMark={guaMark} guaNum={num} />
    </PageShell>
  );
}
