import { renderElementorContent, renderPostContent } from '../WPRenderer/WPRenderer'
import { PostData } from '@/types/entities'

const Post = ({ post }: { post: PostData }) => {
    const getHtml = (el: {
        id: string
        elType: string
        elements: any[]
        settings: any
    }) => {
        let htmlString = ''

        if (el.elements.length > 0) {
            el.elements.map(child => {
                htmlString = htmlString + getHtml(child)
            })
        }

        if (el.settings.html) {
            htmlString = htmlString + el.settings.html
        }

        return htmlString
    }

    const preProcessElementor = () => {
        let htmlString = ''

        post.wp_postmeta && post.wp_postmeta.map(meta => {
            if (meta.meta_key === '_elementor_data') {
                const elements = JSON.parse(meta.meta_value)
                if (Array.isArray(elements)) {
                    elements.map((el: {
                        id: string
                        elType: string
                        elements: any[]
                        settings: any
                    }) => {
                        htmlString = htmlString + getHtml(el)
                    })
                }
            }
        })

        return htmlString
    }

    return (
        <div className="container mx-auto py-8 max-w-5xl px-2 sm:px-0">
            <article className="prose lg:prose-xl max-w-none">
                {
                    post.thumbnail &&
                    <div>
                        <img className='' src={post.thumbnail.guid} />
                    </div>
                }

                <h1>{post.post_title}</h1>

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

                {post.wp_postmeta && post.wp_postmeta.find(meta => meta.meta_key === '_elementor_data') && renderElementorContent(preProcessElementor())}
                {renderPostContent(post.post_content)}
            </article>
        </div>
    )
}

export default Post