(function (wp) {
    if (!wp || !wp.plugins || !wp.element || !wp.components) {
        return;
    }

    // PluginSidebar lives in wp.editPost (WP 5.x–6.5) or wp.editor (WP 6.6+)
    var PluginSidebar = (wp.editPost && wp.editPost.PluginSidebar)
                     || (wp.editor && wp.editor.PluginSidebar)
                     || null;
    var PluginSidebarMoreMenuItem = (wp.editPost && wp.editPost.PluginSidebarMoreMenuItem)
                                 || (wp.editor && wp.editor.PluginSidebarMoreMenuItem)
                                 || null;

    if (!PluginSidebar) {
        return; // no sidebar API available at all
    }

    var registerPlugin = wp.plugins.registerPlugin;
    var el = wp.element.createElement;
    var Fragment = wp.element.Fragment;

    var brandName = (window.seoFuryGutenberg && window.seoFuryGutenberg.brandName) ? window.seoFuryGutenberg.brandName : 'SEO Fury';
    var useEffect = wp.element.useEffect;
    var useRef = wp.element.useRef;
    var useCallback = wp.element.useCallback;

    // Lightning bolt SVG icon (brand red gradient)
    var lightningIcon = el('svg', {
        xmlns: 'http://www.w3.org/2000/svg',
        viewBox: '0 0 200 200',
        width: 20,
        height: 20
    },
    el('defs', {},
        el('linearGradient', { id: 'sf-grad', x1: '23%', y1: '90%', x2: '62%', y2: '18%' },
            el('stop', { offset: '0', stopColor: '#E00000' }),
            el('stop', { offset: '1', stopColor: '#FF2727' })
        )
    ),
    el('path', {
        fill: 'url(#sf-grad)',
        d: 'M165.1,85.6c7-7.4,4.6-17.1-4.2-17.1h-60c-2.8,0-2.3-3.9,0.6-4.9l36.8-12.4c5.6-1.9,10.8-6,14-11.1l16.1-25.6C173,7.4,169.8,0,162.3,0H85c-5.6,0-11.7,4.2-14.1,9.8l-40.4,95.5c-2.8,6.6,0.6,12.4,7.3,12.4H80l-30,75.7c-2.5,6.3,4.9,9.1,9.9,3.8L165.1,85.6z'
    }));

    var originalParent = null;
    var originalNextSibling = null;

    function rememberOriginalPlacement(metabox) {
        if (!originalParent) {
            originalParent = metabox.parentNode;
            originalNextSibling = metabox.nextSibling;
        }
    }

    function hideBottomMetabox() {
        var metabox = document.getElementById('seo_fury_post_meta');
        if (!metabox) return;

        var postboxWrapper = metabox.closest('.postbox');
        if (postboxWrapper && postboxWrapper.parentNode) {
            var isInMetaboxArea = postboxWrapper.closest('.edit-post-layout__metaboxes') ||
                                  postboxWrapper.closest('#normal-sortables') ||
                                  postboxWrapper.closest('#advanced-sortables');
            if (isInMetaboxArea) {
                postboxWrapper.style.display = 'none';
            }
        }
    }

    function moveMetaboxBack(keepHidden) {
        var metabox = document.getElementById('seo_fury_post_meta');
        if (!metabox || !originalParent) return;

        if (metabox.parentNode === originalParent) {
            return;
        }

        var postboxWrapper = originalParent.closest('.postbox');
        if (postboxWrapper) {
            postboxWrapper.style.display = '';
        }

        if (originalNextSibling && originalNextSibling.parentNode === originalParent) {
            originalParent.insertBefore(metabox, originalNextSibling);
        } else {
            originalParent.appendChild(metabox);
        }

        metabox.dataset.seoFuryMoved = '0';
        document.body.classList.remove('seo-fury-metabox-in-sidebar');

        if (keepHidden) {
            hideBottomMetabox();
        }
    }

    function SeoFurySidebar() {
        var containerRef = useRef(null);
        var metaboxRef = useRef(null);
        var pollIntervalRef = useRef(null);

        function moveMetaboxToSidebar(node, metabox) {
            rememberOriginalPlacement(metabox);
            hideBottomMetabox();
            metabox.dataset.seoFuryMoved = '1';
            node.appendChild(metabox);
            metabox.style.display = 'block';
            document.body.classList.add('seo-fury-metabox-in-sidebar');
            metaboxRef.current = metabox;
        }

        function returnMetaboxToOriginal() {
            var metabox = metaboxRef.current;
            if (!metabox || !originalParent) return;
            if (originalNextSibling && originalNextSibling.parentNode === originalParent) {
                originalParent.insertBefore(metabox, originalNextSibling);
            } else {
                originalParent.appendChild(metabox);
            }
            metabox.dataset.seoFuryMoved = '0';
            metabox.style.display = 'none';
            document.body.classList.remove('seo-fury-metabox-in-sidebar');
        }

        // Ref callback: called when the container div is mounted/unmounted
        var setContainerRef = useCallback(function (node) {
            // Cleanup any pending poll interval
            if (pollIntervalRef.current) {
                clearInterval(pollIntervalRef.current);
                pollIntervalRef.current = null;
            }

            if (!node) {
                // Container unmounting - move metabox back SYNCHRONOUSLY before it's lost
                returnMetaboxToOriginal();
                containerRef.current = null;
                return;
            }

            containerRef.current = node;

            // Container mounted - move metabox into it
            var metabox = document.getElementById('seo_fury_post_meta');

            if (metabox) {
                if (metabox.parentNode !== node) {
                    moveMetaboxToSidebar(node, metabox);
                }
            } else {
                // Metabox may not be in DOM yet, wait for it
                var attempts = 0;
                pollIntervalRef.current = setInterval(function () {
                    attempts++;
                    var mb = document.getElementById('seo_fury_post_meta');
                    if (mb) {
                        clearInterval(pollIntervalRef.current);
                        pollIntervalRef.current = null;
                        if (containerRef.current && mb.parentNode !== containerRef.current) {
                            moveMetaboxToSidebar(containerRef.current, mb);
                        }
                    }
                    if (attempts >= 30) {
                        clearInterval(pollIntervalRef.current);
                        pollIntervalRef.current = null;
                    }
                }, 200);
            }
        }, []);

        useEffect(function () {
            return function () {
                if (pollIntervalRef.current) {
                    clearInterval(pollIntervalRef.current);
                    pollIntervalRef.current = null;
                }
            };
        }, []);

        // Render PluginSidebar with a container div as child
        // The ref callback will handle moving the metabox into this div
        return el(
            PluginSidebar,
            { name: 'seo-fury-sidebar', title: brandName, icon: lightningIcon },
            el('div', {
                id: 'seo-fury-sidebar-container',
                className: 'seo-fury-sidebar',
                ref: setContainerRef
            })
        );
    }

    registerPlugin('seo-fury-sidebar', {
        render: function () {
            var children = [];
            if (PluginSidebarMoreMenuItem) {
                children.push(
                    el(
                        PluginSidebarMoreMenuItem,
                        { target: 'seo-fury-sidebar', icon: lightningIcon },
                        brandName
                    )
                );
            }
            children.push(el(SeoFurySidebar));
            return el(Fragment, null, children);
        }
    });

    function hookSaveEvents() {
        document.addEventListener('submit', function (event) {
            if (event.target && event.target.id === 'post') {
                moveMetaboxBack();
            }
        }, true);

        if (wp.data && wp.data.subscribe && wp.data.select) {
            var isSaving = false;
            wp.data.subscribe(function () {
                var editorStore = wp.data.select('core/editor');
                if (!editorStore || !editorStore.isSavingPost) return;

                var saving = editorStore.isSavingPost();
                if (saving && !isSaving) {
                    isSaving = true;
                    moveMetaboxBack();
                }
                if (!saving && isSaving) {
                    isSaving = false;
                }
            });
        }
    }

    document.body.classList.add('seo-fury-gutenberg-active');

    if (wp.domReady) {
        wp.domReady(function () {
            hookSaveEvents();
        });
    } else {
        document.addEventListener('DOMContentLoaded', function () {
            hookSaveEvents();
        });
    }
})(window.wp);
