import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { HeroBanner } from "@/app/components/HeroBanner";
import Link from "next/link";
import prisma from "@/lib/prisma";

function stripHtml(html: string | null | undefined): string {
  if (!html) return "";
  return html.replace(/<[^>]*>/g, "").trim();
}

// 서버 전용 페이지: params가 Promise일 수 있어 안전 언랩 후 절대 URL로 fetch합니다.
export default async function PostDetail({ params }: { params: any }) {
  const p = params?.then ? await params : params;
  const id = p.id as string; // slug 값이 들어옴
  const h = await headers();
  const host = h.get("host") ?? "localhost:3000";
  const proto = h.get("x-forwarded-proto") ?? "http";
  const base = process.env.NEXT_PUBLIC_BASE_URL || `${proto}://${host}`;
  const res = await fetch(new URL(`/api/posts/${id}`, base).toString(), { cache: "no-store" });
  if (!res.ok) return notFound();
  const { post } = await res.json();
  const createdAt = post?.createdAt ? new Date(post.createdAt) : null;

  // 같은 게시판의 다른 게시글 10개 가져오기 (현재 게시글 제외)
  const relatedPosts = post?.boardId
    ? await prisma.post.findMany({
        where: {
          boardId: post.boardId,
          id: { not: id },
          status: { not: "deleted" },
        },
        orderBy: { createdAt: "desc" },
        take: 10,
        select: {
          id: true,
          title: true,
          createdAt: true,
          author: { select: { nickname: true } },
          stat: { select: { views: true, recommendCount: true, commentsCount: true } },
        },
      })
    : [];

  return (
    <div className="space-y-6">
      {/* 상단 배너 */}
      <section>
        <HeroBanner />
      </section>

      {/* 본문 카드 */}
      <section className="rounded-xl overflow-hidden bg-white">
        <header className="px-4 py-3 border-b border-neutral-200">
          <h1 className="text-xl md:text-2xl font-bold text-neutral-900 break-words">{post.title}</h1>
          {createdAt && (
            <p className="mt-1 text-xs text-neutral-500">{createdAt.toLocaleString()}</p>
          )}
        </header>
        <div className="p-4 md:p-6">
          <div 
            className="prose max-w-none break-words" 
            dangerouslySetInnerHTML={{ __html: post.content || "" }}
            style={{
              wordBreak: "break-word",
            }}
          />
        </div>
        <footer className="px-4 py-3 border-t border-neutral-200 flex gap-2">
          <form action={`/api/posts/${post.id}/recommend`} method="post">
            <button type="submit" className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm hover:bg-neutral-800">추천</button>
          </form>
          <form action={`/api/posts/${post.id}/report`} method="post">
            <button type="submit" className="h-9 px-4 rounded-md border border-neutral-300 bg-white text-sm hover:bg-neutral-100">신고</button>
          </form>
        </footer>
      </section>

      {/* 같은 게시판 게시글 목록 */}
      {relatedPosts.length > 0 && (
        <section className="rounded-xl overflow-hidden bg-white">
          <header className="px-4 py-3 border-b border-neutral-200">
            <h2 className="text-lg font-bold text-neutral-900">같은 게시판 게시글</h2>
          </header>
          <div>
            <ul className="divide-y divide-[#ececec]">
              {relatedPosts.map((p) => {
                const postDate = new Date(p.createdAt);
                return (
                  <li key={p.id} className="px-4 py-2.5 hover:bg-neutral-50 transition-colors">
                    <Link href={`/posts/${p.id}`} className="block">
                      <div className="grid grid-cols-1 md:grid-cols-[1fr_120px_120px_80px] items-center gap-2">
                        <div className="min-w-0">
                          <div className="truncate text-[15px] md:text-base text-neutral-900">
                            {stripHtml(p.title)}
                          </div>
                        </div>
                        <div className="md:w-[120px] text-xs text-neutral-600 text-center hidden md:flex items-center justify-center gap-2">
                          <span className="truncate max-w-[84px]">{p.author?.nickname ?? "익명"}</span>
                        </div>
                        <div className="md:w-[120px] text-[11px] text-[#8c8c8c] text-center flex items-center justify-center gap-3">
                          <span>조회 {p.stat?.views ?? 0}</span>
                          <span>추천 {p.stat?.recommendCount ?? 0}</span>
                          <span>댓글 {p.stat?.commentsCount ?? 0}</span>
                        </div>
                        <div className="md:w-[80px] text-[11px] text-neutral-500 text-right hidden md:block">
                          {postDate.toLocaleDateString()}
                        </div>
                      </div>
                    </Link>
                  </li>
                );
              })}
            </ul>
          </div>
        </section>
      )}
    </div>
  );
}


