import React, { useEffect, useRef } from 'react';
import { NodeViewWrapper, ReactNodeViewRenderer } from '@tiptap/react';
import { Node } from '@tiptap/core';

// 1. The React Component (Live View inside Editor)
const SocialEmbedComponent = (props) => {
    const { node, selected } = props;
    const { url, type } = node.attrs;
    const containerRef = useRef(null);

    // Load Social Scripts and Process Embeds
    useEffect(() => {
        if (!url) return;

        if (type === 'twitter') {
            // Load Twitter Script if not exists
            if (!window.twttr) {
                const script = document.createElement("script");
                script.src = "https://platform.twitter.com/widgets.js";
                script.async = true;
                document.body.appendChild(script);
            } else {
                window.twttr.widgets.load(containerRef.current);
            }
        } 
        
        else if (type === 'instagram') {
            // Load Instagram Script if not exists
            if (!window.instgrm) {
                const script = document.createElement("script");
                script.src = "https://www.instagram.com/embed.js";
                script.async = true;
                document.body.appendChild(script);
            } else if (window.instgrm.Embeds) {
                window.instgrm.Embeds.process();
            }
        }
    }, [url, type]);

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

    return (
        <NodeViewWrapper className={`my-6 flex justify-center ${selected ? 'ring-2 ring-primary rounded-[var(--radius)]' : ''}`}>
            <div className="w-full max-w-[550px] overflow-hidden rounded-[var(--radius)] border bg-card shadow-sm">
                
                {/* Visual Header */}
                <div className={`p-2 text-xs text-center uppercase tracking-wider border-b font-bold flex items-center justify-center gap-2 ${
                    type === 'twitter' ? 'bg-black text-white' : 'bg-gradient-to-r from-purple-500 to-pink-500 text-white'
                }`}>
                    {type === 'twitter' ? 'X (Formerly Twitter) Live' : 'Instagram Post Live'}
                </div>
                
                {/* Live Embed Area */}
                <div className="p-4 bg-white flex justify-center min-h-[150px]" ref={containerRef}>
                    {type === 'twitter' ? (
                        <blockquote className="twitter-tweet" data-dnt="true">
                            <a href={cleanUrl}></a>
                        </blockquote>
                    ) : (
                        <blockquote 
                            className="instagram-media" 
                            data-instgrm-permalink={cleanUrl} 
                            data-instgrm-version="14"
                            style={{ width: '100%' }}
                        >
                            <a href={cleanUrl}>Loading Instagram...</a>
                        </blockquote>
                    )}
                </div>
            </div>
        </NodeViewWrapper>
    );
};

// 2. The Tiptap Extension Definition
export default Node.create({
    name: 'socialEmbed',
    group: 'block',
    atom: true, 

    addAttributes() {
        return {
            url: { default: null },
            type: { default: 'twitter' },
        };
    },

    parseHTML() {
        return [
            {
                tag: 'div[data-social-embed]',
                getAttrs: (element) => ({
                    url: element.getAttribute('data-url'),
                    type: element.getAttribute('data-type'),
                }),
            },
        ];
    },

    renderHTML({ HTMLAttributes }) {
        return ['div', { 
            'data-social-embed': 'true',
            'data-type': HTMLAttributes.type,
            'data-url': HTMLAttributes.url,
            'class': 'social-embed-placeholder hidden'
        }];
    },

    addNodeView() {
        return ReactNodeViewRenderer(SocialEmbedComponent);
    },
});