(function(wp){
    const { registerPlugin } = wp.plugins;
    const { PanelBody, TextControl, SelectControl, Button, Notice, Spinner, CheckboxControl, ToggleControl } = wp.components; // These are fine
    const { useSelect, useDispatch } = wp.data;
    const { Fragment, useState, useEffect, useCallback, useMemo } = wp.element;

    // Safe apiFetch wrapper that injects the WP REST nonce localized by PHP
    function apiFetchWithNonce(options) {
        var nonce = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.rest_nonce) ? fajaedeseo_ajax.rest_nonce : null;
        if (typeof options === 'string') {
            return wp.apiFetch({ path: options, headers: nonce ? { 'X-WP-Nonce': nonce } : {} });
        }
        var headers = Object.assign({}, options.headers || {});
        if (nonce) headers['X-WP-Nonce'] = nonce;
        return wp.apiFetch(Object.assign({}, options, { headers: headers }));
    }

    // Helper functions (no change needed)
    function extractKeywords(content) {
        if (!content) return [];
        const stopwords = ['de','het','een','en','van','ik','te','dat','die','in','op','voor','met','is','om','als','aan','bij','om','over','door','niet','te','naar','voor','the','is','at','which','on','and','a','to','of','in','it','with','as','for','its','by','an','but','be','are','this','that'];
        
        // Strip HTML and keep alphanumeric characters (including common accents for Dutch)
        const doc = new DOMParser().parseFromString(content, 'text/html');
        const cleanText = (doc.body.textContent || "").toLowerCase();
        const words = cleanText.match(/[a-z0-9\u00C0-\u017F]+/gu) || [];
        
        let freq = {};
        words.forEach(w => {
            if (!stopwords.includes(w) && w.length > 2) {
                freq[w] = (freq[w] || 0) + 1;
            }
        });
        
        const extracted = Object.entries(freq).sort((a,b) => b[1]-a[1]).slice(0,8).map(x=>x[0]);
        if (extracted.length === 0 && cleanText.trim().length > 0) {
            // Fallback for very short or non-keyword-rich content
            return ['content', 'seo', 'wordpress', 'ai', 'blog'];
        }
        return extracted;
    }
    function countHeadings(content) {
        return (content.match(/<h[2-6][^>]*>/g) || []).length;
    }

    function classifyLinkStatus(link, siteUrl) {
        link = (link || '').trim();
        if (!link || link.startsWith('#') || link.startsWith('mailto:') || link.startsWith('tel:') || link.startsWith('javascript:')) {
            return 'ignore';
        }
        
        if (link.match(/^www\./i)) {
            return 'broken';
        }

        let isInternal = false;
        
        if (link.startsWith('/') || (!link.startsWith('http://') && !link.startsWith('https://'))) {
            isInternal = true;
        } else {
            const cleanSiteUrl = siteUrl.replace(/^https?:\/\//i, '').replace(/\/$/, '').toLowerCase();
            const cleanLink = link.replace(/^https?:\/\//i, '').toLowerCase();
            if (cleanLink.startsWith(cleanSiteUrl)) {
                isInternal = true;
            }
        }

        try {
            const baseUrlWithSlash = siteUrl.endsWith('/') ? siteUrl : siteUrl + '/';
            new URL(link, baseUrlWithSlash);
            return isInternal ? 'internal' : 'external';
        } catch {
            return 'broken';
        }
    }

    function getInternalLinks(content, siteUrl) {
        const regex = /<a\s[^>]*?href=["']([^"']+)["']/gi;
        let count = 0, match;
        while ((match = regex.exec(content))) {
            if (classifyLinkStatus(match[1], siteUrl) === 'internal') {
                count++;
            }
        }
        return count;
    }
    function countImagesWithAlt(content) {
        const imgTags = content.match(/<img [^>]*>/g) || [];
        return imgTags.filter(tag => /alt=["'][^"']+["']/i.test(tag)).length;
    }
    function getLinks(content) {
        const regex = /<a\s[^>]*?href=["']([^"']+)["']/gi;
        let links = [], match;
        while ((match = regex.exec(content))) {
            links.push(match[1]);
        }
        return links;
    }
    function classifyLinks(links, siteUrl) {
        let internal = 0, external = 0, broken = 0;
        links.forEach(link => {
            const status = classifyLinkStatus(link, siteUrl);
            if (status === 'internal') internal++;
            else if (status === 'external') external++;
            else if (status === 'broken') broken++;
        });
        return { internal, external, broken };
    }
    function keywordDensity(text, keyword) {
        if (!keyword) return 0;
        const words = text.toLowerCase().split(/\s+/);
        const count = words.filter(w => w === keyword.toLowerCase()).length;
        return words.length ? (count / words.length) * 100 : 0;
    }
    function averageSentenceLength(text) {
        const sentences = text.match(/[^.!?]+[.!?]+/g) || [];
        if (!sentences.length) return 0;
        const words = text.trim().split(/\s+/).length;
        return words / sentences.length;
    }
    function passiveVoicePercent(text) {
        const sentences = text.match(/[^.!?]+[.!?]+/g) || [];
        if (!sentences.length) return 0;
        const passiveRegex = /\b(was|were|is|are|been|be|being)\b\s+\w+ed\b/;
        let passiveCount = sentences.reduce((acc, s) => acc + (passiveRegex.test(s.toLowerCase()) ? 1 : 0), 0);
        return (passiveCount / sentences.length) * 100;
    }
    
    // NIEUW: Syllable counter (nodig voor Flesch score)
    function countSyllables(word) {
        word = word.toLowerCase();
        if(word.length <= 3) return 1;
        word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
        word = word.replace(/^y/, '');
        return word.match(/[aeiouy]{1,2}/g) ? word.match(/[aeiouy]{1,2}/g).length : 1;
    }

    // NIEUW: Flesch Reading Ease Calculation
    function fleschReadingEase(text) {
        const sentences = text.match(/[^.!?]+[.!?]+/g) || [];
        if (!sentences.length) return 0;
        // Strip HTML tags
        const cleanText = text.replace(/<[^>]+>/g, ' ');
        const words = cleanText.trim().split(/\s+/).filter(w => w.length > 0);
        const wordCount = words.length;
        if (!wordCount) return 0;
        
        const totalSyllables = words.reduce((acc, word) => acc + countSyllables(word), 0);
        const asl = wordCount / sentences.length; // Average Sentence Length
        const asw = totalSyllables / wordCount;   // Average Syllables per Word
        
        // Formula: 206.835 - (1.015 * ASL) - (84.6 * ASW)
        let score = 206.835 - (1.015 * asl) - (84.6 * asw);
        return Math.max(0, Math.min(100, score));
    }

    function readabilitySuggestions(avgSentenceLen, passivePercent, fleschScore) {
        const suggestions = [];
        if (avgSentenceLen > 20) suggestions.push('Try shorter sentences');
        if (passivePercent > 15) suggestions.push('Reduce passive voice');
        if (fleschScore < 60) suggestions.push('Text is difficult to read (aim for 60+)');
        return suggestions;
    }


    // AuditPanel component (unchanged except safer checks)
    const AuditPanel = () => {
        const [auditData, setAuditData] = useState(null);
        const [loadingAudit, setLoadingAudit] = useState(true);
        const [isGeneratingPdf, setIsGeneratingPdf] = useState(false);
        const settingsUrl = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.settings_url) ? fajaedeseo_ajax.settings_url : '#';
        const hasWhiteLabel = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.has_white_label) ? fajaedeseo_ajax.has_white_label : false;

        useEffect(() => {
            setLoadingAudit(true);
            apiFetchWithNonce('/fajaedeseo/v1/site-audit').then(data => {
                setAuditData(data);
                setLoadingAudit(false);
            }).catch(() => {
                setAuditData(null);
                setLoadingAudit(false);
            });
        }, []);

        const seoIssues = (auditData && Array.isArray(auditData.seo_issues)) ? auditData.seo_issues : [];
        const recommendations = (auditData && Array.isArray(auditData.recommendations)) ? auditData.recommendations : [];
        const orphanPages = (auditData && Array.isArray(auditData.orphan_pages)) ? auditData.orphan_pages : [];

        return (
            wp.element.createElement(PanelBody, { title: 'Site Audit & SEO Score', initialOpen: false },
                loadingAudit ? wp.element.createElement(Spinner, null)
                : auditData ?
                    wp.element.createElement('div', null,
                        wp.element.createElement('p', { style: { fontWeight: 'bold', color: !auditData.is_pro ? '#555' : (auditData.overall_score >= 80 ? 'green' : (auditData.overall_score >= 60 ? 'orange' : 'red')) } }, 
                            auditData.is_pro ? `🔎 Overall SEO Score: ${auditData.overall_score}%` : `🔎 Overall SEO Score:  Locked (Pro)`
                        ),
                        wp.element.createElement('div', { style: { margin: '8px 0' } },
                            'Pages Indexed: ',
                            auditData.pages_indexed !== undefined ? wp.element.createElement('span', { style: { fontWeight: 'bold' } }, auditData.pages_indexed) : wp.element.createElement('span', null, 'Unknown')
                        ),
                        wp.element.createElement('div', { style: { margin: '8px 0' } },
                            'Total Visitors: ',
                            auditData.total_visitors !== undefined ? wp.element.createElement('span', { style: { fontWeight: 'bold' } }, auditData.total_visitors) : wp.element.createElement('span', null, '0')
                        ),
                        wp.element.createElement('div', { style: { margin: '8px 0' } }, 
                            'Page Speed: ', 
                            (auditData.is_pro && auditData.page_speed !== null)
                                ? wp.element.createElement('span', { style: { fontWeight: 'bold', color: auditData.page_speed >= 80 ? 'green' : (auditData.page_speed >= 60 ? 'orange' : 'red') } }, auditData.page_speed, '/100')
                                : wp.element.createElement('span', { style: { fontStyle: 'italic', color: '#666' } }, '🔒 Locked (Pro)')
                        ),
                        !auditData.is_pro && wp.element.createElement(Button, {
                            isSecondary: true,
                            isSmall: true,
                            style: { marginTop: '10px', width: '100%', justifyContent: 'center' },
                            onClick: () => window.open(settingsUrl, '_blank')
                        }, '🔓 Activate Pro License'),
                        wp.element.createElement('h4', null, 'Issues'),
                        seoIssues.length ? wp.element.createElement('ul', null, seoIssues.map((issue, i) =>
                            wp.element.createElement('li', { key: i }, `${issue.issue}: ${issue.count}`)
                        )) : wp.element.createElement('p', null, 'No major issues found!'),
                        
                        wp.element.createElement('h4', null, 'Orphan Pages Detectie'),
                        auditData.has_advanced_links ? (
                            orphanPages.length > 0 ? (
                                wp.element.createElement('div', { style: { maxHeight: '150px', overflowY: 'auto', border: '1px solid #ddd', padding: '5px', borderRadius: '4px', fontSize: '11px' } },
                                    wp.element.createElement('ul', { style: { margin: 0, paddingLeft: '15px' } },
                                        orphanPages.map((page, i) => 
                                            wp.element.createElement('li', { key: i }, 
                                                wp.element.createElement('a', { href: page.url, target: '_blank', rel: 'noopener noreferrer' }, page.title || 'Untitled')
                                            )
                                        )
                                    )
                                )
                            ) : wp.element.createElement('p', { style: { color: 'green', fontSize: '11px' } }, 'No orphan pages found! Great job.')
                        ) : wp.element.createElement('p', { style: { fontStyle: 'italic', color: '#666', fontSize: '11px' } }, '🔒 Locked (Premium)'),

                        // GEO DATA SECTION
                        auditData.geo_data && wp.element.createElement(Fragment, null,
                            wp.element.createElement('h4', null, 'Visitor Geography'),
                            wp.element.createElement('div', {style:{display:'flex', gap:'10px'}},
                                wp.element.createElement('div', {style:{flex:1}},
                                    wp.element.createElement('strong', {style:{fontSize:'11px'}}, 'Top Countries'),
                                    wp.element.createElement('ul', {style:{margin:'5px 0', fontSize:'11px', color:'#555', paddingLeft:'10px'}},
                                        (auditData.geo_data.countries && auditData.geo_data.countries.length) ? auditData.geo_data.countries.map((c, i) => wp.element.createElement('li', {key:i}, `${c.name}: ${c.count}`)) : wp.element.createElement('li', null, 'No data yet')
                                    )
                                ),
                                wp.element.createElement('div', {style:{flex:1}},
                                    wp.element.createElement('strong', {style:{fontSize:'11px'}}, 'Top Regions'),
                                    auditData.is_pro ? wp.element.createElement('ul', {style:{margin:'5px 0', fontSize:'11px', color:'#555', paddingLeft:'10px'}},
                                        (auditData.geo_data.regions && auditData.geo_data.regions.length) ? auditData.geo_data.regions.map((c, i) => wp.element.createElement('li', {key:i}, `${c.name}: ${c.count}`)) : wp.element.createElement('li', null, 'No data yet')
                                    ) : wp.element.createElement('ul', {style:{margin:'5px 0', fontSize:'11px', color:'#888', paddingLeft:'10px', fontStyle:'italic'}},
                                        wp.element.createElement('li', null, '🔒 Locked (Pro)')
                                    )
                                ),
                                wp.element.createElement('div', {style:{flex:1}},
                                    wp.element.createElement('strong', {style:{fontSize:'11px'}}, 'Top Cities'),
                                    auditData.is_pro ? wp.element.createElement('ul', {style:{margin:'5px 0', fontSize:'11px', color:'#555', paddingLeft:'10px'}},
                                        (auditData.geo_data.cities && auditData.geo_data.cities.length) ? auditData.geo_data.cities.map((c, i) => wp.element.createElement('li', {key:i}, `${c.name}: ${c.count}`)) : wp.element.createElement('li', null, 'No data yet')
                                    ) : wp.element.createElement('ul', {style:{margin:'5px 0', fontSize:'11px', color:'#888', paddingLeft:'10px', fontStyle:'italic'}},
                                        wp.element.createElement('li', null, '🔒 Locked (Pro)')
                                    )
                                )
                            )
                        ),

                        wp.element.createElement('h4', null, 'Recommendations'),
                        recommendations.length ? wp.element.createElement('ul', null, recommendations.map((rec, i) =>
                            wp.element.createElement('li', { key: i }, rec)
                        )) : wp.element.createElement('p', null, 'Looking good!'),
                        auditData.extra_tips && wp.element.createElement('div', { style: { marginTop: '12px', fontStyle: 'italic' } }, 'Extra tip: ', auditData.extra_tips),
                        
                        // PDF Generate Button (Agency)
                        hasWhiteLabel && wp.element.createElement(Button, {
                            isSecondary: true,
                            isSmall: true,
                            disabled: isGeneratingPdf,
                            style: { marginTop: '15px', width: '100%', justifyContent: 'center' },
                            onClick: () => {
                                setIsGeneratingPdf(true);
                                const postId = wp.data.select('core/editor').getCurrentPostId();
                                apiFetchWithNonce({
                                    path: `/fajaedeseo/v1/generate-pdf?type=audit&post_id=${postId}`,
                                    method: 'GET'
                                }).then(res => {
                                    if (res && res.pdf) {
                                        const linkSource = `data:application/pdf;base64,${res.pdf}`;
                                        const downloadLink = document.createElement("a");
                                        downloadLink.href = linkSource;
                                        downloadLink.download = "seo-audit-report.pdf";
                                        downloadLink.click();
                                    }
                                    setIsGeneratingPdf(false);
                                }).catch(() => setIsGeneratingPdf(false));
                            }
                        }, isGeneratingPdf ? wp.element.createElement(Spinner, null) : '📄 Download Agency PDF Report')
                    ) : wp.element.createElement('p', { style: { color: 'red' } }, 'Audit data unavailable.')
            )
        );
    };

    // Main Sidebar component with updated PluginSidebar and optimized hooks usage
    const Sidebar = () => {
        // Late-bind components to ensure they are available during render
        // Prioritize wp.editor namespace as recommended by deprecation warnings
        const PluginSidebar = wp.editor?.PluginSidebar || wp.editPost?.PluginSidebar || wp.editSite?.PluginSidebar;
        const PluginSidebarMoreMenuItem = wp.editor?.PluginSidebarMoreMenuItem || wp.editPost?.PluginSidebarMoreMenuItem || wp.editSite?.PluginSidebarMoreMenuItem;

        const meta = useSelect(select => {
            const editor = select('core/editor');
            return editor ? editor.getEditedPostAttribute('meta') : undefined;
        }) || {};
        const postContent = useSelect(select => {
            const editor = select('core/editor');
            return editor ? editor.getEditedPostContent() : undefined;
        }) || '';
        const postTitle = useSelect(select => {
            const editor = select('core/editor');
            return editor ? editor.getEditedPostAttribute('title') : undefined;
        }) || '';
        const postType = useSelect(select => {
            const editor = select('core/editor');
            return (editor && editor.getCurrentPostType) ? editor.getCurrentPostType() : null;
        });

        const { editPost } = useDispatch('core/editor');
        const { createErrorNotice } = useDispatch('core/notices'); 
        // Use fallback image from localized PHP data when available (keeps assets local)
        const fallbackImageUrl = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.fallback_image) ? fajaedeseo_ajax.fallback_image : '';
        const isPro = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.is_pro) ? fajaedeseo_ajax.is_pro : false;
        const isPremium = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.is_premium) ? fajaedeseo_ajax.is_premium : false;
        const hasAdvancedLinks = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.has_advanced_links) ? fajaedeseo_ajax.has_advanced_links : false;
        const hasWhiteLabel = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.has_white_label) ? fajaedeseo_ajax.has_white_label : false;
        const keywordLimit = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.keyword_limit) ? fajaedeseo_ajax.keyword_limit : (isPro ? 5 : 1);
        const featuredImageUrl = meta.featured_image_url || fallbackImageUrl;
        
        const currentKeywords = useMemo(() => {
            const raw = meta._fajaedeseo_focus_keyword || '';
            return raw ? raw.split(',').map(k => k.trim()).filter(k => k.length > 0) : [];
        }, [meta._fajaedeseo_focus_keyword]);

        const [aiLoading, setAiLoading] = useState(false);
        const [seoScore, setSeoScore] = useState(meta._fajaedeseo_seo_score || 0);
        const [feedback, setFeedback] = useState([]);
        const siteUrl = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.site_url) ? fajaedeseo_ajax.site_url : window.location.origin;
        const settingsUrl = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.settings_url) ? fajaedeseo_ajax.settings_url : '#';
        const [editingLinkIndex, setEditingLinkIndex] = useState(-1);
        const twitterHandle = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.twitter_handle) ? fajaedeseo_ajax.twitter_handle : '';
        const facebookHandle = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.facebook_handle) ? fajaedeseo_ajax.facebook_handle : '';
        const [tempLinkUrl, setTempLinkUrl] = useState('');
        const [grammarIssues, setGrammarIssues] = useState(null);
        const [keywordSuggestions, setKeywordSuggestions] = useState([]);
        const [isFetchingKeywords, setIsFetchingKeywords] = useState(false);
        const [serpData, setSerpData] = useState(null);
        const [isAnalyzingSerp, setIsAnalyzingSerp] = useState(false);
        const [contentPrompt, setContentPrompt] = useState(''); // NEW: State for content prompt
        const [generatedContent, setGeneratedContent] = useState(''); // NEW: State for generated content
        const [isGeneratingContent, setIsGeneratingContent] = useState(false); // NEW: State for content generation loading
        const [h2Suggestions, setH2Suggestions] = useState([]); // NEW: State for H2 suggestions
        const [isGeneratingH2, setIsGeneratingH2] = useState(false); // NEW: State for H2 generation loading
        const [isGeneratingSerpPdf, setIsGeneratingSerpPdf] = useState(false);
        const [serpError, setSerpError] = useState(null); // NEW: State for SERP error handling
        const [isGeneratingPostTitle, setIsGeneratingPostTitle] = useState(false);
        const [generatedPostTitle, setGeneratedPostTitle] = useState('');
        const [imagePrompt, setImagePrompt] = useState('');
        const [generatedImage, setGeneratedImage] = useState(null);
        const [isGeneratingImage, setIsGeneratingImage] = useState(false);
        const [internalLinkSuggestions, setInternalLinkSuggestions] = useState([]);
        const [isGeneratingInternalLinks, setIsGeneratingInternalLinks] = useState(false);
        
        const [isGeneratingFaq, setIsGeneratingFaq] = useState(false);
        const [generatedFaq, setGeneratedFaq] = useState('');
        const [isOptimizingExtraction, setIsOptimizingExtraction] = useState(false);
        const [extractionInput, setExtractionInput] = useState('');
        const [extractionOutput, setExtractionOutput] = useState('');

        const mainKeyword = currentKeywords[0] || '';

        // Keyword Suggesties afhandelen (Lokaal voor Gratis, API met Caching voor Pro)
        useEffect(() => {
            if (!postContent || postContent.trim().length === 0) {
                setKeywordSuggestions([]);
                return;
            }

            // Altijd eerst lokale suggesties laden voor directe weergave
            const localSuggestions = extractKeywords(postContent);
            
            if (!isPro) {
                setKeywordSuggestions(localSuggestions);
                return;
            }

            // In Pro: toon direct lokale suggesties, maar plan een AI upgrade
            setKeywordSuggestions(localSuggestions);

            const timer = setTimeout(() => {
                if (postContent.length < 50) return;
                
                setIsFetchingKeywords(true);
                apiFetchWithNonce({
                    path: '/fajaedeseo/v1/suggest-keywords',
                    method: 'POST',
                    data: { content: postContent }
                }).then(res => {
                    if (res && res.keywords && Array.isArray(res.keywords) && res.keywords.length >= 1) {
                        setKeywordSuggestions(res.keywords);
                    }
                    setIsFetchingKeywords(false);
                }).catch(() => {
                    setKeywordSuggestions(extractKeywords(postContent));
                    setIsFetchingKeywords(false);
                });
            }, 2000); // Debounce API aanroepen

            return () => clearTimeout(timer);
        }, [postContent, isPro]);

        // SERP Analyse uitvoeren
        const runSerpAnalysis = useCallback(() => {
            if (!mainKeyword) return;
            setIsAnalyzingSerp(true);
            setSerpError(null);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/competitor-analysis',
                method: 'POST',
                data: { keyword: mainKeyword }
            }).then(res => {
                if (res && res.serp) {
                    setSerpData(res.serp);
                }
                setIsAnalyzingSerp(false);
            }).catch((err) => {
                setSerpError(err && err.message ? err.message : "Er is een fout opgetreden bij het ophalen van de SERP data.");
                setIsAnalyzingSerp(false);
            });
        }, [mainKeyword]);

        const headingCount = useMemo(() => countHeadings(postContent), [postContent]);
        const internalLinkCount = useMemo(() => getInternalLinks(postContent, siteUrl), [postContent, siteUrl]);
        const imagesWithAltCount = useMemo(() => countImagesWithAlt(postContent), [postContent]);
        const links = useMemo(() => getLinks(postContent), [postContent]);
        const linkStats = useMemo(() => classifyLinks(links, siteUrl), [links, siteUrl]);
        const analysisData = useMemo(() => ({
            density: keywordDensity(postContent, mainKeyword),
            avgSentLen: averageSentenceLength(postContent),
            passivePercent: passiveVoicePercent(postContent),
            fleschScore: fleschReadingEase(postContent) // NIEUW
        }), [postContent, mainKeyword]);
        const writingSuggestions = useMemo(() => readabilitySuggestions(analysisData.avgSentLen, analysisData.passivePercent, analysisData.fleschScore), 
            [analysisData.avgSentLen, analysisData.passivePercent, analysisData.fleschScore]);

        // Advanced Link Manager Logic
        const linkObjects = useMemo(() => {
            const regex = /<a\s+([^>]*?)href=["']([^"']*)["']([^>]*?)>([\s\S]*?)<\/a>/gi;
            let links = [];
            let match;
            while ((match = regex.exec(postContent))) {
                const href = (match[2] || '').trim();
                const text = match[4];
                const combinedAttrs = match[1] + " " + match[3];
                const targetMatch = combinedAttrs.match(/target=["']([^"']*)["']/i);
                const relMatch = combinedAttrs.match(/rel=["']([^"']*)["']/i);
                
                const status = classifyLinkStatus(href, siteUrl);
                const isBroken = (status === 'broken');

                links.push({ href, text, target: targetMatch ? targetMatch[1] : '', rel: relMatch ? relMatch[1] : '', isBroken });
            }
            return links;
        }, [postContent, siteUrl]);

        const modifyLink = useCallback((index, action, value) => {
            const regex = /<a\s+([^>]*?)href=["']([^"']*)["']([^>]*?)>([\s\S]*?)<\/a>/gi;
            let count = 0;
            const newContent = postContent.replace(regex, (fullTag, before, href, after, text) => {
                if (count === index) {
                    if (action === 'unlink') return text; // Remove tag, keep text
                    
                    let newHref = (action === 'url') ? value : href;
                    // Determine new attributes based on action or existing value
                    let currentTarget = (before + after).match(/target=["']([^"']*)["']/i)?.[1] || '';
                    let currentRel = (before + after).match(/rel=["']([^"']*)["']/i)?.[1] || '';

                    let newTarget = (action === 'target') ? (value ? '_blank' : '') : currentTarget;
                    let newRel = (action === 'rel') ? (value ? 'nofollow' : '') : currentRel;
                    
                    // Strip existing attributes to avoid duplicates, then rebuild
                    let attrs = (before + " " + after)
                        .replace(/href=["'][^"']*["']/gi, '')
                        .replace(/target=["'][^"']*["']/gi, '')
                        .replace(/rel=["'][^"']*["']/gi, '')
                        .replace(/\s+/g, ' ').trim();
                        
                    let tag = `<a href="${newHref}"`;
                    if (attrs) tag += ` ${attrs}`;
                    if (newTarget) tag += ` target="${newTarget}"`;
                    if (newRel) tag += ` rel="${newRel}"`;
                    tag += `>${text}</a>`;
                    return tag;
                }
                count++;
                return fullTag;
            });
            editPost({ content: newContent });
        }, [postContent, editPost]);

        const calculateScore = useCallback(() => {
            let score = 0, localFeedback = [];
            if (meta._fajaedeseo_meta_title) {
                const len = meta._fajaedeseo_meta_title.length;
                const titleStr = String(meta._fajaedeseo_meta_title);
                if (len >= 40 && len <= 60) score++;
                else localFeedback.push('Title length (40–60 chars)');
                if (mainKeyword && titleStr.toLowerCase().includes(mainKeyword.toLowerCase())) score++;
                else if (mainKeyword) localFeedback.push('Primary keyword in title');
            } else { localFeedback.push('Add a meta title'); }
            if (meta._fajaedeseo_meta_desc) {
                const len = meta._fajaedeseo_meta_desc.length;
                const descStr = String(meta._fajaedeseo_meta_desc);
                if (len > 80 && len <= 160) score++;
                else localFeedback.push('Description length (80–160 chars)');
                if (mainKeyword && descStr.toLowerCase().includes(mainKeyword.toLowerCase())) score++;
                else if (mainKeyword) localFeedback.push('Primary keyword in description');
            } else { localFeedback.push('Add a meta description'); }
            if (headingCount >= 2) score++; else localFeedback.push('Add more headings');
            if (imagesWithAltCount > 0) score++; else localFeedback.push('Add alt text to images');
            return { score, max: 6, localFeedback };
        }, [meta._fajaedeseo_meta_title, meta._fajaedeseo_meta_desc, mainKeyword, headingCount, imagesWithAltCount]);

        useEffect(() => {
            if (!postType) return;
            const { score, localFeedback } = calculateScore();
            setSeoScore(score);
            setFeedback(localFeedback);

            // Voorkom infinite loop door alleen te updaten als de score echt anders is in de database
            const savedScore = parseInt(meta._fajaedeseo_seo_score) || 0;
            if (savedScore !== score) {
                editPost({ meta: { _fajaedeseo_seo_score: score } });
            }
        }, [meta._fajaedeseo_seo_score, calculateScore, editPost, postType]);

        const setMeta = useCallback((key, value) => {
            if (value === undefined || value === null) return;
            editPost({ meta: { [key]: value } });
        }, [editPost]);

        const toggleKeyword = useCallback((kw) => {
            let newKeywords;
            if (currentKeywords.includes(kw)) {
                newKeywords = currentKeywords.filter(k => k !== kw);
            } else {
                if (currentKeywords.length >= keywordLimit) {
                    if (keywordLimit === 1) {
                        newKeywords = [kw]; // For free users, replace the single keyword
                    } else {
                        createErrorNotice(`You can select a maximum of ${keywordLimit} focus keywords.`, { type: 'snackbar' });
                        return; // Limit reached for Pro users, do not add more
                    }
                } else {
                    newKeywords = [...currentKeywords, kw];
                }
            }
            setMeta('_fajaedeseo_focus_keyword', newKeywords.join(', '));
        }, [currentKeywords, keywordLimit, setMeta, createErrorNotice]);

        // Filter "Edit Page" from postTitle - WordPress adds this automatically in editor
        let cleanPostTitle = postTitle
            .replace(/^Edie  (?:Page|Post)\s+/gi, '')  // Also remove it anywhere
            .replace(/["']/g, '')  // Remove all quotes
            .trim();
        if (!cleanPostTitle) cleanPostTitle = 'Post';

        const aiSuggest = useCallback((field) => {
            setAiLoading(true);
            const type = (field === '_fajaedeseo_meta_title') ? 'title' : 'desc';

            // Call API (Free: Template-based, Pro: Full AI)
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/generate-meta',
                method: 'POST',
                data: { 
                    content: postContent, 
                    type: type,
                    postTitle: cleanPostTitle,
                    siteName: (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.site_name) ? fajaedeseo_ajax.site_name : 'Site',
                    focus_keyword: mainKeyword
                }
            }).then(res => {
                if(res.generated) setMeta(field, res.generated);
                setAiLoading(false);
            }).catch(err => {
                setAiLoading(false);
                const siteName = (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.site_name) ? fajaedeseo_ajax.site_name : 'Site Name';
                let suggestion = (field === '_fajaedeseo_meta_title') ? `${cleanPostTitle} | ${siteName}` : `Discover ${cleanPostTitle} on ${siteName}...`;
                setMeta(field, suggestion);
            });
        }, [postContent, cleanPostTitle, setMeta]);

    const runGrammarCheck = useCallback(() => {
        const issues = [];
        
        // 1. Maak de tekst schoon (Verwijder HTML tags en WordPress comments)
        // Verbeterde schoonmaak om valse meldingen door HTML-tags te voorkomen
        let cleanText = postContent
            .replace(/<!--[\s\S]*?-->/g, "") // Verwijder comments
            .replace(/&nbsp;/g, " ");        // Vervang harde spaties

        // Vervang blok-elementen door een enter (voorkomt dat zinnen aan elkaar plakken)
        cleanText = cleanText.replace(/<\/?(p|div|br|h[1-6]|li|ul|ol|blockquote|pre|section|article|header|footer|aside|main|nav)[^>]*>/gi, "\n");
        // Verwijder overige (inline) tags volledig (voorkomt dat '<b>' als spatie wordt gezien)
        cleanText = cleanText.replace(/<[^>]+>/g, "");

        // 2. Capitalization Check (Loop door alle matches)
        const capRegex = /[.!?]\s+([a-z])/g;
        let match;
        const abbreviations = ['e.g', 'i.e', 'etc', 'vs', 'mr', 'mrs', 'dr', 'prof', 'sr', 'jr', 'st', 'b.v'];
        
        while ((match = capRegex.exec(cleanText)) !== null) {
            const index = match.index;
            // Check of het een afkorting is (kijk naar de tekst ervoor)
            const precedingText = cleanText.substring(Math.max(0, index - 5), index).toLowerCase();
            const isAbbreviation = abbreviations.some(abbr => precedingText.endsWith(abbr));
            
            if (!isAbbreviation) {
                const start = Math.max(0, index - 10);
                const end = Math.min(cleanText.length, index + 25);
                let snippet = cleanText.substring(start, end).replace(/\s+/g, ' ');
                issues.push(`Capitalization: "...${snippet}..."`);
            }
            if (issues.length >= 5) break; // Max 5 meldingen om de lijst overzichtelijk te houden
        }

        // 3. Double Spaces Check (Alleen in schone tekst)
        // Zoek naar: letter/punt, 2+ spaties, letter/cijfer
        // Gebruik [ ]{2,} om alleen spaties te vinden, geen enters (\n)
        const doubleSpaceRegex = /([a-z0-9,.])[ ]{2,}([a-z0-9])/gi;
        while ((match = doubleSpaceRegex.exec(cleanText)) !== null) {
             const start = Math.max(0, match.index - 10);
             const end = Math.min(cleanText.length, match.index + 25);
             let snippet = cleanText.substring(start, end).replace(/\n/g, ' ');
             issues.push(`Double spaces: "...${snippet}..."`);
             if (issues.length >= 50) break; // Limiet verhoogd zodat je de hele lijst ziet
        }

        // 4. Weak words
        const fillerMatch = cleanText.match(/\b(very|really|basically|actually)\b/i);
        if (fillerMatch) {
            issues.push(`Weak word found: "${fillerMatch[0]}"`);
        }

        // 5. Hedging
        const hedgeMatch = cleanText.match(/\b(i\s+think|i\s+believe)\b/i);
        if (hedgeMatch) {
            issues.push(`Hedging found: "${hedgeMatch[0]}"`);
        }

        // 6. Common Typos (Lichtgewicht spellingscontrole)
        const typos = {
            'vebsite': 'website',
            'teh': 'the',
            'recieve': 'receive',
            'adress': 'address',
            'untill': 'until',
            'occured': 'occurred',
            'seperate': 'separate'
        };

        for (const [typo, correction] of Object.entries(typos)) {
            const regex = new RegExp(`\\b${typo}\\b`, 'gi');
            if (regex.test(cleanText)) {
                issues.push(`Typo: "${typo}" -> "${correction}"`);
            }
        }
        
        setGrammarIssues(issues);
    }, [postContent]);

        // NEW: Function to generate H2 suggestions
        const generateH2Suggestions = useCallback(() => {
            if (!postContent) return;
            setIsGeneratingH2(true);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/generate-h2-headers',
                method: 'POST',
                data: {
                    content: postContent,
                    focus_keyword: mainKeyword
                }
            }).then(res => {
                if (res && res.headers && Array.isArray(res.headers)) {
                    setH2Suggestions(res.headers);
                }
                setIsGeneratingH2(false);
            }).catch(err => {
                createErrorNotice('Failed to generate H2 suggestions: ' + err.message, { type: 'snackbar' });
                setIsGeneratingH2(false);
            });
        }, [postContent, mainKeyword, createErrorNotice]);

        // NEW: Function to insert H2 into content
        const insertH2IntoContent = useCallback((header) => {
            if (wp.blocks && wp.data) {
                const { insertBlock } = wp.data.dispatch('core/block-editor');
                const { getSelectedBlockClientId, getBlockIndex } = wp.data.select('core/block-editor');
                const { createBlock } = wp.blocks;

                const selectedClientId = getSelectedBlockClientId();
                const blockToInsert = createBlock('core/heading', { level: 2, content: header });

                if (selectedClientId) {
                    const selectedIndex = getBlockIndex(selectedClientId);
                    insertBlock(blockToInsert, selectedIndex + 1);
                } else {
                    insertBlock(blockToInsert); // Appends to the end if nothing selected
                }
                createErrorNotice('H2 header inserted!', { type: 'snackbar' });
            } else {
                // Fallback for older WP versions or if block API is unavailable
                const newContent = postContent + '\n\n<h2>' + header + '</h2>\n';
                editPost({ content: newContent });
                createErrorNotice('H2 header appended to end of content!', { type: 'snackbar' });
            }
        }, [postContent, editPost, createErrorNotice]);

        const generateInternalLinks = useCallback(() => {
            if (!postContent) return;
            setIsGeneratingInternalLinks(true);
            const postId = wp.data.select('core/editor').getCurrentPostId();
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/suggest-internal-links',
                method: 'POST',
                data: { content: postContent, post_id: postId }
            }).then(res => {
                if (res && res.suggestions && Array.isArray(res.suggestions)) {
                    setInternalLinkSuggestions(res.suggestions);
                } else {
                    createErrorNotice('No suitable links found.', { type: 'snackbar' });
                }
                setIsGeneratingInternalLinks(false);
            }).catch(err => {
                createErrorNotice('Failed to suggest links: ' + err.message, { type: 'snackbar' });
                setIsGeneratingInternalLinks(false);
            });
        }, [postContent, createErrorNotice]);

        const applyInternalLink = useCallback((suggestion, index) => {
            if (!suggestion.anchor || !suggestion.url) return;
            
            // Gebruik een case-insensitive reguliere expressie en verwijder overtollige spaties
            const cleanAnchor = suggestion.anchor.trim();
            if (!cleanAnchor) return;
            
            const escapedAnchor = cleanAnchor.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(`\\b${escapedAnchor}\\b`, 'i');
            
            let countReplaced = 0;
            let insideA = false;
            
            const chunks = postContent.split(/(<[^>]+>)/g);
            const newChunks = chunks.map(chunk => {
                if (/^<a\b/i.test(chunk)) insideA = true;
                if (/^<\/a>/i.test(chunk)) insideA = false;
                
                if (chunk.startsWith('<')) return chunk; // Skip HTML tags
                if (insideA) return chunk;               // Skip existing links
                if (countReplaced > 0) return chunk;     // Only replace once
                
                if (regex.test(chunk)) {
                    countReplaced++;
                    return chunk.replace(regex, `<a href="${suggestion.url}">$&</a>`);
                }
                return chunk;
            });
            
            if (countReplaced > 0) {
                const newContent = newChunks.join('');
                if (newContent !== postContent) {
                    editPost({ content: newContent });
                    createErrorNotice('Internal link inserted!', { type: 'snackbar' });
                    setInternalLinkSuggestions(prev => prev.filter((_, i) => i !== index));
                    return;
                }
            }
            createErrorNotice('Anchor text not found in content (might already be linked).', { type: 'snackbar' });
        }, [postContent, editPost, createErrorNotice]);

        // NEW: Function to generate content
        const generateContent = useCallback(() => {
            if (!contentPrompt) {
                createErrorNotice('Please enter a prompt for content generation.', { type: 'snackbar' });
                return;
            }
            setIsGeneratingContent(true);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/generate-content',
                method: 'POST',
                data: {
                    prompt: contentPrompt,
                    focus_keyword: mainKeyword,
                    context_content: postContent // Provide current content as context
                }
            }).then(res => {
                if (res && res.content) {
                    setGeneratedContent(res.content);
                }
                setIsGeneratingContent(false);
            }).catch(err => {
                createErrorNotice('Failed to generate content: ' + err.message, { type: 'snackbar' });
                setIsGeneratingContent(false);
            });
        }, [contentPrompt, mainKeyword, postContent, createErrorNotice]);

        // NEW: Function to insert generated content into editor
        const insertGeneratedContent = useCallback(() => {
            if (!generatedContent) return;
            // Use wp.blocks.rawHandler to convert HTML string to blocks
            const blocks = wp.blocks.rawHandler({ HTML: generatedContent });
            wp.data.dispatch('core/block-editor').insertBlocks(blocks);
            createErrorNotice('Generated content inserted!', { type: 'snackbar' });
            setGeneratedContent(''); // Clear generated content after insertion
        }, [generatedContent, createErrorNotice]);

        // NEW: Function to generate post title
        const generatePostTitle = useCallback(() => {
            setIsGeneratingPostTitle(true);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/generate-post-title',
                method: 'POST',
                data: {
                    content: postContent,
                    focus_keyword: mainKeyword
                }
            }).then(res => {
                if (res && res.title) {
                    setGeneratedPostTitle(res.title);
                    createErrorNotice('Post title generated!', { type: 'snackbar', isDismissible: true });
                }
                setIsGeneratingPostTitle(false);
            }).catch(err => {
                createErrorNotice('Failed to generate post title: ' + err.message, { type: 'snackbar' });
                setIsGeneratingPostTitle(false);
            });
        }, [postContent, mainKeyword, createErrorNotice]);

        // NEW: Function to insert generated post title into editor
        const insertGeneratedPostTitle = useCallback(() => {
            if (!generatedPostTitle) return;
            editPost({ title: generatedPostTitle });
            createErrorNotice('Post title updated!', { type: 'snackbar', isDismissible: true });
            setGeneratedPostTitle(''); // Clear after insertion
        }, [generatedPostTitle, editPost, createErrorNotice]);

        // NEW: Function to generate AI FAQs
        const generateFaq = useCallback(() => {
            if (!postContent) return;
            setIsGeneratingFaq(true);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/generate-faq',
                method: 'POST',
                data: { content: postContent, focus_keyword: mainKeyword }
            }).then(res => {
                if (res && res.faq_html) {
                    const blocks = wp.blocks.rawHandler({ HTML: res.faq_html });
                    wp.data.dispatch('core/block-editor').insertBlocks(blocks);
                    setMeta('_fajaedeseo_schema_type', 'FAQPage');
                    createErrorNotice('AI FAQ block inserted!', { type: 'snackbar', isDismissible: true });
                }
                setIsGeneratingFaq(false);
            }).catch(err => {
                createErrorNotice('Failed to generate FAQ: ' + err.message, { type: 'snackbar' });
                setIsGeneratingFaq(false);
            });
        }, [postContent, mainKeyword, createErrorNotice, setMeta]);

        // NEW: Function to optimize extraction text
        const optimizeExtractionText = useCallback(() => {
            if (!extractionInput) return;
            setIsOptimizingExtraction(true);
            apiFetchWithNonce({
                path: '/fajaedeseo/v1/optimize-extraction',
                method: 'POST',
                data: { text: extractionInput }
            }).then(res => {
                if (res && res.optimized_text) setExtractionOutput(res.optimized_text);
                setIsOptimizingExtraction(false);
            }).catch(() => setIsOptimizingExtraction(false));
        }, [extractionInput]);

        // This is a pure function, no need for useCallback.
        const scoreColor = (val) => val >= 5 ? 'green' : val >= 3 ? 'orange' : 'red';

        // Als de editor nog niet klaar is of componenten ontbreken, wacht op volgende render in plaats van null te retourneren
        if ( ! postType || ! PluginSidebar || ! PluginSidebarMoreMenuItem ) return null;

        return (
            wp.element.createElement(Fragment, null,
                wp.element.createElement(PluginSidebarMoreMenuItem, {
                    target: 'fajaedeseo-ai-panel',
                    icon: 'admin-site-alt3'
                }, 'fajaedeSEO'),
                wp.element.createElement(PluginSidebar, { name: 'fajaedeseo-ai-panel', title: 'fajaedeSEO', icon: 'admin-site-alt3' },
                    wp.element.createElement(PanelBody, { title: 'SEO Meta Fields', initialOpen: true },
                        wp.element.createElement(TextControl, {
                            label: isPro ? `Focus Keywords (Max ${keywordLimit})` : 'Focus Keyword',
                            value: meta._fajaedeseo_focus_keyword || '',
                            onChange: (val) => setMeta('_fajaedeseo_focus_keyword', val),
                            help: isPro ? 'Selected phrases for SEO analysis.' : 'Target phrase for score and suggestions.',
                            __next40pxDefaultSize: true,
                        }),

                        wp.element.createElement('div', { style: { marginBottom: '10px' } },
                            wp.element.createElement('strong', null, 'Keyword Suggestions: '),
                            isFetchingKeywords && wp.element.createElement(Spinner, { style: { display: 'inline-block', marginLeft: '5px', verticalAlign: 'middle' } }),
                            keywordSuggestions.map(kw =>
                                wp.element.createElement('span', {
                                    key: kw,
                                    className: currentKeywords.includes(kw) ? 'is-active' : '',
                                    style: {
                                        background: currentKeywords.includes(kw) ? '#0073aa' : '#efefef',
                                        color: currentKeywords.includes(kw) ? '#fff' : '#000',
                                        borderRadius: '12px',
                                        margin: '2px',
                                        padding: '4px 9px',
                                        fontSize: '13px',
                                        cursor: 'pointer',
                                        display: 'inline-block'
                                    },
                                    onClick: () => toggleKeyword(kw)
                                }, kw)
                            )
                        ),
                        wp.element.createElement(TextControl, {
                            label: 'AI Meta Title',
                            value: meta._fajaedeseo_meta_title || '',
                            onChange: (val) => setMeta('_fajaedeseo_meta_title', val),
                            help: '40–60 chars, use keyword.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        }),
                        wp.element.createElement('div', { style: { fontSize: '11px', color: meta._fajaedeseo_meta_title && meta._fajaedeseo_meta_title.length >= 40 && meta._fajaedeseo_meta_title.length <= 60 ? '#28a745' : '#dc3545', marginBottom: '12px' } }, 
                            `${(meta._fajaedeseo_meta_title || '').length} / 60 chars`
                        ),
                        wp.element.createElement(Button, {
                            isSmall: true,
                            isSecondary: true,
                            disabled: aiLoading,
                            style: { marginBottom: '12px' },
                            onClick: () => aiSuggest('_fajaedeseo_meta_title')
                        }, aiLoading ? '…' : '🔮Title Suggest'),
                        wp.element.createElement(TextControl, {
                            label: 'AI Meta Description',
                            value: meta._fajaedeseo_meta_desc || '',
                            onChange: (val) => setMeta('_fajaedeseo_meta_desc', val),
                            help: '80–160 chars, summarize content.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        }),
                        wp.element.createElement('div', { style: { fontSize: '11px', color: meta._fajaedeseo_meta_desc && meta._fajaedeseo_meta_desc.length >= 80 && meta._fajaedeseo_meta_desc.length <= 160 ? '#28a745' : '#dc3545', marginBottom: '12px' } }, 
                            `${(meta._fajaedeseo_meta_desc || '').length} / 160 chars`
                        ),
                        wp.element.createElement(Button, {
                            isSmall: true,
                            isSecondary: true,
                            disabled: aiLoading,
                            onClick: () => aiSuggest('_fajaedeseo_meta_desc')
                        }, aiLoading ? '…' : '✨Desc Suggest (Pro AI)'),
                        wp.element.createElement('div', { style: { marginTop: '16px', textAlign: 'center' } },
                        feedback.length ? 
                            wp.element.createElement(Notice, { status: 'warning', isDismissible: false }, 'Suggestions: ', feedback.join(', ')) 
                            : wp.element.createElement(Notice, { status: 'success', isDismissible: false }, 'Great job! Keep it up.')
                    )
                ),
                    wp.element.createElement(PanelBody, { title: 'SEO Writing Analysis', initialOpen: false },
                        wp.element.createElement('div', null,
                            'Keyword Density: ',
                            wp.element.createElement('span', { style: { fontWeight: '600', color: analysisData.density >= 0.5 ? 'green' : 'red' } }, `${analysisData.density.toFixed(2)}%`)
                        ),
                        wp.element.createElement('div', null,
                            'Average Sentence Length: ',
                            wp.element.createElement('span', { style: { fontWeight: '600', color: analysisData.avgSentLen <= 20 ? 'green' : 'red' } }, analysisData.avgSentLen.toFixed(1))
                        ),
                        wp.element.createElement('div', null,
                            'Passive Voice Usage: ',
                            wp.element.createElement('span', { style: { fontWeight: '600', color: analysisData.passivePercent <= 15 ? 'green' : 'red' } }, `${analysisData.passivePercent.toFixed(1)}%`)
                        ),
                        wp.element.createElement('div', null,
                            'Reading Ease (Flesch): ',
                            wp.element.createElement('span', { style: { fontWeight: '600', color: analysisData.fleschScore >= 60 ? 'green' : 'orange' } }, Math.round(analysisData.fleschScore) + '/100')
                        ),
                        writingSuggestions.length
                            ? wp.element.createElement(Notice, { status: 'warning', isDismissible: false }, 'Writing Tips: ', writingSuggestions.join(', '))
                            : wp.element.createElement(Notice, { status: 'success', isDismissible: false }, 'Good writing style detected.'),
                        
                        // NIEUW: Style & Typo Check Sectie (Pro)
                        wp.element.createElement('hr', { style: { margin: '15px 0', border: 'none', borderTop: '1px solid #eee' } }),
                        wp.element.createElement('strong', null, '✍️ Style & Typo Check (Pro)'),
                        isPro ? wp.element.createElement(Fragment, null,
                            wp.element.createElement(Button, { 
                                isSecondary: true, 
                                isSmall: true, 
                                style: { marginTop: '10px', width: '100%', justifyContent: 'center' },
                                onClick: runGrammarCheck
                            }, 'Check Writing'),
                            grammarIssues !== null && (grammarIssues.length > 0 ? 
                                wp.element.createElement(Notice, { status: 'warning', isDismissible: false, style: { marginTop: '10px' } }, 
                                    wp.element.createElement('ul', { style: { margin: 0, paddingLeft: '15px' } }, grammarIssues.map((issue, i) => wp.element.createElement('li', { key: i }, issue)))
                                ) : wp.element.createElement(Notice, { status: 'success', isDismissible: false, style: { marginTop: '10px' } }, "No basic style issues found.")
                            )
                        ) : wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Pro to unlock Style & Typo checks.')
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI Content Generator', initialOpen: false },
                        !isPro ? wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Pro to unlock AI Content Generation.')
                        : wp.element.createElement(Fragment, null,
                            wp.element.createElement(TextControl, {
                                label: 'Topic / Instructions',
                                value: contentPrompt,
                                onChange: (val) => setContentPrompt(val),
                                help: 'e.g., "Write an introduction about the benefits of SEO"',
                                __next40pxDefaultSize: true,
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(Button, {
                                isPrimary: true,
                                isSmall: true,
                                disabled: isGeneratingContent || !contentPrompt,
                                style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                                onClick: generateContent
                            }, isGeneratingContent ? wp.element.createElement(Spinner, null) : '✍️ Write Content'),
                            
                            generatedContent && wp.element.createElement(Fragment, null,
                                wp.element.createElement('div', { style: { background: '#f0f0f0', padding: '10px', borderRadius: '4px', marginBottom: '10px', maxHeight: '200px', overflowY: 'auto', fontSize: '12px' }, dangerouslySetInnerHTML: { __html: generatedContent } }),
                                wp.element.createElement('div', { style: { display: 'flex', gap: '5px' } },
                                    wp.element.createElement(Button, {
                                        isSecondary: true,
                                        isSmall: true,
                                        style: { flex: 1, justifyContent: 'center' },
                                        onClick: insertGeneratedContent
                                    }, 'Insert into Editor'),
                                    wp.element.createElement(Button, {
                                        isSecondary: true,
                                        isSmall: true,
                                        title: 'Regenerate',
                                        disabled: isGeneratingContent,
                                        onClick: generateContent
                                    }, isGeneratingContent ? wp.element.createElement(Spinner, null) : '🔄')
                                )
                            ),

                            wp.element.createElement('hr', { style: { margin: '15px 0', border: 'none', borderTop: '1px solid #eee' } }),

                            wp.element.createElement(Button, {
                                isSecondary: true,
                                isSmall: true,
                                disabled: isGeneratingPostTitle,
                                style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                                onClick: generatePostTitle
                            }, isGeneratingPostTitle ? wp.element.createElement(Spinner, null) : '✨ Generate Catchy Post Title'),
                            
                            generatedPostTitle && wp.element.createElement(Fragment, null,
                                wp.element.createElement('div', { style: { background: '#f0f0f0', padding: '10px', borderRadius: '4px', marginBottom: '10px', fontSize: '13px', fontWeight: 'bold' } }, generatedPostTitle),
                                wp.element.createElement('div', { style: { display: 'flex', gap: '5px' } },
                                    wp.element.createElement(Button, {
                                        isSecondary: true,
                                        isSmall: true,
                                        style: { flex: 1, justifyContent: 'center' },
                                        onClick: insertGeneratedPostTitle
                                    }, 'Insert Title'),
                                    wp.element.createElement(Button, {
                                        isSecondary: true,
                                        isSmall: true,
                                        title: 'Regenerate',
                                        disabled: isGeneratingPostTitle,
                                        onClick: generatePostTitle
                                    }, isGeneratingPostTitle ? wp.element.createElement(Spinner, null) : '🔄')
                                )
                            )
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI Image Generator', initialOpen: false },
                        !isPro ? wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Pro to unlock AI Image Generation.')
                        : wp.element.createElement(Fragment, null,
                            wp.element.createElement(TextControl, {
                                label: 'Image Description',
                                value: imagePrompt,
                                onChange: (val) => setImagePrompt(val),
                                help: 'Describe the image you want to generate (e.g. "A futuristic city skyline at sunset").',
                                __next40pxDefaultSize: true,
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(Button, {
                                isPrimary: true,
                                isSmall: true,
                                disabled: isGeneratingImage || !imagePrompt,
                                style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                                onClick: () => {
                                    setIsGeneratingImage(true);
                                    const postId = wp.data.select('core/editor').getCurrentPostId();
                                    apiFetchWithNonce({
                                        path: '/fajaedeseo/v1/generate-image',
                                        method: 'POST',
                                        data: { prompt: imagePrompt, post_id: postId }
                                    }).then(res => {
                                        if (res && res.success) {
                                            setGeneratedImage({ url: res.image_url, id: res.attachment_id, alt: imagePrompt });
                                            createErrorNotice('Image generated and saved to media library!', { type: 'snackbar', isDismissible: true });
                                        }
                                        setIsGeneratingImage(false);
                                    }).catch(err => {
                                        createErrorNotice('Failed to generate image: ' + err.message, { type: 'snackbar' });
                                        setIsGeneratingImage(false);
                                    });
                                }
                            }, isGeneratingImage ? wp.element.createElement(Spinner, null) : '🎨 Generate Image'),
                            
                            isGeneratingImage && wp.element.createElement('p', { style: { fontSize: '11px', color: '#666', textAlign: 'center', marginTop: '-5px', marginBottom: '10px', fontStyle: 'italic' } }, 'Generating image... This process can take up to 2 minutes.'),

                            generatedImage && wp.element.createElement(Fragment, null,
                                wp.element.createElement('img', {
                                    src: generatedImage.url,
                                    alt: generatedImage.alt,
                                    style: { width: '100%', height: 'auto', borderRadius: '4px', marginBottom: '10px', border: '1px solid #ddd' }
                                }),
                                wp.element.createElement(Button, {
                                    isSecondary: true,
                                    isSmall: true,
                                    style: { width: '100%', justifyContent: 'center' },
                                    onClick: () => {
                                        if (wp.blocks && wp.data) {
                                            const { insertBlock } = wp.data.dispatch('core/block-editor');
                                            const { getSelectedBlockClientId, getBlockIndex } = wp.data.select('core/block-editor');
                                            const { createBlock } = wp.blocks;

                                            const selectedClientId = getSelectedBlockClientId();
                                            const imageBlock = createBlock('core/image', {
                                                url: generatedImage.url,
                                                id: generatedImage.id,
                                                alt: generatedImage.alt
                                            });

                                            if (selectedClientId) {
                                                const selectedIndex = getBlockIndex(selectedClientId);
                                                insertBlock(imageBlock, selectedIndex + 1);
                                            } else {
                                                insertBlock(imageBlock);
                                            }
                                            createErrorNotice('Image inserted into post!', { type: 'snackbar' });
                                            setGeneratedImage(null);
                                            setImagePrompt('');
                                        }
                                    }
                                }, 'Insert into Editor')
                            )
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI Header Suggestions', initialOpen: false }, // NEW: AI Header Suggestions Panel
                        wp.element.createElement(Button, {
                            isPrimary: true,
                            isSmall: true,
                            disabled: isGeneratingH2 || !isPro,
                            style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                            onClick: generateH2Suggestions
                        }, isGeneratingH2 ? wp.element.createElement(Spinner, null) : 'Generate H2 Suggestions'),
                        !isPro && wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Pro to unlock AI Header Suggestions.'),
                        h2Suggestions.length > 0 && wp.element.createElement(Fragment, null,
                            wp.element.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '10px', marginBottom: '10px' } },
                                wp.element.createElement('h4', { style: { margin: 0 } }, 'Suggested H2s:'),
                                wp.element.createElement(Button, {
                                    isSecondary: true,
                                    isSmall: true,
                                    title: 'Regenerate',
                                    disabled: isGeneratingH2,
                                    onClick: generateH2Suggestions
                                }, isGeneratingH2 ? wp.element.createElement(Spinner, null) : '🔄')
                            ),
                            wp.element.createElement('ul', { style: { margin: 0, paddingLeft: '15px' } },
                                h2Suggestions.map((header, i) =>
                                    wp.element.createElement('li', { key: i, style: { marginBottom: '5px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
                                        wp.element.createElement('span', null, header),
                                        wp.element.createElement(Button, {
                                            isSmall: true,
                                            isSecondary: true,
                                            onClick: () => insertH2IntoContent(header)
                                        }, 'Insert')
                                    )
                                )
                            )
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI FAQ Builder (GEO)', initialOpen: false },
                        wp.element.createElement('p', { style: { fontSize: '12px', color: '#666' } }, 'Generates AI Overview-friendly questions and answers based on user intent. Automatically inserts into your content.'),
                        wp.element.createElement(Button, {
                            isPrimary: true,
                            isSmall: true,
                            disabled: isGeneratingFaq || !isPremium,
                            style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                            onClick: generateFaq
                        }, isGeneratingFaq ? wp.element.createElement(Spinner, null) : '🤖 Build AI FAQ Block'),
                        !isPremium && wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Premium to unlock AI FAQ Builder.')
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI Extraction Optimizer', initialOpen: false },
                        wp.element.createElement('p', { style: { fontSize: '12px', color: '#666' } }, 'Make paragraphs highly extractable for Gemini & AI Overviews. Paste a paragraph below to optimize it.'),
                        wp.element.createElement(TextControl, {
                            label: 'Paragraph to Optimize',
                            value: extractionInput,
                            onChange: (val) => setExtractionInput(val),
                            help: 'Paste your introductory paragraph here.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        }),
                        wp.element.createElement(Button, {
                            isPrimary: true,
                            isSmall: true,
                            disabled: isOptimizingExtraction || !extractionInput || !isPremium,
                            style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                            onClick: optimizeExtractionText
                        }, isOptimizingExtraction ? wp.element.createElement(Spinner, null) : '⚡ Optimize for AI Search'),
                        !isPremium && wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Premium to unlock AI Extraction Optimizer.'),
                        extractionOutput && wp.element.createElement(Fragment, null,
                            wp.element.createElement('div', { style: { background: '#e0f7fa', padding: '10px', borderRadius: '4px', marginBottom: '10px', fontSize: '13px', borderLeft: '3px solid #00acc1' } }, 
                                wp.element.createElement('strong', null, 'AI-Optimized Answer:'),
                                wp.element.createElement('p', { style: { margin: '5px 0 0 0' } }, extractionOutput)
                            ),
                            wp.element.createElement(Button, {
                                isSecondary: true,
                                isSmall: true,
                                style: { width: '100%', justifyContent: 'center' },
                                onClick: () => { navigator.clipboard.writeText(extractionOutput); createErrorNotice('Copied to clipboard!', { type: 'snackbar', isDismissible: true }); }
                            }, '📋 Copy to Clipboard')
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'AI Internal Link Suggestions', initialOpen: false },
                        wp.element.createElement(Button, {
                            isPrimary: true,
                            isSmall: true,
                            disabled: isGeneratingInternalLinks || !hasAdvancedLinks,
                            style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                            onClick: generateInternalLinks
                        }, isGeneratingInternalLinks ? wp.element.createElement(Spinner, null) : '🔗 Suggest Internal Links'),
                        !hasAdvancedLinks && wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '10px', marginTop: '10px', borderRadius: '4px', fontSize: '12px', color: '#666' } }, '🔒 Upgrade to Premium to unlock AI Link Suggestions.'),
                        internalLinkSuggestions.length > 0 && wp.element.createElement('div', { style: { marginTop: '10px' } },
                            wp.element.createElement('p', { style: { fontSize: '12px', marginBottom: '8px' } }, 'Suggested links based on your content:'),
                            internalLinkSuggestions.map((sug, i) => 
                                wp.element.createElement('div', { key: i, style: { background: '#f9f9f9', padding: '10px', marginBottom: '8px', borderRadius: '4px', borderLeft: '3px solid #0073aa' } },
                                    wp.element.createElement('div', { style: { fontSize: '12px', fontWeight: 'bold' } }, `"${sug.anchor}"`),
                                    wp.element.createElement('div', { style: { fontSize: '11px', color: '#666', marginBottom: '8px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, `↳ ${sug.url}`),
                                    wp.element.createElement(Button, {
                                        isSecondary: true,
                                        isSmall: true,
                                        style: { width: '100%', justifyContent: 'center' },
                                        onClick: () => applyInternalLink(sug, i)
                                    }, 'Apply Link')
                                )
                            )
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'Content Analysis', initialOpen: false },
                        wp.element.createElement('div', null,
                            'Headings found: ',
                            wp.element.createElement('span', { style: { color: headingCount >= 2 ? 'green' : 'red', fontWeight: '600' } }, headingCount)
                        ),
                        wp.element.createElement('div', null,
                            'Internal links: ',
                            wp.element.createElement('span', { style: { color: internalLinkCount > 0 ? 'green' : 'red', fontWeight: '600' } }, internalLinkCount)
                        ),
                        wp.element.createElement('div', null,
                            'Images with alt text: ',
                            wp.element.createElement('span', { style: { color: imagesWithAltCount > 0 ? 'green' : 'red', fontWeight: '600' } }, imagesWithAltCount)
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'Links Analysis', initialOpen: false },
                        wp.element.createElement('div', null, `Internal links: ${linkStats.internal}`),
                        wp.element.createElement('div', null, `External links: ${linkStats.external}`),
                        wp.element.createElement('div', null, `Invalid URLs: ${linkStats.broken}`),
                        linkStats.broken > 0 ?
                            wp.element.createElement(Notice, { status: 'error', isDismissible: false }, 'Warning: Invalid URLs found!')
                            : null,
                        
                        // Link Manager UI
                        wp.element.createElement('hr', { style: { margin: '15px 0', border: 'none', borderTop: '1px solid #eee' } }),
                        wp.element.createElement('strong', null, '🔗 Link Manager'),
                        wp.element.createElement('div', { style: { marginTop: '10px', maxHeight: '300px', overflowY: 'auto' } },
                            linkObjects.length === 0 ? wp.element.createElement('p', { style: { fontStyle: 'italic', color: '#666' } }, 'No links found in content.') :
                            linkObjects.map((link, idx) => 
                                wp.element.createElement('div', { key: idx, style: { background: '#f9f9f9', padding: '10px', marginBottom: '8px', borderRadius: '4px', borderLeft: link.isBroken ? '3px solid red' : '3px solid #0073aa' } },
                                    wp.element.createElement('div', { style: { marginBottom: '5px', fontWeight: '600', fontSize: '12px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, 
                                        link.text || '(Image/No Text)'
                                    ),
                                    
                                    // Link Changer Input
                                    editingLinkIndex === idx ? 
                                        wp.element.createElement('div', { style: { display: 'flex', gap: '5px', marginBottom: '5px' } },
                                            wp.element.createElement('input', { 
                                                type: 'text', 
                                                value: tempLinkUrl, 
                                                onChange: (e) => setTempLinkUrl(e.target.value),
                                                style: { flex: 1, fontSize: '12px', padding: '4px' }
                                            }),
                                            wp.element.createElement(Button, { isSmall: true, isPrimary: true, onClick: () => { modifyLink(idx, 'url', tempLinkUrl); setEditingLinkIndex(-1); } }, '✓'),
                                            wp.element.createElement(Button, { isSmall: true, isSecondary: true, onClick: () => setEditingLinkIndex(-1) }, '✕')
                                        )
                                    :
                                        wp.element.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '5px' } },
                                            wp.element.createElement('a', { href: link.href, target: '_blank', style: { fontSize: '11px', color: link.isBroken ? 'red' : '#0073aa', maxWidth: '70%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, link.href),
                                            wp.element.createElement(Button, { isSmall: true, icon: 'edit', label: 'Edit URL', onClick: () => { setTempLinkUrl(link.href); setEditingLinkIndex(idx); } })
                                        ),

                                    // Options: New Tab, Nofollow, Unlink
                                    wp.element.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '8px' } },
                                        wp.element.createElement('div', { style: { display: 'flex', gap: '10px' } },
                                            wp.element.createElement(CheckboxControl, {
                                                label: 'New Tab',
                                                checked: link.target === '_blank',
                                                onChange: (val) => modifyLink(idx, 'target', val),
                                                style: { marginBottom: 0 },
                                                __nextHasNoMarginBottom: true
                                            }),
                                            wp.element.createElement(CheckboxControl, {
                                                label: 'Nofollow',
                                                checked: link.rel.includes('nofollow'),
                                                onChange: (val) => modifyLink(idx, 'rel', val),
                                                style: { marginBottom: 0 },
                                                __nextHasNoMarginBottom: true
                                            })
                                        ),
                                        wp.element.createElement(Button, { isSmall: true, isDestructive: true, icon: 'editor-unlink', label: 'Remove Link (Keep Text)', onClick: () => modifyLink(idx, 'unlink') })
                                    )
                                )
                            )
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: isPro ? 'Social Preview' : 'Social Preview (Pro Functie)', initialOpen: false },
                        !isPro ? wp.element.createElement('div', { className: 'fajaedeseo-pro-upsell-container' },
                            wp.element.createElement('div', { className: 'fajaedeseo-blur-preview' },
                                wp.element.createElement('img', { src: (typeof fajaedeseo_ajax !== 'undefined' && fajaedeseo_ajax.facebook_image) ? fajaedeseo_ajax.facebook_image : '', alt: 'Facebook Preview' }),
                                wp.element.createElement('div', { className: 'fajaedeseo-upsell-overlay' },
                                    wp.element.createElement('span', { className: 'fajaedeseo-lock-icon' }, '🔒'),
                                    wp.element.createElement('h4', null, 'Ontgrendel Social AI Cards'),
                                    wp.element.createElement('p', null, 'Zorg dat je links op WhatsApp, LinkedIn en Facebook opvallen met een mooie afbeelding en titel in plaats van een saaie grijze link.'),
                                    wp.element.createElement(Button, {
                                        isPrimary: true,
                                        style: { width: '100%', justifyContent: 'center' },
                                        onClick: () => window.open(settingsUrl, '_blank')
                                    }, 'Upgrade naar Pro')
                                )
                            )
                        ) : wp.element.createElement(Fragment, null,
                            wp.element.createElement('p', { style: { marginBottom: '6px', fontWeight: '600' } }, 'Image Preview'),
                            wp.element.createElement('img', {
                                src: featuredImageUrl,
                                alt: 'Social Share Preview Image',
                                style: { maxWidth: '100%', height: 'auto', borderRadius: '8px', border: '1px solid #ddd', marginBottom: '20px' }
                            }),

                            // Twitter Card Preview
                            wp.element.createElement('div', { style: { border: '1px solid #e1e8ed', borderRadius: '14px', overflow: 'hidden', marginBottom: '20px', background: '#fff' } },
                                wp.element.createElement('div', { style: { padding: '10px 15px', borderBottom: '1px solid #e1e8ed', display: 'flex', alignItems: 'center', gap: '10px' } },
                                    wp.element.createElement('img', { src: fajaedeseo_ajax.twitter_image, style: { width: '24px', height: '24px', borderRadius: '50%' } }),
                                    wp.element.createElement('span', { style: { fontWeight: 'bold', fontSize: '14px', color: '#14171a' } }, 'User Name'),
                                    twitterHandle && wp.element.createElement('span', { style: { fontSize: '14px', color: '#657786' } }, `@${twitterHandle.replace('@', '')}`)
                                ),
                                wp.element.createElement('div', { style: { padding: '15px' } },
                                    wp.element.createElement('div', { style: { border: '1px solid #e1e8ed', borderRadius: '14px', overflow: 'hidden' } },
                                        featuredImageUrl && wp.element.createElement('img', {
                                            src: featuredImageUrl,
                                            alt: 'Twitter Card Image',
                                            style: { width: '100%', height: 'auto', display: 'block' }
                                        }),
                                        wp.element.createElement('div', { style: { padding: '12px', background: '#f5f8fa' } },
                                            wp.element.createElement('p', { style: { fontSize: '16px', fontWeight: 'bold', color: '#14171a', margin: '0 0 5px 0' } }, meta._fajaedeseo_meta_title || cleanPostTitle),
                                            wp.element.createElement('p', { style: { fontSize: '14px', color: '#657786', margin: '0 0 5px 0', lineHeight: '1.3' } }, meta._fajaedeseo_meta_desc || 'Summarize your content here...'),
                                            wp.element.createElement('p', { style: { fontSize: '13px', color: '#657786', margin: '0' } }, siteUrl.replace(/^(https?:\/\/)?(www\.)?/, ''))
                                        )
                                    )
                                )
                            ),

                            // Facebook Open Graph Preview
                            wp.element.createElement('div', { style: { border: '1px solid #dadde1', borderRadius: '3px', overflow: 'hidden', marginBottom: '20px', background: '#f0f2f5' } },
                                wp.element.createElement('div', { style: { padding: '12px', background: '#f7f7f7', borderBottom: '1px solid #dadde1', display: 'flex', alignItems: 'center', gap: '10px' } },
                                    wp.element.createElement('img', { src: fajaedeseo_ajax.facebook_image, style: { width: '24px', height: '24px', borderRadius: '50%' } }),
                                    wp.element.createElement('span', { style: { fontWeight: 'bold', fontSize: '14px', color: '#1c1e21' } }, 'Facebook User'),
                                    facebookHandle && wp.element.createElement('span', { style: { fontSize: '14px', color: '#606770' } }, `(${facebookHandle.replace('@', '')})`)
                                ),
                                wp.element.createElement('div', { style: { background: '#fff', border: '1px solid #dadde1', borderRadius: '3px', overflow: 'hidden' } },
                                    featuredImageUrl && wp.element.createElement('img', {
                                        src: featuredImageUrl,
                                        alt: 'Facebook Open Graph Image',
                                        style: { width: '100%', height: 'auto', display: 'block' }
                                    }),
                                    wp.element.createElement('div', { style: { padding: '12px' } },
                                        wp.element.createElement('p', { style: { fontSize: '12px', textTransform: 'uppercase', color: '#606770', margin: '0 0 5px 0' } }, siteUrl.replace(/^(https?:\/\/)?(www\.)?/, '')),
                                        wp.element.createElement('p', { style: { fontSize: '16px', fontWeight: 'bold', color: '#1c1e21', margin: '0 0 5px 0' } }, meta._fajaedeseo_meta_title || cleanPostTitle),
                                        wp.element.createElement('p', { style: { fontSize: '14px', color: '#606770', margin: '0', lineHeight: '1.3' } }, meta._fajaedeseo_meta_desc || 'Summarize your content here...')
                                    )
                                )
                            )
                        )
                    ),

                    wp.element.createElement('div', { style: { marginTop: '10px', marginBottom: '10px', textAlign: 'center' } },
                        wp.element.createElement('strong', {
                            style: {
                                padding: '6px 14px',
                                borderRadius: '18px',
                                background: scoreColor(seoScore),
                                color: '#fff',
                                display: 'inline-block',
                                fontWeight: 'bold'
                            }
                        }, `SEO Score: ${seoScore} / 6`)
                    ),

                    wp.element.createElement(AuditPanel, null),

                    wp.element.createElement(PanelBody, { title: 'Competitor Analysis (SERP)', initialOpen: false },
                        !mainKeyword ? wp.element.createElement('p', { style: { fontStyle: 'italic', fontSize: '12px' } }, 'Please set a focus keyword first.')
                        : wp.element.createElement(Fragment, null,
                            wp.element.createElement(Button, {
                                isSecondary: true,
                                isSmall: true,
                                disabled: isAnalyzingSerp,
                                style: { width: '100%', justifyContent: 'center', marginBottom: '10px' },
                                onClick: runSerpAnalysis
                            }, isAnalyzingSerp ? wp.element.createElement(Spinner, null) : `Analyze "${mainKeyword}"`),
                            serpError && wp.element.createElement('div', { style: { color: '#d63638', marginBottom: '10px', fontSize: '12px', borderLeft: '3px solid #d63638', paddingLeft: '8px' } }, serpError),
                            serpData && !serpError && wp.element.createElement('div', null,
                                wp.element.createElement('strong', { style: { fontSize: '12px', display: 'block', marginBottom: '8px' } }, 'Top 5 Competitors:'),
                                wp.element.createElement('ul', { style: { paddingLeft: '15px', marginTop: '5px', fontSize: '11px' } },
                                    serpData.results && serpData.results.length > 0 ? 
                                        serpData.results.map((result, i) => 
                                            wp.element.createElement('li', { key: i, style: { marginBottom: '12px', borderBottom: '1px solid #eee', paddingBottom: '8px' } },
                                                wp.element.createElement('a', {
                                                    href: result.url || '#', 
                                                    target: '_blank', 
                                                    style: { fontWeight: '600', display: 'block', textDecoration: 'none', fontSize: '12px' } 
                                                }, result.title || 'No title'),
                                                wp.element.createElement('span', { style: { color: '#006621', fontSize: '10px', display: 'block', marginBottom: '4px' } }, result.url ? new URL(result.url).hostname : ''),
                                                result.snippet && wp.element.createElement('p', { style: { fontSize: '11px', color: '#555', margin: 0, lineHeight: '1.4' } }, result.snippet)
                                            )
                                        ) : wp.element.createElement('li', null, 'No results found.')
                                )
                            ),
                            // PDF Generate Button for SERP (Agency)
                            hasWhiteLabel && serpData && wp.element.createElement(Button, {
                                isSecondary: true,
                                isSmall: true,
                                disabled: isGeneratingSerpPdf,
                                style: { marginTop: '15px', width: '100%', justifyContent: 'center' },
                                onClick: () => {
                                    setIsGeneratingSerpPdf(true);
                                    apiFetchWithNonce({
                                        path: `/fajaedeseo/v1/generate-pdf?type=serp&keyword=${encodeURIComponent(mainKeyword)}`,
                                        method: 'GET'
                                    }).then(res => {
                                        if (res && res.pdf) {
                                            const linkSource = `data:application/pdf;base64,${res.pdf}`;
                                            const downloadLink = document.createElement("a");
                                            downloadLink.href = linkSource;
                                            downloadLink.download = "seo-serp-report.pdf";
                                            downloadLink.click();
                                        }
                                        setIsGeneratingSerpPdf(false);
                                    }).catch(() => setIsGeneratingSerpPdf(false));
                                }
                            }, isGeneratingSerpPdf ? wp.element.createElement(Spinner, null) : '📄 Download Agency SERP Report')
                        )
                    ),

                    wp.element.createElement(PanelBody, { title: 'Technical SEO (Pro)', initialOpen: false },
                        !isPro ? wp.element.createElement('div', { style: { background: '#f8f9fa', padding: '15px', border: '1px solid #ddd', borderRadius: '4px', textAlign: 'center' } },
                            wp.element.createElement('div', { style: { fontSize: '24px', marginBottom: '10px' } }, '🔒'),
                            wp.element.createElement('p', { style: { fontWeight: 'bold', marginBottom: '5px' } }, 'Unlock Technical SEO'),
                            wp.element.createElement('p', { style: { fontSize: '13px', color: '#666', marginBottom: '15px' } }, 
                                'Get full control over Robots.txt, Indexing, Nofollow links, and advanced Schema types like FAQ, Review, and Product.'
                            ),
                            wp.element.createElement(Button, { isPrimary: true, onClick: () => window.open(settingsUrl, '_blank') }, 'Upgrade to Pro')
                        ) : wp.element.createElement(Fragment, null,
                        wp.element.createElement(SelectControl, {
                            label: 'Robots Indexing',
                            value: meta._fajaedeseo_robots_index || 'index',
                            options: [
                                { label: 'Index (Default)', value: 'index' },
                                { label: 'No Index (Hidden from Google)', value: 'noindex' }
                            ],
                            onChange: (val) => setMeta('_fajaedeseo_robots_index', val),
                            help: 'Control if search engines should show this page.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        }),
                        wp.element.createElement(SelectControl, {
                            label: 'Robots Following',
                            value: meta._fajaedeseo_robots_follow || 'follow',
                            options: [
                                { label: 'Follow (Default)', value: 'follow' },
                                { label: 'No Follow (Don\'t follow links)', value: 'nofollow' }
                            ],
                            onChange: (val) => setMeta('_fajaedeseo_robots_follow', val),
                            help: 'Control if search engines should follow links on this page.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        }),
                        wp.element.createElement(SelectControl, {
                            label: 'Schema Type',
                            value: meta._fajaedeseo_schema_type || 'Article',
                            options: [
                                { label: 'Article (Default)', value: 'Article' },
                                { label: 'News Article', value: 'NewsArticle' },
                                { label: 'Blog Posting', value: 'BlogPosting' },
                                { label: 'Product', value: 'Product' },
                                { label: 'Service', value: 'Service' },
                                { label: 'Review', value: 'Review' },
                                { label: 'FAQ Page', value: 'FAQPage' },
                                { label: 'How-To', value: 'HowTo' },
                                { label: 'Local Business', value: 'LocalBusiness' },
                                { label: 'Event', value: 'Event' },
                                { label: 'Recipe', value: 'Recipe' },
                                { label: 'Software Application', value: 'SoftwareApplication' },
                                { label: 'Video Object', value: 'VideoObject' },
                                { label: 'Course', value: 'Course' },
                                { label: 'Job Posting', value: 'JobPosting' },
                                { label: 'Medical Condition', value: 'MedicalCondition' },
                                { label: 'Dataset', value: 'Dataset' },
                                { label: 'Book', value: 'Book' },
                                { label: 'Movie', value: 'Movie' },
                                { label: 'Music Album', value: 'MusicAlbum' },
                                { label: 'Podcast Episode', value: 'PodcastEpisode' },
                                { label: 'Quiz', value: 'Quiz' },
                                { label: 'Restaurant', value: 'Restaurant' },
                                { label: 'Q&A Page', value: 'QAPage' },
                                { label: 'Profile Page', value: 'ProfilePage' }
                            ],
                            onChange: (val) => setMeta('_fajaedeseo_schema_type', val),
                            help: 'Define the content type for Rich Snippets.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        })
                    )),

                    wp.element.createElement(PanelBody, { title: 'Canonical URL', initialOpen: false },
                        wp.element.createElement(TextControl, {
                            label: 'Canonical URL',
                            value: meta._fajaedeseo_canonical || '',
                            onChange: (val) => setMeta('_fajaedeseo_canonical', val),
                            help: 'Use this to point search engines to the original source URL. Adjust if necessary and click save.',
                            __next40pxDefaultSize: true,
                            __nextHasNoMarginBottom: true
                        })
                    ),

                    wp.element.createElement(PanelBody, { title: 'Performance & Speed (Pro)', initialOpen: false },
                        !isPro ? wp.element.createElement('div', { style: { padding: '10px', background: '#f0f0f0', borderRadius: '4px' } }, 
                            '🚀 Upgrade to Pro to unlock one-click performance optimizations.'
                        ) : wp.element.createElement(Fragment, null,
                            wp.element.createElement(ToggleControl, {
                                label: 'Fast LCP Loading',
                                help: 'Optimizes Largest Contentful Paint by preloading critical assets.',
                                checked: !!meta._fajaedeseo_pro_lcp_optimized,
                                onChange: (val) => setMeta('_fajaedeseo_pro_lcp_optimized', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Enhanced Lazy Loading',
                                help: 'Forces advanced lazy loading on all images in this post.',
                                checked: !!meta._fajaedeseo_pro_lazy_load,
                                onChange: (val) => setMeta('_fajaedeseo_pro_lazy_load', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Non-blocking Ads',
                                help: 'Loads advertisement scripts after the main content is ready.',
                                checked: !!meta._fajaedeseo_pro_defer_ads,
                                onChange: (val) => setMeta('_fajaedeseo_pro_defer_ads', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Optimize CSS & JS',
                                help: 'Minifies and defers non-critical styles and scripts.',
                                checked: !!meta._fajaedeseo_pro_optimize_assets,
                                onChange: (val) => setMeta('_fajaedeseo_pro_optimize_assets', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Google Fonts Swap',
                                help: 'Enforces font-display: swap for better text visibility during load.',
                                checked: !!meta._fajaedeseo_pro_font_swap,
                                onChange: (val) => setMeta('_fajaedeseo_pro_font_swap', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Conditional Script Loading',
                                help: 'Only loads heavy scripts like CF7 or reCAPTCHA if strictly needed.',
                                checked: !!meta._fajaedeseo_pro_conditional_scripts,
                                onChange: (val) => setMeta('_fajaedeseo_pro_conditional_scripts', val),
                                __nextHasNoMarginBottom: true
                            }),
                            wp.element.createElement(ToggleControl, {
                                label: 'Semantic HTML Structure',
                                help: 'Wraps content in <main> and <article> tags for better indexing.',
                                checked: !!meta._fajaedeseo_pro_semantic_html,
                                onChange: (val) => setMeta('_fajaedeseo_pro_semantic_html', val),
                                __nextHasNoMarginBottom: true
                        })
                        )
                    )
                )
            )
        );
    };

    // Registreer direct. Gutenberg handelt timing af via dependencies (wp-edit-post, etc.)
    try {
        registerPlugin('fajaedeseo-ai-plugin-sidebar', {
            render: Sidebar,
            icon: 'admin-site-alt3' // De wereldbol
        });
    } catch ( e ) {
        console.error( 'fajaedeseo: Registration failed', e );
    }

})(window.wp);
