import React, { useMemo, useEffect } from 'react';
import parse, { domToReact } from 'html-react-parser';
import DOMPurify from 'dompurify';
import InlineRelatedWidget from './InlineRelatedWidget';
import { useLightbox } from '@/Components/LightboxProvider'; 

// --- NATIVE TWITTER (X) EMBED ---
const NativeTwitterEmbed = ({ url }) => {
    useEffect(() => {
        const scriptId = 'twitter-wjs';
        if (!document.getElementById(scriptId)) {
            const script = document.createElement("script");
            script.id = scriptId;
            script.src = "https://platform.twitter.com/widgets.js";
            script.async = true;
            document.body.appendChild(script);
        } else if (window.twttr && window.twttr.widgets) {
            window.twttr.widgets.load();
        }
    }, [url]);

    return (
        <div className="flex justify-center w-full my-8">
            <div className="w-full max-w-[550px] min-h-[350px] border border-border bg-muted/10 rounded-[var(--radius)] flex items-center justify-center relative overflow-hidden">
                <blockquote className="twitter-tweet w-full" data-dnt="true">
                    <a href={url}></a>
                </blockquote>
            </div>
        </div>
    );
};

// --- NATIVE INSTAGRAM EMBED ---
const NativeInstagramEmbed = ({ url }) => {
    useEffect(() => {
        const scriptId = 'instagram-wjs';
        if (!document.getElementById(scriptId)) {
            const script = document.createElement("script");
            script.id = scriptId;
            script.src = "https://www.instagram.com/embed.js";
            script.async = true;
            document.body.appendChild(script);
        } else if (window.instgrm && window.instgrm.Embeds) {
            window.instgrm.Embeds.process();
        }
    }, [url]);

    const cleanUrl = url.split('?')[0].replace(/\/$/, '') + '/';

    return (
        <div className="flex justify-center w-full my-8">
            <div className="w-full max-w-[540px] min-h-[500px] border border-border bg-muted/5 rounded-[var(--radius)] flex items-center justify-center relative overflow-hidden">
                <blockquote 
                    className="instagram-media" 
                    data-instgrm-permalink={cleanUrl} 
                    data-instgrm-version="14"
                    style={{ background: '#FFF', border: '0', borderRadius: 'var(--radius)', boxShadow: '0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15)', margin: '1px', maxWidth: '540px', minWidth: '326px', padding: '0', width: '99.375%'}}
                >
                    <a href={cleanUrl}>View this post on Instagram</a>
                </blockquote>
            </div>
        </div>
    );
};

export default function ArticleBody({ post, inlineRelated }) {
    const { openLightbox } = useLightbox();

    const contentParts = useMemo(() => {
        if (!post.content) return { first: '', second: '' };

        // --- XSS PROTECTION: Sanitize HTML content before parsing ---
        const cleanContent = DOMPurify.sanitize(post.content, {
            ADD_TAGS: ['iframe', 'blockquote'], 
            ADD_ATTR: [
                'allowfullscreen', 'allow', 'frameborder', 'target', 
                'data-instgrm-permalink', 'data-instgrm-version', 
                'data-social-embed', 'data-type', 'data-url', 
                'data-youtube-video', 'data-dnt'
            ]
        });

        const paragraphs = cleanContent.split('</p>');
        
        if (paragraphs.length < 6 || !inlineRelated || inlineRelated.length === 0) {
            return { first: cleanContent, second: '' };
        }
        
        const injectionIndex = 5; 
        const firstPart = paragraphs.slice(0, injectionIndex).map(p => p + '</p>').join('');
        const secondPart = paragraphs.slice(injectionIndex).map(p => p + '</p>').join('');
        
        return { first: firstPart, second: secondPart };
    }, [post.content, inlineRelated]);

    const parseOptions = {
        replace: (domNode) => {
            // 1. Social Embeds (Replaces placeholder divs with Native components)
            if (domNode.attribs && domNode.attribs['data-social-embed'] === 'true') {
                const { 'data-type': type, 'data-url': url } = domNode.attribs;
                const finalUrl = type === 'twitter' ? url.replace('x.com', 'twitter.com') : url;
                
                if (type === 'twitter') {
                    return <NativeTwitterEmbed url={finalUrl} />;
                } else if (type === 'instagram') {
                    return <NativeInstagramEmbed url={finalUrl} />;
                }
            }

            // 2. YouTube/Iframe Embeds (Responsive Aspect Ratio)
            if (domNode.name === 'iframe' || (domNode.attribs && domNode.attribs['data-youtube-video'] !== undefined)) {
                const iframeNode = domNode.name === 'iframe' ? domNode : domNode.children?.find(child => child.name === 'iframe');
                if (iframeNode && iframeNode.attribs) {
                    return (
                        <div className="relative w-full aspect-video my-8 bg-black shadow-sm overflow-hidden rounded-[var(--radius)]">
                            <iframe 
                                {...iframeNode.attribs}
                                className="absolute top-0 left-0 w-full h-full border-0"
                                allowFullScreen
                                loading="lazy"
                            />
                        </div>
                    );
                }
            }

            // 3. Regular Images
            if (domNode.name === 'img') {
                const { src, alt } = domNode.attribs;
                return (
                    <img 
                        src={src} 
                        alt={alt || 'Article Image'} 
                        className="cursor-zoom-in hover:opacity-95 transition-opacity w-full h-auto rounded-[var(--radius)]"
                        onClick={() => openLightbox([{ src, title: alt }])} 
                    />
                );
            }

            // 4. Figure Images with Caption (Tiptap extension output)
            if (domNode.name === 'figure' && domNode.attribs?.class?.includes('image-figure')) {
                const imgTag = domNode.children?.find(child => child.name === 'img');
                if (imgTag) {
                    const { src, alt } = imgTag.attribs;
                    const figCaptionNode = domNode.children?.find(child => child.name === 'figcaption');
                    let hasCaptionText = figCaptionNode && figCaptionNode.children?.length > 0;

                    return (
                        <figure className="image-figure my-8 overflow-hidden border bg-muted/20 rounded-[var(--radius)]">
                            <img 
                                src={src} 
                                alt={alt || 'Article Image'} 
                                className="w-full h-auto block m-0 cursor-zoom-in hover:opacity-95 transition-opacity"
                                onClick={() => openLightbox([{ src, title: alt }])} 
                            />
                            {hasCaptionText && (
                                <figcaption className="text-center text-sm text-muted-foreground p-3 italic bg-background/50 border-t">
                                    {domToReact(figCaptionNode.children)}
                                </figcaption>
                            )}
                        </figure>
                    );
                }
            }
        }
    };

    return (
        <div className="prose prose-lg dark:prose-invert max-w-none 
            prose-headings:font-serif prose-headings:font-bold 
            prose-p:text-gray-700 dark:prose-p:text-gray-300 prose-p:leading-8 
            prose-a:text-primary hover:prose-a:opacity-80
            prose-img:rounded-[var(--radius)] mb-12">
            
            {parse(contentParts.first, parseOptions)}
            
            {contentParts.second && (
                <InlineRelatedWidget categoryName={post.category?.name} posts={inlineRelated} />
            )}
            
            {parse(contentParts.second || (contentParts.first ? '' : cleanContent), parseOptions)}
        </div>
    );
}