(function (wp) {
    // Safety check: ensure all required WP dependencies are loaded
    if (!wp || !wp.plugins || !wp.editPost || !wp.components || !wp.data || !wp.element) {
        console.error('QuikVox AI: Required WordPress dependencies not loaded');
        return;
    }

    const { registerPlugin } = wp.plugins;
    const { PluginDocumentSettingPanel } = wp.editPost;
    const { PanelRow, Button } = wp.components;
    const { withSelect } = wp.data;
    const { createElement } = wp.element;
    const { __ } = wp.i18n;

    const PodcastmakerPostSidebar = ({ postId, postTitle }) => {
        if (!postId) return null;

        const handleCreateScript = async () => {
            // Check for unsaved changes
            const isDirty = wp.data.select('core/editor').isEditedPostDirty();

            if (isDirty) {
                // Auto-save the post
                try {
                    await wp.data.dispatch('core/editor').savePost();
                    // Wait a moment for save to complete
                    await new Promise(resolve => setTimeout(resolve, 500));
                } catch (error) {
                    console.error('Failed to save post:', error);
                    alert(__('Failed to save the post. Please try again.', 'quikvox-ai'));
                    return;
                }
            }

            // Navigate to the script workspace and request the audio sidebar to auto-open.
            const adminUrl = window.PodcastmakerPostData?.adminUrl || window.location.origin + '/wp-admin/';
            const url = `${adminUrl}post-new.php?post_type=podcastmaker_script&source_post_id=${postId}&podcastmaker_open=1`;
            window.location.href = url;  // Same window navigation
        };

        return createElement(PluginDocumentSettingPanel, {
            name: 'podcastmaker-post-panel',
            title: 'QuikVox AI',
            icon: 'microphone',
        },

            createElement(PanelRow, {},
                createElement(Button, {
                    isPrimary: true,
                    isLarge: true,
                    onClick: handleCreateScript,
                    style: {
                        width: '100%',
                        justifyContent: 'center',
                        backgroundColor: '#00a32a',
                        borderColor: '#00a32a',
                        fontSize: '14px',
                        fontWeight: '600',
                        padding: '12px 20px',
                        height: 'auto'
                    }
                }, `🎙️ ${__('Create Audio', 'quikvox-ai')}`)
            )
        );
    };

    const PodcastmakerPostSidebarWithData = withSelect((select) => {
        return {
            postId: select('core/editor').getCurrentPostId(),
            postTitle: select('core/editor').getEditedPostAttribute('title'),
        };
    })(PodcastmakerPostSidebar);

    registerPlugin('podcastmaker-post-sidebar', {
        render: PodcastmakerPostSidebarWithData,
        icon: 'microphone',
    });


    // DISABLED: Panel repositioning causes React DOM conflicts
    // The direct DOM manipulation is incompatible with Gutenberg's React-based editor
    // Attempting to move panels causes "removeChild" errors when React re-renders
    // 
    // Future improvement: Use WordPress API when available to control panel order
    // For now, the panel will appear in its default position

    /*
    // Move Podcaster panel to the top of the sidebar
    const movePanelToTop = () => {
        // Safety check: don't manipulate DOM during React updates
        try {
            // Find the Podcaster panel by looking for the button text
            const panels = document.querySelectorAll('.components-panel__body');
            let podcastPanel = null;

            panels.forEach(panel => {
                const button = panel.querySelector('button');
                if (button && button.textContent.includes('QuikVox AI')) {
                    podcastPanel = panel;
                }
            });

            if (podcastPanel) {
                const sidebar = podcastPanel.closest('.components-panel');
                // Only move if not already at top AND parent exists
                if (sidebar && sidebar.firstChild !== podcastPanel && sidebar.contains(podcastPanel)) {
                    // Check if the panel is still attached to the DOM
                    if (document.body.contains(podcastPanel)) {
                        // Move to first position
                        sidebar.insertBefore(podcastPanel, sidebar.firstChild);
                        console.log('QuikVox AI panel moved to top');
                    }
                }
            }
        } catch (error) {
            // Silently catch errors to prevent breaking the editor
            console.debug('QuikVox AI: Panel repositioning skipped', error.message);
        }
    };

    // Run on load and periodically to ensure panel stays at top
    // But stop trying after initial attempts to avoid conflicts
    let attemptCount = 0;
    const maxAttempts = 5;

    const tryMovePanelToTop = () => {
        if (attemptCount < maxAttempts) {
            movePanelToTop();
            attemptCount++;
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', tryMovePanelToTop);
    } else {
        tryMovePanelToTop();
    }

    // Also run after delays to catch late-rendered panels, but limit attempts
    setTimeout(tryMovePanelToTop, 100);
    setTimeout(tryMovePanelToTop, 500);
    setTimeout(tryMovePanelToTop, 1000);
    setTimeout(tryMovePanelToTop, 2000);
    */

})(window.wp);
