(function(wp) {
    const { registerPlugin } = wp.plugins;
    const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost || wp.editor;
    const { PanelBody, SelectControl, Button, Spinner, ExternalLink } = wp.components;
    const { useState, useEffect } = wp.element;
    const { useSelect, useDispatch } = wp.data;
    const { createElement: el } = wp.element;
    const apiFetch = wp.apiFetch;
    const __ = wp.i18n.__;

    // Guard: if Gutenberg components not available, bail
    if (!registerPlugin || (!wp.editPost && !wp.editor)) {
        return;
    }

    const LanguageIcon = el('svg', {
        xmlns: 'http://www.w3.org/2000/svg',
        viewBox: '0 0 24 24',
        width: 24,
        height: 24,
    }, el('path', {
        d: 'M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0014.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z',
        fill: 'currentColor'
    }));

    function LangForgeSidebar() {
        const postId = useSelect(function(select) {
            return select('core/editor').getCurrentPostId();
        });

        const postType = useSelect(function(select) {
            return select('core/editor').getCurrentPostType();
        });

        const [language, setLanguage] = useState('');
        const [translations, setTranslations] = useState({});
        const [loading, setLoading] = useState(true);
        const [creating, setCreating] = useState(null);

        var languages = window.lfGutenberg ? window.lfGutenberg.languages : {};
        var defaultLang = window.lfGutenberg ? window.lfGutenberg.defaultLanguage : '';
        var ajaxUrl = window.lfGutenberg ? window.lfGutenberg.ajaxUrl : '';
        var nonce = window.lfGutenberg ? window.lfGutenberg.nonce : '';

        useEffect(function() {
            if (!postId) return;

            apiFetch({ path: '/langforge/v1/translations/' + postId }).then(function(data) {
                setLanguage(data.language || defaultLang);
                setTranslations(data.translations || {});
                setLoading(false);
            }).catch(function() {
                setLoading(false);
            });
        }, [postId]);

        function handleLanguageChange(newLang) {
            setLanguage(newLang);

            // Save via REST API
            apiFetch({
                path: '/wp/v2/' + getRestBase(postType) + '/' + postId,
                method: 'POST',
                data: { lf_language: newLang }
            });
        }

        function getRestBase(type) {
            var map = { post: 'posts', page: 'pages' };
            return map[type] || type;
        }

        function createTranslation(targetLang) {
            setCreating(targetLang);

            var formData = new FormData();
            formData.append('action', 'lf_create_translation');
            formData.append('nonce', nonce);
            formData.append('post_id', postId);
            formData.append('language', targetLang);

            fetch(ajaxUrl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin',
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                setCreating(null);
                if (data.success && data.data.edit_url) {
                    // Add to translations list
                    var newTrans = Object.assign({}, translations);
                    newTrans[targetLang] = {
                        id: data.data.post_id,
                        title: __('(New translation)', 'langforge'),
                        status: 'draft',
                        edit_link: data.data.edit_url,
                    };
                    setTranslations(newTrans);
                }
            })
            .catch(function() {
                setCreating(null);
            });
        }

        if (loading) {
            return el(PluginSidebar, {
                name: 'langforge-sidebar',
                title: __('LangForge', 'langforge'),
                icon: LanguageIcon,
            }, el('div', { style: { padding: '16px', textAlign: 'center' } },
                el(Spinner)
            ));
        }

        var langOptions = Object.keys(languages).map(function(code) {
            return { label: languages[code].native_name, value: code };
        });

        var translationItems = Object.keys(languages).filter(function(code) {
            return code !== language;
        }).map(function(code) {
            var trans = translations[code];
            var lang = languages[code];

            if (trans) {
                return el('div', {
                    key: code,
                    style: {
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: '8px 0',
                        borderBottom: '1px solid #e0e0e0'
                    }
                },
                    el('span', null, lang.native_name),
                    el('div', null,
                        el('span', {
                            style: {
                                display: 'inline-block',
                                padding: '2px 6px',
                                borderRadius: '3px',
                                fontSize: '11px',
                                marginRight: '8px',
                                background: trans.status === 'publish' ? '#00a32a' : '#dba617',
                                color: '#fff'
                            }
                        }, trans.status),
                        el(ExternalLink, {
                            href: trans.edit_link,
                            style: { fontSize: '12px' }
                        }, __('Edit', 'langforge'))
                    )
                );
            }

            return el('div', {
                key: code,
                style: {
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: '8px 0',
                    borderBottom: '1px solid #e0e0e0'
                }
            },
                el('span', { style: { color: '#757575' } }, lang.native_name),
                el(Button, {
                    variant: 'secondary',
                    isSmall: true,
                    isBusy: creating === code,
                    disabled: creating !== null,
                    onClick: function() { createTranslation(code); }
                }, creating === code ? el(Spinner) : __('+ Create', 'langforge'))
            );
        });

        // Calculate translation progress
        var totalLangs = Object.keys(languages).length - 1;
        var translatedCount = Object.keys(translations).filter(function(code) {
            return code !== language;
        }).length;
        var progressPct = totalLangs > 0 ? Math.round((translatedCount / totalLangs) * 100) : 0;

        return el(PluginSidebar, {
            name: 'langforge-sidebar',
            title: __('LangForge', 'langforge'),
            icon: LanguageIcon,
        },
            el(PanelBody, { title: __('Post Language', 'langforge'), initialOpen: true },
                el(SelectControl, {
                    label: __('Language', 'langforge'),
                    value: language,
                    options: langOptions,
                    onChange: handleLanguageChange,
                })
            ),
            el(PanelBody, { title: __('Translations', 'langforge'), initialOpen: true },
                el('div', { style: { marginBottom: '12px' } },
                    el('div', {
                        style: {
                            display: 'flex',
                            justifyContent: 'space-between',
                            marginBottom: '4px',
                            fontSize: '12px',
                            color: '#757575'
                        }
                    },
                        el('span', null, __('Progress', 'langforge')),
                        el('span', null, progressPct + '%')
                    ),
                    el('div', {
                        style: {
                            height: '4px',
                            background: '#e0e0e0',
                            borderRadius: '2px',
                            overflow: 'hidden'
                        }
                    },
                        el('div', {
                            style: {
                                height: '100%',
                                width: progressPct + '%',
                                background: progressPct === 100 ? '#00a32a' : '#2271b1',
                                borderRadius: '2px',
                                transition: 'width 0.3s'
                            }
                        })
                    )
                ),
                translationItems
            )
        );
    }

    registerPlugin('langforge-sidebar', {
        render: LangForgeSidebar,
        icon: LanguageIcon,
    });

})(window.wp);
