(function(wp) {
    if (!wp.plugins || !wp.editPost) return;

    var el = wp.element.createElement;
    var useState = wp.element.useState;
    var useEffect = wp.element.useEffect;
    var useRef = wp.element.useRef;
    var useSelect = wp.data.useSelect;
    var PanelBody = wp.components.PanelBody;
    var Button = wp.components.Button;
    var Spinner = wp.components.Spinner;

    function SEOSidebar() {
        var postId = useSelect(function(s) { return s('core/editor').getCurrentPostId(); });

        // Track whether the post content has changed since last schema generation
        var editedContent = useSelect(function(s) {
            var post = s('core/editor').getEditedPostContent();
            return post || '';
        });

        var _s = useState(null), data = _s[0], setData = _s[1];
        var _l = useState(true), loading = _l[0], setLoading = _l[1];

        // Schema state
        var _schema = useState(null), schemaData = _schema[0], setSchemaData = _schema[1];
        var _schemaLoading = useState(false), schemaLoading = _schemaLoading[0], setSchemaLoading = _schemaLoading[1];
        var _isDirty = useState(false), isDirty = _isDirty[0], setIsDirty = _isDirty[1];

        // Content snapshot at the time of last schema generation
        var lastSchemaContent = useRef('');

        // Load SEO data on mount
        useEffect(function() {
            if (!postId) return;
            fetch(seoforgeAdmin.restUrl + '/analyze/' + postId, {
                headers: { 'X-WP-Nonce': seoforgeAdmin.restNonce }
            })
                .then(function(r) { return r.json(); })
                .then(function(d) { setData(d); setLoading(false); })
                .catch(function() { setLoading(false); });

            // Load existing schema data (cached AI result)
            fetch(seoforgeAdmin.restUrl + '/schema/' + postId, {
                headers: { 'X-WP-Nonce': seoforgeAdmin.restNonce }
            })
                .then(function(r) { return r.ok ? r.json() : null; })
                .then(function(d) {
                    if (d) {
                        setSchemaData(d);
                        lastSchemaContent.current = editedContent;
                    }
                })
                .catch(function() {});
        }, [postId]);

        // Track content changes — mark isDirty when content changed after last generation
        useEffect(function() {
            if (!lastSchemaContent.current) return; // No schema generated yet, nothing to mark dirty
            if (editedContent !== lastSchemaContent.current) {
                setIsDirty(true);
            }
        }, [editedContent]);

        // Manual schema regeneration
        function regenerateSchema() {
            if (!postId || schemaLoading) return;
            setSchemaLoading(true);
            fetch(seoforgeAdmin.restUrl + '/schema/detect/' + postId, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': seoforgeAdmin.restNonce,
                    'Content-Type': 'application/json'
                }
            })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d && (d.detected_types || d.json_ld)) {
                        setSchemaData(d);
                    }
                    lastSchemaContent.current = editedContent;
                    setIsDirty(false);
                    setSchemaLoading(false);
                })
                .catch(function() { setSchemaLoading(false); });
        }

        if (loading) {
            return el(
                wp.editPost.PluginSidebar,
                { name: 'seoforge', title: 'AI SEO', icon: 'chart-line' },
                el('div', { style: { padding: 16, textAlign: 'center' } }, el(Spinner))
            );
        }

        var score = data ? data.score || 0 : 0;
        var issues = data ? data.issues || [] : [];
        var scoreColor = score >= 80 ? '#059669' : score >= 50 ? '#D97706' : '#DC2626';

        // Schema badges
        var detectedTypes = (schemaData && schemaData.detected_types) ? schemaData.detected_types : [];

        // Update Schema button style — highlight orange when isDirty
        var updateBtnStyle = {
            position: 'relative',
            width: '100%',
            justifyContent: 'center'
        };

        return el(
            wp.editPost.PluginSidebar,
            { name: 'seoforge', title: 'AI SEO', icon: 'chart-line' },

            // SEO Score panel
            el(PanelBody, { title: 'SEO Score', initialOpen: true },
                el('div', { style: { textAlign: 'center', margin: '8px 0' } },
                    el('div', { style: { fontSize: 36, fontWeight: 700, color: scoreColor } }, score),
                    el('div', { style: { fontSize: 12, color: '#64748B' } }, 'out of 100')
                )
            ),

            // Issues panel
            el(PanelBody, { title: 'Issues (' + issues.length + ')', initialOpen: issues.length > 0 },
                issues.length === 0
                    ? el('p', { style: { color: '#059669' } }, 'No issues found!')
                    : issues.map(function(i, idx) {
                        var c = i.severity === 'error' ? '#DC2626' : i.severity === 'warning' ? '#D97706' : '#FF6B35';
                        return el('div', {
                            key: idx,
                            style: {
                                padding: '4px 8px',
                                margin: '3px 0',
                                borderLeft: '3px solid ' + c,
                                borderRadius: 4,
                                fontSize: 12,
                                background: '#f8fafc'
                            }
                        }, i.message);
                    })
            ),

            // Schema panel
            el(PanelBody, { title: 'Schema Markup', initialOpen: true },

                // Detected schema type badges
                detectedTypes.length > 0 && el('div', { style: { marginBottom: 10 } },
                    el('div', { style: { fontSize: 11, color: '#64748B', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Detected types'),
                    el('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 4 } },
                        detectedTypes.map(function(type, idx) {
                            return el('span', {
                                key: idx,
                                style: {
                                    background: '#EFF6FF',
                                    color: '#1D4ED8',
                                    border: '1px solid #BFDBFE',
                                    borderRadius: 12,
                                    padding: '2px 8px',
                                    fontSize: 11,
                                    fontWeight: 500
                                }
                            }, type);
                        })
                    )
                ),

                // No schema yet message
                !schemaData && !schemaLoading && el('p', { style: { fontSize: 12, color: '#94A3B8', marginBottom: 8 } },
                    'No schema generated yet. Click "Update Schema" to detect and generate schema markup for this post.'
                ),

                // isDirty indicator
                isDirty && el('div', {
                    style: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: 6,
                        padding: '6px 8px',
                        background: '#FFF7ED',
                        border: '1px solid #FED7AA',
                        borderRadius: 4,
                        marginBottom: 8,
                        fontSize: 12,
                        color: '#92400E'
                    }
                },
                    el('span', { style: { width: 8, height: 8, borderRadius: '50%', background: '#F97316', flexShrink: 0, display: 'inline-block' } }),
                    'Content changed — schema may be outdated'
                ),

                // Update Schema button
                el('div', { style: updateBtnStyle },
                    el(Button, {
                        variant: isDirty ? 'primary' : 'secondary',
                        onClick: regenerateSchema,
                        disabled: schemaLoading,
                        style: { width: '100%', justifyContent: 'center' }
                    },
                        schemaLoading
                            ? el('span', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
                                el(Spinner),
                                'Detecting schema...'
                              )
                            : el('span', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
                                el('span', { className: 'dashicons dashicons-update', style: { fontSize: 16, width: 16, height: 16 } }),
                                isDirty ? 'Update Schema' : 'Regenerate Schema'
                              )
                    )
                )
            )
 // Re-analyze button removed — score updates live.
        );
    }

    wp.plugins.registerPlugin('seoforge-sidebar', { render: SEOSidebar, icon: 'chart-line' });
})(window.wp);
