import PostGrid from "@/components/WP/PostGrid/PostGrid.server";
import { renderPostContent } from "@/components/WPRenderer/WPRenderer";
import parse, { DOMNode } from 'html-react-parser'

interface PageProps {
    params: { slug: string; page: string };
}

export function extractPostGridId(content: string): number | null {
    let gridId: number | null = null;

    parse(content, {
        replace: (domNode: DOMNode) => {
            // Only check text nodes
            if ("data" in domNode && typeof domNode.data === "string") {
                const match = domNode.data.match(/\[the-post-grid\s+id="(\d+)"/);
                if (match) {
                    gridId = Number(match[1]);
                    return; // stop parsing
                }
            }
        },
    });

    return gridId;
}


export default async function PostPage({ params }: PageProps) {
    const { slug, page } = await params;
    const pageNum = Number(page) || 1;

    // 1. Fetch the WP page content (same as page 1)
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/pages/${slug}`, {
        next: { revalidate: 60 },
    });
    const pageData = await res.json();

    if (!pageData) return <p>Page not found</p>;

    // 2. Extract grid ID from shortcode
    const gridId = extractPostGridId(pageData.post_content);

    return (
        <div className="container mx-auto py-8 max-w-5xl">
            <article className="prose lg:prose-xl max-w-none">
                <h1>{pageData.post_title}</h1>

                {pageData.post_type === 'post' && (
                    <div className="text-gray-600 mb-6">
                        <time>
                            {new Date(pageData.post_date).toLocaleString('ru-RU')}
                        </time>
                    </div>
                )}

                {renderPostContent(pageData.post_content, { page: pageNum })}
            </article>
        </div>
    )

    return (
        <article>
            <h1>{pageData.title}</h1>

            {/* {gridId && <PostGrid id={gridId} page={pageNum} />} */}
            {renderPostContent(pageData.post_content, { page: pageNum })}

        </article>
    );
}
