/**
 * AnchorKit Table of Contents Block
 * 
 * A comprehensive Gutenberg block for inserting and customizing the Table of Contents
 */

(function () {
    // Ensure wp.blocks exists
    if (typeof wp === 'undefined' || !wp.blocks) {
        console.error('AnchorKit: WordPress blocks API not available');
        return;
    }

    const anchorkitDebugLog = (...args) => {
        if (!window || !window.anchorkitDebug) {
            return;
        }

        if (window.console && typeof window.console.log === 'function') {
            window.console.log(...args);
        }
    };

    const { registerBlockType } = wp.blocks;
    const { InspectorControls } = wp.blockEditor || wp.editor;
    const {
        PanelBody,
        Placeholder,
        Button,
        ButtonGroup,
        ToggleControl,
        SelectControl,
        TextControl,
        RangeControl,
        Notice,
        CheckboxControl,
        ColorPicker,
        BaseControl,
        TextareaControl,
        Spinner,
        ExternalLink
    } = wp.components;
    const { __, sprintf } = wp.i18n;
    const { Fragment, RawHTML, useEffect, useRef, useState } = wp.element;
    const apiFetch = wp.apiFetch;
    const { addQueryArgs } = wp.url || { addQueryArgs: function (path) { return path; } };

    /**
     * Fallback collapsible initialization for editor preview
     * This runs if the main table-of-contents.js hasn't loaded yet
     */
    function initializeCollapsibleFallback(container) {
        // Prevent duplicate initialization
        if (container.hasAttribute('data-anchorkit-fallback-initialized')) {
            return;
        }
        container.setAttribute('data-anchorkit-fallback-initialized', 'true');

        const toggleBtn = container.querySelector('.anchorkit-toc-toggle-button');
        const tocTitle = container.querySelector('.anchorkit-toc-title');
        const list = container.querySelector('.anchorkit-toc-list');

        if (!toggleBtn || !list || !tocTitle) {
            anchorkitDebugLog('AnchorKit Fallback: Missing required elements for collapsible');
            return;
        }

        anchorkitDebugLog('AnchorKit: Using fallback collapsible initialization');

        // Set initial height
        const isCollapsed = container.classList.contains('anchorkit-toc-collapsed');
        if (isCollapsed) {
            list.style.height = '0px';
        } else {
            list.style.height = list.scrollHeight + 'px';
        }

        // Toggle function
        const toggleToc = function (e) {
            if (e && e.target.closest('.anchorkit-toc-toggle-button') && e.currentTarget !== e.target.closest('.anchorkit-toc-toggle-button')) {
                return;
            }

            const collapsed = container.classList.contains('anchorkit-toc-collapsed');
            const expanding = collapsed;

            toggleBtn.setAttribute('aria-expanded', expanding);

            if (expanding) {
                list.style.height = list.scrollHeight + 'px';
                container.classList.remove('anchorkit-toc-collapsed');
                container.classList.add('anchorkit-toc-expanded');
                list.removeAttribute('aria-hidden');
            } else {
                list.style.height = list.scrollHeight + 'px';
                list.offsetHeight; // force reflow
                list.style.height = '0px';
                container.classList.add('anchorkit-toc-collapsed');
                container.classList.remove('anchorkit-toc-expanded');
                list.setAttribute('aria-hidden', 'true');
            }
        };

        // Add click events
        toggleBtn.addEventListener('click', toggleToc);
        tocTitle.addEventListener('click', toggleToc);

        // Add keyboard support
        tocTitle.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                toggleToc(e);
            }
        });

        // PRO FEATURE: View More functionality
        const viewMoreBtn = container.querySelector('.anchorkit-toc-view-more-btn');
        if (viewMoreBtn) {
            const initialCount = parseInt(viewMoreBtn.getAttribute('data-initial-count')) || 5;
            const viewMoreText = viewMoreBtn.getAttribute('data-view-more-text') || 'View More';
            const viewLessText = viewMoreBtn.getAttribute('data-view-less-text') || 'View Less';
            const tocItems = Array.from(container.querySelectorAll('.anchorkit-toc-item:not(.anchorkit-toc-view-more-item)'));
            const textSpan = viewMoreBtn.querySelector('.anchorkit-toc-view-more-text');

            // Initially hide items beyond the initial count
            tocItems.forEach(function (item, index) {
                if (index >= initialCount) {
                    item.classList.add('anchorkit-toc-hidden-item');
                }
            });

            // If all items would be visible, remove the button
            if (tocItems.length <= initialCount) {
                const wrapper = viewMoreBtn.closest('.anchorkit-toc-view-more-item');
                if (wrapper) wrapper.remove();
            } else {
                // Toggle function
                viewMoreBtn.addEventListener('click', function (e) {
                    e.preventDefault();
                    const isExpanded = this.getAttribute('aria-expanded') === 'true';

                    if (isExpanded) {
                        // Collapse - hide items beyond initial count
                        tocItems.forEach(function (item, index) {
                            if (index >= initialCount) {
                                item.classList.add('anchorkit-toc-hidden-item');
                            }
                        });
                        this.setAttribute('aria-expanded', 'false');
                        container.classList.remove('anchorkit-toc-view-more-expanded');
                        if (textSpan) textSpan.textContent = viewMoreText;
                    } else {
                        // Expand - show all items
                        tocItems.forEach(function (item) {
                            item.classList.remove('anchorkit-toc-hidden-item');
                        });
                        this.setAttribute('aria-expanded', 'true');
                        container.classList.add('anchorkit-toc-view-more-expanded');
                        if (textSpan) textSpan.textContent = viewLessText;
                    }

                    // Update list height if collapsible and expanded
                    if (container.classList.contains('anchorkit-toc-collapsible') && list && container.classList.contains('anchorkit-toc-expanded')) {
                        // Recalculate height after showing/hiding items
                        requestAnimationFrame(function () {
                            requestAnimationFrame(function () {
                                list.style.height = list.scrollHeight + 'px';
                            });
                        });
                    }
                });

                // Keyboard accessibility
                viewMoreBtn.addEventListener('keydown', function (e) {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        this.click();
                    }
                });
            }
        }

        anchorkitDebugLog('AnchorKit Fallback: Collapsible initialized successfully');
    }

    /**
     * Sanitize attributes to match the registered block schema
     * This ensures the REST API endpoint accepts the attributes without validation errors
     */
    function sanitizeAttributes(attrs) {
        if (!attrs || typeof attrs !== 'object') {
            return { preview: true };
        }

        // Define valid attribute keys based on the registered schema
        // Only include attributes that are registered in the block schema
        const sanitized = {
            preview: true
        };

        // Boolean attributes
        const booleanAttrs = [
            'showTitle', 'collapsible', 'smoothScroll', 'hierarchicalView',
            'showNumerals', 'entranceAnimation', 'hideOnMobile', 'sticky',
            'scrollSpy', 'viewMoreEnabled', 'showReadingTime', 'showWordCount',
            'advancedTypographyOverride', 'backToTopLink', 'schemaEnabled',
            'acfEnabled', 'ampEnabled'
        ];

        // Number attributes
        const numberAttrs = [
            'minHeadingsToShow', 'scrollOffset', 'scrollDuration',
            'mobileBreakpoint', 'tocWidth',
            'stickyOffset', 'viewMoreInitialCount', 'readingSpeed',
            'titleFontSize', 'h2FontSize', 'h3FontSize', 'h4FontSize',
            'h5FontSize', 'h6FontSize', 'lineHeight', 'letterSpacing',
            'backToTopFontSize',
            // Design override sizing
            'containerPadding', 'containerBorderWidth', 'containerBorderRadius',
            // Box shadow components
            'shadowHOffsetLight', 'shadowVOffsetLight', 'shadowBlurLight', 'shadowSpreadLight', 'shadowOpacityLight',
            'shadowHOffsetDark', 'shadowVOffsetDark', 'shadowBlurDark', 'shadowSpreadDark', 'shadowOpacityDark'
        ];

        // String attributes
        const stringAttrs = [
            'align', 'title', 'initialState', 'scrollEasing', 'stylePreset',
            'bulletStyle', 'bulletCharacter', 'bulletColor', 'numberingStyle',
            'numberingFormat', 'numberingSeparator', 'animationType',
            'tocAlignment', 'tocFloat', 'ariaLabel', 'customCssClass', 'customId',
            'customLabels', 'anchorFormat', 'anchorPrefix', 'acfFieldNames',
            'acfMergeMode', 'stickyPosition', 'viewMoreText', 'viewLessText',
            'timeFormat', 'textTransform', 'linkUnderline', 'backToTopText', 'excludeSelectors',
            'excludeRegex', 'excludeKeywords', 'schemaType',
            // Theme override
            'theme',
            // Design override colors
            'bgColorLight', 'textColorLight', 'linkColorLight', 'linkHoverColorLight', 'borderColorLight', 'bulletColorLight',
            'bgColorDark', 'textColorDark', 'linkColorDark', 'linkHoverColorDark', 'borderColorDark', 'bulletColorDark',
            // Box shadow colors
            'shadowColorLight', 'shadowColorDark'
        ];

        // Array attributes
        const arrayAttrs = ['headingLevels'];

        // Process each attribute type
        booleanAttrs.forEach(function (key) {
            if (key in attrs && attrs[key] !== undefined && attrs[key] !== null) {
                sanitized[key] = Boolean(attrs[key]);
            }
        });

        numberAttrs.forEach(function (key) {
            if (key in attrs && attrs[key] !== undefined && attrs[key] !== null) {
                const num = Number(attrs[key]);
                if (!isNaN(num)) {
                    sanitized[key] = num;
                }
            }
        });

        stringAttrs.forEach(function (key) {
            if (key in attrs && attrs[key] !== undefined && attrs[key] !== null) {
                const strValue = String(attrs[key]);
                // Only include non-empty strings (except for some that can be empty like excludeSelectors)
                const canBeEmpty = ['excludeSelectors', 'excludeRegex', 'excludeKeywords', 'customCssClass', 'customId', 'customLabels', 'acfFieldNames', 'acfMergeMode', 'anchorPrefix'];
                if (strValue !== '' || canBeEmpty.indexOf(key) !== -1) {
                    sanitized[key] = strValue;
                }
            }
        });

        arrayAttrs.forEach(function (key) {
            if (key === 'headingLevels') {
                // Ensure headingLevels is a valid array with string values
                if (key in attrs && Array.isArray(attrs[key])) {
                    sanitized[key] = attrs[key].filter(function (item) {
                        return typeof item === 'string' && /^h[1-6]$/.test(item);
                    });
                    // Ensure at least one heading level is selected
                    if (sanitized[key].length === 0) {
                        sanitized[key] = ['h2', 'h3', 'h4'];
                    }
                } else {
                    // Default if not provided or invalid
                    sanitized[key] = ['h2', 'h3', 'h4'];
                }
            } else if (key in attrs && Array.isArray(attrs[key])) {
                sanitized[key] = attrs[key];
            }
        });

        // Design override flag
        if ('designOverride' in attrs) {
            sanitized.designOverride = Boolean(attrs.designOverride);
        }
        if ('boxShadowEnabled' in attrs) {
            sanitized.boxShadowEnabled = Boolean(attrs.boxShadowEnabled);
        }

        // Always include critical settings with explicit values (even if default/undefined)
        // This ensures the server always receives these settings for proper rendering

        // Numerals settings
        sanitized.showNumerals = attrs.showNumerals === true;
        sanitized.numberingStyle = attrs.numberingStyle || 'hierarchical';
        sanitized.numberingFormat = attrs.numberingFormat || 'decimal';
        sanitized.numberingSeparator = attrs.numberingSeparator || '.';

        // Typography settings
        sanitized.lineHeight = typeof attrs.lineHeight === 'number' ? attrs.lineHeight : 1.6;
        sanitized.letterSpacing = typeof attrs.letterSpacing === 'number' ? attrs.letterSpacing : 0;

        // View settings
        sanitized.hierarchicalView = attrs.hierarchicalView !== false;

        return sanitized;
    }

    function AnchorKitServerRender(props) {
        const { attributes } = props;
        const [response, setResponse] = useState({ rendered: null, error: null, renderCount: 0 });
        const lastRequestRef = useRef(0);
        const previewContainerRef = useRef(null);
        const renderCountRef = useRef(0);

        // Get current editor content for live preview (updates when content changes)
        const editorSelector = wp.data?.select?.('core/editor');
        const currentContent = editorSelector && editorSelector.getEditedPostContent ? editorSelector.getEditedPostContent() : '';

        useEffect(function () {
            let isSubscribed = true;
            let debounceTimer = null;

            const currentPostId = editorSelector && editorSelector.getCurrentPostId ? editorSelector.getCurrentPostId() : undefined;
            const validPostId = typeof currentPostId === 'number' && currentPostId > 0 ? currentPostId : undefined;

            // Use custom REST endpoint that bypasses WordPress's strict validation
            const endpoint = '/anchorkit/v1/block-preview';

            const sanitizedAttributes = sanitizeAttributes(attributes);

            const requestData = {
                attributes: sanitizedAttributes
            };
            if (validPostId) {
                requestData.post_id = validPostId;
            }
            // Pass current editor content for live preview of unsaved changes
            if (currentContent) {
                requestData.content = currentContent;
            }

            const fetchPreview = function (requestId) {
                apiFetch({
                    path: endpoint,
                    method: 'POST',
                    data: requestData
                }).then(function (res) {
                    if (!isSubscribed || lastRequestRef.current !== requestId) return;
                    renderCountRef.current++;
                    setResponse({ rendered: res.rendered || '', error: null, renderCount: renderCountRef.current });
                }).catch(function () {
                    if (!isSubscribed || lastRequestRef.current !== requestId) return;
                    setResponse(function (prev) {
                        return { rendered: prev.rendered, error: true };
                    });
                });
            };

            debounceTimer = setTimeout(function () {
                const requestId = Date.now();
                lastRequestRef.current = requestId;
                fetchPreview(requestId);
            }, 250);

            return function () {
                isSubscribed = false;
                if (debounceTimer) {
                    clearTimeout(debounceTimer);
                }
            };
        }, [JSON.stringify(attributes), currentContent]);

        useEffect(function () {
            if (!previewContainerRef.current || !response.rendered) {
                return;
            }

            // Use event delegation with capture to handle clicks before Gutenberg intercepts them
            // This is necessary because Gutenberg's block selection can prevent click events
            // from reaching the actual TOC elements
            var clickHandler = function (e) {
                var target = e.target;
                var container = previewContainerRef.current;
                if (!container) return;

                // Check if click is on toggle button or title (for expand/collapse)
                var toggleBtn = target.closest('.anchorkit-toc-toggle-button');
                var tocTitle = target.closest('.anchorkit-toc-title');
                var viewMoreBtn = target.closest('.anchorkit-toc-view-more-btn');

                if (toggleBtn || tocTitle || viewMoreBtn) {
                    var tocContainer = target.closest('.anchorkit-toc-container');
                    if (!tocContainer) return;

                    var list = tocContainer.querySelector('.anchorkit-toc-list');
                    var isCollapsible = tocContainer.classList.contains('anchorkit-toc-collapsible');

                    // Only stop propagation if we're actually going to handle this click
                    // (collapsible is enabled for toggle/title, or it's a view more button)
                    if (((toggleBtn || tocTitle) && isCollapsible) || viewMoreBtn) {
                        e.stopPropagation();
                    }

                    // Handle toggle button or title click (expand/collapse)
                    // Only allow if collapsible is enabled (container has anchorkit-toc-collapsible class)
                    if ((toggleBtn || tocTitle) && list && isCollapsible) {
                        var actualToggleBtn = tocContainer.querySelector('.anchorkit-toc-toggle-button');
                        var collapsed = tocContainer.classList.contains('anchorkit-toc-collapsed');
                        var expanding = collapsed;

                        if (actualToggleBtn) {
                            actualToggleBtn.setAttribute('aria-expanded', expanding);
                        }

                        if (expanding) {
                            list.style.height = list.scrollHeight + 'px';
                            tocContainer.classList.remove('anchorkit-toc-collapsed');
                            tocContainer.classList.add('anchorkit-toc-expanded');
                            list.removeAttribute('aria-hidden');
                        } else {
                            list.style.height = list.scrollHeight + 'px';
                            list.offsetHeight; // force reflow
                            list.style.height = '0px';
                            tocContainer.classList.add('anchorkit-toc-collapsed');
                            tocContainer.classList.remove('anchorkit-toc-expanded');
                            list.setAttribute('aria-hidden', 'true');
                        }
                    }

                    // Handle view more button click
                    if (viewMoreBtn) {
                        e.preventDefault();
                        var initialCount = parseInt(viewMoreBtn.getAttribute('data-initial-count')) || 5;
                        var viewMoreText = viewMoreBtn.getAttribute('data-view-more-text') || 'View More';
                        var viewLessText = viewMoreBtn.getAttribute('data-view-less-text') || 'View Less';
                        var tocItems = Array.from(tocContainer.querySelectorAll('.anchorkit-toc-item:not(.anchorkit-toc-view-more-item)'));
                        var textSpan = viewMoreBtn.querySelector('.anchorkit-toc-view-more-text');
                        var isExpanded = viewMoreBtn.getAttribute('aria-expanded') === 'true';

                        if (isExpanded) {
                            // Collapse - hide items beyond initial count
                            tocItems.forEach(function (item, index) {
                                if (index >= initialCount) {
                                    item.classList.add('anchorkit-toc-hidden-item');
                                }
                            });
                            viewMoreBtn.setAttribute('aria-expanded', 'false');
                            tocContainer.classList.remove('anchorkit-toc-view-more-expanded');
                            if (textSpan) textSpan.textContent = viewMoreText;
                        } else {
                            // Expand - show all items
                            tocItems.forEach(function (item) {
                                item.classList.remove('anchorkit-toc-hidden-item');
                            });
                            viewMoreBtn.setAttribute('aria-expanded', 'true');
                            tocContainer.classList.add('anchorkit-toc-view-more-expanded');
                            if (textSpan) textSpan.textContent = viewLessText;
                        }

                        // Update list height if collapsible and expanded
                        if (isCollapsible && list && tocContainer.classList.contains('anchorkit-toc-expanded')) {
                            // Wait for DOM to apply display changes (double RAF ensures CSS is applied)
                            requestAnimationFrame(function () {
                                requestAnimationFrame(function () {
                                    // Temporarily remove height to let the browser calculate content height
                                    var previousTransition = list.style.transition;
                                    list.style.transition = 'none';
                                    list.style.height = 'auto';
                                    // Force reflow and measure exact content height
                                    var targetHeight = list.scrollHeight;
                                    list.offsetHeight; // reflow
                                    // Restore transition and apply precise height
                                    list.style.transition = previousTransition;
                                    list.style.height = targetHeight + 'px';
                                });
                            });
                        }
                    }
                }
            };

            // Function to initialize TOC containers (for initial state setup)
            var initializePreview = function () {
                if (!previewContainerRef.current) return;

                // Find all TOC containers in the preview
                var previewContainers = previewContainerRef.current.querySelectorAll('.anchorkit-toc-container');

                if (previewContainers.length === 0) {
                    anchorkitDebugLog('AnchorKit: No TOC containers found in preview');
                    return;
                }

                anchorkitDebugLog('AnchorKit: Found ' + previewContainers.length + ' TOC container(s) in preview');

                // Set initial state for each container
                previewContainers.forEach(function (container) {
                    var list = container.querySelector('.anchorkit-toc-list');
                    var toggleBtn = container.querySelector('.anchorkit-toc-toggle-button');
                    var isCollapsible = container.classList.contains('anchorkit-toc-collapsible');

                    // Handle view more initial state FIRST (before calculating heights)
                    var viewMoreBtn = container.querySelector('.anchorkit-toc-view-more-btn');
                    if (viewMoreBtn) {
                        var initialCount = parseInt(viewMoreBtn.getAttribute('data-initial-count')) || 5;
                        var tocItems = Array.from(container.querySelectorAll('.anchorkit-toc-item:not(.anchorkit-toc-view-more-item)'));

                        // Initially hide items beyond the initial count
                        tocItems.forEach(function (item, index) {
                            if (index >= initialCount) {
                                item.classList.add('anchorkit-toc-hidden-item');
                            }
                        });

                        // If all items would be visible, hide the button wrapper
                        if (tocItems.length <= initialCount) {
                            var wrapper = viewMoreBtn.closest('.anchorkit-toc-view-more-item');
                            if (wrapper) wrapper.style.display = 'none';
                        }
                    }

                    // Only set fixed height if collapsible is enabled
                    if (list && isCollapsible) {
                        // Set initial height based on state (after view more items are hidden)
                        var isCollapsed = container.classList.contains('anchorkit-toc-collapsed');
                        if (isCollapsed) {
                            list.style.height = '0px';
                        } else {
                            list.style.height = list.scrollHeight + 'px';
                        }
                    }

                    // Set initial aria-expanded state
                    if (toggleBtn) {
                        toggleBtn.setAttribute('aria-expanded', !container.classList.contains('anchorkit-toc-collapsed'));
                    }
                });
            };

            // Add click handler with capture to intercept before Gutenberg
            previewContainerRef.current.addEventListener('click', clickHandler, true);

            // Wait for DOM to be ready then set initial state
            var timeoutId = setTimeout(initializePreview, 100);

            // Cleanup function
            return function () {
                clearTimeout(timeoutId);
                if (previewContainerRef.current) {
                    previewContainerRef.current.removeEventListener('click', clickHandler, true);
                }
            };
        }, [response.rendered]);

        if (response.error && !response.rendered) {
            return wp.element.createElement(
                'div',
                { className: 'anchorkit-block-preview-wrapper' },
                wp.element.createElement(
                    'p',
                    { style: { margin: '0 0 10px', fontSize: '13px', color: '#666' } },
                    wp.element.createElement('strong', null, __('Table of Contents Preview', 'anchorkit-table-of-contents'))
                ),
                wp.element.createElement(
                    'p',
                    { style: { margin: 0, fontSize: '12px', color: '#666' } },
                    __('Preview unavailable inside the editor. The TOC will still render on the frontend.', 'anchorkit-table-of-contents')
                )
            );
        }

        if (!response.rendered) {
            return wp.element.createElement(Spinner, null);
        }

        // Use render count as key to force React to re-render when response changes
        const renderKey = 'render-' + (response.renderCount || 0);

        return wp.element.createElement(
            'div',
            { className: 'anchorkit-block-preview-wrapper', ref: previewContainerRef, key: renderKey },
            wp.element.createElement(RawHTML, { key: 'html-' + renderKey }, response.rendered)
        );
    }

    // Use custom SVG icon
    const blockIcon = wp.element.createElement('svg', {
        width: 24,
        height: 24,
        viewBox: '0 0 24 24',
        fill: 'none',
        xmlns: 'http://www.w3.org/2000/svg'
    },
        wp.element.createElement('path', {
            d: 'M0 1.44C0 0.64471 0.64471 0 1.44 0H12V12H0V1.44Z',
            fill: '#BBD0FF'
        }),
        wp.element.createElement('path', {
            d: 'M12 0H22.56C23.3553 0 24 0.64471 24 1.44V12H12V0Z',
            fill: '#E7C6FF'
        }),
        wp.element.createElement('path', {
            d: 'M12 12H24V22.56C24 23.3553 23.3553 24 22.56 24H12V12Z',
            fill: '#B8C0FF'
        }),
        wp.element.createElement('path', {
            d: 'M0 12H12V24H1.44C0.64471 24 0 23.3553 0 22.56V12Z',
            fill: '#C8B6FF'
        })
    );

    /**
     * Register the Table of Contents block
     */
    registerBlockType('anchorkit/table-of-contents', {
        title: __('AnchorKit: TOC', 'anchorkit-table-of-contents'),
        description: __('Display an automatically generated table of contents based on your page headings.', 'anchorkit-table-of-contents'),
        icon: blockIcon,
        category: 'anchorkit',
        keywords: [
            __('table of contents', 'anchorkit-table-of-contents'),
            __('toc', 'anchorkit-table-of-contents'),
            __('navigation', 'anchorkit-table-of-contents'),
        ],
        supports: {
            html: false,
            multiple: true,
            align: ['wide', 'full', 'left', 'right', 'center'],
            customClassName: false,
            typography: false,
            color: false,
        },
        attributes: {
            align: {
                type: 'string'
            },
            // Content Settings
            title: {
                type: 'string',
                default: 'Table of Contents'
            },
            showTitle: {
                type: 'boolean',
                default: true
            },
            headingLevels: {
                type: 'array',
                default: ['h2', 'h3', 'h4']
            },
            excludeSelectors: {
                type: 'string',
                default: ''
            },
            excludeRegex: {
                type: 'string',
                default: ''
            },
            minHeadingsToShow: {
                type: 'number',
                default: 2
            },

            // Behavior Settings
            collapsible: {
                type: 'boolean',
                default: true
            },
            initialState: {
                type: 'string',
                default: 'expanded'
            },
            smoothScroll: {
                type: 'boolean',
                default: true
            },
            scrollOffset: {
                type: 'number',
                default: 0
            },
            scrollEasing: {
                type: 'string',
                default: 'ease-in-out'
            },
            scrollDuration: {
                type: 'number',
                default: 500
            },
            hierarchicalView: {
                type: 'boolean',
                default: true
            },

            // Style & Appearance
            stylePreset: {
                type: 'string',
                default: 'inherit'
            },
            bulletStyle: {
                type: 'string',
                default: 'disc'
            },
            bulletCharacter: {
                type: 'string',
                default: '•'
            },
            bulletColor: {
                type: 'string',
                default: '#0073AA'
            },
            showNumerals: {
                type: 'boolean',
                default: false
            },
            numberingStyle: {
                type: 'string',
                default: 'hierarchical'
            },
            numberingFormat: {
                type: 'string',
                default: 'decimal'
            },
            numberingSeparator: {
                type: 'string',
                default: '.'
            },
            // Design override scaffold
            designOverride: {
                type: 'boolean',
                default: false
            },
            // Per-block Theme override (inherit/system/light/dark)
            theme: {
                type: 'string',
                default: 'inherit'
            },
            // Box shadow toggle
            boxShadowEnabled: {
                type: 'boolean',
                default: false
            },
            // Per-block Container Styling
            containerPadding: { type: 'number' },
            containerBorderWidth: { type: 'number' },
            containerBorderRadius: { type: 'number' },
            // Per-block Colors (Light) - defaults match auto-inserted TOC custom styling
            bgColorLight: { type: 'string', default: '#FFFFFF' },
            textColorLight: { type: 'string', default: '#333333' },
            linkColorLight: { type: 'string', default: '#0073AA' },
            linkHoverColorLight: { type: 'string', default: '#005177' },
            borderColorLight: { type: 'string', default: '#DDDDDD' },
            bulletColorLight: { type: 'string', default: '#0073AA' },
            // Per-block Colors (Dark) - defaults match auto-inserted TOC custom styling
            bgColorDark: { type: 'string', default: '#1e1e1e' },
            textColorDark: { type: 'string', default: '#e0e0e0' },
            linkColorDark: { type: 'string', default: '#7ec4ee' },
            linkHoverColorDark: { type: 'string', default: '#a8d8f0' },
            borderColorDark: { type: 'string', default: '#404040' },
            bulletColorDark: { type: 'string', default: '#7ec4ee' },
            // Box Shadow components (Light)
            shadowHOffsetLight: { type: 'number', default: 0 },
            shadowVOffsetLight: { type: 'number', default: 4 },
            shadowBlurLight: { type: 'number', default: 6 },
            shadowSpreadLight: { type: 'number', default: 0 },
            shadowColorLight: { type: 'string', default: '#000000' },
            shadowOpacityLight: { type: 'number', default: 0.1 },
            // Box Shadow components (Dark)
            shadowHOffsetDark: { type: 'number', default: 0 },
            shadowVOffsetDark: { type: 'number', default: 2 },
            shadowBlurDark: { type: 'number', default: 8 },
            shadowSpreadDark: { type: 'number', default: 0 },
            shadowColorDark: { type: 'string', default: '#000000' },
            shadowOpacityDark: { type: 'number', default: 0.3 },
            entranceAnimation: {
                type: 'boolean',
                default: false
            },
            animationType: {
                type: 'string',
                default: 'fade'
            },

            // Advanced Settings
            hideOnMobile: {
                type: 'boolean',
                default: false
            },
            mobileBreakpoint: {
                type: 'number',
                default: 782
            },
            tocWidth: {
                type: 'number',
                default: 100
            },
            tocAlignment: {
                type: 'string',
                default: 'center'
            },
            tocFloat: {
                type: 'string',
                default: 'none'
            },
            ariaLabel: {
                type: 'string'
            },
            customCssClass: {
                type: 'string',
                default: ''
            },
            customId: {
                type: 'string',
                default: ''
            },
            customLabels: {
                type: 'string'
            },
            anchorFormat: {
                type: 'string',
                default: 'auto'
            },
            anchorPrefix: {
                type: 'string',
                default: 'section'
            },
            acfEnabled: {
                type: 'boolean'
            },
            acfFieldNames: {
                type: 'string'
            },
            acfMergeMode: {
                type: 'string'
            },
            ampEnabled: {
                type: 'boolean'
            },

            // PRO Settings - Sticky TOC
            sticky: {
                type: 'boolean'
            },
            stickyPosition: {
                type: 'string'
            },
            stickyOffset: {
                type: 'number'
            },
            scrollSpy: {
                type: 'boolean',
                default: true
            },

            // PRO Settings - View More
            viewMoreEnabled: {
                type: 'boolean',
                default: false
            },
            viewMoreInitialCount: {
                type: 'number',
                default: 5
            },
            viewMoreText: {
                type: 'string',
                default: 'View More'
            },
            viewLessText: {
                type: 'string',
                default: 'View Less'
            },

            // PRO Settings - Reading Time
            showReadingTime: {
                type: 'boolean'
            },
            readingSpeed: {
                type: 'number'
            },
            showWordCount: {
                type: 'boolean'
            },
            timeFormat: {
                type: 'string'
            },
            // PRO Settings - Advanced Typography
            advancedTypographyOverride: {
                type: 'boolean',
                default: false
            },
            titleFontSize: {
                type: 'number',
                default: 20
            },
            h2FontSize: {
                type: 'number',
                default: 18
            },
            h3FontSize: {
                type: 'number',
                default: 16
            },
            h4FontSize: {
                type: 'number',
                default: 14
            },
            h5FontSize: {
                type: 'number',
                default: 13
            },
            h6FontSize: {
                type: 'number',
                default: 12
            },
            lineHeight: {
                type: 'number',
                default: 1.6
            },
            letterSpacing: {
                type: 'number',
                default: 0
            },
            textTransform: {
                type: 'string',
                default: 'none'
            },
            linkUnderline: {
                type: 'string',
                default: 'none'
            },
            // PRO Settings - Back to Top
            backToTopLink: {
                type: 'boolean'
            },
            backToTopText: {
                type: 'string'
            },
            backToTopFontSize: {
                type: 'number'
            },

            excludeKeywords: {
                type: 'string',
                default: ''
            },
            schemaEnabled: {
                type: 'boolean'
            },
            schemaType: {
                type: 'string'
            },
        },

        /**
         * Edit function - renders the block in the editor
         */
        edit: function (props) {
            const { attributes, setAttributes } = props;
            const isPro = anchorkitBlockSettings && anchorkitBlockSettings.isPro;
            const blockDefaults = (anchorkitBlockSettings && anchorkitBlockSettings.defaults) || {};
            const [designPreviewMode, setDesignPreviewMode] = useState('light');

            const hasAttribute = function (key) {
                return Object.prototype.hasOwnProperty.call(attributes, key);
            };
            const hasDefault = function (key) {
                return Object.prototype.hasOwnProperty.call(blockDefaults, key);
            };
            const getDefaultValue = function (key) {
                return hasDefault(key) ? blockDefaults[key] : undefined;
            };
            const getBooleanValue = function (key, fallback) {
                if (typeof attributes[key] === 'boolean') {
                    return attributes[key];
                }
                const def = getDefaultValue(key);
                if (typeof def === 'boolean') {
                    return def;
                }
                return typeof fallback === 'boolean' ? fallback : false;
            };
            const getNumberValue = function (key, fallback) {
                if (typeof attributes[key] === 'number') {
                    return attributes[key];
                }
                const def = getDefaultValue(key);
                if (typeof def === 'number') {
                    return def;
                }
                return typeof fallback === 'number' ? fallback : undefined;
            };
            const getStringValue = function (key, fallback) {
                if (typeof attributes[key] === 'string' && attributes[key] !== '') {
                    return attributes[key];
                }
                const def = getDefaultValue(key);
                if (typeof def === 'string' && def !== '') {
                    return def;
                }
                return typeof fallback === 'string' ? fallback : '';
            };
            const getInheritableString = function (key, fallback) {
                if (hasAttribute(key) && typeof attributes[key] === 'string') {
                    return attributes[key];
                }
                return typeof fallback === 'string' ? fallback : '';
            };
            const getResetBoolean = function (key, fallback) {
                const value = getDefaultValue(key);
                if (typeof value === 'boolean') {
                    return value;
                }
                return typeof fallback === 'boolean' ? fallback : false;
            };
            const getResetNumber = function (key, fallback) {
                const value = getDefaultValue(key);
                if (typeof value === 'number' && !isNaN(value)) {
                    return value;
                }
                return typeof fallback === 'number' ? fallback : undefined;
            };
            const getResetString = function (key, fallback, allowEmpty) {
                const value = getDefaultValue(key);
                if (typeof value === 'string') {
                    if (value !== '' || allowEmpty) {
                        return value;
                    }
                }
                if (typeof fallback === 'string') {
                    return fallback;
                }
                return allowEmpty ? '' : '';
            };
            const getResetArray = function (key, fallback) {
                const value = getDefaultValue(key);
                if (Array.isArray(value) && value.length) {
                    return value;
                }
                return Array.isArray(fallback) ? fallback : [];
            };

            /**
             * Creates a Pro feature section.
             * Only shows content for Pro users, returns null for free users.
             *
             * @param {string} title - Section title
             * @param {string} description - Feature description (unused when isPro is false)
             * @param {Array} benefitsList - Array of feature benefits (unused when isPro is false)
             * @param {Array} children - Array of control elements
             * @returns {Object|null} Section element for Pro users, null for free users
             */
            const createProPanel = function(title, description, benefitsList, children) {
                const { createElement, Fragment } = wp.element;

                // For free users, don't show anything (no upgrade prompts)
                if (!isPro) {
                    return null;
                }

                // For Pro users, show fully functional controls
                return createElement(
                    Fragment,
                    null,
                    createElement(
                        'div',
                        {
                            className: 'anchorkit-pro-section-header',
                            style: {
                                marginTop: '16px',
                                marginBottom: '12px',
                                paddingTop: '16px',
                                borderTop: '1px solid #e0e0e0'
                            }
                        },
                        createElement('strong', { style: { fontSize: '13px', color: '#1e1e1e' } }, title)
                    ),
                    children
                );
            };

            const stickyValue = getBooleanValue('sticky', false);
            const stickyPositionValue = getStringValue('stickyPosition', 'content');
            const stickyOffsetRaw = getNumberValue('stickyOffset', 20);
            const stickyOffsetValue = typeof stickyOffsetRaw === 'number' ? stickyOffsetRaw : 20;
            const showReadingTimeValue = getBooleanValue('showReadingTime', false);
            const showWordCountValue = getBooleanValue('showWordCount', false);
            const readingSpeedRaw = getNumberValue('readingSpeed', 200);
            const readingSpeedValue = typeof readingSpeedRaw === 'number' ? readingSpeedRaw : 200;
            const timeFormatValue = getStringValue('timeFormat', 'min_read');
            const backToTopLinkValue = getBooleanValue('backToTopLink', false);
            const backToTopTextValue = getStringValue('backToTopText', __('Back to Top', 'anchorkit-table-of-contents'));
            const backToTopFontSizeRaw = getNumberValue('backToTopFontSize', 14);
            const backToTopFontSizeValue = typeof backToTopFontSizeRaw === 'number' ? backToTopFontSizeRaw : 14;
            const globalStylePreset = (blockDefaults && blockDefaults.stylePreset) || 'minimal';
            const stylePresetSelection = attributes.stylePreset || 'inherit';
            const presetLabels = {
                minimal: __('Minimal', 'anchorkit-table-of-contents'),
                classic: __('Classic ⚡', 'anchorkit-table-of-contents'),
                modern: __('Modern ⚡', 'anchorkit-table-of-contents')
            };
            const resolvePresetLabel = function (value) {
                return presetLabels[value] || value;
            };
            const sanitizeMergeMode = function (value) {
                var allowed = ['before', 'after', 'replace'];
                return allowed.indexOf(value) !== -1 ? value : 'after';
            };
            const sanitizeSchemaType = function (value) {
                var allowed = ['Article', 'BlogPosting', 'WebPage', 'HowTo', 'FAQPage', 'NewsArticle', 'TechArticle', 'Course'];
                return allowed.indexOf(value) !== -1 ? value : 'Article';
            };
            const acfEnabledValue = getBooleanValue('acfEnabled', false);
            const acfFieldNamesValue = getInheritableString('acfFieldNames', getDefaultValue('acfFieldNames') || '');
            const acfMergeModeValue = sanitizeMergeMode(
                hasAttribute('acfMergeMode') && typeof attributes.acfMergeMode === 'string' && attributes.acfMergeMode !== ''
                    ? attributes.acfMergeMode
                    : getDefaultValue('acfMergeMode')
            );
            const ampEnabledValue = getBooleanValue('ampEnabled', false);
            const schemaEnabledValue = getBooleanValue('schemaEnabled', false);
            const schemaTypeValue = sanitizeSchemaType(
                hasAttribute('schemaType') && typeof attributes.schemaType === 'string' && attributes.schemaType !== ''
                    ? attributes.schemaType
                    : getDefaultValue('schemaType')
            );
            const customLabelsValue = hasAttribute('customLabels')
                ? attributes.customLabels
                : (getDefaultValue('customLabels') || '');
            const ariaLabelDefault = getDefaultValue('ariaLabel') || (attributes.title || __('Table of Contents', 'anchorkit-table-of-contents'));
            const ariaLabelValue = hasAttribute('ariaLabel')
                ? (typeof attributes.ariaLabel === 'string' ? attributes.ariaLabel : '')
                : ariaLabelDefault;

            useEffect(function () {
                if (!attributes.designOverride && designPreviewMode !== 'light') {
                    setDesignPreviewMode('light');
                }
            }, [attributes.designOverride, designPreviewMode]);

            const renderDesignColorControls = function (mode) {
                const isLight = mode === 'light';
                const resolveValue = function (lightKey, darkKey) {
                    return isLight ? (attributes[lightKey] || '') : (attributes[darkKey] || '');
                };
                const updateValue = function (lightKey, darkKey, color) {
                    const key = isLight ? lightKey : darkKey;
                    const update = {};
                    update[key] = color;
                    setAttributes(update);
                };
                const renderPicker = function (label, lightKey, darkKey) {
                    return wp.element.createElement(
                        BaseControl,
                        { label: label, className: 'anchorkit-color-field' },
                        wp.element.createElement(ColorPicker, {
                            color: resolveValue(lightKey, darkKey),
                            onChangeComplete: function (value) { updateValue(lightKey, darkKey, value?.hex || ''); },
                            disableAlpha: true
                        })
                    );
                };

                return wp.element.createElement(
                    'div',
                    {
                        className: 'anchorkit-design-color-stack anchorkit-design-color-stack--' + (isLight ? 'light' : 'dark')
                    },
                    wp.element.createElement(
                        'p',
                        { style: { fontWeight: 600, margin: '0 0 12px' } },
                        isLight ? __('Design Colors — Light', 'anchorkit-table-of-contents') : __('Design Colors — Dark', 'anchorkit-table-of-contents')
                    ),
                    renderPicker(__('Background', 'anchorkit-table-of-contents'), 'bgColorLight', 'bgColorDark'),
                    renderPicker(__('Text', 'anchorkit-table-of-contents'), 'textColorLight', 'textColorDark'),
                    renderPicker(__('Link', 'anchorkit-table-of-contents'), 'linkColorLight', 'linkColorDark'),
                    renderPicker(__('Link Hover', 'anchorkit-table-of-contents'), 'linkHoverColorLight', 'linkHoverColorDark'),
                    renderPicker(__('Border', 'anchorkit-table-of-contents'), 'borderColorLight', 'borderColorDark'),
                    renderPicker(__('Bullet', 'anchorkit-table-of-contents'), 'bulletColorLight', 'bulletColorDark')
                );
            };

            const renderShadowControls = function (mode) {
                const isLight = mode === 'light';
                const suffix = isLight ? 'Light' : 'Dark';
                const modeLabel = isLight ? __('Light Mode Shadow', 'anchorkit-table-of-contents') : __('Dark Mode Shadow', 'anchorkit-table-of-contents');
                const defaults = isLight
                    ? { opacity: 0.1, h: 0, v: 4, b: 6, s: 0 }
                    : { opacity: 0.3, h: 0, v: 2, b: 8, s: 0 };

                const makeKey = function (base) {
                    return base + suffix;
                };

                const getValue = function (key, fallback) {
                    const fullKey = makeKey(key);
                    const value = attributes[fullKey];
                    return typeof value === 'number' || typeof value === 'string' ? value : fallback;
                };

                const updateValue = function (key, value) {
                    const fullKey = makeKey(key);
                    const update = {};
                    update[fullKey] = value;
                    setAttributes(update);
                };

                return wp.element.createElement(
                    Fragment,
                    null,
                    wp.element.createElement(
                        'p',
                        { style: { marginBottom: '8px', fontWeight: 600 } },
                        modeLabel
                    ),
                    wp.element.createElement(
                        BaseControl,
                        { label: __('Color', 'anchorkit-table-of-contents') },
                        wp.element.createElement(ColorPicker, {
                            color: attributes[makeKey('shadowColor')] || '#000000',
                            onChangeComplete: function (value) { updateValue('shadowColor', value?.hex || ''); },
                            disableAlpha: true
                        })
                    ),
                    wp.element.createElement(RangeControl, {
                        __nextHasNoMarginBottom: true,
                        __next40pxDefaultSize: true,
                        label: __('Opacity', 'anchorkit-table-of-contents'),
                        value: typeof attributes[makeKey('shadowOpacity')] === 'number' ? attributes[makeKey('shadowOpacity')] : defaults.opacity,
                        onChange: function (value) { updateValue('shadowOpacity', value); },
                        min: 0, max: 1, step: 0.05
                    }),
                    wp.element.createElement(RangeControl, {
                        __nextHasNoMarginBottom: true,
                        __next40pxDefaultSize: true,
                        label: __('Horizontal Offset (px)', 'anchorkit-table-of-contents'),
                        value: getValue('shadowHOffset', defaults.h),
                        onChange: function (value) { updateValue('shadowHOffset', value); },
                        min: -100, max: 100
                    }),
                    wp.element.createElement(RangeControl, {
                        __nextHasNoMarginBottom: true,
                        __next40pxDefaultSize: true,
                        label: __('Vertical Offset (px)', 'anchorkit-table-of-contents'),
                        value: getValue('shadowVOffset', defaults.v),
                        onChange: function (value) { updateValue('shadowVOffset', value); },
                        min: -100, max: 100
                    }),
                    wp.element.createElement(RangeControl, {
                        __nextHasNoMarginBottom: true,
                        __next40pxDefaultSize: true,
                        label: __('Blur (px)', 'anchorkit-table-of-contents'),
                        value: getValue('shadowBlur', defaults.b),
                        onChange: function (value) { updateValue('shadowBlur', value); },
                        min: 0, max: 200
                    }),
                    wp.element.createElement(RangeControl, {
                        __nextHasNoMarginBottom: true,
                        __next40pxDefaultSize: true,
                        label: __('Spread (px)', 'anchorkit-table-of-contents'),
                        value: getValue('shadowSpread', defaults.s),
                        onChange: function (value) { updateValue('shadowSpread', value); },
                        min: -50, max: 50
                    })
                );
            };

            // Check if settings are available
            if (typeof anchorkitBlockSettings === 'undefined') {
                return wp.element.createElement(
                    Placeholder,
                    {
                        icon: blockIcon,
                        label: __('Table of Contents', 'anchorkit-table-of-contents'),
                        instructions: __('Loading...', 'anchorkit-table-of-contents'),
                    }
                );
            }

            // Check if TOC is enabled in settings
            if (!anchorkitBlockSettings.isEnabled) {
                return wp.element.createElement(
                    Placeholder,
                    {
                        icon: blockIcon,
                        label: __('Table of Contents', 'anchorkit-table-of-contents'),
                        instructions: __('The Table of Contents feature is currently disabled.', 'anchorkit-table-of-contents'),
                    },
                    wp.element.createElement(
                        Button,
                        {
                            variant: 'primary',
                            href: anchorkitBlockSettings.settingsUrl,
                            target: '_blank',
                        },
                        __('Enable in Settings', 'anchorkit-table-of-contents')
                    )
                );
            }

            // Helper to clear all per-block design overrides back to preset defaults
            var getDesignOverrideResetAttributes = function () {
                return {
                    designOverride: false,
                    theme: 'inherit',
                    boxShadowEnabled: false,
                    containerPadding: undefined,
                    containerBorderWidth: undefined,
                    containerBorderRadius: undefined,
                    // Light mode colors
                    bgColorLight: '',
                    textColorLight: '',
                    linkColorLight: '',
                    linkHoverColorLight: '',
                    borderColorLight: '',
                    bulletColorLight: '',
                    // Dark mode colors
                    bgColorDark: '',
                    textColorDark: '',
                    linkColorDark: '',
                    linkHoverColorDark: '',
                    borderColorDark: '',
                    bulletColorDark: '',
                    // Light shadow defaults
                    shadowHOffsetLight: 0,
                    shadowVOffsetLight: 4,
                    shadowBlurLight: 6,
                    shadowSpreadLight: 0,
                    shadowColorLight: '#000000',
                    shadowOpacityLight: 0.1,
                    // Dark shadow defaults
                    shadowHOffsetDark: 0,
                    shadowVOffsetDark: 2,
                    shadowBlurDark: 8,
                    shadowSpreadDark: 0,
                    shadowColorDark: '#000000',
                    shadowOpacityDark: 0.3
                };
            };

            // Reset Functions
            var resetAllSettings = function () {
                if (confirm(__('Are you sure you want to reset ALL TOC settings to their default values? This will affect Content, Behavior, Appearance, and all other settings. This cannot be undone.', 'anchorkit-table-of-contents'))) {
                    var defaultSettings = {
                        title: getResetString('title', 'Table of Contents'),
                        showTitle: getResetBoolean('showTitle', true),
                        headingLevels: getResetArray('headingLevels', ['h2', 'h3', 'h4']),
                        excludeSelectors: getResetString('excludeSelectors', '', true),
                        excludeKeywords: getResetString('excludeKeywords', '', true),
                        excludeRegex: getResetString('excludeRegex', '', true),
                        minHeadingsToShow: getResetNumber('minHeadingsToShow', 2),
                        minHeadingDepth: getResetNumber('minHeadingDepth', 1),
                        maxHeadingDepth: getResetNumber('maxHeadingDepth', 6),
                        collapsible: getResetBoolean('collapsible', true),
                        initialState: getResetString('initialState', 'expanded'),
                        smoothScroll: getResetBoolean('smoothScroll', true),
                        scrollOffset: getResetNumber('scrollOffset', 0),
                        scrollEasing: getResetString('scrollEasing', 'ease-in-out'),
                        scrollDuration: getResetNumber('scrollDuration', 500),
                        hierarchicalView: getResetBoolean('hierarchicalView', true),
                        sticky: getResetBoolean('sticky', false),
                        stickyPosition: getResetString('stickyPosition', 'content'),
                        stickyOffset: getResetNumber('stickyOffset', 20),
                        scrollSpy: getResetBoolean('scrollSpy', !!(anchorkitBlockSettings && anchorkitBlockSettings.isPro)),
                        viewMoreEnabled: getResetBoolean('viewMoreEnabled', false),
                        viewMoreInitialCount: getResetNumber('viewMoreInitialCount', 5),
                        viewMoreText: getResetString('viewMoreText', 'View More', true),
                        viewLessText: getResetString('viewLessText', 'View Less', true),
                        stylePreset: 'inherit',
                        bulletStyle: getResetString('bulletStyle', 'disc'),
                        bulletCharacter: getResetString('bulletCharacter', '•', true),
                        bulletColor: '#0073AA',
                        showNumerals: getResetBoolean('showNumerals', false),
                        numberingStyle: getResetString('numberingStyle', 'hierarchical'),
                        numberingFormat: getResetString('numberingFormat', 'decimal'),
                        numberingSeparator: getResetString('numberingSeparator', '.', true),
                        entranceAnimation: getResetBoolean('entranceAnimation', false),
                        animationType: getResetString('animationType', 'fade'),
                        hideOnMobile: getResetBoolean('hideOnMobile', false),
                        mobileBreakpoint: getResetNumber('mobileBreakpoint', 782),
                        tocWidth: getResetNumber('tocWidth', 100),
                        tocAlignment: getResetString('tocAlignment', 'center'),
                        tocFloat: getResetString('tocFloat', 'none'),
                        advancedTypographyOverride: getResetBoolean('advancedTypographyOverride', false),
                        titleFontSize: getResetNumber('titleFontSize', 20),
                        h2FontSize: getResetNumber('h2FontSize', 18),
                        h3FontSize: getResetNumber('h3FontSize', 16),
                        h4FontSize: getResetNumber('h4FontSize', 14),
                        h5FontSize: getResetNumber('h5FontSize', 13),
                        h6FontSize: getResetNumber('h6FontSize', 12),
                        lineHeight: getResetNumber('lineHeight', 1.6),
                        letterSpacing: getResetNumber('letterSpacing', 0),
                        textTransform: getResetString('textTransform', 'none'),
                        linkUnderline: getResetString('linkUnderline', 'none'),
                        showReadingTime: getResetBoolean('showReadingTime', false),
                        showWordCount: getResetBoolean('showWordCount', false),
                        readingSpeed: getResetNumber('readingSpeed', 200),
                        timeFormat: getResetString('timeFormat', 'min_read'),
                        backToTopLink: getResetBoolean('backToTopLink', false),
                        backToTopText: getResetString('backToTopText', __('Back to Top', 'anchorkit-table-of-contents'), true),
                        backToTopFontSize: getResetNumber('backToTopFontSize', 14),
                        schemaEnabled: getResetBoolean('schemaEnabled', false),
                        schemaType: getResetString('schemaType', 'Article'),
                        ariaLabel: getResetString('ariaLabel', '', true),
                        customCssClass: getResetString('customCssClass', '', true),
                        customId: getResetString('customId', '', true),
                        customLabels: getResetString('customLabels', '', true),
                        acfEnabled: getResetBoolean('acfEnabled', false),
                        acfFieldNames: getResetString('acfFieldNames', '', true),
                        acfMergeMode: getResetString('acfMergeMode', 'after'),
                        anchorFormat: getResetString('anchorFormat', 'auto'),
                        anchorPrefix: getResetString('anchorPrefix', 'section', true),
                        ampEnabled: getResetBoolean('ampEnabled', false)
                    };
                    setAttributes(Object.assign({}, defaultSettings, getDesignOverrideResetAttributes()));
                }
            };

            var resetContentSettings = function () {
                if (confirm(__('Reset Content settings to defaults?', 'anchorkit-table-of-contents'))) {
                    setAttributes({
                        title: getResetString('title', 'Table of Contents'),
                        showTitle: getResetBoolean('showTitle', true),
                        headingLevels: getResetArray('headingLevels', ['h2', 'h3', 'h4']),
                        excludeSelectors: getResetString('excludeSelectors', '', true),
                        excludeKeywords: getResetString('excludeKeywords', '', true),
                        excludeRegex: getResetString('excludeRegex', '', true),
                        minHeadingsToShow: getResetNumber('minHeadingsToShow', 2),
                        minHeadingDepth: getResetNumber('minHeadingDepth', 1),
                        maxHeadingDepth: getResetNumber('maxHeadingDepth', 6),
                        showReadingTime: getResetBoolean('showReadingTime', false),
                        showWordCount: getResetBoolean('showWordCount', false),
                        readingSpeed: getResetNumber('readingSpeed', 200),
                        timeFormat: getResetString('timeFormat', 'min_read')
                    });
                }
            };

            var resetBehaviorSettings = function () {
                if (confirm(__('Reset Behavior settings to defaults?', 'anchorkit-table-of-contents'))) {
                    setAttributes({
                        collapsible: getResetBoolean('collapsible', true),
                        initialState: getResetString('initialState', 'expanded'),
                        smoothScroll: getResetBoolean('smoothScroll', true),
                        scrollOffset: getResetNumber('scrollOffset', 0),
                        scrollEasing: getResetString('scrollEasing', 'ease-in-out'),
                        scrollDuration: getResetNumber('scrollDuration', 500),
                        hierarchicalView: getResetBoolean('hierarchicalView', true),
                        sticky: getResetBoolean('sticky', false),
                        stickyPosition: getResetString('stickyPosition', 'content'),
                        stickyOffset: getResetNumber('stickyOffset', 20),
                        scrollSpy: getResetBoolean('scrollSpy', !!(anchorkitBlockSettings && anchorkitBlockSettings.isPro)),
                        viewMoreEnabled: getResetBoolean('viewMoreEnabled', false),
                        viewMoreInitialCount: getResetNumber('viewMoreInitialCount', 5),
                        viewMoreText: getResetString('viewMoreText', 'View More', true),
                        viewLessText: getResetString('viewLessText', 'View Less', true),
                        backToTopLink: getResetBoolean('backToTopLink', false),
                        backToTopText: getResetString('backToTopText', __('Back to Top', 'anchorkit-table-of-contents'), true),
                        backToTopFontSize: getResetNumber('backToTopFontSize', 14)
                    });
                }
            };

            var resetAppearanceSettings = function () {
                if (confirm(__('Reset Appearance settings to defaults?', 'anchorkit-table-of-contents'))) {
                    setAttributes(Object.assign({}, getDesignOverrideResetAttributes(), {
                        stylePreset: 'inherit',
                        bulletStyle: getResetString('bulletStyle', 'disc'),
                        bulletCharacter: getResetString('bulletCharacter', '•', true),
                        bulletColor: '#0073AA',
                        showNumerals: getResetBoolean('showNumerals', false),
                        numberingStyle: getResetString('numberingStyle', 'hierarchical'),
                        numberingFormat: getResetString('numberingFormat', 'decimal'),
                        numberingSeparator: getResetString('numberingSeparator', '.', true),
                        entranceAnimation: getResetBoolean('entranceAnimation', false),
                        animationType: getResetString('animationType', 'fade'),
                        advancedTypographyOverride: getResetBoolean('advancedTypographyOverride', false),
                        titleFontSize: getResetNumber('titleFontSize', 20),
                        h2FontSize: getResetNumber('h2FontSize', 18),
                        h3FontSize: getResetNumber('h3FontSize', 16),
                        h4FontSize: getResetNumber('h4FontSize', 14),
                        h5FontSize: getResetNumber('h5FontSize', 13),
                        h6FontSize: getResetNumber('h6FontSize', 12),
                        lineHeight: getResetNumber('lineHeight', 1.6),
                        letterSpacing: getResetNumber('letterSpacing', 0),
                        textTransform: getResetString('textTransform', 'none'),
                        linkUnderline: getResetString('linkUnderline', 'none')
                    }));
                }
            };

            var resetAdvancedSettings = function () {
                if (confirm(__('Reset Advanced settings to defaults?', 'anchorkit-table-of-contents'))) {
                    setAttributes({
                        hideOnMobile: getResetBoolean('hideOnMobile', false),
                        mobileBreakpoint: getResetNumber('mobileBreakpoint', 782),
                        tocWidth: getResetNumber('tocWidth', 100),
                        tocAlignment: getResetString('tocAlignment', 'center'),
                        tocFloat: getResetString('tocFloat', 'none'),
                        customCssClass: getResetString('customCssClass', '', true),
                        customId: getResetString('customId', '', true),
                        ariaLabel: getResetString('ariaLabel', '', true)
                    });
                }
            };

            var resetSeoSettings = function () {
                if (confirm(__('Reset Structure & SEO settings to defaults?', 'anchorkit-table-of-contents'))) {
                    setAttributes({
                        schemaEnabled: getResetBoolean('schemaEnabled', false),
                        schemaType: getResetString('schemaType', 'Article'),
                        acfEnabled: getResetBoolean('acfEnabled', false),
                        acfFieldNames: getResetString('acfFieldNames', '', true),
                        acfMergeMode: getResetString('acfMergeMode', 'after'),
                        anchorFormat: getResetString('anchorFormat', 'auto'),
                        anchorPrefix: getResetString('anchorPrefix', 'section', true),
                        ampEnabled: getResetBoolean('ampEnabled', false)
                    });
                }
            };

            // Build the editor UI
            const editorControls = [
                // Inspector Controls (Sidebar Settings)
                wp.element.createElement(
                    InspectorControls,
                    { key: 'inspector' },

                    // Content Settings
                    wp.element.createElement(
                        PanelBody,
                        {
                            title: __('Content', 'anchorkit-table-of-contents'),
                            initialOpen: true
                        },
                        wp.element.createElement(
                            Notice,
                            {
                                status: 'info',
                                isDismissible: false,
                                className: 'anchorkit-block-settings-notice',
                                style: { marginBottom: '16px' }
                            },
                            __('Changes here override your global AnchorKit settings for this post only.', 'anchorkit-table-of-contents')
                        ),
                        wp.element.createElement(
                            'div',
                            {
                                style: {
                                    marginBottom: '24px',
                                    paddingBottom: '16px',
                                    borderBottom: '1px solid #ddd'
                                }
                            },
                            wp.element.createElement(
                                Button,
                                {
                                    variant: 'secondary',
                                    isDestructive: true,
                                    onClick: resetAllSettings,
                                    style: { width: '100%', justifyContent: 'center' }
                                },
                                '↻ ' + __('Reset All Settings to Defaults', 'anchorkit-table-of-contents')
                            )
                        ),
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Show Title', 'anchorkit-table-of-contents'),
                                checked: attributes.showTitle,
                                onChange: function (value) { setAttributes({ showTitle: value }); },
                                help: __('Disable to hide the heading entirely.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.showTitle && wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('TOC Title', 'anchorkit-table-of-contents'),
                                value: attributes.title,
                                onChange: function (value) { setAttributes({ title: value }); },
                                help: __('Displayed above the TOC when enabled.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            'div',
                            { className: 'anchorkit-heading-levels-group' },
                            wp.element.createElement('p', { style: { marginBottom: '4px', fontWeight: 600 } }, __('Include Heading Levels', 'anchorkit-table-of-contents')),
                            wp.element.createElement('p', { style: { marginTop: 0, marginBottom: '8px', fontSize: '12px', color: '#50575e' } }, __('Defaults to H2-H4 when nothing is selected. Use this to fine-tune the outline for this post only.', 'anchorkit-table-of-contents')),
                            ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(function (level) {
                                return wp.element.createElement(CheckboxControl, {
                                    __nextHasNoMarginBottom: true,
                                    key: level,
                                    label: level.toUpperCase(),
                                    checked: Array.isArray(attributes.headingLevels) ? attributes.headingLevels.includes(level) : false,
                                    onChange: function (checked) {
                                        var current = Array.isArray(attributes.headingLevels) ? attributes.headingLevels.slice() : [];
                                        if (checked) {
                                            if (!current.includes(level)) current.push(level);
                                        } else {
                                            current = current.filter(function (item) { return item !== level; });
                                            if (!current.length) {
                                                current = ['h2'];
                                            }
                                        }
                                        current.sort(function (a, b) {
                                            var order = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
                                            return order.indexOf(a) - order.indexOf(b);
                                        });
                                        setAttributes({ headingLevels: current });
                                    }
                                });
                            })
                        ),
                        wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Minimum Headings to Show', 'anchorkit-table-of-contents'),
                                value: attributes.minHeadingsToShow,
                                onChange: function (value) { setAttributes({ minHeadingsToShow: value }); },
                                min: 1,
                                max: 10,
                                help: __('TOC renders only when at least this many headings exist.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Exclude Selectors (CSS)', 'anchorkit-table-of-contents'),
                                value: attributes.excludeSelectors,
                                onChange: function (value) { setAttributes({ excludeSelectors: value }); },
                                help: __('Comma-separated CSS selectors. Example: .toc-exclude, #skip-heading', 'anchorkit-table-of-contents'),
                                placeholder: '.toc-exclude, .no-toc'
                            }
                        ),
                        isPro && wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Exclude Keywords', 'anchorkit-table-of-contents'),
                                value: attributes.excludeKeywords,
                                onChange: function (value) { setAttributes({ excludeKeywords: value }); },
                                help: __('Comma-separated keywords. Headings containing these words will be excluded.', 'anchorkit-table-of-contents'),
                                placeholder: 'sponsored, advertisement'
                            }
                        ),
                        isPro && wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Exclude Words', 'anchorkit-table-of-contents'),
                                value: attributes.excludeRegex,
                                onChange: function (value) { setAttributes({ excludeRegex: value }); },
                                help: __('Remove words from TOC labels. Example: "Step 1: Title" becomes "Title"', 'anchorkit-table-of-contents'),
                                placeholder: __('step, chapter, section', 'anchorkit-table-of-contents')
                            }
                        ),

                        // PRO: Reading Time & Word Count
                        createProPanel(
                            __('Reading Time & Word Count', 'anchorkit-table-of-contents'),
                            __('Display estimated reading time and word counts for each section in your Table of Contents to help readers manage their time.', 'anchorkit-table-of-contents'),
                            [
                                __('Estimated reading time per section', 'anchorkit-table-of-contents'),
                                __('Customizable reading speed (WPM)', 'anchorkit-table-of-contents'),
                                __('Word count display option', 'anchorkit-table-of-contents'),
                                __('Multiple time format styles', 'anchorkit-table-of-contents')
                            ],
                            [
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        label: __('Show Reading Time', 'anchorkit-table-of-contents'),
                                        checked: showReadingTimeValue,
                                        onChange: function (value) { setAttributes({ showReadingTime: value }); },
                                        help: __('Display estimated reading time beside items.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                showReadingTimeValue && wp.element.createElement(
                                    RangeControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Reading Speed (WPM)', 'anchorkit-table-of-contents'),
                                        value: readingSpeedValue,
                                        onChange: function (value) { setAttributes({ readingSpeed: value }); },
                                        min: 100,
                                        max: 400,
                                        help: __('Words per minute used to compute timing.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                showReadingTimeValue && wp.element.createElement(
                                    SelectControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Time Format', 'anchorkit-table-of-contents'),
                                        value: timeFormatValue,
                                        options: [
                                            { label: __('"5 min read"', 'anchorkit-table-of-contents'), value: 'min_read' },
                                            { label: __('"~5 minutes"', 'anchorkit-table-of-contents'), value: 'minutes' },
                                            { label: __('"5m"', 'anchorkit-table-of-contents'), value: 'short' }
                                        ],
                                        onChange: function (value) { setAttributes({ timeFormat: value }); },
                                        help: __('Choose how the reading time text should appear.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        label: __('Show Word Count', 'anchorkit-table-of-contents'),
                                        checked: showWordCountValue,
                                        onChange: function (value) { setAttributes({ showWordCount: value }); },
                                        help: __('Display the detected word count for each heading.', 'anchorkit-table-of-contents')
                                    }
                                )
                            ]
                        ),
                        wp.element.createElement(
                            'div',
                            { style: { marginTop: '20px', paddingTop: '16px', borderTop: '1px solid #e0e0e0', textAlign: 'center' } },
                            wp.element.createElement(
                                Button,
                                {
                                    variant: 'link',
                                    isDestructive: true,
                                    onClick: resetContentSettings,
                                    style: { fontSize: '13px' }
                                },
                                '↻ ' + __('Reset Content Settings', 'anchorkit-table-of-contents')
                            )
                        )
                    ),

                    // Behavior Settings
                    wp.element.createElement(
                        PanelBody,
                        {
                            title: __('Behavior', 'anchorkit-table-of-contents'),
                            initialOpen: false
                        },
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Collapsible', 'anchorkit-table-of-contents'),
                                checked: attributes.collapsible,
                                onChange: function (value) { setAttributes({ collapsible: value }); },
                                help: __('Allow users to collapse/expand the TOC.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.collapsible && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Initial State', 'anchorkit-table-of-contents'),
                                value: attributes.initialState,
                                options: [
                                    { label: __('Expanded', 'anchorkit-table-of-contents'), value: 'expanded' },
                                    { label: __('Collapsed', 'anchorkit-table-of-contents'), value: 'collapsed' }
                                ],
                                onChange: function (value) { setAttributes({ initialState: value }); },
                                help: __('Default state when the page loads.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Smooth Scrolling', 'anchorkit-table-of-contents'),
                                checked: attributes.smoothScroll,
                                onChange: function (value) { setAttributes({ smoothScroll: value }); },
                                help: __('Enable smooth scrolling to anchors.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Scroll Offset (px)', 'anchorkit-table-of-contents'),
                                value: attributes.scrollOffset,
                                onChange: function (value) { setAttributes({ scrollOffset: value }); },
                                min: 0,
                                max: 200,
                                help: __('Distance from top when scrolling to headings.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.smoothScroll && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Scroll Easing', 'anchorkit-table-of-contents'),
                                value: attributes.scrollEasing,
                                options: [
                                    { label: __('Ease In-Out', 'anchorkit-table-of-contents'), value: 'ease-in-out' },
                                    { label: __('Ease In', 'anchorkit-table-of-contents'), value: 'ease-in' },
                                    { label: __('Ease Out', 'anchorkit-table-of-contents'), value: 'ease-out' },
                                    { label: __('Ease', 'anchorkit-table-of-contents'), value: 'ease' },
                                    { label: __('Linear', 'anchorkit-table-of-contents'), value: 'linear' },
                                    { label: __('Bouncy', 'anchorkit-table-of-contents'), value: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)' }
                                ],
                                onChange: function (value) { setAttributes({ scrollEasing: value }); },
                                help: __('Custom easing curve for smooth scroll animation.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.smoothScroll && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Scroll Duration (ms)', 'anchorkit-table-of-contents'),
                                value: attributes.scrollDuration,
                                onChange: function (value) { setAttributes({ scrollDuration: value }); },
                                min: 100,
                                max: 2000,
                                step: 50,
                                help: __('How long the smooth scroll animation should run.', 'anchorkit-table-of-contents')
                            }
                        ),

                        // PRO: Sticky TOC & Scroll Spy
                        createProPanel(
                            __('Sticky TOC & Scroll Spy', 'anchorkit-table-of-contents'),
                            __('Keep your Table of Contents visible while users scroll, with intelligent scroll spy highlighting and sidebar positioning options.', 'anchorkit-table-of-contents'),
                            [
                                __('Sticky positioning with customizable offset', 'anchorkit-table-of-contents'),
                                __('Scroll spy - highlights current section', 'anchorkit-table-of-contents'),
                                __('Sidebar placement (left, right, or in-content)', 'anchorkit-table-of-contents'),
                                __('Optional "Back to Top" link', 'anchorkit-table-of-contents')
                            ],
                            [
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        label: __('Enable Sticky TOC', 'anchorkit-table-of-contents'),
                                        checked: stickyValue,
                                        onChange: function (value) { setAttributes({ sticky: value }); },
                                        help: __('Keep TOC visible while scrolling.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && wp.element.createElement(
                                    SelectControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Sticky Position', 'anchorkit-table-of-contents'),
                                        value: stickyPositionValue,
                                        options: [
                                            { label: __('In Content', 'anchorkit-table-of-contents'), value: 'content' },
                                            { label: __('Left Sidebar', 'anchorkit-table-of-contents'), value: 'left' },
                                            { label: __('Right Sidebar', 'anchorkit-table-of-contents'), value: 'right' }
                                        ],
                                        onChange: function (value) { setAttributes({ stickyPosition: value }); },
                                        help: __('Where to position the sticky TOC.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && wp.element.createElement(
                                    RangeControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Sticky Offset (px)', 'anchorkit-table-of-contents'),
                                        value: stickyOffsetValue,
                                        onChange: function (value) { setAttributes({ stickyOffset: value }); },
                                        min: 0,
                                        max: 200,
                                        help: __('Distance from top when sticky.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && wp.element.createElement(
                                    ToggleControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        label: __('Scroll Spy', 'anchorkit-table-of-contents'),
                                        checked: attributes.scrollSpy,
                                        onChange: function (value) { setAttributes({ scrollSpy: value }); },
                                        help: __('Highlight current section as you scroll.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && wp.element.createElement(
                                    ToggleControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        label: __('Back to Top Link', 'anchorkit-table-of-contents'),
                                        checked: backToTopLinkValue,
                                        onChange: function (value) { setAttributes({ backToTopLink: value }); },
                                        help: __('Add a "Back to Top" link at the end of the sticky TOC.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && backToTopLinkValue && wp.element.createElement(
                                    TextControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Back to Top Text', 'anchorkit-table-of-contents'),
                                        value: backToTopTextValue,
                                        onChange: function (value) { setAttributes({ backToTopText: value }); },
                                        help: __('Text displayed for the back to top link.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                stickyValue && backToTopLinkValue && wp.element.createElement(
                                    RangeControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Back to Top Font Size (px)', 'anchorkit-table-of-contents'),
                                        value: backToTopFontSizeValue,
                                        onChange: function (value) { setAttributes({ backToTopFontSize: value }); },
                                        min: 10,
                                        max: 32,
                                        help: __('Font size for the back to top link.', 'anchorkit-table-of-contents')
                                    }
                                )
                            ]
                        ),

                        // PRO: View More
                        isPro && wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('View More', 'anchorkit-table-of-contents'),
                                checked: attributes.viewMoreEnabled,
                                onChange: function (value) { setAttributes({ viewMoreEnabled: value }); },
                                help: __('Show "View More" button to expand/collapse additional items.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.viewMoreEnabled && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Initial Item Count', 'anchorkit-table-of-contents'),
                                value: attributes.viewMoreInitialCount,
                                onChange: function (value) { setAttributes({ viewMoreInitialCount: value }); },
                                min: 1,
                                max: 20,
                                help: __('Number of items to show initially.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.viewMoreEnabled && wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('View More Text', 'anchorkit-table-of-contents'),
                                value: attributes.viewMoreText,
                                onChange: function (value) { setAttributes({ viewMoreText: value }); },
                                help: __('Text for the expand button.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.viewMoreEnabled && wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('View Less Text', 'anchorkit-table-of-contents'),
                                value: attributes.viewLessText,
                                onChange: function (value) { setAttributes({ viewLessText: value }); },
                                help: __('Text for the collapse button.', 'anchorkit-table-of-contents')
                            }
                        ),

                        wp.element.createElement(
                            'div',
                            { style: { marginTop: '20px', paddingTop: '16px', borderTop: '1px solid #e0e0e0', textAlign: 'center' } },
                            wp.element.createElement(
                                Button,
                                {
                                    variant: 'link',
                                    isDestructive: true,
                                    onClick: resetBehaviorSettings,
                                    style: { fontSize: '13px' }
                                },
                                '↻ ' + __('Reset Behavior Settings', 'anchorkit-table-of-contents')
                            )
                        )
                    ),

                    // Appearance
                    wp.element.createElement(
                        PanelBody,
                        {
                            title: __('Appearance', 'anchorkit-table-of-contents'),
                            initialOpen: false
                        },
                        // Design Override Toggle (Pro)
                        isPro && wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Customize Design (per block)', 'anchorkit-table-of-contents'),
                                checked: !!attributes.designOverride,
                                onChange: function (value) { setAttributes({ designOverride: value }); },
                                help: __('Enable to override global design for this block.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.designOverride && wp.element.createElement(
                            Notice,
                            { status: 'info', isDismissible: false },
                            __('Leave any color empty to inherit the active theme\'s value.', 'anchorkit-table-of-contents')
                        ),
                        wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Style Preset', 'anchorkit-table-of-contents'),
                                value: stylePresetSelection,
                                options: isPro ? [
                                    {
                                        label: sprintf(__('Use Global Preset (%s)', 'anchorkit-table-of-contents'), resolvePresetLabel(globalStylePreset)),
                                        value: 'inherit'
                                    },
                                    { label: __('Minimal', 'anchorkit-table-of-contents'), value: 'minimal' },
                                    { label: __('Classic', 'anchorkit-table-of-contents'), value: 'classic' },
                                    { label: __('Modern', 'anchorkit-table-of-contents'), value: 'modern' }
                                ] : [
                                    {
                                        label: sprintf(__('Use Global Preset (%s)', 'anchorkit-table-of-contents'), resolvePresetLabel(globalStylePreset)),
                                        value: 'inherit'
                                    },
                                    { label: __('Minimal', 'anchorkit-table-of-contents'), value: 'minimal' }
                                ],
                                onChange: function (value) { setAttributes({ stylePreset: value }); },
                                help: __('Choose a visual style preset.', 'anchorkit-table-of-contents')
                            }
                        ),
                        // Live theme override (affects frontend rendering) - Pro only
                        isPro && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Theme Override (Live Output)', 'anchorkit-table-of-contents'),
                                value: attributes.theme || 'inherit',
                                options: [
                                    { label: __('Inherit Global', 'anchorkit-table-of-contents'), value: 'inherit' },
                                    { label: __('System (follow visitor preference)', 'anchorkit-table-of-contents'), value: 'system' },
                                    { label: __('Light', 'anchorkit-table-of-contents'), value: 'light' },
                                    { label: __('Dark', 'anchorkit-table-of-contents'), value: 'dark' }
                                ],
                                onChange: function (value) { setAttributes({ theme: value }); },
                                help: __('Controls what visitors see on the live site. "System" follows each visitor\'s OS preference.', 'anchorkit-table-of-contents')
                            }
                        ),
                        // Sticky wrapper for EDIT MODE and all design override sections (until Box Shadow)
                        isPro && attributes.designOverride && wp.element.createElement(
                            'div',
                            { className: 'anchorkit-design-override-sticky-wrapper' },
                            // Editor preview toggle for editing light/dark variants
                            wp.element.createElement(
                                BaseControl,
                                {
                                    label: __('Edit Mode', 'anchorkit-table-of-contents'),
                                    help: __('Switch between configuring the Light and Dark versions. Only affects the editor preview.', 'anchorkit-table-of-contents'),
                                    className: 'anchorkit-edit-mode-control'
                                },
                                wp.element.createElement(
                                    ButtonGroup,
                                    null,
                                    wp.element.createElement(
                                        Button,
                                        {
                                            variant: designPreviewMode === 'light' ? 'primary' : 'secondary',
                                            onClick: function () { setDesignPreviewMode('light'); },
                                            className: 'anchorkit-edit-mode-button'
                                        },
                                        wp.element.createElement(
                                            'span',
                                            { className: 'anchorkit-edit-mode-icon', 'aria-hidden': 'true' },
                                            wp.element.createElement('svg', {
                                                xmlns: 'http://www.w3.org/2000/svg',
                                                viewBox: '0 0 24 24',
                                                width: 14,
                                                height: 14,
                                                fill: 'none',
                                                stroke: 'currentColor',
                                                strokeWidth: 2,
                                                style: { marginRight: '6px' }
                                            },
                                                wp.element.createElement('circle', { cx: 12, cy: 12, r: 5 }),
                                                wp.element.createElement('line', { x1: 12, y1: 1, x2: 12, y2: 3 }),
                                                wp.element.createElement('line', { x1: 12, y1: 21, x2: 12, y2: 23 }),
                                                wp.element.createElement('line', { x1: 4.22, y1: 4.22, x2: 5.64, y2: 5.64 }),
                                                wp.element.createElement('line', { x1: 18.36, y1: 18.36, x2: 19.78, y2: 19.78 }),
                                                wp.element.createElement('line', { x1: 1, y1: 12, x2: 3, y2: 12 }),
                                                wp.element.createElement('line', { x1: 21, y1: 12, x2: 23, y2: 12 }),
                                                wp.element.createElement('line', { x1: 4.22, y1: 19.78, x2: 5.64, y2: 18.36 }),
                                                wp.element.createElement('line', { x1: 18.36, y1: 5.64, x2: 19.78, y2: 4.22 })
                                            ),
                                            __('Light', 'anchorkit-table-of-contents')
                                        )
                                    ),
                                    wp.element.createElement(
                                        Button,
                                        {
                                            variant: designPreviewMode === 'dark' ? 'primary' : 'secondary',
                                            onClick: function () { setDesignPreviewMode('dark'); },
                                            className: 'anchorkit-edit-mode-button'
                                        },
                                        wp.element.createElement(
                                            'span',
                                            { className: 'anchorkit-edit-mode-icon', 'aria-hidden': 'true' },
                                            wp.element.createElement('svg', {
                                                xmlns: 'http://www.w3.org/2000/svg',
                                                viewBox: '0 0 24 24',
                                                width: 14,
                                                height: 14,
                                                fill: 'none',
                                                stroke: 'currentColor',
                                                strokeWidth: 2,
                                                style: { marginRight: '6px' }
                                            },
                                                wp.element.createElement('path', { d: 'M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z' })
                                            ),
                                            __('Dark', 'anchorkit-table-of-contents')
                                        )
                                    )
                                )
                            ),
                            isPro && attributes.designOverride && wp.element.createElement(
                                SelectControl,
                                {
                                    __nextHasNoMarginBottom: true,
                                    __next40pxDefaultSize: true,
                                    label: __('Bullet Style ⚡', 'anchorkit-table-of-contents'),
                                    value: attributes.bulletStyle,
                                    options: [
                                        { label: __('None', 'anchorkit-table-of-contents'), value: 'none' },
                                        { label: __('Disc', 'anchorkit-table-of-contents'), value: 'disc' },
                                        { label: __('Circle', 'anchorkit-table-of-contents'), value: 'circle' },
                                        { label: __('Square', 'anchorkit-table-of-contents'), value: 'square' },
                                        { label: __('Arrow', 'anchorkit-table-of-contents'), value: 'arrow' },
                                        { label: __('Chevron', 'anchorkit-table-of-contents'), value: 'chevron' },
                                        { label: __('Custom Character', 'anchorkit-table-of-contents'), value: 'custom_character' }
                                    ],
                                    onChange: function (value) { setAttributes({ bulletStyle: value }); },
                                    help: __('Choose the bullet style for TOC items.', 'anchorkit-table-of-contents')
                                }
                            ),
                            isPro && attributes.designOverride && attributes.bulletStyle === 'custom_character' && wp.element.createElement(
                                TextControl,
                                {
                                    __nextHasNoMarginBottom: true,
                                    __next40pxDefaultSize: true,
                                    label: __('Custom Character', 'anchorkit-table-of-contents'),
                                    value: attributes.bulletCharacter,
                                    onChange: function (value) { setAttributes({ bulletCharacter: value }); },
                                    help: __('Enter any character or emoji (e.g., ★, ✓, →, 🎯). Color is set below.', 'anchorkit-table-of-contents'),
                                    maxLength: 2,
                                    placeholder: '•'
                                }
                            ),
                            // Design Override Colors (Light/Dark via edit mode)
                            isPro && attributes.designOverride && renderDesignColorControls(designPreviewMode),
                            // Design Override: Container Sizing
                            isPro && attributes.designOverride && wp.element.createElement(
                                PanelBody,
                                { title: __('Container', 'anchorkit-table-of-contents'), initialOpen: false },
                                wp.element.createElement(RangeControl, {
                                    __nextHasNoMarginBottom: true,
                                    __next40pxDefaultSize: true,
                                    label: __('Padding (px)', 'anchorkit-table-of-contents'),
                                    value: typeof attributes.containerPadding === 'number' ? attributes.containerPadding : 15,
                                    onChange: function (value) { setAttributes({ containerPadding: value }); },
                                    min: 0, max: 60,
                                    help: __('Set 0 to remove inner spacing.', 'anchorkit-table-of-contents')
                                }),
                                wp.element.createElement(RangeControl, {
                                    __nextHasNoMarginBottom: true,
                                    __next40pxDefaultSize: true,
                                    label: __('Border Width (px)', 'anchorkit-table-of-contents'),
                                    value: typeof attributes.containerBorderWidth === 'number' ? attributes.containerBorderWidth : 1,
                                    onChange: function (value) { setAttributes({ containerBorderWidth: value }); },
                                    min: 0, max: 12,
                                    help: __('Set 0 for borderless.', 'anchorkit-table-of-contents')
                                }),
                                wp.element.createElement(RangeControl, {
                                    __nextHasNoMarginBottom: true,
                                    __next40pxDefaultSize: true,
                                    label: __('Border Radius (px)', 'anchorkit-table-of-contents'),
                                    value: typeof attributes.containerBorderRadius === 'number' ? attributes.containerBorderRadius : 4,
                                    onChange: function (value) { setAttributes({ containerBorderRadius: value }); },
                                    min: 0, max: 48
                                })
                            ),
                            // Design Override: Box Shadow (Pro)
                            isPro && attributes.designOverride && wp.element.createElement(
                                PanelBody,
                                {
                                    title: __('Box Shadow', 'anchorkit-table-of-contents'),
                                    initialOpen: false,
                                    className: 'anchorkit-box-shadow-panel anchorkit-box-shadow-panel--' + (designPreviewMode === 'dark' ? 'dark' : 'light')
                                },
                                wp.element.createElement(ToggleControl, {
                                    __nextHasNoMarginBottom: true,
                                    label: __('Enable Box Shadow', 'anchorkit-table-of-contents'),
                                    checked: !!attributes.boxShadowEnabled,
                                    onChange: function (value) { setAttributes({ boxShadowEnabled: value }); },
                                    help: __('Control per-block shadow for light/dark.', 'anchorkit-table-of-contents')
                                }),
                                !!attributes.boxShadowEnabled && renderShadowControls(designPreviewMode)
                            ),
                            // Spacer after Box Shadow to ensure sticky ends after this section
                            attributes.designOverride && wp.element.createElement(
                                'div',
                                { style: { marginBottom: '16px' } }
                            )
                        ),
                        isPro && wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Entrance Animation', 'anchorkit-table-of-contents'),
                                checked: attributes.entranceAnimation,
                                onChange: function (value) { setAttributes({ entranceAnimation: value }); },
                                help: __('Animate the TOC when it first appears.', 'anchorkit-table-of-contents')
                            }
                        ),
                        isPro && attributes.entranceAnimation && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Animation Style', 'anchorkit-table-of-contents'),
                                value: attributes.animationType,
                                options: [
                                    { label: __('Fade', 'anchorkit-table-of-contents'), value: 'fade' },
                                    { label: __('Slide Up', 'anchorkit-table-of-contents'), value: 'slide-up' },
                                    { label: __('Slide In', 'anchorkit-table-of-contents'), value: 'slide-in' },
                                    { label: __('Zoom', 'anchorkit-table-of-contents'), value: 'zoom' }
                                ],
                                onChange: function (value) { setAttributes({ animationType: value }); },
                                help: __('Choose how the TOC animates on load.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Hierarchical View', 'anchorkit-table-of-contents'),
                                checked: attributes.hierarchicalView,
                                onChange: function (value) { setAttributes({ hierarchicalView: value }); },
                                help: __('Indent headings based on their level.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Show Numerals', 'anchorkit-table-of-contents'),
                                checked: attributes.showNumerals,
                                onChange: function (value) { setAttributes({ showNumerals: value }); },
                                help: __('Display hierarchical numbering.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.showNumerals && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Numbering Style', 'anchorkit-table-of-contents'),
                                value: attributes.numberingStyle,
                                options: [
                                    { label: __('Hierarchical (1, 1.1, 1.2)', 'anchorkit-table-of-contents'), value: 'hierarchical' },
                                    { label: __('Flat (1, 2, 3)', 'anchorkit-table-of-contents'), value: 'flat' }
                                ],
                                onChange: function (value) { setAttributes({ numberingStyle: value }); }
                            }
                        ),
                        attributes.showNumerals && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Numbering Format', 'anchorkit-table-of-contents'),
                                value: attributes.numberingFormat,
                                options: [
                                    { label: __('Decimal', 'anchorkit-table-of-contents'), value: 'decimal' },
                                    { label: __('Decimal (01)', 'anchorkit-table-of-contents'), value: 'decimal_leading_zero' },
                                    { label: __('Upper Roman (I)', 'anchorkit-table-of-contents'), value: 'upper_roman' },
                                    { label: __('Lower Roman (i)', 'anchorkit-table-of-contents'), value: 'lower_roman' },
                                    { label: __('Upper Alpha (A)', 'anchorkit-table-of-contents'), value: 'upper_alpha' },
                                    { label: __('Lower Alpha (a)', 'anchorkit-table-of-contents'), value: 'lower_alpha' }
                                ],
                                onChange: function (value) { setAttributes({ numberingFormat: value }); }
                            }
                        ),
                        attributes.showNumerals && wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Separator', 'anchorkit-table-of-contents'),
                                value: attributes.numberingSeparator,
                                options: [
                                    { label: __('Dot (.)', 'anchorkit-table-of-contents'), value: '.' },
                                    { label: __('Dash (-)', 'anchorkit-table-of-contents'), value: '-' },
                                    { label: __('Middle dot (·)', 'anchorkit-table-of-contents'), value: '·' }
                                ],
                                onChange: function (value) { setAttributes({ numberingSeparator: value }); },
                                help: __('Used between levels and after the number', 'anchorkit-table-of-contents')
                            }
                        ),

                        wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Line Height', 'anchorkit-table-of-contents'),
                                value: attributes.lineHeight,
                                onChange: function (value) { setAttributes({ lineHeight: value }); },
                                min: 1.0,
                                max: 3.0,
                                step: 0.1,
                                help: __('Controls vertical spacing for multi-line TOC entries.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Letter Spacing (px)', 'anchorkit-table-of-contents'),
                                value: attributes.letterSpacing,
                                onChange: function (value) { setAttributes({ letterSpacing: value }); },
                                min: -2,
                                max: 5,
                                step: 0.1,
                                help: __('Add or reduce spacing between letters in TOC links.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Text Transform', 'anchorkit-table-of-contents'),
                                value: attributes.textTransform,
                                options: [
                                    { label: __('None', 'anchorkit-table-of-contents'), value: 'none' },
                                    { label: __('UPPERCASE', 'anchorkit-table-of-contents'), value: 'uppercase' },
                                    { label: __('lowercase', 'anchorkit-table-of-contents'), value: 'lowercase' },
                                    { label: __('Capitalize Each Word', 'anchorkit-table-of-contents'), value: 'capitalize' }
                                ],
                                onChange: function (value) { setAttributes({ textTransform: value }); },
                                help: __('Control casing for TOC item labels.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Link Underline', 'anchorkit-table-of-contents'),
                                value: attributes.linkUnderline,
                                options: [
                                    { label: __('None', 'anchorkit-table-of-contents'), value: 'none' },
                                    { label: __('Always Underlined', 'anchorkit-table-of-contents'), value: 'always' },
                                    { label: __('Underline on Hover', 'anchorkit-table-of-contents'), value: 'hover' },
                                    { label: __('No Underline on Hover', 'anchorkit-table-of-contents'), value: 'hover_none' }
                                ],
                                onChange: function (value) { setAttributes({ linkUnderline: value }); },
                                help: __('Choose when to display underlines on TOC links.', 'anchorkit-table-of-contents')
                            }
                        ),

                        // PRO: Custom Font Sizes
                        isPro && wp.element.createElement(
                            'div',
                            { style: { marginTop: '16px', paddingTop: '16px', borderTop: '1px solid #e0e0e0' } },
                            wp.element.createElement(
                                ToggleControl,
                                {
                                    __nextHasNoMarginBottom: true,
                                    label: __('Custom Font Sizes', 'anchorkit-table-of-contents'),
                                    checked: !!attributes.advancedTypographyOverride,
                                    onChange: function (value) { setAttributes({ advancedTypographyOverride: value }); },
                                    help: __('Override default font sizes for each heading level.', 'anchorkit-table-of-contents')
                                }
                            )
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Title Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.titleFontSize,
                                onChange: function (value) { setAttributes({ titleFontSize: value }); },
                                min: 12,
                                max: 32,
                                help: __('Font size for the TOC title.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('H2 Items Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.h2FontSize,
                                onChange: function (value) { setAttributes({ h2FontSize: value }); },
                                min: 10,
                                max: 24,
                                help: __('Font size for H2 level items.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('H3 Items Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.h3FontSize,
                                onChange: function (value) { setAttributes({ h3FontSize: value }); },
                                min: 10,
                                max: 24,
                                help: __('Font size for H3 level items.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('H4 Items Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.h4FontSize,
                                onChange: function (value) { setAttributes({ h4FontSize: value }); },
                                min: 10,
                                max: 24,
                                help: __('Font size for H4 level items.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('H5 Items Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.h5FontSize,
                                onChange: function (value) { setAttributes({ h5FontSize: value }); },
                                min: 10,
                                max: 24,
                                help: __('Font size for H5 level items.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.advancedTypographyOverride && isPro && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('H6 Items Font Size (px)', 'anchorkit-table-of-contents'),
                                value: attributes.h6FontSize,
                                onChange: function (value) { setAttributes({ h6FontSize: value }); },
                                min: 10,
                                max: 24,
                                help: __('Font size for H6 level items.', 'anchorkit-table-of-contents')
                            }
                        ),

                        wp.element.createElement(
                            'div',
                            { style: { marginTop: '20px', paddingTop: '16px', borderTop: '1px solid #e0e0e0', textAlign: 'center' } },
                            wp.element.createElement(
                                Button,
                                {
                                    variant: 'link',
                                    isDestructive: true,
                                    onClick: resetAppearanceSettings,
                                    style: { fontSize: '13px' }
                                },
                                '↻ ' + __('Reset Appearance Settings', 'anchorkit-table-of-contents')
                            )
                        )
                    ),

                    // Advanced & Accessibility
                    wp.element.createElement(
                        PanelBody,
                        {
                            title: __('Advanced & Accessibility', 'anchorkit-table-of-contents'),
                            initialOpen: false
                        },
                        wp.element.createElement(
                            ToggleControl,
                            {
                                __nextHasNoMarginBottom: true,
                                label: __('Hide on Mobile', 'anchorkit-table-of-contents'),
                                checked: attributes.hideOnMobile,
                                onChange: function (value) { setAttributes({ hideOnMobile: value }); },
                                help: __('Hide TOC on small screens.', 'anchorkit-table-of-contents')
                            }
                        ),
                        attributes.hideOnMobile && wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Mobile Breakpoint (px)', 'anchorkit-table-of-contents'),
                                value: attributes.mobileBreakpoint,
                                onChange: function (value) { setAttributes({ mobileBreakpoint: value }); },
                                min: 320,
                                max: 1200,
                                help: __('Screen width below which TOC is hidden.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            RangeControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('TOC Width (%)', 'anchorkit-table-of-contents'),
                                value: attributes.tocWidth,
                                onChange: function (value) { setAttributes({ tocWidth: value }); },
                                min: 20,
                                max: 100,
                                help: __('Maximum width as percentage of container.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            SelectControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('TOC Alignment', 'anchorkit-table-of-contents'),
                                value: attributes.tocAlignment,
                                options: [
                                    { label: __('Left', 'anchorkit-table-of-contents'), value: 'left' },
                                    { label: __('Center', 'anchorkit-table-of-contents'), value: 'center' },
                                    { label: __('Right', 'anchorkit-table-of-contents'), value: 'right' }
                                ],
                                onChange: function (value) { setAttributes({ tocAlignment: value }); },
                                help: __('Control horizontal alignment when the TOC is not floating or sticky.', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('ARIA Label', 'anchorkit-table-of-contents'),
                                value: ariaLabelValue,
                                onChange: function (value) { setAttributes({ ariaLabel: value }); },
                                help: __('Accessible label for screen readers.', 'anchorkit-table-of-contents'),
                                placeholder: __('Table of Contents', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Additional CSS Class(es)', 'anchorkit-table-of-contents'),
                                value: attributes.customCssClass,
                                onChange: function (value) { setAttributes({ customCssClass: value }); },
                                help: __('Space-separated class names for custom styling.', 'anchorkit-table-of-contents'),
                                placeholder: __('my-toc custom-design', 'anchorkit-table-of-contents')
                            }
                        ),
                        wp.element.createElement(
                            TextControl,
                            {
                                __nextHasNoMarginBottom: true,
                                __next40pxDefaultSize: true,
                                label: __('Custom TOC ID', 'anchorkit-table-of-contents'),
                                value: attributes.customId,
                                onChange: function (value) { setAttributes({ customId: value }); },
                                help: __('Custom ID for the TOC container (for CSS/JavaScript targeting).', 'anchorkit-table-of-contents'),
                                placeholder: __('my-custom-toc', 'anchorkit-table-of-contents')
                            }
                        ),
                        // PRO: Custom Labels & Anchor Formats
                        createProPanel(
                            __('Custom Labels & Anchor IDs', 'anchorkit-table-of-contents'),
                            __('Customize how headings appear in your TOC and control anchor ID generation for better URLs and link management.', 'anchorkit-table-of-contents'),
                            [
                                __('Replace heading text with custom labels', 'anchorkit-table-of-contents'),
                                __('JSON-based label mapping', 'anchorkit-table-of-contents'),
                                __('3 anchor ID format options', 'anchorkit-table-of-contents'),
                                __('Custom prefix for sequential IDs', 'anchorkit-table-of-contents')
                            ],
                            [
                                wp.element.createElement(
                                    TextareaControl,
                                    {
                                        label: __('Custom Heading Labels (JSON)', 'anchorkit-table-of-contents'),
                                        value: customLabelsValue,
                                        onChange: function (value) { setAttributes({ customLabels: value }); },
                                        help: __('Replace heading text in TOC only. Format: {"Original": "New Label"}', 'anchorkit-table-of-contents'),
                                        rows: 4,
                                        placeholder: '{"Introduction": "Start Here", "FAQ": "Questions"}'
                                    }
                                ),
                                wp.element.createElement(
                                    SelectControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Anchor ID Format', 'anchorkit-table-of-contents'),
                                        value: attributes.anchorFormat,
                                        options: [
                                            { label: __('Auto (from heading text)', 'anchorkit-table-of-contents'), value: 'auto' },
                                            { label: __('Sequential numbers (toc-1, toc-2...)', 'anchorkit-table-of-contents'), value: 'sequential' },
                                            { label: __('Custom prefix + sanitized heading', 'anchorkit-table-of-contents'), value: 'prefixed' }
                                        ],
                                        onChange: function (value) { setAttributes({ anchorFormat: value }); },
                                        help: __('How anchor IDs are generated for headings.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                attributes.anchorFormat === 'prefixed' && wp.element.createElement(
                                    TextControl,
                                    {
                                        __nextHasNoMarginBottom: true,
                                        __next40pxDefaultSize: true,
                                        label: __('Custom Anchor Prefix', 'anchorkit-table-of-contents'),
                                        value: attributes.anchorPrefix,
                                        onChange: function (value) { setAttributes({ anchorPrefix: value }); },
                                        help: __('Prefix for anchor IDs. Example result: section-introduction', 'anchorkit-table-of-contents'),
                                        placeholder: 'section'
                                    }
                                )
                            ]
                        ),
                        // PRO: ACF & AMP Compatibility
                        createProPanel(
                            __('ACF & AMP Compatibility', 'anchorkit-table-of-contents'),
                            __('Extend your Table of Contents to include headings from Advanced Custom Fields and ensure AMP-compliant rendering for faster mobile experiences.', 'anchorkit-table-of-contents'),
                            [
                                __('Merge ACF field headings into TOC', 'anchorkit-table-of-contents'),
                                __('Configure merge mode (before/after/replace)', 'anchorkit-table-of-contents'),
                                __('Specify custom ACF field names', 'anchorkit-table-of-contents'),
                                __('AMP-compatible simplified rendering', 'anchorkit-table-of-contents')
                            ],
                            [
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        label: __('Enable ACF Integration', 'anchorkit-table-of-contents'),
                                        checked: acfEnabledValue,
                                        onChange: function (value) { setAttributes({ acfEnabled: value }); },
                                        help: __('Merge headings stored in specified ACF fields with the main content.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                acfEnabledValue && wp.element.createElement(
                                    TextControl,
                                    {
                                        label: __('ACF Field Names', 'anchorkit-table-of-contents'),
                                        value: acfFieldNamesValue,
                                        onChange: function (value) { setAttributes({ acfFieldNames: value }); },
                                        help: __('Comma-separated field names to scan for headings.', 'anchorkit-table-of-contents'),
                                        placeholder: 'hero_content, body_sections'
                                    }
                                ),
                                acfEnabledValue && wp.element.createElement(
                                    SelectControl,
                                    {
                                        label: __('ACF Merge Mode', 'anchorkit-table-of-contents'),
                                        value: acfMergeModeValue,
                                        options: [
                                            { label: __('Before main content', 'anchorkit-table-of-contents'), value: 'before' },
                                            { label: __('After main content', 'anchorkit-table-of-contents'), value: 'after' },
                                            { label: __('Replace main content', 'anchorkit-table-of-contents'), value: 'replace' }
                                        ],
                                        onChange: function (value) { setAttributes({ acfMergeMode: value }); },
                                        help: __('Decide where ACF headings should be inserted relative to the main content.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        label: __('Enable AMP Compatibility', 'anchorkit-table-of-contents'),
                                        checked: ampEnabledValue,
                                        onChange: function (value) { setAttributes({ ampEnabled: value }); },
                                        help: __('Render a simplified TOC when the page is viewed via AMP.', 'anchorkit-table-of-contents')
                                    }
                                )
                            ]
                        ),

                        // PRO: Schema Markup
                        createProPanel(
                            __('Schema Markup', 'anchorkit-table-of-contents'),
                            __('Add Schema.org structured data to your Table of Contents for enhanced SEO and rich search results.', 'anchorkit-table-of-contents'),
                            [
                                __('Schema.org JSON-LD structured data', 'anchorkit-table-of-contents'),
                                __('8 content type options (Article, HowTo, FAQ, etc.)', 'anchorkit-table-of-contents'),
                                __('Improves search engine understanding', 'anchorkit-table-of-contents'),
                                __('Enables rich snippets in search results', 'anchorkit-table-of-contents')
                            ],
                            [
                                wp.element.createElement(
                                    ToggleControl,
                                    {
                                        label: __('Enable Schema Markup', 'anchorkit-table-of-contents'),
                                        checked: schemaEnabledValue,
                                        onChange: function (value) { setAttributes({ schemaEnabled: value }); },
                                        help: __('Add Schema.org structured data for SEO.', 'anchorkit-table-of-contents')
                                    }
                                ),
                                schemaEnabledValue && wp.element.createElement(
                                    SelectControl,
                                    {
                                        label: __('Schema Type', 'anchorkit-table-of-contents'),
                                        value: schemaTypeValue,
                                        options: [
                                            { label: __('Article', 'anchorkit-table-of-contents'), value: 'Article' },
                                            { label: __('Blog Posting', 'anchorkit-table-of-contents'), value: 'BlogPosting' },
                                            { label: __('Web Page', 'anchorkit-table-of-contents'), value: 'WebPage' },
                                            { label: __('How-To', 'anchorkit-table-of-contents'), value: 'HowTo' },
                                            { label: __('FAQ Page', 'anchorkit-table-of-contents'), value: 'FAQPage' },
                                            { label: __('News Article', 'anchorkit-table-of-contents'), value: 'NewsArticle' },
                                            { label: __('Tech Article', 'anchorkit-table-of-contents'), value: 'TechArticle' },
                                            { label: __('Course', 'anchorkit-table-of-contents'), value: 'Course' }
                                        ],
                                        onChange: function (value) { setAttributes({ schemaType: value }); },
                                        help: __('Type of schema markup to use.', 'anchorkit-table-of-contents')
                                    }
                                )
                            ]
                        ),
                        wp.element.createElement(
                            'div',
                            { style: { marginTop: '20px', paddingTop: '16px', borderTop: '1px solid #e0e0e0', textAlign: 'center' } },
                            wp.element.createElement(
                                Button,
                                {
                                    variant: 'link',
                                    isDestructive: true,
                                    onClick: resetAdvancedSettings,
                                    style: { fontSize: '13px' }
                                },
                                '↻ ' + __('Reset Advanced Settings', 'anchorkit-table-of-contents')
                            )
                        )
                    )
                )
            ];

            // Override preview theme locally so the editor matches the currently edited variant
            const previewAttributes = attributes.designOverride
                ? Object.assign({}, attributes, { theme: designPreviewMode === 'dark' ? 'dark' : 'light' })
                : attributes;

            // Add the preview using ServerSideRender if available
            editorControls.push(
                wp.element.createElement(
                    AnchorKitServerRender,
                    {
                        key: 'preview',
                        attributes: previewAttributes
                    }
                )
            );

            return wp.element.createElement(Fragment, null, editorControls);
        },

        /**
         * Save function - returns null for dynamic blocks (server-side rendered)
         */
        save: function () {
            // Return null for dynamic blocks - rendering happens server-side
            return null;
        },
    });

    anchorkitDebugLog('AnchorKit: Table of Contents block registered successfully');
})();
