import Link from "next/link";
import { notFound } from "next/navigation";
import { getAllPosts, getPostByUrlSlug } from "../../../lib/content";
import PostGallery from "../../../components/PostGallery";

function galleryItems(block: string) {
  const items = [] as { source: string; caption: string }[];
  Array.from(block.matchAll(/!\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g)).forEach((match) => items.push({ source: match[1].trim(), caption: (match[2] || match[1].replace(/\.[^.]+$/, "").replaceAll("_", " ")).trim() }));
  Array.from(block.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)).forEach((match) => items.push({ source: match[2].trim(), caption: (match[1] || match[2].split("/").pop() || "image").trim() }));
  return items;
}

export async function generateStaticParams() {
  return (await getAllPosts()).map((post) => ({ slug: post.urlSlug }));
}

export default async function BlogPostPage({ params }: { params: { slug: string } }) {
  const post = await getPostByUrlSlug(params.slug);
  if (!post) notFound();
  const thumbnail = post.thumbnail?.startsWith("/") ? post.thumbnail : null;
  return <main className="post-page section"><Link className="back-link" href="/blog">← 블로그 목록</Link><header className="post-header"><p className="eyebrow">{post.category}</p><h1>{post.title}</h1><p>{post.description}</p>{thumbnail && <img className="post-thumbnail" src={thumbnail} alt={post.title} />}<small>{post.publishedAt}</small></header><article className="post-body">{post.content.split(/\n\s*\n/).map((rawBlock, index) => {
    const block = rawBlock.trim();
    if (/^>\s*\[!gallery\]/i.test(block)) {
      return <PostGallery key={index} items={galleryItems(block)} />;
    }
    if (block.startsWith("# ")) return null;
    if (block.startsWith("## ")) return <h2 key={index}>{block.slice(3)}</h2>;
    if (/^>\s*갤러리 캡션 예시:/.test(block)) return <p className="gallery-note" key={index}>{block.replace(/^>\s*/, "")}</p>;
    return <p key={index}>{block}</p>;
  })}</article></main>;
}
