/* stylelint-disable */
/**
 * AnchorKit Admin JavaScript
 * Handles real-time updates of settings without requiring form submission
 */
(function ($) {
    'use strict';

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

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

    // Store form values to detect changes
    const originalFormValues = {};

    // Reference to the notification element
    let notificationTimeout;

    // Keep track of pending AJAX requests
    let pendingRequests = {};

    // Keep track of recently updated values to prevent duplicate updates
    let recentlyUpdatedValues = {};

    // Keep track of changed settings
    let changedSettings = new Set();

    /**
     * Initialize responsive tabs dropdown
     */
    function initResponsiveTabs() {
        const $dropdown = $('.anchorkit-tabs-dropdown');
        const $button = $('.anchorkit-tabs-dropdown-button');
        const $activeTab = $('.anchorkit-admin').data('active-tab');

        // Set the active tab as a data attribute for styling
        $button.attr('data-active-tab', $activeTab);

        // Toggle dropdown when button is clicked
        $button.on('click', function (e) {
            e.preventDefault();
            $dropdown.toggleClass('open');

            // Ensure dropdown is visible above content by adding a high z-index to parent
            if ($dropdown.hasClass('open')) {
                $dropdown.css('z-index', '1000');
            } else {
                // Return to original z-index when closed
                $dropdown.css('z-index', '100');
            }
        });

        // Close dropdown when clicking outside
        $(document).on('click', function (e) {
            if (!$(e.target).closest('.anchorkit-tabs-dropdown').length) {
                $dropdown.removeClass('open');
                $dropdown.css('z-index', '100');
            }
        });
    }

    /**
     * Debounce function to limit how often a function can be called
     * @param {Function} func - The function to debounce
     * @param {number} wait - The time to wait in milliseconds
     * @return {Function} The debounced function
     */
    function debounce(func, wait) {
        let timeout;
        return function () {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                // Log when debounced function actually executes
                const settingName = args[0];
                if (settingName && settingName.includes('shadow')) {
                    anchorkitDebugLog('[AnchorKit Shadow] >>> Executing debounced save for:', settingName);
                }
                func.apply(context, args);
            }, wait);
        };
    }

    /**
     * Update the Custom Styling info box (live update when toggle changes)
     * @param {boolean} isCustomStylingEnabled - Whether custom styling is enabled
     */
    function updateCustomStylingInfoBox(isCustomStylingEnabled) {
        // Update the activation card
        updateActivationCard(isCustomStylingEnabled);

        // Update lock states on cards controlled by Custom Styling mode
        updateCustomStylingLocks(isCustomStylingEnabled);
    }

    /**
     * Get the current preset name (works across tabs)
     * @returns {string} Capitalized preset name (e.g., "Minimal", "Classic", "Modern")
     */
    function getCurrentPresetName() {
        // Try to get from checked radio button first (if on Quick Start tab)
        let currentPreset = $('input[name="anchorkit_toc_style_preset"]:checked').val();

        // If not found in DOM, try getting from localized script data (always available)
        if (!currentPreset && typeof anchorkit_ajax !== 'undefined' && anchorkit_ajax.current_preset) {
            currentPreset = anchorkit_ajax.current_preset;
        }

        // Fallback to 'minimal' if still not found
        if (!currentPreset) {
            currentPreset = 'minimal';
        }

        // Capitalize for display (minimal → Minimal, classic → Classic, modern → Modern)
        return currentPreset.charAt(0).toUpperCase() + currentPreset.slice(1);
    }

    /**
     * Update the activation card appearance and content
     * @param {boolean} isCustomStylingEnabled - Whether custom styling is enabled
     */
    function updateActivationCard(isCustomStylingEnabled) {
        const $card = $('#anchorkit-custom-styling-activation-card');
        if (!$card.length) return;

        // Update card class (warning vs info)
        if (isCustomStylingEnabled) {
            $card.removeClass('info').addClass('warning');
        } else {
            $card.removeClass('warning').addClass('info');
        }

        // Update icon
        const $icon = $card.find('.anchorkit-custom-styling-icon').first();
        if ($icon.length) {
            $icon.text(isCustomStylingEnabled ? '🎨' : 'ℹ️');
        }

        // Update heading text
        const $heading = $card.find('.anchorkit-custom-styling-header').first();
        if ($heading.length) {
            const headingText = isCustomStylingEnabled ? 'Custom Styling Mode Active' : 'Using Preset Styling';
            const iconHtml = $icon.length ? $icon[0].outerHTML : '';
            $heading.html(iconHtml + headingText);
        }

        // Get current preset name using the helper function
        const presetName = getCurrentPresetName();

        // Update description text
        const $description = $card.find('.anchorkit-custom-styling-description').first();
        if ($description.length) {
            if (isCustomStylingEnabled) {
                $description.html(
                    '<strong>You\'re in full control.</strong> Custom styling is enabled and overriding the <strong>' + presetName + '</strong> preset. ' +
                    'All color, typography, and spacing settings below will be applied to your Table of Contents.'
                );
            } else {
                $description.html(
                    '<strong>Currently using the ' + presetName + ' preset.</strong> ' +
                    'Enable custom styling below to unlock full control over style customization.'
                );
            }
        }

        // Handle note paragraph (show when enabled, hide when disabled)
        let $note = $card.find('.anchorkit-custom-styling-note').first();
        if (isCustomStylingEnabled) {
            if ($note.length === 0) {
                // Create and add the note paragraph
                $note = $('<p class="anchorkit-custom-styling-note">' +
                    '<strong>Note:</strong> When custom styling is active, your preset\'s design is replaced with your custom settings. ' +
                    'Use the controls below for colors, typography, borders, and container spacing, and keep managing bullet styles and width in their dedicated cards.' +
                    '</p>');
                $description.after($note);
            } else {
                $note.show();
            }
        } else {
            if ($note.length) {
                $note.hide();
            }
        }

        // Update toggle label
        const $toggleLabel = $card.find('.anchorkit-custom-styling-toggle-label').first();
        if ($toggleLabel.length) {
            $toggleLabel.text((isCustomStylingEnabled ? 'Disable' : 'Enable') + ' Custom Styling Mode');
        }

        // Update helper text
        const $helperText = $card.find('.anchorkit-custom-styling-helper').first();
        if ($helperText.length) {
            $helperText.text(isCustomStylingEnabled
                ? 'Turn this off to return to your preset design.'
                : 'Turn this on to unlock full customization of colors, fonts, and spacing.');
        }

        // Update Custom Styling Settings card description
        updateCustomStylingSettingsDescription(isCustomStylingEnabled);
    }

    /**
     * Update Custom Styling Settings card description
     * @param {boolean} isCustomStylingEnabled - Whether custom styling is enabled
     */
    function updateCustomStylingSettingsDescription(isCustomStylingEnabled) {
        const $description = $('#anchorkit-custom-styling-settings-description');
        if (!$description.length) return;

        // Get current preset name using the helper function
        const presetName = getCurrentPresetName();

        if (isCustomStylingEnabled) {
            $description.html(
                'Customize colors, fonts, and spacing for your Table of Contents. These settings override the <strong>' + presetName + '</strong> preset.'
            );
        } else {
            $description.html(
                '<em>Enable Custom Styling Mode above to unlock these settings.</em>'
            );
        }
    }

    /**
     * Toggle the lock state for a card and its interactive controls
     * @param {jQuery} $card - Card element to update
     * @param {boolean} locked - Whether the card should be locked
     */
    function toggleCardLock($card, locked) {
        const $overlay = $card.find('.anchorkit-lock-overlay');
        const $fields = $card.find('input, select, textarea, button').filter(function () {
            const $field = $(this);
            if ($field.closest('.anchorkit-lock-overlay').length) {
                return false;
            }
            return !$field.is('[data-lock-ignore]');
        });

        $card.toggleClass('is-locked', locked);
        $card.attr('data-lock-state', locked ? 'locked' : 'unlocked');
        $card.attr('aria-disabled', locked ? 'true' : 'false');

        if ($overlay.length) {
            $overlay.attr('aria-hidden', locked ? 'false' : 'true');
        }

        $fields.each(function () {
            const $field = $(this);
            if (locked) {
                if (!$field.data('anchorkitLockStored')) {
                    $field.data('anchorkitLockStored', true);
                    $field.data('anchorkitLockOriginalDisabled', $field.prop('disabled'));
                }
                $field.prop('disabled', true);
            } else if ($field.data('anchorkitLockStored')) {
                const original = $field.data('anchorkitLockOriginalDisabled');
                $field.prop('disabled', original);
                $field.removeData('anchorkitLockStored');
                $field.removeData('anchorkitLockOriginalDisabled');
            }
        });
    }

    /**
     * Update lockable card states when Custom Styling mode changes
     * @param {boolean} isCustomStylingEnabled - Whether custom styling is enabled
     */
    function updateCustomStylingLocks(isCustomStylingEnabled) {
        $('.anchorkit-lockable-card').each(function () {
            const $card = $(this);
            const modesRaw = $card.data('lockMode');
            const modes = (typeof modesRaw === 'string' ? modesRaw : (modesRaw || ''))
                .toString()
                .split(/\s+/)
                .filter(Boolean);

            if (!modes.length) {
                return;
            }

            let shouldLock = false;
            modes.forEach(function (mode) {
                if (mode === 'custom-on' && isCustomStylingEnabled) {
                    shouldLock = true;
                } else if (mode === 'custom-off' && !isCustomStylingEnabled) {
                    shouldLock = true;
                }
            });

            toggleCardLock($card, shouldLock);
        });
    }

    /**
     * Initialize lock state for cards controlled by Custom Styling
     */
    function initializeCustomStylingLocks() {
        const $toggle = $('input[name="anchorkit_toc_custom_styling"]');
        const isEnabled = $toggle.length ? $toggle.is(':checked') : false;
        updateCustomStylingLocks(isEnabled);
    }

    /**
     * Show a notification message
     * @param {string} message - The message to display
     * @param {string} type - The type of message (success, error, or info)
     * @param {Object} options - Additional options for the notification
     */
    function showNotification(message, type = 'success', options = {}) {
        const notification = $('#anchorkit-notification');

        // Check if notification element exists
        if (!notification.length) {
            console.error('Notification container not found. Message was:', message);
            return;
        }

        const duration = options.duration || 3000;

        // Clear any existing timeout
        if (notificationTimeout) {
            clearTimeout(notificationTimeout);
        }

        // Set the message
        notification.find('.anchorkit-notification-message').text(message);

        // Reset classes and add the type class
        notification.removeClass('success error info').addClass(type);

        // Show the right icon
        notification.find('.anchorkit-notification-icon').hide();
        notification.find('.' + type + '-icon').show();

        // Use explicit styles to ensure visibility
        notification.css({
            'opacity': '1',
            'visibility': 'visible',
            'transform': 'translateX(-50%) translateY(0)',
            'z-index': '100000'
        });

        // Hide the notification after the duration
        notificationTimeout = setTimeout(() => {
            notification.css({
                'opacity': '0',
                'visibility': 'hidden',
                'transform': 'translateX(-50%) translateY(20px)'
            });
        }, duration);
    }

    /**
     * Get a user-friendly name for a setting
     * @param {string} name - The setting name
     * @return {string} A friendly display name
     */
    function getFriendlySettingName(name) {
        const nameMap = {
            // General settings
            'anchorkit_enable_feature': 'Reading Time feature',
            'anchorkit_wpm': 'Words per minute',
            'anchorkit_insert_before_content': 'Show before content',
            'anchorkit_insert_before_excerpt': 'Show before excerpt',

            // Page settings
            'anchorkit_label': 'Reading time label',
            'anchorkit_postfix': 'Reading time plural text',
            'anchorkit_postfix_singular': 'Reading time singular text',
            'anchorkit_text_size_value': 'Text size value',
            'anchorkit_text_size_unit': 'Text size unit',
            'anchorkit_prefix_font_weight': 'Label font weight',
            'anchorkit_prefix_color': 'Prefix color',
            'anchorkit_text_font_weight': 'Time font weight',
            'anchorkit_text_color': 'Reading time text color',

            // Excerpt settings
            'anchorkit_excerpt_label': 'Excerpt label',
            'anchorkit_excerpt_postfix': 'Excerpt plural text',
            'anchorkit_excerpt_postfix_singular': 'Excerpt singular text',
            'anchorkit_excerpt_text_size_value': 'Excerpt text size value',
            'anchorkit_excerpt_text_size_unit': 'Excerpt text size unit',
            'anchorkit_excerpt_prefix_font_weight': 'Excerpt label font weight',
            'anchorkit_excerpt_prefix_color': 'Excerpt prefix color',
            'anchorkit_excerpt_text_font_weight': 'Excerpt time font weight',
            'anchorkit_excerpt_text_color': 'Excerpt reading time text color',

            // Post types
            'reading_time_post_types': 'Post types',
            'anchorkit_progress_bar_post_types': 'Progress bar post types',
            'anchorkit_back_to_top_post_types': 'Back to top post types'
        };

        return nameMap[name] || name.replace(/_/g, ' ').replace(/anchorkit/g, '').trim();
    }

    /**
     * Get a descriptive message about the update
     * @param {string} name - The setting name
     * @param {mixed} value - The new setting value
     * @return {string} A descriptive message
     */
    function getUpdateMessage(name, value) {
        // For checkbox toggles, convert string/numeric values to boolean for consistent message selection
        let isChecked = false;
        if (value === '1' || value === 1 || value === true) {
            isChecked = true;
        }

        const messages = {
            'anchorkit_enable_reading_time': isChecked ? 'Reading time feature enabled' : 'Reading time feature disabled',
            'anchorkit_enable_progress_bar': isChecked ? 'Reading progress bar enabled' : 'Reading progress bar disabled',
            'anchorkit_enable_back_to_top': isChecked ? 'Back to top button enabled' : 'Back to top button disabled',
            'anchorkit_insert_before_content': isChecked ? 'Reading time will appear before content' : 'Reading time will not appear before content',
            'anchorkit_insert_before_excerpt': isChecked ? 'Reading time will appear before excerpt' : 'Reading time will not appear before excerpt',
            'anchorkit_reading_time_prefix': 'Reading time prefix updated',
            'anchorkit_reading_time_suffix': 'Reading time suffix updated',
            'anchorkit_reading_time_color': 'Reading time text color updated',
            'anchorkit_reading_time_font_size': 'Reading time font size updated',
            'anchorkit_progress_bar_color': 'Progress bar color updated',
            'anchorkit_progress_bar_height': 'Progress bar height updated',
            'anchorkit_progress_bar_position': 'Progress bar position updated',
            'anchorkit_progress_bar_preview_enabled': isChecked ? 'Progress bar preview enabled' : 'Progress bar preview disabled',
            'anchorkit_back_to_top_color': 'Back to top button color updated',
            'anchorkit_back_to_top_size': 'Back to top button size updated',
            'anchorkit_back_to_top_position': 'Back to top button position updated',
            'anchorkit_back_to_top_autohide': isChecked ? 'Back to top button will automatically hide' : 'Back to top button will not automatically hide',
            'anchorkit_back_to_top_fade_duration': 'Back to top button fade duration updated',
            'anchorkit_back_to_top_margin_x': 'Back to top button margin x updated',
            'anchorkit_back_to_top_margin_y': 'Back to top button margin y updated',
            'anchorkit_back_to_top_scroll_offset': 'Back to top button scroll offset updated',
            'anchorkit_back_to_top_scroll_duration': 'Back to top button scroll duration updated',
            'anchorkit_back_to_top_small_device_width': 'Back to top button small device width updated',
            'anchorkit_back_to_top_small_window_width': 'Back to top button small window width updated',
            'anchorkit_back_to_top_icon_width': 'Back to top button icon width updated',
            'anchorkit_back_to_top_icon_height': 'Back to top button icon height updated',
            'anchorkit_back_to_top_auto_hide_after': 'Back to top button auto hide after updated',
            'anchorkit_back_to_top_progress_thickness': 'Back to top button progress thickness updated',
            'anchorkit_progress_bar_animation_speed': 'Progress bar animation speed updated',
            'anchorkit_toc_enabled': isChecked ? 'Table of Contents enabled' : 'Table of Contents disabled',
            'anchorkit_toc_post_types': isChecked ? 'Table of Contents will be automatically inserted into selected post types' : 'Table of Contents will not be automatically inserted into selected post types',
            'anchorkit_toc_automatic_insertion': isChecked ? 'Table of Contents will be automatically inserted' : 'Table of Contents will not be automatically inserted',
            'anchorkit_toc_position': 'Table of Contents position updated',
            'anchorkit_toc_collapsible': isChecked ? 'Table of Contents will be collapsible' : 'Table of Contents will not be collapsible',
            'anchorkit_toc_initial_state': 'Table of Contents initial state updated',
            'anchorkit_toc_smooth_scroll': isChecked ? 'Table of Contents will use smooth scrolling' : 'Table of Contents will not use smooth scrolling',
            'anchorkit_toc_hierarchical_view': isChecked ? 'Table of Contents will show headings in a hierarchical view' : 'Table of Contents will not show headings in a hierarchical view',
            'anchorkit_toc_show_numerals': isChecked ? 'Table of Contents will show numerals' : 'Table of Contents will not show numerals',
            'anchorkit_toc_live_preview_enabled': isChecked ? 'Table of Contents live preview enabled' : 'Table of Contents live preview disabled',
            'anchorkit_toc_theme': 'Table of Contents theme updated',
            'anchorkit_toc_bg_color': 'Table of Contents background color updated',
            'anchorkit_toc_text_color': 'Table of Contents text color updated',
            'anchorkit_toc_link_color': 'Table of Contents link color updated',
            'anchorkit_toc_link_hover_color': 'Table of Contents link hover color updated',
            'anchorkit_toc_active_link_color': 'Table of Contents active link color updated',
            'anchorkit_toc_border_color': 'Table of Contents border color updated',
            'anchorkit_toc_font_family': 'Table of Contents font family updated',
            'anchorkit_toc_font_size': 'Table of Contents font size updated',
            'anchorkit_toc_padding': 'Table of Contents padding updated',
            'anchorkit_toc_border_width': 'Table of Contents border width updated',
            'anchorkit_toc_border_radius': 'Table of Contents border radius updated',
            'anchorkit_toc_include_headings': 'Table of Contents include headings updated',
            'anchorkit_toc_min_headings': 'Table of Contents minimum headings updated',
            'anchorkit_toc_exclude_selectors': 'Table of Contents exclude selectors updated',
            'anchorkit_toc_title_text': 'Table of Contents title text updated',
            'anchorkit_toc_hide_on_mobile': isChecked ? 'Table of Contents will be hidden on mobile devices' : 'Table of Contents will not be hidden on mobile devices',
            'anchorkit_toc_aria_label': 'Table of Contents aria label updated',
            'anchorkit_toc_back_to_top_link': isChecked ? 'Table of Contents will include a link to scroll back to top' : 'Table of Contents will not include a link to scroll back to top',
            'anchorkit_toc_back_to_top_text': 'Table of Contents back to top text updated',
            'anchorkit_toc_back_to_top_font_size': 'Table of Contents back to top font size updated',
            'anchorkit_toc_view_more_enabled': isChecked ? 'View More feature enabled' : 'View More feature disabled',
            'anchorkit_toc_initial_count': 'Initial visible TOC items count updated',
            'anchorkit_toc_view_more_text': 'View More button text updated',
            'anchorkit_toc_view_less_text': 'View Less button text updated',
            'anchorkit_toc_scroll_offset': 'Scroll offset updated',
            'anchorkit_toc_mobile_breakpoint': 'Mobile breakpoint updated',
            'anchorkit_toc_target_selector': 'Target element selector updated',
            'anchorkit_toc_custom_css': 'Custom CSS updated',
            'anchorkit_toc_exclude_selectors': 'Exclude selectors updated',
            'anchorkit_toc_custom_labels': 'Custom heading labels updated',
            'anchorkit_toc_label_text': 'TOC label text updated',
            'anchorkit_toc_show_label': isChecked ? 'TOC label will be shown' : 'TOC label will be hidden',
            'anchorkit_toc_bullet_style': 'Bullet style updated',
            'anchorkit_toc_bullet_character': 'Bullet character updated',
            'anchorkit_toc_bullet_color': 'Bullet color updated',
            'anchorkit_toc_width': 'TOC width updated',
            'anchorkit_toc_alignment': 'TOC alignment updated',
            'anchorkit_toc_style_preset': 'TOC style preset updated',
            'anchorkit_toc_custom_styling': isChecked ? 'Custom styling mode enabled' : 'Custom styling mode disabled',
            'anchorkit_toc_box_shadow_enabled': isChecked ? 'Box shadow enabled' : 'Box shadow disabled',
            'anchorkit_toc_entrance_animation': isChecked ? 'Entrance animation enabled' : 'Entrance animation disabled',
            'anchorkit_toc_show_reading_time': isChecked ? 'Reading time will be shown in TOC' : 'Reading time will not be shown in TOC',
            'anchorkit_toc_schema_enabled': isChecked ? 'Schema markup enabled' : 'Schema markup disabled'
        };

        // Generic fallback for live preview toggles
        if (name.endsWith('_live_preview_enabled')) {
            // Try to extract the feature name from the setting name
            let feature = name.replace(/^anchorkit_/, '').replace(/_live_preview_enabled$/, '').replace(/_/g, ' ');
            feature = feature.replace(/\b\w/g, c => c.toUpperCase()); // Capitalize each word
            return isChecked ? `${feature} live preview enabled` : `${feature} live preview disabled`;
        }

        return messages[name] || 'Setting updated';
    }

    /**
     * Check if a value has been recently updated to prevent duplicate requests
     * @param {string} name - The setting name
     * @param {mixed} value - The setting value
     * @return {boolean} Whether this is a duplicate update
     */
    function isDuplicateUpdate(name, value) {
        // No recent update for this setting
        if (!recentlyUpdatedValues[name]) {
            return false;
        }

        // Check if values are the same
        const recentValue = recentlyUpdatedValues[name].value;
        const isSameValue = JSON.stringify(value) === JSON.stringify(recentValue);

        // Check if time is within cooldown period (1 second)
        const timeSinceUpdate = Date.now() - recentlyUpdatedValues[name].time;
        const isWithinCooldown = timeSinceUpdate < 1000;

        return isSameValue && isWithinCooldown;
    }

    /**
     * Record a recent update to prevent duplicates
     * @param {string} name - The setting name
     * @param {mixed} value - The setting value
     */
    function recordUpdate(name, value) {
        recentlyUpdatedValues[name] = {
            value: value,
            time: Date.now()
        };
    }

    /**
     * Validate numeric input against min/max limits
     * @param {string} name - The setting name
     * @param {mixed} value - The setting value
     * @return {object} Validation result with value and isValid properties
     */
    function validateNumericInput(name, value) {
        // Define numeric limits for client-side validation
        const numericLimits = {
            'anchorkit_toc_font_size': [10, 24, 'int'],
            'anchorkit_toc_back_to_top_font_size': [10, 24, 'int'],
            'anchorkit_toc_padding': [0, 50, 'int'],
            'anchorkit_toc_border_width': [0, 10, 'int'],
            'anchorkit_toc_border_radius': [0, 30, 'int'],
            'anchorkit_toc_min_headings': [1, 10, 'int'],
            'anchorkit_toc_scroll_offset': [0, 200, 'int'],
            'anchorkit_toc_width': [20, 100, 'int'],
            'anchorkit_toc_mobile_breakpoint': [320, 1200, 'int'],
            // Pro features - Sticky TOC
            'anchorkit_toc_sticky_offset': [0, 200, 'int'],
            // Pro features - Advanced Styling
            'anchorkit_toc_shadow_h_offset_light': [-100, 100, 'int'],
            'anchorkit_toc_shadow_v_offset_light': [-100, 100, 'int'],
            'anchorkit_toc_shadow_blur_light': [0, 100, 'int'],
            'anchorkit_toc_shadow_spread_light': [-50, 50, 'int'],
            'anchorkit_toc_shadow_opacity_light': [0, 1, 'float'],
            'anchorkit_toc_shadow_h_offset_dark': [-100, 100, 'int'],
            'anchorkit_toc_shadow_v_offset_dark': [-100, 100, 'int'],
            'anchorkit_toc_shadow_blur_dark': [0, 100, 'int'],
            'anchorkit_toc_shadow_spread_dark': [-50, 50, 'int'],
            'anchorkit_toc_shadow_opacity_dark': [0, 1, 'float'],
            'anchorkit_toc_line_height': [1, 3, 'float'],
            'anchorkit_toc_letter_spacing': [-2, 5, 'float'],
            // Pro features - Smart Heading Detection
            'anchorkit_toc_min_heading_depth': [1, 6, 'int'],
            'anchorkit_toc_max_heading_depth': [1, 6, 'int'],
            // Pro features - Reading Time & Metadata
            'anchorkit_toc_reading_speed': [100, 400, 'int'],
            // Pro features - Enhanced Navigation
            'anchorkit_toc_scroll_duration': [200, 2000, 'int'],
            // Pro features - View More
            'anchorkit_toc_initial_count': [1, 50, 'int']
        };

        // Check if there are limits for this field
        if (numericLimits[name]) {
            const [min, max, type] = numericLimits[name];
            let numValue = type === 'int' ? parseInt(value, 10) : parseFloat(value);

            // Handle validation
            if (isNaN(numValue)) {
                return { value: min, isValid: false, message: 'Must be a valid number' };
            }

            if (numValue < min) {
                return { value: min, isValid: false, message: 'Minimum value is ' + min };
            }

            if (numValue > max) {
                return { value: max, isValid: false, message: 'Maximum value is ' + max };
            }

            return { value: numValue, isValid: true };
        }

        // If not a numeric field with limits, return as valid
        return { value: value, isValid: true };
    }

    /**
     * Show a validation error message near an input field
     * @param {jQuery} input - The input element
     * @param {string} message - The error message to display
     */
    function showFieldError(input, message) {
        // Remove any existing error notices
        removeFieldError(input);

        // Create MD3 compliant error styling with icon
        const errorNotice = $(
            '<div class="field-error-message">' +
            '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#B3261E" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>' +
            '<span>' + message + '</span>' +
            '</div>'
        );

        // Add error state to the input
        input.addClass('error');

        // Add the error message after the input container's parent
        // This positions it below the field rather than beside it
        input.closest('.form-group').append(errorNotice);

        // Auto-remove after 5 seconds
        setTimeout(() => {
            errorNotice.fadeOut(function () {
                $(this).remove();
                input.removeClass('error');
            });
        }, 5000);
    }

    /**
     * Remove validation error message from a field
     * @param {jQuery} input - The input element
     */
    function removeFieldError(input) {
        input.closest('.form-group').find('.field-error-message').remove();
        input.removeClass('error');
    }

    /**
     * Update a setting via AJAX
     * @param {string} name - Option name
     * @param {mixed} value - Option value
     * @param {string} group - Option group
     */
    function updateSetting(name, value, group) {
        // Skip if it's a duplicate
        if (isDuplicateUpdate(name, value)) {
            return;
        }

        // Record the update
        recordUpdate(name, value);

        // Update in DOM (skip for icon collection radio to preserve user selection state)
        if (name !== 'anchorkit_back_to_top_collection_icon') {
            updateInDOM(name, value);
        }

        // Note: Validation is now handled in the blur event listener for numeric inputs
        // This prevents duplicate error messages and allows immediate value correction

        // Prepare data for AJAX
        const data = {
            action: 'anchorkit_update_setting',
            option_name: name,
            option_value: value,
            group: group || '',
            nonce: anchorkit_ajax.nonce
        };

        // Send to server
        $.post(anchorkit_ajax.ajax_url, data, function (response) {
            // Log shadow component save success
            if (name && name.includes('shadow')) {
                anchorkitDebugLog('[AnchorKit Shadow] ✓ AJAX completed for:', name, '| Success:', response.success);
            }

            if (response.success) {
                // Update localized cache for cross-tab settings
                if (typeof anchorkit_ajax !== 'undefined') {
                    if (name === 'anchorkit_toc_style_preset') {
                        anchorkit_ajax.current_preset = value;
                    } else if (name === 'anchorkit_toc_custom_styling') {
                        anchorkit_ajax.custom_styling = value;
                    } else if (name === 'anchorkit_toc_show_label') {
                        anchorkit_ajax.show_label = value;
                    } else if (name === 'anchorkit_toc_title_text') {
                        anchorkit_ajax.title_text = value;
                    } else if (name === 'anchorkit_toc_collapsible') {
                        anchorkit_ajax.collapsible = value;
                    } else if (name === 'anchorkit_toc_hierarchical_view') {
                        anchorkit_ajax.hierarchical_view = value;
                    } else if (name === 'anchorkit_toc_bullet_style') {
                        anchorkit_ajax.bullet_style = value;
                    } else if (name === 'anchorkit_toc_bullet_character') {
                        anchorkit_ajax.bullet_character = value;
                    } else if (name === 'anchorkit_toc_view_more_enabled') {
                        anchorkit_ajax.view_more_enabled = value;
                    } else if (name === 'anchorkit_toc_initial_count') {
                        anchorkit_ajax.initial_count = value;
                    } else if (name === 'anchorkit_toc_view_more_text') {
                        anchorkit_ajax.view_more_text = value;
                    } else if (name === 'anchorkit_toc_view_less_text') {
                        anchorkit_ajax.view_less_text = value;
                    } else if (name === 'anchorkit_toc_back_to_top_link') {
                        anchorkit_ajax.back_to_top_link = value;
                    } else if (name === 'anchorkit_toc_back_to_top_text') {
                        anchorkit_ajax.back_to_top_text = value;
                    } else if (name === 'anchorkit_toc_back_to_top_font_size') {
                        anchorkit_ajax.back_to_top_font_size = value;
                    } else if (name === 'anchorkit_toc_alignment') {
                        anchorkit_ajax.alignment = value;
                    }
                }

                // Refresh UI components after AJAX success
                refreshUIComponents();

                // Show notification
                showNotification(getUpdateMessage(name, value));

                // If the setting is collection icon, ensure the chosen radio remains checked
                if (name === 'anchorkit_back_to_top_collection_icon') {
                    const selector = 'input[name="' + name + '"][value="' + value + '"]';
                    $(selector).prop('checked', true);
                    if (typeof highlightSelectedIcon === 'function') {
                        highlightSelectedIcon();
                    }
                }

                // Update reset button state
                const $settingInput = $('input[name="' + name + '"], select[name="' + name + '"]');
                const $card = $settingInput.closest('.anchorkit-card');

                // Check if we have all the settings in the card
                if ($card.length) {
                    const settings = getCardSettings($card);
                    updateResetButtonState($card, settings);
                }

                // Update global reset button
                updateGlobalResetButtonState();
            } else {
                // Only show inline field error if not auto-correcting (suppress global toast)
                const $settingInput = $('input[name="' + name + '"], select[name="' + name + '"]');
                const isAutoCorrecting = $settingInput.data('auto-correcting');

                if (!isAutoCorrecting) {
                    console.error('Error updating setting:', response.data);
                    // Prefer field-level error to avoid duplicate global notifications
                    showFieldError($settingInput, 'Could not save. Please try again.');
                    // Auto-clear after a short delay
                    setTimeout(function () { removeFieldError($settingInput); }, 4000);
                }
            }
        }).fail(function (xhr, status, error) {
            // Only show inline field error if not auto-correcting (suppress global toast)
            const $settingInput = $('input[name="' + name + '"], select[name="' + name + '"]');
            const isAutoCorrecting = $settingInput.data('auto-correcting');

            if (!isAutoCorrecting) {
                console.error('AJAX error:', status, error, xhr);
                showFieldError($settingInput, 'Network error. Please try again.');
                setTimeout(function () { removeFieldError($settingInput); }, 4000);
            }
        });
    }

    // Create debounced versions of updateSetting for different input types
    const debouncedUpdateSetting = debounce(updateSetting, 500);
    const debouncedColorUpdate = debounce(updateSetting, 100);

    // Expose core update helpers globally for cross-script usage (e.g., preview scripts)
    window.anchorkitUpdateSetting = updateSetting;
    window.anchorkitDebouncedUpdateSetting = debouncedUpdateSetting;
    window.anchorkitDebouncedColorUpdate = debouncedColorUpdate;

    /**
     * Initialize event listeners for form elements
     */
    function initializeFormListeners() {
        // Find all forms in the admin area
        const forms = $('.anchorkit-admin form');

        // Remove their submit event to prevent traditional form submission
        forms.on('submit', function (e) {
            e.preventDefault();
            return false;
        });

        // Remove the submit button
        forms.find('.submit').remove();

        // Store original form values
        forms.find('input, select, textarea').each(function () {
            const input = $(this);
            const name = input.attr('name');

            if (!name) return;

            // Store checkbox or radio values
            if (input.attr('type') === 'checkbox' || input.attr('type') === 'radio') {
                originalFormValues[name] = input.prop('checked');
            }
            // Store array values
            else if (name.endsWith('[]')) {
                const baseName = name.slice(0, -2);
                if (!originalFormValues[baseName]) {
                    originalFormValues[baseName] = [];
                }
                if (input.prop('checked')) {
                    originalFormValues[baseName].push(input.val());
                }
            }
            // Store regular input values
            else {
                originalFormValues[name] = input.val();
            }
        });

        // Attach change event handlers to form elements
        forms.find('input, select, textarea').on('change', function () {
            const input = $(this);

            if (input.is(':disabled')) {
                return;
            }

            const name = input.attr('name');
            const group = getOptionGroup(input);

            if (!name) return;

            // Live update info box when custom styling toggle changes
            if (name === 'anchorkit_toc_custom_styling') {
                updateCustomStylingInfoBox(input.is(':checked'));
            }

            // Update preset info box when preset changes
            if (name === 'anchorkit_toc_style_preset') {
                // For radio buttons, get the value, not boolean
                const presetValue = input.is(':radio') ? input.val() : value;
                updatePresetInfoBox(presetValue);

                // Also update the custom styling activation card to show the new preset name
                const $customStylingToggle = $('input[name="anchorkit_toc_custom_styling"]');
                if ($customStylingToggle.length) {
                    updateCustomStylingInfoBox($customStylingToggle.is(':checked'));
                }
            }

            // Check for numeric field validation on blur (after user finishes typing)
            if (input.is('input[type="number"]') || (input.is('input[type="text"]') && !isNaN(parseFloat(input.val())))) {
                input.on('blur', function () {
                    const $input = $(this);
                    const currentValue = $input.val();

                    // Always clear the auto-correcting flag at the start of validation
                    // This ensures subsequent validations work correctly
                    $input.data('auto-correcting', false);

                    // Clear any existing error timeout
                    const existingTimeout = $input.data('error-timeout');
                    if (existingTimeout) {
                        clearTimeout(existingTimeout);
                        $input.data('error-timeout', null);
                    }

                    const validationResult = validateNumericInput(name, currentValue);

                    if (!validationResult.isValid) {
                        anchorkitDebugLog('Validation failed for', name, '- Current:', currentValue, 'Correcting to:', validationResult.value);

                        // Mark that we're auto-correcting (prevents change event from firing)
                        $input.data('auto-correcting', true);

                        // Update the input with the corrected value
                        $input.val(validationResult.value);

                        // Show field error message (below the field)
                        showFieldError($input, validationResult.message);

                        // Directly save without triggering change event
                        $.post(anchorkit_ajax.ajax_url, {
                            action: 'anchorkit_update_setting',
                            option_name: name,
                            option_value: validationResult.value,
                            group: group || '',
                            nonce: anchorkit_ajax.nonce
                        }, function (response) {
                            if (response.success) {
                                anchorkitDebugLog('Auto-corrected value saved:', name, validationResult.value);
                            } else {
                                console.error('Failed to save auto-corrected value:', response);
                            }
                        }).fail(function (xhr, status, error) {
                            console.error('AJAX error during auto-correction:', error);
                        });

                        // Update previews with the valid value
                        const card = $input.closest('.anchorkit-card');
                        if (card.length) {
                            updatePreviewIfExists(card);
                        }

                        // Auto-clear the error and flag after 4 seconds
                        const errorTimeout = setTimeout(function () {
                            removeFieldError($input);
                            $input.data('auto-correcting', false);
                            $input.data('error-timeout', null);
                            anchorkitDebugLog('Cleared error for', name);
                        }, 4000);

                        // Store the timeout ID so we can clear it if needed
                        $input.data('error-timeout', errorTimeout);
                    } else {
                        // Valid input, remove any existing errors
                        anchorkitDebugLog('Validation passed for', name, '- Value:', currentValue);
                        removeFieldError($input);
                        $input.data('auto-correcting', false);
                    }
                });
            }

            // Handle different input types
            if (input.attr('type') === 'checkbox') {
                // Handle checkbox arrays
                if (name.endsWith('[]')) {
                    const baseName = name.slice(0, -2);
                    const checkboxes = $(`input[name="${name}"]:checked`);
                    const values = checkboxes.map(function () {
                        return $(this).val();
                    }).get();

                    debouncedUpdateSetting(baseName, values, group);
                } else {
                    // Regular checkbox
                    debouncedUpdateSetting(name, input.prop('checked') ? 1 : 0, group);

                    // Manually trigger conditional field visibility update for this checkbox
                    updateConditionalFieldsForControl(input);
                }
            } else if (input.attr('type') === 'radio') {
                // Immediately update on radio button change to persist selection
                updateSetting(name, input.val(), group);

                // Manually trigger conditional field visibility update for radio buttons
                updateConditionalFieldsForControl(input);
            } else {
                // Regular inputs, selects, textareas
                // Skip if we're auto-correcting (validation already saved it)
                if (!input.data('auto-correcting')) {
                    debouncedUpdateSetting(name, input.val(), group);
                }

                // For selects, also update conditional fields immediately
                if (input.is('select')) {
                    updateConditionalFieldsForControl(input);
                }
            }
        });

        // Special handling for color inputs
        forms.find('input[type="color"]').each(function () {
            const colorInput = $(this);
            const container = colorInput.closest('.input-container');

            // Remove any existing color-value spans
            container.find('.color-value').not(':first').remove();

            // Get or create the color value span
            let colorValue = container.find('.color-value');
            if (colorValue.length === 0) {
                colorValue = $('<span class="color-value"></span>');
                container.append(colorValue);
            }

            // Update the color value display
            colorValue.text(colorInput.val().toUpperCase());

            // Track color input changes
            colorInput.on('input', function () {
                const newValue = $(this).val().toUpperCase();
                colorValue.text(newValue);
            });
        });

        // Prevent clicks on toggle switch label text from triggering the checkbox
        // Only allow clicks directly on the .m3-track to toggle
        initializeToggleSwitchRestrictions();
    }

    /**
     * Restrict toggle switch clicks to only the track area
     * Prevents accidental toggles when clicking on white space or label text
     */
    function initializeToggleSwitchRestrictions() {
        // Explicitly handle clicks on the track/thumb to toggle the checkbox
        // This must be handled BEFORE the label wrapper handler to prevent double-triggering
        $(document).on('click', '.m3-track, .m3-thumb', function (e) {
            e.stopPropagation(); // Prevent bubbling to label wrapper
            e.preventDefault(); // Prevent default label behavior
            const $switch = $(this).closest('.m3-switch');
            const checkbox = $switch.find('input[type="checkbox"]');

            if (checkbox.length) {
                // Toggle the checkbox
                checkbox.prop('checked', !checkbox.prop('checked')).trigger('change');
            }

            return false;
        });

        // Prevent all other clicks on the label wrapper from triggering the checkbox
        $(document).on('click', '.m3-switch', function (e) {
            // If click originated from track/thumb, it's already handled above
            if ($(e.target).closest('.m3-track').length > 0) {
                return; // Already handled
            }

            // Block all other clicks (label text, whitespace, etc.)
            e.preventDefault();
            e.stopPropagation();
            return false;
        });
    }

    /**
     * Get the option group from a form element
     * @param {jQuery} element - The form element
     * @return {string} The option group name
     */
    function getOptionGroup(element) {
        const form = element.closest('form');
        const hiddenInputs = form.find('input[type="hidden"]');

        for (let i = 0; i < hiddenInputs.length; i++) {
            const input = $(hiddenInputs[i]);
            const name = input.attr('name');

            if (name && name.includes('_nonce')) {
                // Extract group name from the nonce field name
                // e.g. reading_time_settings_group-options-nonce
                const match = name.match(/^(.+?)-options-nonce$/);
                if (match && match[1]) {
                    return match[1];
                }
            }
        }

        return '';
    }

    /**
     * Add event listener for notification close button
     */
    function initializeNotification() {
        $(document).on('click', '#anchorkit-notification .anchorkit-notification-close', function () {
            const notification = $('#anchorkit-notification');

            // Clear any existing timeout
            if (notificationTimeout) {
                clearTimeout(notificationTimeout);
            }

            // Hide the notification
            notification.css({
                'opacity': '0',
                'visibility': 'hidden',
                'transform': 'translateX(-50%) translateY(20px)'
            });
        });
    }

    /**
     * Add reset to default buttons to applicable cards
     */
    function addResetButtons() {
        // Define default values for settings
        const defaultValues = {

            // Table of Contents Settings
            'anchorkit_toc_enabled': true,
            'anchorkit_toc_post_types': ['post', 'page'],
            'anchorkit_toc_automatic_insertion': true,
            'anchorkit_toc_position': 'before_first_heading',
            'anchorkit_toc_collapsible': true,
            'anchorkit_toc_initial_state': 'expanded',
            'anchorkit_toc_smooth_scroll': true,
            'anchorkit_toc_hierarchical_view': true,
            'anchorkit_toc_show_numerals': false,
            'anchorkit_toc_bullet_style': 'disc',
            'anchorkit_toc_bullet_character': '•',
            'anchorkit_toc_numbering_style': 'hierarchical',
            'anchorkit_toc_numbering_format': 'decimal',
            'anchorkit_toc_numbering_separator': '.',
            'anchorkit_toc_live_preview_enabled': false,
            'anchorkit_toc_theme': 'system',
            // Light mode color defaults
            'anchorkit_toc_bg_color_light': '#FFFFFF',
            'anchorkit_toc_text_color_light': '#333333',
            'anchorkit_toc_link_color_light': '#0073AA',
            'anchorkit_toc_link_hover_color_light': '#005177',
            'anchorkit_toc_active_link_color_light': '#00A0D2',
            'anchorkit_toc_border_color_light': '#DDDDDD',
            'anchorkit_toc_bullet_color_light': '#0073AA',
            // Dark mode color defaults
            'anchorkit_toc_bg_color_dark': '#1e1e1e',
            'anchorkit_toc_text_color_dark': '#e0e0e0',
            'anchorkit_toc_link_color_dark': '#7ec4ee',
            'anchorkit_toc_link_hover_color_dark': '#a8d8f0',
            'anchorkit_toc_active_link_color_dark': '#5ba3d0',
            'anchorkit_toc_border_color_dark': '#404040',
            'anchorkit_toc_bullet_color_dark': '#7ec4ee',
            // Legacy color defaults (keep for backward compatibility)
            'anchorkit_toc_bg_color': '#FFFFFF',
            'anchorkit_toc_text_color': '#333333',
            'anchorkit_toc_link_color': '#0073AA',
            'anchorkit_toc_link_hover_color': '#005177',
            'anchorkit_toc_active_link_color': '#00A0D2',
            'anchorkit_toc_border_color': '#DDDDDD',
            'anchorkit_toc_font_family': 'inherit',
            'anchorkit_toc_font_size': 14,
            'anchorkit_toc_padding': 15,
            'anchorkit_toc_border_width': 1,
            'anchorkit_toc_border_radius': 4,
            'anchorkit_toc_include_headings': ['h2', 'h3', 'h4'],
            'anchorkit_toc_min_headings': 2,
            'anchorkit_toc_exclude_selectors': '',
            'anchorkit_toc_title_text': 'Table of Contents',
            'anchorkit_toc_show_label': true,
            'anchorkit_toc_style_preset': 'minimal',
            'anchorkit_toc_scroll_offset': 0,
            'anchorkit_toc_width': 80,
            'anchorkit_toc_alignment': 'center',
            'anchorkit_toc_float': 'none',
            'anchorkit_toc_custom_styling': false,
            'anchorkit_toc_hide_on_mobile': false,
            'anchorkit_toc_mobile_breakpoint': 782,
            'anchorkit_toc_aria_label': '',
            'anchorkit_toc_back_to_top_link': false,
            'anchorkit_toc_back_to_top_text': 'Back to Top',
            'anchorkit_toc_back_to_top_font_size': 14,
            'anchorkit_toc_custom_labels': '',
            'anchorkit_toc_anchor_format': 'auto',
            'anchorkit_toc_anchor_prefix': 'section',
            // Pro features - Sticky TOC
            'anchorkit_toc_sticky_enabled': false,
            'anchorkit_toc_sticky_position': 'content',
            'anchorkit_toc_sticky_offset': 20,
            // Pro features - Advanced Styling
            'anchorkit_toc_box_shadow_enabled': false,
            'anchorkit_toc_box_shadow_custom': '0 4px 6px rgba(0, 0, 0, 0.1)',
            'anchorkit_toc_box_shadow_light': '0 4px 6px rgba(0, 0, 0, 0.1)',
            'anchorkit_toc_box_shadow_dark': '0 2px 8px rgba(0, 0, 0, 0.3)',
            // Box Shadow Components - Light Mode
            'anchorkit_toc_shadow_h_offset_light': 0,
            'anchorkit_toc_shadow_v_offset_light': 4,
            'anchorkit_toc_shadow_blur_light': 6,
            'anchorkit_toc_shadow_spread_light': 0,
            'anchorkit_toc_shadow_color_light': '#000000',
            'anchorkit_toc_shadow_opacity_light': 0.1,
            // Box Shadow Components - Dark Mode
            'anchorkit_toc_shadow_h_offset_dark': 0,
            'anchorkit_toc_shadow_v_offset_dark': 2,
            'anchorkit_toc_shadow_blur_dark': 8,
            'anchorkit_toc_shadow_spread_dark': 0,
            'anchorkit_toc_shadow_color_dark': '#000000',
            'anchorkit_toc_shadow_opacity_dark': 0.3,
            'anchorkit_toc_entrance_animation': false,
            'anchorkit_toc_animation_type': 'fade',
            'anchorkit_toc_line_height': 1.6,
            'anchorkit_toc_letter_spacing': 0,
            'anchorkit_toc_text_transform': 'none',
            'anchorkit_toc_link_underline': 'none',
            'anchorkit_toc_custom_id': '',
            'anchorkit_toc_custom_class': '',
            'anchorkit_toc_custom_css': '',
            // Pro features - Advanced Typography
            'anchorkit_toc_advanced_typography_override': false,
            'anchorkit_toc_title_font_size': '20',
            'anchorkit_toc_h2_font_size': '18',
            'anchorkit_toc_h3_font_size': '16',
            'anchorkit_toc_h4_font_size': '14',
            'anchorkit_toc_h5_font_size': '13',
            'anchorkit_toc_h6_font_size': '12',
            // Pro features - Advanced Content Filtering
            'anchorkit_toc_exclude_keywords': '',
            'anchorkit_toc_exclude_regex': '',
            // Pro features - Smart Heading Detection
            'anchorkit_toc_auto_fix_hierarchy': false,
            'anchorkit_toc_min_heading_depth': 2,
            'anchorkit_toc_max_heading_depth': 4,
            // Pro features - Reading Time & Metadata
            'anchorkit_toc_show_reading_time': false,
            'anchorkit_toc_reading_speed': 200,
            'anchorkit_toc_show_word_count': false,
            'anchorkit_toc_time_format': 'min_read',
            // Pro features - Schema.org & Rich Snippets
            'anchorkit_toc_schema_enabled': false,
            'anchorkit_toc_schema_type': 'Article',
            // Pro features - Enhanced Navigation
            'anchorkit_toc_scroll_easing': 'ease-in-out',
            'anchorkit_toc_scroll_duration': 500,
            // Pro features - View More
            'anchorkit_toc_view_more_enabled': false,
            'anchorkit_toc_initial_count': 5,
            'anchorkit_toc_view_more_text': 'View More',
            'anchorkit_toc_view_less_text': 'View Less',
            // Pro features - ACF Integration
            'anchorkit_toc_acf_enabled': false,
            'anchorkit_toc_acf_field_names': '',
            'anchorkit_toc_acf_merge_mode': 'after',
            // Pro features - AMP Compatibility
            'anchorkit_toc_amp_enabled': false
        };

        // Reset icon as SVG
        const resetIcon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 12h7V5l-2.35 1.35z"/></svg>';

        // Check each card if it has any settings that can be reset
        $('.anchorkit-card').each(function () {
            const card = $(this);
            let hasResettableSettings = false;
            const settingsInCard = {};

            // Find all inputs in the card
            card.find('input, select, textarea').each(function () {
                const input = $(this);
                const name = input.attr('name');

                // Skip inputs without names or array inputs that aren't radio buttons
                if (!name || (name.endsWith('[]') && input.attr('type') !== 'radio')) return;

                // Check if this setting has a default value
                if (defaultValues.hasOwnProperty(name)) {
                    hasResettableSettings = true;
                    settingsInCard[name] = {
                        element: input,
                        defaultValue: defaultValues[name]
                    };
                }
            });

            // Special case: do NOT add a reset button to the Table of Contents Activation card (only contains anchorkit_toc_enabled toggle)
            const isTocActivationCard = card.find('input[name="anchorkit_toc_enabled"]').length === 1 && card.find('input, select, textarea').length === 1;
            if (isTocActivationCard) return;

            // Add reset button if the card has resettable settings
            if (hasResettableSettings) {
                // Create button if it doesn't exist
                if (card.find('.anchorkit-reset-button').length === 0) {
                    const resetButton = $(`<button type="button" class="anchorkit-reset-button">${resetIcon} Reset to Default</button>`);
                    card.append(resetButton);

                    // Add click handler for the reset button
                    resetButton.on('click', function (e) {
                        // Prevent default action for all clicks
                        e.preventDefault();

                        // Check if button is disabled in any way
                        if ($(this).prop('disabled') || $(this).hasClass('disabled') || $(this).attr('aria-disabled') === 'true') {
                            // Stop propagation to prevent any parent handlers from firing
                            e.stopPropagation();
                            return false;
                        }

                        // Store reference to the card and settings
                        const $dialog = $('#anchorkit-reset-dialog');
                        $dialog.data('card', card);
                        $dialog.data('settings', settingsInCard);

                        // Show the confirmation dialog after a brief delay
                        setTimeout(() => {
                            $dialog.show();
                        }, 50);

                        // Set up the confirm button action
                        $('.anchorkit-modal-confirm').off('click').on('click', function () {
                            // Get the stored card and settings
                            const targetCard = $dialog.data('card');
                            const targetSettings = $dialog.data('settings');

                            // Hide the dialog
                            $dialog.hide();

                            // Reset the settings
                            resetCardSettings(targetCard, targetSettings);
                        });
                    });

                    // Store settings in card data for later reference
                    card.data('settingsInCard', settingsInCard);

                    // Check if any settings need reset and update button state
                    updateResetButtonState(card, settingsInCard);

                    // Add change event listeners to all inputs in the card
                    Object.keys(settingsInCard).forEach(settingName => {
                        const setting = settingsInCard[settingName];
                        const input = setting.element;

                        // When a setting changes, update the reset button state
                        if (settingName === 'anchorkit_back_to_top_show_test_button') {
                            // Special handling for test button toggle
                            input.on('change click', function () {
                                setTimeout(() => {
                                    updateResetButtonState(card, settingsInCard);
                                }, 100);
                            });
                        } else {
                            // Standard handling for other inputs
                            input.on('change input', function () {
                                updateResetButtonState(card, settingsInCard);
                            });
                        }
                    });

                    // Add event listener for collection icon radio buttons
                    card.find('input[name="anchorkit_back_to_top_collection_icon"]').on('change', function () {
                        updateResetButtonState(card, settingsInCard);
                    });

                } else {
                    // If button already exists, just update its state
                    updateResetButtonState(card, settingsInCard);
                }
            }
        });
    }

    /**
     * Update the state of a reset button based on whether any settings need to be reset
     * @param {jQuery} card - The card element
     * @param {Object} settings - Object with settings in the card
     */
    function updateResetButtonState(card, settings) {
        const resetButton = card.find('.anchorkit-reset-button');
        if (!resetButton.length) return;

        // Check if this is the Scrolling Behavior card
        const isScrollBehaviorCard = card.find('h2').text().includes('Scrolling Behavior');

        // NEW: Check if this is the Icon Style card so we can apply special logic
        const isIconStyleCard = card.find('h2').text().includes('Icon Style');

        // Check if any settings differ from their default values
        let needsReset = false;
        let debugInfo = {};

        Object.keys(settings).forEach(name => {
            const setting = settings[name];
            const input = setting.element;
            const defaultValue = setting.defaultValue;
            const currentValue = getCurrentInputValue(input);

            // Store debug info
            if (isScrollBehaviorCard) {
                debugInfo[name] = {
                    defaultValue: defaultValue,
                    currentValue: currentValue,
                    isDifferent: !valuesEqual(currentValue, defaultValue)
                };
            }

            // Compare current value with default
            if (!valuesEqual(currentValue, defaultValue)) {
                needsReset = true;
            }
        });

        // Special handling for radio button collection icons
        if (card.find('input[name="anchorkit_back_to_top_collection_icon"]').length) {
            const defaultIcon = 'a-arrow-up-bold.svg';
            // Use fallback default if none selected
            let selectedIcon = card.find('input[name="anchorkit_back_to_top_collection_icon"]:checked').val();
            selectedIcon = selectedIcon || defaultIcon;
            if (selectedIcon !== defaultIcon) {
                needsReset = true;
            }
        }

        // Specific check for Scrolling Behavior card with Auto Hide toggle and Animation Type
        if (isScrollBehaviorCard) {
            anchorkitDebugLog('Scrolling Behavior Card Settings:', {
                needsReset: needsReset,
                settingsDebug: debugInfo
            });

            // Check main settings directly with hard-coded values
            const autohideChecked = card.find('input[name="anchorkit_back_to_top_autohide"]').prop('checked');
            const scrollDuration = card.find('input[name="anchorkit_back_to_top_scroll_duration"]').val();
            const animationType = card.find('select[name="anchorkit_back_to_top_scroll_animation"]').val();
            const autoHideDelay = card.find('input[name="anchorkit_back_to_top_auto_hide_after"]').val();

            // Check if all settings match their defaults
            const allAtDefaults =
                autohideChecked === true &&
                scrollDuration === '400' &&
                animationType === 'linear' &&
                autoHideDelay === '0';

            anchorkitDebugLog('Direct check results:', {
                autohideChecked,
                scrollDuration,
                animationType,
                autoHideDelay,
                allAtDefaults
            });

            // If all settings match defaults, force button to disabled state regardless of comparison result
            if (allAtDefaults) {
                needsReset = false;
            }
        }

        // NEW: Specific check for Icon Style card. If ALL icon-related settings match their
        // defaults we force the button into the disabled state.
        if (isIconStyleCard) {
            // Collect current icon settings directly from the DOM after any changes/reset
            const iconColor = card.find('input[name="anchorkit_back_to_top_icon_color"]').val().toLowerCase();
            const iconWidth = card.find('input[name="anchorkit_back_to_top_icon_width"]').val();
            const iconHeight = card.find('input[name="anchorkit_back_to_top_icon_height"]').val();
            // Use fallback to default if none selected
            let selectedIcon = card.find('input[name="anchorkit_back_to_top_collection_icon"]:checked').val();
            selectedIcon = selectedIcon || 'a-arrow-up-bold.svg';
            const allAtDefaults = (
                iconColor === '#ffffff' &&
                iconWidth === '16' &&
                iconHeight === '16' &&
                selectedIcon === 'a-arrow-up-bold.svg'
            );

            // Debug output to help trace issues when testing
            anchorkitDebugLog('Icon Style Card – direct defaults check', {
                iconColor,
                iconWidth,
                iconHeight,
                selectedIcon,
                allAtDefaults,
                needsResetBefore: needsReset
            });

            if (allAtDefaults) {
                needsReset = false;
            }
        }

        // Update button state
        if (needsReset) {
            resetButton.removeClass('disabled');
            resetButton.prop('disabled', false);
            resetButton.attr('aria-disabled', 'false');
            resetButton.attr('title', 'Reset these settings to their default values');
            resetButton.css('opacity', '');
        } else {
            resetButton.addClass('disabled');
            resetButton.prop('disabled', true);
            resetButton.attr('aria-disabled', 'true');
            resetButton.attr('title', 'Settings are already at default values');
            resetButton.css('opacity', '0.38');
        }
    }

    /**
     * Get the current value of an input element
     * @param {jQuery} input - The input element
     * @return {*} The current value of the input
     */
    function getCurrentInputValue(input) {
        if (input.attr('type') === 'checkbox') {
            return input.prop('checked');
        } else if (input.attr('type') === 'radio') {
            // For radio inputs, return the selected value of the group
            return $(`input[name="${input.attr('name')}"]:checked`).val();
        } else if (input.attr('type') === 'color') {
            return input.val().toLowerCase();
        } else if (input.is('select')) {
            return input.val();
        } else {
            return input.val();
        }
    }

    /**
     * Compare two values for equality, handling special cases
     * @param {*} value1 - First value
     * @param {*} value2 - Second value
     * @return {boolean} Whether the values are equal
     */
    function valuesEqual(value1, value2) {
        // Handle color values (normalize to lowercase)
        if (typeof value1 === 'string' && typeof value2 === 'string' &&
            (value1.startsWith('#') || value2.startsWith('#'))) {
            return value1.toLowerCase() === value2.toLowerCase();
        }

        // Handle boolean/checkbox values
        if (typeof value1 === 'boolean' || typeof value2 === 'boolean') {
            // Convert string '1'/'0' to boolean if needed
            if (value1 === '1') value1 = true;
            if (value1 === '0') value1 = false;
            if (value2 === '1') value2 = true;
            if (value2 === '0') value2 = false;

            // Convert truthy/falsy values for checkboxes
            return Boolean(value1) === Boolean(value2);
        }

        // Handle numeric values
        if (!isNaN(value1) && !isNaN(value2)) {
            return Number(value1) === Number(value2);
        }

        // Default comparison
        return value1 === value2;
    }

    /**
     * Reset settings in a card to their default values
     * @param {jQuery} card - The card element
     * @param {Object} settings - Object with settings to reset
     */
    function resetCardSettings(card, settings) {
        // Extract setting names from the settings object
        const settingNames = Object.keys(settings);

        // Check if this card contains the collection icon radio buttons
        const hasIconCollection = card.find('input[name="anchorkit_back_to_top_collection_icon"]').length > 0;

        // Add collection icon to settings if present in this card but not already included
        if (hasIconCollection && !settingNames.includes('anchorkit_back_to_top_collection_icon')) {
            settingNames.push('anchorkit_back_to_top_collection_icon');
        }

        // Send AJAX request to reset the settings
        $.ajax({
            url: anchorkit_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'anchorkit_reset_settings',
                settings: settingNames,
                nonce: anchorkit_ajax.nonce
            },
            beforeSend: function () {
                // Show loading indicator
                showNotification('Resetting settings...', 'info');
            },
            success: function (response) {
                if (response.success) {
                    // Log debug information
                    anchorkitDebugLog('Reset settings response:', response);

                    // Process the response
                    if (response.data.success_count > 0) {
                        // Update the UI based on the reset values
                        Object.keys(settings).forEach(name => {
                            const setting = settings[name];
                            const input = setting.element;
                            const defaultValue = setting.defaultValue;

                            if (!input || input.length === 0) return;

                            if (input.attr('type') === 'checkbox') {
                                const wasChecked = input.prop('checked');
                                input.prop('checked', defaultValue);
                                const isChecked = input.prop('checked');

                                if (wasChecked !== isChecked) {
                                    let triggerChangeEvent = false;
                                    const togglesRequiringChangeEvent = [
                                        "anchorkit_back_to_top_autohide",
                                        "anchorkit_back_to_top_progress_indicator",
                                        "anchorkit_back_to_top_hide_small_device",
                                        "anchorkit_back_to_top_hide_small_window",
                                        "anchorkit_insert_before_excerpt",
                                        "anchorkit_insert_before_content",
                                        "anchorkit_toc_live_preview_enabled",
                                        "anchorkit_toc_hierarchical_view",
                                        "anchorkit_toc_show_numerals",
                                        "anchorkit_toc_collapsible",
                                        "anchorkit_toc_box_shadow_enabled",
                                        "anchorkit_toc_entrance_animation",
                                        "anchorkit_toc_custom_styling",
                                        "anchorkit_toc_hide_on_mobile",
                                        "anchorkit_toc_back_to_top_link",
                                        "anchorkit_toc_show_reading_time",
                                        "anchorkit_toc_schema_enabled",
                                        "anchorkit_toc_show_label",
                                        "anchorkit_toc_view_more_enabled",
                                        "anchorkit_toc_smooth_scroll",
                                        "anchorkit_toc_automatic_insertion",
                                        "anchorkit_toc_advanced_typography_override",
                                        "anchorkit_toc_sticky_enabled",
                                        "anchorkit_toc_acf_enabled",
                                    ];

                                    if (togglesRequiringChangeEvent.includes(name)) {
                                        triggerChangeEvent = true;
                                    }

                                    if (triggerChangeEvent) {
                                        setTimeout(function () {
                                            input.trigger("change");
                                            if (name === "anchorkit_insert_before_excerpt") {
                                                $('.anchorkit-excerpt-card').toggleClass('anchorkit-hidden-card', !input.prop('checked'));
                                            }
                                            // Update conditional fields visibility for advanced typography override
                                            if (name === "anchorkit_toc_advanced_typography_override") {
                                                updateConditionalFieldsForControl(input);
                                            }
                                            // Update conditional fields visibility for sticky TOC toggle
                                            if (name === "anchorkit_toc_sticky_enabled") {
                                                updateConditionalFieldsForControl(input);
                                            }
                                            // Update conditional fields visibility for ACF Integration toggle
                                            if (name === "anchorkit_toc_acf_enabled") {
                                                updateConditionalFieldsForControl(input);
                                            }
                                            // Update shadow component fields when box shadow is reset
                                            if (name === "anchorkit_toc_box_shadow_enabled") {
                                                updateConditionalFieldsForControl(input);
                                                // Also update visible shadow component fields to show reset values
                                                updateShadowComponentFieldsAfterReset();
                                            }
                                        }, 10);
                                    }
                                }

                                if (name === 'anchorkit_back_to_top_show_test_button') {
                                    anchorkitDebugLog('Reset test button toggle to:', defaultValue);
                                    setTimeout(function () {
                                        if (typeof window.updateTestButton === 'function') {
                                            anchorkitDebugLog('Direct call to updateTestButton after resetting toggle');
                                            window.updateTestButton();
                                        } else {
                                            console.error('updateTestButton function not available globally');
                                        }
                                    }, 100);
                                }
                            } else if (input.attr('type') === 'radio') {
                                card.find(`input[name="${name}"][value="${defaultValue}"]`).prop('checked', true);
                            } else if (input.attr('type') === 'color') {
                                input.val(defaultValue);
                                const valueDisplay = input.siblings('.color-value');
                                if (valueDisplay.length) {
                                    valueDisplay.text(defaultValue.toUpperCase());
                                }
                                if (name === 'anchorkit_back_to_top_progress_color') {
                                    input.trigger('input');
                                }
                            } else if (input.is('select')) {
                                input.val(defaultValue);
                                // Trigger change for selects that control conditional fields
                                if (name === 'anchorkit_back_to_top_icon_type' || name === 'anchorkit_toc_anchor_format') {
                                    input.trigger('change');
                                }
                            } else {
                                input.val(defaultValue);
                                if (name === 'anchorkit_back_to_top_progress_thickness') {
                                    input.trigger('input');
                                }
                                // Re-render custom labels interface when reset
                                if (name === 'anchorkit_toc_custom_labels' && typeof window.renderCustomLabels === 'function') {
                                    setTimeout(function () {
                                        window.renderCustomLabels();
                                    }, 10);
                                }
                                // Re-render ACF fields interface when reset
                                if (name === 'anchorkit_toc_acf_field_names' && typeof window.renderACFFields === 'function') {
                                    setTimeout(function () {
                                        window.renderACFFields();
                                    }, 10);
                                }
                                // Re-render CSS classes interface when reset
                                if (name === 'anchorkit_toc_custom_class' && typeof window.renderCSSClasses === 'function') {
                                    setTimeout(function () {
                                        window.renderCSSClasses();
                                    }, 10);
                                }
                            }
                        });

                        if (hasIconCollection &&
                            response.data.results &&
                            response.data.results['anchorkit_back_to_top_collection_icon'] &&
                            response.data.results['anchorkit_back_to_top_collection_icon'].status === 'success') {
                            const defaultIcon = 'a-arrow-up-bold.svg';
                            anchorkitDebugLog('Resetting icon to default:', defaultIcon);
                            const iconRadio = card.find(`input[name="anchorkit_back_to_top_collection_icon"][value="${defaultIcon}"]`);
                            iconRadio.prop('checked', true);
                            iconRadio.trigger('change');
                            iconRadio.closest('.icon-option').click();
                            $('input[name="anchorkit_back_to_top_collection_icon"]').not(`[value="${defaultIcon}"]`).prop('checked', false);
                            setTimeout(function () {
                                if ($('input[name="anchorkit_back_to_top_collection_icon"]:checked').val() !== defaultIcon) {
                                    $('input[name="anchorkit_back_to_top_collection_icon"]').prop('checked', false);
                                    iconRadio.prop('checked', true).trigger('change');
                                }
                            }, 50);
                        }

                        const hasBackToTopSettings = Object.keys(settings).some(name => name.startsWith('anchorkit_back_to_top_'));

                        if ((hasBackToTopSettings || hasIconCollection) && typeof window.updateButtonPreview === 'function') {
                            anchorkitDebugLog('Calling updateButtonPreview after reset');
                            setTimeout(function () {
                                window.updateButtonPreview();
                                if (typeof window.updateTestButton === 'function') {
                                    anchorkitDebugLog('Calling updateTestButton after reset');
                                    window.updateTestButton();
                                }
                            }, 100);
                        }

                        updatePreviewIfExists(card);

                        if (Object.prototype.hasOwnProperty.call(settings, 'anchorkit_toc_custom_styling')) {
                            setTimeout(function () {
                                updateTocPreviewClasses();
                            }, 10);
                        }

                        showNotification(response.data.message || 'Settings reset to default values', 'success');

                        updateResetButtonState(card, settings);
                    } else if (response.data.unchanged_count > 0) {
                        showNotification('No changes needed - all settings already at default values', 'info');
                    } else {
                        showNotification('No settings were reset', 'error');
                    }
                } else {
                    // Handle error in the response
                    showNotification(response.data && response.data.message ? response.data.message : 'Error resetting settings', 'error');
                }
            },
            error: function (xhr, status, error) {
                // Handle AJAX error
                console.error('Error resetting settings:', error);
                showNotification('Error: ' + (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'Failed to reset settings'), 'error');
            }
        });
    }

    /**
     * Update preview elements if they exist within or related to a card
     * @param {jQuery} card - The card element
     */
    function updatePreviewIfExists(card) {
        // Determine what type of card this is by its content
        if (card.find('input[name="anchorkit_label"]').length ||
            card.find('input[name="anchorkit_postfix"]').length) {
            // This is a text customization card, update page preview
            updatePagePreview();
        }
        else if (card.find('input[name="anchorkit_excerpt_label"]').length ||
            card.find('input[name="anchorkit_excerpt_postfix"]').length) {
            // This is an excerpt text customization card, update excerpt preview
            updateExcerptPreview();
        }
        else if (card.find('input[name="anchorkit_text_size_value"]').length) {
            // This is a typography card, update page preview
            updatePagePreview();
        }
        else if (card.find('input[name="anchorkit_excerpt_text_size_value"]').length) {
            // This is an excerpt typography card, update excerpt preview
            updateExcerptPreview();
        }
        // Check if this is a back to top button card
        else if (card.find('input[name^="anchorkit_back_to_top_"]').length) {
            // This is a back to top button card, update the button preview
            if (typeof window.updateButtonPreview === 'function') {
                window.updateButtonPreview();
            }
        }
        // Check if this is a progress bar card
        else if (card.find('input[name^="anchorkit_progress_bar_"]').length) {
            // Update progress bar preview if the updatePreviewProgressBar function exists
            if (typeof window.updatePreviewProgressBar === 'function') {
                window.updatePreviewProgressBar();
            }
        }
        // Check if this is a TOC settings card (Quick Start header label, etc.)
        else if (
            card.find('input[name^="anchorkit_toc_"]').length ||
            card.find('select[name^="anchorkit_toc_"]').length ||
            card.find('textarea[name^="anchorkit_toc_"]').length
        ) {
            // Immediately refresh both main and sidebar TOC previews after reset
            if (typeof window.updateTocPreview === 'function') {
                window.updateTocPreview();
            }
            if (typeof window.updateSidebarPreview === 'function') {
                window.updateSidebarPreview();
            }
        }
    }

    /**
     * Update the page preview with current values
     */
    function updatePagePreview() {
        const pageSizeValueInput = $('input[name="anchorkit_text_size_value"]');
        const pageSizeUnitSelect = $('select[name="anchorkit_text_size_unit"]');
        const pagePreviewPrefix = $('#page-preview-prefix');
        const pagePreviewTime = $('#page-preview-time');
        const pageLabelInput = $('input[name="anchorkit_label"]');
        const pagePluralInput = $('input[name="anchorkit_postfix"]');
        const pagePrefixWeight = $('select[name="anchorkit_prefix_font_weight"]');
        const pagePrefixColor = $('input[name="anchorkit_prefix_color"]');
        const pageTextWeight = $('select[name="anchorkit_text_font_weight"]');
        const pageTextColor = $('input[name="anchorkit_text_color"]');

        if (pagePreviewPrefix && pagePreviewTime) {
            // Update text content
            if (pageLabelInput) {
                pagePreviewPrefix.text(pageLabelInput.val());
            }

            if (pagePluralInput) {
                pagePreviewTime.text('3 ' + pagePluralInput.val());
            }

            // Update styles
            if (pageSizeValueInput && pageSizeUnitSelect) {
                const size = pageSizeValueInput.val() + pageSizeUnitSelect.val();
                pagePreviewPrefix.css('fontSize', size);
                pagePreviewTime.css('fontSize', size);
            }

            if (pagePrefixWeight) {
                pagePreviewPrefix.css('fontWeight', pagePrefixWeight.val());
            }

            if (pagePrefixColor) {
                pagePreviewPrefix.css('color', pagePrefixColor.val());
            }

            if (pageTextWeight) {
                pagePreviewTime.css('fontWeight', pageTextWeight.val());
            }

            if (pageTextColor) {
                pagePreviewTime.css('color', pageTextColor.val());
            }
        }
    }

    /**
     * Update the excerpt preview with current values
     */
    function updateExcerptPreview() {
        const excerptSizeValueInput = $('input[name="anchorkit_excerpt_text_size_value"]');
        const excerptSizeUnitSelect = $('select[name="anchorkit_excerpt_text_size_unit"]');
        const excerptPreviewPrefix = $('#excerpt-preview-prefix');
        const excerptPreviewTime = $('#excerpt-preview-time');
        const excerptLabelInput = $('input[name="anchorkit_excerpt_label"]');
        const excerptPluralInput = $('input[name="anchorkit_excerpt_postfix"]');
        const excerptPrefixWeight = $('select[name="anchorkit_excerpt_prefix_font_weight"]');
        const excerptPrefixColor = $('input[name="anchorkit_excerpt_prefix_color"]');
        const excerptTextWeight = $('select[name="anchorkit_excerpt_text_font_weight"]');
        const excerptTextColor = $('input[name="anchorkit_excerpt_text_color"]');

        if (excerptPreviewPrefix && excerptPreviewTime) {
            // Update text content
            if (excerptLabelInput) {
                excerptPreviewPrefix.text(excerptLabelInput.val());
            }

            if (excerptPluralInput) {
                excerptPreviewTime.text('3 ' + excerptPluralInput.val());
            }

            // Update styles
            if (excerptSizeValueInput && excerptSizeUnitSelect) {
                const size = excerptSizeValueInput.val() + excerptSizeUnitSelect.val();
                excerptPreviewPrefix.css('fontSize', size);
                excerptPreviewTime.css('fontSize', size);
            }

            if (excerptPrefixWeight) {
                excerptPreviewPrefix.css('fontWeight', excerptPrefixWeight.val());
            }

            if (excerptPrefixColor) {
                excerptPreviewPrefix.css('color', excerptPrefixColor.val());
            }

            if (excerptTextWeight) {
                excerptPreviewTime.css('fontWeight', excerptTextWeight.val());
            }

            if (excerptTextColor) {
                excerptPreviewTime.css('color', excerptTextColor.val());
            }
        }
    }

    /**
     * Initialize modal dialogs
     */
    function initModals() {
        // Close modal when clicking the close button or cancel button
        $('.anchorkit-modal-close, .anchorkit-modal-cancel').on('click', function () {
            $(this).closest('.anchorkit-modal').hide();
        });

        // Close modal when clicking outside of it
        $(window).on('click', function (event) {
            if ($(event.target).hasClass('anchorkit-modal')) {
                $('.anchorkit-modal').hide();
            }
        });

        // Initialize focus for reset confirmation dialog
        $('#anchorkit-reset-dialog .anchorkit-modal-confirm').on('focus', function () {
            // Add any additional focus handling if needed
        });
    }

    /**
     * Update conditional fields for a specific control element
     * @param {jQuery} $control - The control element (checkbox, select, etc.)
     */
    function updateConditionalFieldsForControl($control) {
        const name = $control.attr('name');
        if (!name) return;

        // Find all conditional fields controlled by this element
        $(`.conditional-field[data-condition="${name}"]`).each(function () {
            const $field = $(this);
            const conditionValue = $field.data('condition-value');

            // Determine if condition is met
            let currentValue;
            if ($control.is(':checkbox')) {
                currentValue = $control.is(':checked') ? '1' : '0';
            } else if ($control.is(':radio')) {
                currentValue = $control.filter(':checked').val();
            } else {
                currentValue = $control.val();
            }

            const shouldShow = String(currentValue) === String(conditionValue);
            const isVisible = $field.is(':visible');

            // Update visibility with animation
            if (shouldShow && !isVisible) {
                // Show with animation
                $field.stop(true, true)
                    .css({ display: 'block', height: 0, opacity: 0, overflow: 'hidden', marginTop: 0 })
                    .animate({ height: $field[0].scrollHeight, opacity: 1, marginTop: 8 }, 200, 'swing', function () {
                        $(this).css({ height: 'auto', overflow: 'visible' });
                    });
            } else if (!shouldShow && isVisible) {
                // Hide with animation
                $field.stop(true, true)
                    .animate({ height: 0, opacity: 0, marginTop: 0 }, 200, 'swing', function () {
                        $(this).css({ display: 'none', overflow: 'hidden' });
                    });
            }
        });
    }

    /**
     * Update shadow component fields after reset to show default values
     * This ensures the UI reflects reset values without requiring page refresh
     */
    function updateShadowComponentFieldsAfterReset() {
        // Get current active mode (light or dark)
        const currentMode = (typeof preview !== 'undefined' && preview.activeMode) ? preview.activeMode : 'light';

        anchorkitDebugLog('[AnchorKit] Updating shadow component fields after reset, mode:', currentMode);

        // Update visible shadow component fields with their default values from hidden fields
        const shadowComponents = ['h_offset', 'v_offset', 'blur', 'spread', 'color', 'opacity'];

        shadowComponents.forEach(function (component) {
            const hiddenFieldId = `anchorkit_toc_shadow_${component}_${currentMode}`;
            const $hiddenField = $(`#${hiddenFieldId}`);

            if ($hiddenField.length) {
                const defaultValue = $hiddenField.val();
                const $visibleField = $(`#shadow_${component}_visible`);

                if ($visibleField.length) {
                    $visibleField.val(defaultValue);

                    // Update color display if this is a color field
                    if (component === 'color') {
                        const $colorValue = $visibleField.closest('.anchorkit-color-picker').find('.color-value');
                        if ($colorValue.length) {
                            $colorValue.text(defaultValue.toUpperCase());
                        }
                    }

                    anchorkitDebugLog(`[AnchorKit] Updated ${component} field to:`, defaultValue);
                }
            }
        });

        // Update the preview shadow if preview is active
        if (typeof window.anchorkitCombineShadowComponents === 'function' &&
            typeof window.anchorkitApplyPreviewBoxShadow === 'function') {
            const shadowString = window.anchorkitCombineShadowComponents(currentMode);
            window.anchorkitApplyPreviewBoxShadow(shadowString, currentMode);
            anchorkitDebugLog('[AnchorKit] Applied reset shadow to preview:', shadowString);
        }
    }

    /**
     * Handle conditional visibility for fields with data-condition attributes
     * Shows or hides dependent form fields based on control element state
     */
    function initConditionalFields() {
        // Find all conditional fields
        $('.conditional-field[data-condition]').each(function () {
            const $field = $(this);
            const conditionName = $field.data('condition');
            const conditionValue = $field.data('condition-value');

            // Find the control element (input, select, etc.)
            const $control = $(`[name="${conditionName}"]`);

            if ($control.length === 0) {
                // Control not found - this is normal for multi-tab setups where the control
                // is on a different tab. Silently skip this field.
                return;
            }

            // Helper to check if condition is met
            function isConditionMet() {
                let currentValue;

                if ($control.is(':checkbox')) {
                    // For checkboxes, check if checked (1) or not (0)
                    currentValue = $control.is(':checked') ? '1' : '0';
                } else if ($control.is(':radio')) {
                    // For radio buttons, get the checked value
                    currentValue = $control.filter(':checked').val();
                } else {
                    // For other inputs and selects, get the value
                    currentValue = $control.val();
                }

                // Convert condition value to string for comparison
                return String(currentValue) === String(conditionValue);
            }

            // Helper to update field visibility with smooth animation
            function updateFieldVisibility() {
                const shouldShow = isConditionMet();
                const isVisible = $field.is(':visible');

                if (shouldShow && !isVisible) {
                    // For TOC preview container, we need special handling
                    const isTocPreview = $field.hasClass('toc-preview-container');

                    if (isTocPreview) {
                        // Show preview with proper height calculation
                        $field.stop(true, true)
                            .css({ display: 'block', maxHeight: 0, opacity: 0, overflow: 'hidden', marginTop: 0 })
                            .animate({ maxHeight: 2000, opacity: 1, marginTop: 12 }, 300, 'swing', function () {
                                $(this).css({ maxHeight: 'none', overflow: 'hidden' });
                                // Ensure preview content is visible and trigger preview update
                                $field.find('#toc-preview').css({ display: 'block', opacity: 1 });
                                $field.find('.anchorkit-toc-list').css({ height: 'auto', opacity: 1 });
                                // Trigger preview update after animation completes
                                setTimeout(function () {
                                    if (typeof window.updateTocPreview === 'function') {
                                        window.updateTocPreview();
                                    }
                                    if (typeof window.updateSidebarPreview === 'function') {
                                        window.updateSidebarPreview();
                                    }
                                }, 50);
                            });
                    } else {
                        // Show with animation (standard fields)
                        $field.stop(true, true)
                            .css({ display: 'block', height: 0, opacity: 0, overflow: 'hidden', marginTop: 0 })
                            .animate({ height: $field[0].scrollHeight, opacity: 1, marginTop: 8 }, 200, 'swing', function () {
                                $(this).css({ height: 'auto', overflow: 'visible' });
                            });
                    }
                } else if (!shouldShow && isVisible) {
                    // For TOC preview container, we need special handling
                    const isTocPreview = $field.hasClass('toc-preview-container');

                    if (isTocPreview) {
                        // Hide preview with max-height animation
                        $field.stop(true, true)
                            .animate({ maxHeight: 0, opacity: 0, marginTop: 0 }, 300, 'swing', function () {
                                $(this).css({ display: 'none', overflow: 'hidden' });
                            });
                    } else {
                        // Hide with animation (standard fields)
                        $field.stop(true, true)
                            .animate({ height: 0, opacity: 0, marginTop: 0 }, 200, 'swing', function () {
                                $(this).css({ display: 'none', overflow: 'hidden' });
                            });
                    }
                }
            }

            // Set initial state
            const isTocPreview = $field.hasClass('toc-preview-container');
            if (isConditionMet()) {
                if (isTocPreview) {
                    $field.css({ display: 'block', marginTop: '12px', maxHeight: 'none', overflow: 'hidden', opacity: 1 });
                    // Ensure preview content is visible
                    $field.find('#toc-preview').css({ display: 'block', opacity: 1 });
                    $field.find('.anchorkit-toc-list').css({ height: 'auto', opacity: 1 });
                } else {
                    $field.css({ display: 'block', marginTop: '8px' });
                }
            } else {
                $field.css({ display: 'none' });
            }

            // Bind change events
            $control.off('change.conditional').on('change.conditional', updateFieldVisibility);

            // For radio buttons, we need to listen to all radios with the same name
            if ($control.is(':radio')) {
                $(`input[name="${conditionName}"]`).off('change.conditional').on('change.conditional', updateFieldVisibility);
            }
        });
    }

    /**
     * Initialize everything when document is ready
     */
    $(document).ready(function () {
        // Initialize responsive tabs dropdown
        initResponsiveTabs();

        // Initialize notification UI
        initializeNotification();

        // Initialize form listeners
        initializeFormListeners();

        // CRITICAL FIX: Add explicit blur handler for ACF field names to ensure it saves
        // This field is inside a conditional wrapper which can sometimes prevent change events
        $(document).on('blur', '#anchorkit_toc_acf_field_names', function() {
            const $input = $(this);
            const name = $input.attr('name');
            const value = $input.val();
            
            if (!$input.is(':disabled') && name) {
                const group = ''; // ACF settings don't have a group
                debouncedUpdateSetting(name, value, group);
            }
        });

        // Add reset buttons
        addResetButtons();

        // Initialize color pickers
        initializeColorPickers();

        // Initialize modals
        initModals();

        // Initialize conditional fields
        initConditionalFields();

        // Apply card distinction
        applyCardVisualDistinction();

        // Initialize input containers
        initializeInputContainers();

        // Sync lock overlays with current Custom Styling state
        initializeCustomStylingLocks();

        // Initialize TOC preview if on any TOC-related tab
        const activeTab = $('.anchorkit-admin').data('active-tab');
        if (activeTab === 'quick-start' || activeTab === 'appearance-behavior' ||
            activeTab === 'structure-seo' || activeTab === 'advanced-accessibility') {
            // Initialize TOC preview classes
            updateTocPreviewClasses();

            // Make sure TOC preview visibility is correct on page load
            updateTocPreviewVisibility();
        }
    });

    /**
     * Apply visual distinction classes to cards based on their content
     */
    function applyCardVisualDistinction() {
        // Identify page content related cards
        $('.anchorkit-card').each(function () {
            const card = $(this);

            // Check for Page Preview card
            if (card.find('h2').text() === 'Page Time Preview') {
                card.addClass('page-content-card');
            }

            // Check for Excerpt Preview card
            if (card.find('h2').text() === 'Excerpt Time Preview') {
                card.addClass('excerpt-card');
            }

            // Check for settings related to page content
            if (card.find('input[name="anchorkit_label"]').length ||
                card.find('input[name="anchorkit_postfix"]').length ||
                card.find('input[name="anchorkit_text_size_value"]').length ||
                card.find('select[name="anchorkit_prefix_font_weight"]').length) {
                card.addClass('page-content-card');
            }

            // Check for settings related to excerpt
            if (card.find('input[name="anchorkit_excerpt_label"]').length ||
                card.find('input[name="anchorkit_excerpt_postfix"]').length ||
                card.find('input[name="anchorkit_excerpt_text_size_value"]').length ||
                card.find('select[name="anchorkit_excerpt_prefix_font_weight"]').length) {
                card.addClass('excerpt-card');
            }
        });

        // Add classes to toggle labels
        $('input[name="anchorkit_insert_before_content"]').closest('label').addClass('content-toggle-label');
        $('input[name="anchorkit_insert_before_excerpt"]').closest('label').addClass('excerpt-toggle-label');
    }

    // Handle "Show test button" toggle
    $('#anchorkit_back_to_top_show_test_button').on('change', function () {
        const testButtonSetting = 'anchorkit_back_to_top_show_test_button';
        const isChecked = $(this).prop('checked');

        // Update test button visibility immediately
        $('#test-back-to-top-button').css('display', isChecked ? 'block' : 'none');

        // Check if setting has changed from default
        const defaultValue = true; // Default is true for test button
        if (isChecked !== defaultValue) {
            changedSettings.add(testButtonSetting);
        } else {
            changedSettings.delete(testButtonSetting);
        }

        // Update reset button state
        updateGlobalResetButtonState();

        // Update the setting via AJAX
        const group = getOptionGroup($(this));
        updateSetting(testButtonSetting, isChecked ? 1 : 0, group);
    });

    /**
     * Update reset button state based on changed settings
     */
    function updateGlobalResetButtonState() {
        const $resetButton = $('#anchorkit-reset-settings');
        if (changedSettings.size > 0) {
            $resetButton.prop('disabled', false);
        } else {
            $resetButton.prop('disabled', true);
        }
    }

    /**
     * Test function to check if notifications are working
     * This can be called from the console: testAnchorkitNotification()
     */
    window.testAnchorkitNotification = function () {
        showNotification('Test notification', 'success', { duration: 5000 });
        anchorkitDebugLog('Notification elements:', {
            container: $('#anchorkit-notification').length > 0,
            visible: $('#anchorkit-notification').hasClass('show'),
            message: $('#anchorkit-notification .anchorkit-notification-message').text(),
            styles: {
                display: $('#anchorkit-notification').css('display'),
                position: $('#anchorkit-notification').css('position'),
                visibility: $('#anchorkit-notification').css('visibility'),
                opacity: $('#anchorkit-notification').css('opacity'),
                zIndex: $('#anchorkit-notification').css('z-index')
            }
        });
    };

    window.testReadsyNotification = window.testAnchorkitNotification;

    /**
     * Standardizes all color picker inputs in the admin interface.
     * This ensures consistent styling and behavior across all color pickers.
     */
    function initializeColorPickers() {
        // Find all color inputs that aren't already in a properly structured container
        $('.form-group input[type="color"]').each(function () {
            const $input = $(this);
            const $container = $input.closest('.input-container');

            // Skip if already in a anchorkit-color-picker with proper structure
            if ($container.hasClass('anchorkit-color-picker') &&
                $container.find('.color-value').length === 1) {
                return;
            }

            // Standardize container
            if ($container.length) {
                $container.addClass('anchorkit-color-picker');

                // Check for label and ensure it's before the input with proper 'for' attribute
                let $label = $container.find('label');
                if ($label.length) {
                    // If label doesn't have a for attribute, add it
                    if (!$label.attr('for') && $input.attr('id')) {
                        $label.attr('for', $input.attr('id'));
                    }

                    // Move label before input if it's not already there
                    if ($label.index() > $input.index()) {
                        $label.detach();
                        $input.before($label);
                    }
                }

                // Remove any duplicate color-value spans
                if ($container.find('.color-value').length > 1) {
                    $container.find('.color-value').not(':first').remove();
                }

                // Create color value span if it doesn't exist
                if ($container.find('.color-value').length === 0) {
                    const $colorValue = $('<span class="color-value"></span>');
                    $colorValue.text($input.val().toUpperCase());
                    $container.append($colorValue);
                }
            } else {
                // Create a proper structure if none exists
                const id = $input.attr('id') || '';
                const label = $input.attr('placeholder') || $input.attr('name') || 'Color';

                $input.wrap('<div class="input-container anchorkit-color-picker"></div>');
                const $newContainer = $input.parent();

                // Add label if needed
                if (!$newContainer.find('label').length) {
                    const $label = $('<label></label>')
                        .attr('for', id)
                        .text(label);
                    $input.before($label);
                }

                // Add color value span
                const $colorValue = $('<span class="color-value"></span>');
                $colorValue.text($input.val().toUpperCase());
                $newContainer.append($colorValue);
            }

            // Ensure event handlers are attached properly
            $input.off('input.anchorkit change.anchorkit').on('input.anchorkit change.anchorkit', function () {
                const $colorValue = $(this).closest('.input-container').find('.color-value');
                $colorValue.text($(this).val().toUpperCase());
            });
        });
    }

    /**
     * Triggers after AJAX has updated settings to refresh UI components
     */
    function refreshUIComponents() {
        // Make sure all color pickers are properly standardized
        initializeColorPickers();
        // Ensure input containers and classes are up to date
        initializeInputContainers();

        // Update live previews based on context
        const activePage = $('.anchorkit-admin').data('active-tab');

        // Handle TOC-related tabs
        if (activePage === 'quick-start' || activePage === 'appearance-behavior' ||
            activePage === 'structure-seo' || activePage === 'advanced-accessibility') {
            // Update TOC preview classes and visibility
            updateTocPreviewClasses();
            updateTocPreviewVisibility();
            // Update main TOC preview if function is available
            if (typeof window.updateTocPreview === 'function') {
                window.updateTocPreview();
            }
            // Update sidebar preview (if function is available from toc-admin-preview.js)
            if (typeof window.updateSidebarPreview === 'function') {
                window.updateSidebarPreview();
            }
        }
    }

    /**
     * Update form elements in the DOM after a setting is changed
     * @param {string} name - Setting name
     * @param {mixed} value - New setting value
     */
    function updateInDOM(name, value) {
        // Find all inputs with this name
        const inputs = $('input[name="' + name + '"], select[name="' + name + '"], textarea[name="' + name + '"]');

        if (inputs.length === 0) {
            return;
        }

        inputs.each(function () {
            const input = $(this);
            const type = input.attr('type');

            if (type === 'checkbox') {
                // Convert to boolean
                const isChecked = value === '1' || value === 1 || value === true;
                // Only trigger change if the checked state is actually changing
                const wasChecked = input.prop('checked');
                input.prop('checked', isChecked);
                if (wasChecked !== isChecked) {
                    input.trigger('change');
                }
            } else if (type === 'radio') {
                // Programmatically update radio state without triggering change to avoid duplicate AJAX calls
                input.prop('checked', input.val() === value);
            } else if (type === 'color') {
                // Update color value
                input.val(value);
                const container = input.closest('.input-container');
                const colorValue = container.find('.color-value');
                if (colorValue.length) {
                    colorValue.text(value.toUpperCase());
                }
                input.trigger('change');
            } else {
                // For all other inputs
                input.val(value);
                input.trigger('change');
            }
        });

        // Special handling for array inputs like post types
        if (name.endsWith('[]')) {
            const baseName = name.slice(0, -2);
            const checkboxes = $('input[name="' + name + '"]');

            // Uncheck all then check only those in the value array
            checkboxes.prop('checked', false);
            if (Array.isArray(value)) {
                checkboxes.each(function () {
                    if (value.includes($(this).val())) {
                        $(this).prop('checked', true);
                    }
                });
            }
        }

        // Update any preview that depends on this setting
        updatePreviewForSetting(name);
    }

    /**
     * Update preview for a specific setting
     * @param {string} name - Setting name
     */
    function updatePreviewForSetting(name) {
        // Reading time settings
        if (name.startsWith('anchorkit_label') ||
            name.startsWith('anchorkit_postfix') ||
            name.startsWith('anchorkit_text_')) {
            updatePagePreview();
        }

        // Excerpt settings
        if (name.startsWith('anchorkit_excerpt_')) {
            updateExcerptPreview();
        }

        // Back to top settings
        if (name.startsWith('anchorkit_back_to_top_') && typeof window.updateButtonPreview === 'function') {
            window.updateButtonPreview();
        }

        // Progress bar settings
        if (name.startsWith('anchorkit_progress_bar_') && typeof window.updatePreviewProgressBar === 'function') {
            window.updatePreviewProgressBar();
        }

        // Table of Contents settings
        if (name.startsWith('anchorkit_toc_')) {
            if (name === 'anchorkit_toc_live_preview_enabled') {
                // For the preview toggle, handle visibility separately
                updateTocPreviewVisibility();
            } else if (typeof window.updateTocPreview === 'function') {
                // All other TOC settings trigger full preview refresh
                window.updateTocPreview();
            }
        }
    }

    /**
     * Sync preview metadata with current TOC settings so dependent UI stays accurate.
     */
    function updateTocPreviewClasses() {
        const $sidebar = $('#anchorkit-preview-sidebar');
        if (!$sidebar.length) {
            return;
        }

        const $preview = $('#anchorkit-sidebar-toc-preview');
        const $presetRadio = $('input[name="anchorkit_toc_style_preset"]:checked');
        const $presetSelect = $('select[name="anchorkit_toc_style_preset"]');

        let presetValue = '';
        if ($presetRadio.length) {
            presetValue = $presetRadio.val();
        } else if ($presetSelect.length) {
            presetValue = $presetSelect.val();
        } else if (typeof anchorkit_ajax !== 'undefined' && anchorkit_ajax.current_preset) {
            presetValue = anchorkit_ajax.current_preset;
        }

        const $customStylingToggle = $('input[name="anchorkit_toc_custom_styling"]');
        const customStylingEnabled = $customStylingToggle.length
            ? $customStylingToggle.is(':checked')
            : (typeof anchorkit_ajax !== 'undefined' && !!anchorkit_ajax.custom_styling);

        const $tocEnabledToggle = $('input[name="anchorkit_toc_enabled"]');
        const tocEnabled = $tocEnabledToggle.length ? $tocEnabledToggle.is(':checked') : true;

        const $themeField = $('select[name="anchorkit_toc_theme"]');
        let themeValue = 'system';
        if ($themeField.length) {
            themeValue = $themeField.val();
        } else if (typeof anchorkit_ajax !== 'undefined' && anchorkit_ajax.toc_theme) {
            themeValue = anchorkit_ajax.toc_theme;
        }

        $sidebar.attr('data-toc-enabled', tocEnabled ? '1' : '0');
        $sidebar.attr('data-toc-custom-styling', customStylingEnabled ? '1' : '0');
        $sidebar.attr('data-toc-theme', themeValue || 'system');

        if (presetValue) {
            $sidebar.attr('data-toc-preset', presetValue);
        } else {
            $sidebar.removeAttr('data-toc-preset');
        }

        $sidebar.toggleClass('toc-preview-disabled', !tocEnabled);

        if ($preview.length) {
            const classList = ($preview.attr('class') || '').split(/\s+/);
            const classesToRemove = classList.filter(function (cls) {
                return cls.indexOf('preview-preset-') === 0 || cls === 'preview-custom-styling';
            });

            if (classesToRemove.length) {
                $preview.removeClass(classesToRemove.join(' '));
            }

            if (presetValue) {
                $preview.addClass('preview-preset-' + presetValue);
            }

            if (customStylingEnabled) {
                $preview.addClass('preview-custom-styling');
            }
        }
    }

    /**
     * Update TOC preview container visibility based on the live preview toggle
     */
    function updateTocPreviewVisibility() {
        const previewEnabled = $('input[name="anchorkit_toc_live_preview_enabled"]').prop('checked');
        const $previewContainer = $('.toc-preview-container');

        // The conditional field animation handles the show/hide animation
        // We just need to ensure the content inside is ready and trigger preview update
        if (previewEnabled) {
            // Wait for the conditional field animation to complete
            setTimeout(function () {
                // Ensure preview content is visible
                $previewContainer.find('#toc-preview').css({ display: 'block', opacity: 1 });
                $previewContainer.find('.anchorkit-toc-list').css({ height: 'auto', opacity: 1 });

                // Update the preview with current settings
                if (typeof window.updateTocPreview === 'function') {
                    window.updateTocPreview();
                }
            }, 350); // Wait for the 300ms animation + small buffer
        }
        // When hiding, the conditional field animation handles everything
    }

    /**
     * Checks if a setting is numeric and should be validated
     * @param {string} name - Setting name
     * @return {boolean} Whether the setting is numeric
     */
    function isNumericSetting(name) {
        const numericSettings = [
            'anchorkit_toc_font_size',
            'anchorkit_toc_padding',
            'anchorkit_toc_border_width',
            'anchorkit_toc_border_radius',
            'anchorkit_toc_include_headings',
            'anchorkit_toc_min_headings',
            'anchorkit_toc_exclude_selectors',
            'anchorkit_toc_title_text',
            'anchorkit_toc_hide_on_mobile',
            'anchorkit_toc_aria_label',
            'anchorkit_toc_back_to_top_link'
        ];

        return numericSettings.includes(name);
    }

    /**
     * Get settings contained within a card
     * @param {jQuery} card - The card element
     * @return {Object} Settings in the card
     */
    function getCardSettings(card) {
        const settings = {};
        const defaultValues = {

            // Table of Contents Settings
            'anchorkit_toc_enabled': true,
            'anchorkit_toc_post_types': ['post', 'page'],
            'anchorkit_toc_automatic_insertion': true,
            'anchorkit_toc_position': 'before_first_heading',
            'anchorkit_toc_collapsible': true,
            'anchorkit_toc_initial_state': 'expanded',
            'anchorkit_toc_smooth_scroll': true,
            'anchorkit_toc_hierarchical_view': true,
            'anchorkit_toc_show_numerals': false,
            'anchorkit_toc_bullet_style': 'disc',
            'anchorkit_toc_bullet_character': '•',
            'anchorkit_toc_numbering_style': 'hierarchical',
            'anchorkit_toc_numbering_format': 'decimal',
            'anchorkit_toc_numbering_separator': '.',
            'anchorkit_toc_live_preview_enabled': false,
            'anchorkit_toc_theme': 'system',
            // Light mode color defaults
            'anchorkit_toc_bg_color_light': '#FFFFFF',
            'anchorkit_toc_text_color_light': '#333333',
            'anchorkit_toc_link_color_light': '#0073AA',
            'anchorkit_toc_link_hover_color_light': '#005177',
            'anchorkit_toc_active_link_color_light': '#00A0D2',
            'anchorkit_toc_border_color_light': '#DDDDDD',
            'anchorkit_toc_bullet_color_light': '#0073AA',
            // Dark mode color defaults
            'anchorkit_toc_bg_color_dark': '#1e1e1e',
            'anchorkit_toc_text_color_dark': '#e0e0e0',
            'anchorkit_toc_link_color_dark': '#7ec4ee',
            'anchorkit_toc_link_hover_color_dark': '#a8d8f0',
            'anchorkit_toc_active_link_color_dark': '#5ba3d0',
            'anchorkit_toc_border_color_dark': '#404040',
            'anchorkit_toc_bullet_color_dark': '#7ec4ee',
            // Legacy color defaults (keep for backward compatibility)
            'anchorkit_toc_bg_color': '#FFFFFF',
            'anchorkit_toc_text_color': '#333333',
            'anchorkit_toc_link_color': '#0073AA',
            'anchorkit_toc_link_hover_color': '#005177',
            'anchorkit_toc_active_link_color': '#00A0D2',
            'anchorkit_toc_border_color': '#DDDDDD',
            'anchorkit_toc_font_family': 'inherit',
            'anchorkit_toc_font_size': 14,
            'anchorkit_toc_padding': 15,
            'anchorkit_toc_border_width': 1,
            'anchorkit_toc_border_radius': 4,
            'anchorkit_toc_include_headings': ['h2', 'h3', 'h4'],
            'anchorkit_toc_min_headings': 2,
            'anchorkit_toc_exclude_selectors': '',
            'anchorkit_toc_title_text': 'Table of Contents',
            'anchorkit_toc_show_label': true,
            'anchorkit_toc_style_preset': 'minimal',
            'anchorkit_toc_scroll_offset': 0,
            'anchorkit_toc_width': 80,
            'anchorkit_toc_alignment': 'center',
            'anchorkit_toc_float': 'none',
            'anchorkit_toc_custom_styling': false,
            'anchorkit_toc_hide_on_mobile': false,
            'anchorkit_toc_mobile_breakpoint': 782,
            'anchorkit_toc_aria_label': '',
            'anchorkit_toc_back_to_top_link': false,
            'anchorkit_toc_back_to_top_text': 'Back to Top',
            'anchorkit_toc_back_to_top_font_size': 14,
            'anchorkit_toc_custom_labels': '',
            'anchorkit_toc_anchor_format': 'auto',
            'anchorkit_toc_anchor_prefix': 'section',
            // Pro features - Sticky TOC
            'anchorkit_toc_sticky_enabled': false,
            'anchorkit_toc_sticky_position': 'content',
            'anchorkit_toc_sticky_offset': 20,
            // Pro features - Advanced Styling
            'anchorkit_toc_box_shadow_enabled': false,
            'anchorkit_toc_box_shadow_custom': '0 4px 6px rgba(0, 0, 0, 0.1)',
            'anchorkit_toc_box_shadow_light': '0 4px 6px rgba(0, 0, 0, 0.1)',
            'anchorkit_toc_box_shadow_dark': '0 2px 8px rgba(0, 0, 0, 0.3)',
            // Box Shadow Components - Light Mode
            'anchorkit_toc_shadow_h_offset_light': 0,
            'anchorkit_toc_shadow_v_offset_light': 4,
            'anchorkit_toc_shadow_blur_light': 6,
            'anchorkit_toc_shadow_spread_light': 0,
            'anchorkit_toc_shadow_color_light': '#000000',
            'anchorkit_toc_shadow_opacity_light': 0.1,
            // Box Shadow Components - Dark Mode
            'anchorkit_toc_shadow_h_offset_dark': 0,
            'anchorkit_toc_shadow_v_offset_dark': 2,
            'anchorkit_toc_shadow_blur_dark': 8,
            'anchorkit_toc_shadow_spread_dark': 0,
            'anchorkit_toc_shadow_color_dark': '#000000',
            'anchorkit_toc_shadow_opacity_dark': 0.3,
            'anchorkit_toc_entrance_animation': false,
            'anchorkit_toc_animation_type': 'fade',
            'anchorkit_toc_line_height': 1.6,
            'anchorkit_toc_letter_spacing': 0,
            'anchorkit_toc_text_transform': 'none',
            'anchorkit_toc_link_underline': 'none',
            'anchorkit_toc_custom_id': '',
            'anchorkit_toc_custom_class': '',
            'anchorkit_toc_custom_css': '',
            // Pro features - Advanced Typography
            'anchorkit_toc_advanced_typography_override': false,
            'anchorkit_toc_title_font_size': '20',
            'anchorkit_toc_h2_font_size': '18',
            'anchorkit_toc_h3_font_size': '16',
            'anchorkit_toc_h4_font_size': '14',
            'anchorkit_toc_h5_font_size': '13',
            'anchorkit_toc_h6_font_size': '12',
            // Pro features - Advanced Content Filtering
            'anchorkit_toc_exclude_keywords': '',
            'anchorkit_toc_exclude_regex': '',
            // Pro features - Smart Heading Detection
            'anchorkit_toc_auto_fix_hierarchy': false,
            'anchorkit_toc_min_heading_depth': 2,
            'anchorkit_toc_max_heading_depth': 4,
            // Pro features - Reading Time & Metadata
            'anchorkit_toc_show_reading_time': false,
            'anchorkit_toc_reading_speed': 200,
            'anchorkit_toc_show_word_count': false,
            'anchorkit_toc_time_format': 'min_read',
            // Pro features - Schema.org & Rich Snippets
            'anchorkit_toc_schema_enabled': false,
            'anchorkit_toc_schema_type': 'Article',
            // Pro features - Enhanced Navigation
            'anchorkit_toc_scroll_easing': 'ease-in-out',
            'anchorkit_toc_scroll_duration': 500,
            // Pro features - View More
            'anchorkit_toc_view_more_enabled': false,
            'anchorkit_toc_initial_count': 5,
            'anchorkit_toc_view_more_text': 'View More',
            'anchorkit_toc_view_less_text': 'View Less',
            // Pro features - ACF Integration
            'anchorkit_toc_acf_enabled': false,
            'anchorkit_toc_acf_field_names': '',
            'anchorkit_toc_acf_merge_mode': 'after',
            // Pro features - AMP Compatibility
            'anchorkit_toc_amp_enabled': false
        };

        // Find all inputs in the card
        card.find('input, select, textarea').each(function () {
            const input = $(this);
            const name = input.attr('name');

            // Skip inputs without names or array inputs that aren't radio buttons
            if (!name || (name.endsWith('[]') && input.attr('type') !== 'radio')) return;

            // Check if this setting has a default value
            if (defaultValues.hasOwnProperty(name)) {
                settings[name] = {
                    element: input,
                    defaultValue: defaultValues[name]
                };
            }
        });

        return settings;
    }

    /**
     * Adds unified classes to text, number and select inputs for the
     * new floating-label component. This keeps backward compatibility
     * with existing markup by augmenting, not replacing, classes.
     */
    function initializeInputContainers() {
        $('.input-container').each(function () {
            const $container = $(this);
            // Ensure container has new base class
            if (!$container.hasClass('anchorkit-input-container')) {
                $container.addClass('anchorkit-input-container');
            }

            // Remove the has-placeholder class if present to ensure consistent styling
            if ($container.hasClass('has-placeholder')) {
                $container.removeClass('has-placeholder');
            }

            // Add specific classes to inputs / selects inside
            $container.find('input[type="text"], input[type="number"], textarea').each(function () {
                const $input = $(this);
                if (!$input.hasClass('anchorkit-input')) {
                    $input.addClass('anchorkit-input');
                }
                // Ensure placeholder is single space to enable :placeholder-shown logic
                if (typeof $input.attr('placeholder') === 'undefined' || $input.attr('placeholder') === '') {
                    $input.attr('placeholder', ' ');
                }
            });

            $container.find('select').each(function () {
                const $select = $(this);
                if (!$select.hasClass('anchorkit-select')) {
                    $select.addClass('anchorkit-select');
                }
            });
        });
    }

    /**
     * Initialize Style Preset Picker
     */
    function initStylePresetPicker() {
        $('.anchorkit-preset-option').on('click', function () {
            const $option = $(this);
            const $input = $option.find('input[type="radio"]');

            // Remove selected class from all options
            $('.anchorkit-preset-option').removeClass('selected');

            // Add selected class to clicked option
            $option.addClass('selected');

            // Trigger the radio button change to save via AJAX
            $input.prop('checked', true).trigger('change');
        });

        // Set initial selected state based on checked radio
        $('.anchorkit-preset-picker input[type="radio"]:checked').each(function () {
            $(this).closest('.anchorkit-preset-option').addClass('selected');
        });
    }

    // Initialize preset picker on page load
    initStylePresetPicker();

    /**
     * Initialize Custom Styling Toggle
     * When enabled, copy minimal preset values as starting point
     */
    function initCustomStylingToggle() {
        const $toggle = $('input[name="anchorkit_toc_custom_styling"]');

        $toggle.on('change', function () {
            const isChecked = $(this).is(':checked');

            // Update the activation card UI immediately
            updateCustomStylingInfoBox(isChecked);

            // Refresh the TOC preview to show preset vs custom styling
            if (typeof window.updateSidebarPreview === 'function') {
                window.updateSidebarPreview();
            }

            if (isChecked) {
                // Just turned ON - initialize with minimal preset values if fields are empty/default
                const minimalPresetDefaults = {
                    'anchorkit_toc_bg_color': '#FFFFFF',
                    'anchorkit_toc_text_color': '#333333',
                    'anchorkit_toc_link_color': '#0073AA',
                    'anchorkit_toc_link_hover_color': '#005177',
                    'anchorkit_toc_active_link_color': '#00A0D2',
                    'anchorkit_toc_border_color': '#DDDDDD',
                    'anchorkit_toc_font_family': 'inherit',
                    'anchorkit_toc_font_size': '14',
                    'anchorkit_toc_padding': '15',
                    'anchorkit_toc_border_width': '1',
                    'anchorkit_toc_border_radius': '4'
                };

                // Initialize color pickers with minimal preset values
                Object.keys(minimalPresetDefaults).forEach(function (name) {
                    const $input = $(`input[name="${name}"], select[name="${name}"]`);
                    if ($input.length) {
                        $input.val(minimalPresetDefaults[name]);
                        // Update color picker display if it exists
                        if ($input.attr('type') === 'color') {
                            const $colorValue = $input.siblings('.color-value');
                            if ($colorValue.length) {
                                $colorValue.text(minimalPresetDefaults[name].toUpperCase());
                            }
                        }
                    }
                });
            }
        });
    }

    // Initialize custom styling toggle handler
    initCustomStylingToggle();

    /**
     * Tooltip Keyboard Accessibility
     * Ensures tooltips can be triggered and dismissed with keyboard
     */
    function initTooltipAccessibility() {
        // Handle keyboard events on tooltip icons
        $(document).on('keydown', '.anchorkit-tooltip-icon', function (e) {
            // Enter or Space to show tooltip
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                const $icon = $(this);
                const $tooltip = $icon.siblings('.anchorkit-tooltip-content');

                // Toggle visibility
                if ($tooltip.hasClass('keyboard-visible')) {
                    $tooltip.removeClass('keyboard-visible');
                    $tooltip.css({
                        'opacity': '0',
                        'visibility': 'hidden'
                    });
                } else {
                    // Hide all other tooltips first
                    $('.anchorkit-tooltip-content.keyboard-visible').removeClass('keyboard-visible').css({
                        'opacity': '0',
                        'visibility': 'hidden'
                    });

                    // Show this tooltip
                    $tooltip.addClass('keyboard-visible');
                    $tooltip.css({
                        'opacity': '1',
                        'visibility': 'visible',
                        'pointer-events': 'auto'
                    });
                }
            }

            // Escape to hide tooltip
            if (e.key === 'Escape') {
                $('.anchorkit-tooltip-content.keyboard-visible').removeClass('keyboard-visible').css({
                    'opacity': '0',
                    'visibility': 'hidden'
                });
            }
        });

        // Close tooltip when clicking outside
        $(document).on('click', function (e) {
            if (!$(e.target).closest('.anchorkit-tooltip-wrapper').length) {
                $('.anchorkit-tooltip-content.keyboard-visible').removeClass('keyboard-visible').css({
                    'opacity': '0',
                    'visibility': 'hidden'
                });
            }
        });
    }

    // Initialize tooltip accessibility
    initTooltipAccessibility();

    /**
     * Custom Labels JSON Validation and Auto-Save
     * Validate JSON syntax in real-time and save to database
     */
    const $customLabelsField = $('#anchorkit_toc_custom_labels');
    const $customLabelsError = $('#anchorkit_toc_custom_labels_error');

    if ($customLabelsField.length) {
        $customLabelsField.on('blur', function () {
            const value = $(this).val().trim();

            // If empty, clear any error and save empty value
            if (value === '') {
                $customLabelsError.hide();
                $customLabelsField.css('border-color', '');

                // Save empty value
                updateSetting('anchorkit_toc_custom_labels', '', 'anchorkit_settings');
                return;
            }

            // Try to parse JSON
            try {
                const parsed = JSON.parse(value);

                // Check if it's an object (not array, not null)
                if (typeof parsed !== 'object' || Array.isArray(parsed) || parsed === null) {
                    throw new Error('JSON must be an object with key-value pairs');
                }

                // Valid JSON - save it!
                $customLabelsError.hide();
                $customLabelsField.css('border-color', '#10b981'); // Green border

                // Save to database
                updateSetting('anchorkit_toc_custom_labels', value, 'anchorkit_settings');

                // Clear green border after 2 seconds
                setTimeout(function () {
                    $customLabelsField.css('border-color', '');
                }, 2000);

            } catch (e) {
                // Invalid JSON
                $customLabelsError.text('❌ Invalid JSON format. Example: {"Original Text": "New Label"}').show();
                $customLabelsField.css('border-color', '#dc3545'); // Red border
            }
        });
    }

    /**
     * Update preset info box when preset changes
     * @param {string} presetValue - The preset value (minimal, classic, modern)
     */
    function updatePresetInfoBox(presetValue) {
        const $infoBox = $('#anchorkit-preset-info');
        if ($infoBox.length === 0) return;

        // Map preset values to display names
        const presetNames = {
            'minimal': 'Minimal',
            'classic': 'Classic',
            'modern': 'Modern'
        };

        const presetDisplayName = presetNames[presetValue] || 'Minimal';

        // Update the preset name in the info box
        $infoBox.find('strong').text('Active Preset: ' + presetDisplayName);
        $infoBox.find('p').html(
            'Your TOC is using the <strong>' + presetDisplayName + '</strong> preset from the Quick Start tab. ' +
            'To customize colors, fonts, and spacing beyond the preset, enable <strong>Custom Styling</strong> below.'
        );
    }

    /**
     * Animated Square Logo
     * Pure CSS animation - no JavaScript needed!
     * Colors shift in a clockwise pattern using only the original 4 colors
     */

})(jQuery);

/**
 * Custom TOC Labels - Key-Value Interface
 */
(function ($) {
    'use strict';

    // Initialize the custom labels interface when the page loads
    $(document).ready(function () {
        initCustomLabelsInterface();
    });

    function initCustomLabelsInterface() {
        const container = $('#anchorkit_custom_labels_container');
        const hiddenInput = $('#anchorkit_toc_custom_labels');
        const addButton = $('#anchorkit_add_custom_label');

        if (!container.length || !hiddenInput.length) {
            return;
        }

        // Parse current JSON value and populate the interface
        function renderLabels() {
            container.empty();

            let labels = {};
            try {
                const jsonValue = hiddenInput.val().trim();
                if (jsonValue) {
                    labels = JSON.parse(jsonValue);
                }
            } catch (e) {
                console.error('Error parsing custom labels JSON:', e);
                labels = {};
            }

            const labelKeys = Object.keys(labels);

            if (labelKeys.length === 0) {
                container.html('<div class="anchorkit-no-labels-message">No custom labels yet. Click "Add Custom Label" to create one.</div>');
                return;
            }

            labelKeys.forEach(function (key) {
                addLabelRow(key, labels[key]);
            });
        }

        // Add a new label row to the interface
        function addLabelRow(originalText = '', replacementText = '') {
            const row = $('<div class="anchorkit-custom-label-row"></div>');

            row.html(`
                <input type="text" class="anchorkit-label-original" placeholder="Original heading text" value="${escapeHtml(originalText)}">
                <div class="anchorkit-custom-label-arrow">→</div>
                <input type="text" class="anchorkit-label-replacement" placeholder="Custom label" value="${escapeHtml(replacementText)}">
                <button type="button" class="anchorkit-remove-label-btn" title="Remove">×</button>
            `);

            // Remove empty message if it exists
            container.find('.anchorkit-no-labels-message').remove();
            container.append(row);

            // Auto-focus the first input if both fields are empty
            if (!originalText && !replacementText) {
                row.find('.anchorkit-label-original').focus();
            }
        }

        // Update the hidden JSON field
        function updateHiddenField() {
            const labels = {};

            container.find('.anchorkit-custom-label-row').each(function () {
                const original = $(this).find('.anchorkit-label-original').val().trim();
                const replacement = $(this).find('.anchorkit-label-replacement').val().trim();

                // Only add if both fields have values
                if (original && replacement) {
                    labels[original] = replacement;
                }
            });

            const jsonValue = Object.keys(labels).length > 0 ? JSON.stringify(labels) : '';
            hiddenInput.val(jsonValue);

            // Trigger change event so the AJAX handler saves it
            hiddenInput.trigger('change');
        }

        // Helper function to escape HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function (m) { return map[m]; });
        }

        // Event: Add new label
        addButton.on('click', function (e) {
            e.preventDefault();
            addLabelRow();
        });

        // Event: Remove label
        container.on('click', '.anchorkit-remove-label-btn', function (e) {
            e.preventDefault();
            $(this).closest('.anchorkit-custom-label-row').remove();

            // If no rows left, show empty message
            if (container.find('.anchorkit-custom-label-row').length === 0) {
                container.html('<div class="anchorkit-no-labels-message">No custom labels yet. Click "Add Custom Label" to create one.</div>');
            }

            updateHiddenField();
        });

        // Event: Update hidden field when inputs change
        container.on('input blur', '.anchorkit-label-original, .anchorkit-label-replacement', function () {
            updateHiddenField();
        });

        // Initial render
        renderLabels();

        // Expose renderLabels globally so it can be called when resetting
        window.renderCustomLabels = renderLabels;
    }

})(jQuery);

/**
 * ACF Fields - Dynamic Field List Interface
 */
(function ($) {
    'use strict';

    // Initialize the ACF fields interface when the page loads
    $(document).ready(function () {
        initACFFieldsInterface();
    });

    function initACFFieldsInterface() {
        const container = $('#anchorkit_acf_fields_container');
        const hiddenInput = $('#anchorkit_toc_acf_field_names');
        const addButton = $('#anchorkit_add_acf_field');

        if (!container.length || !hiddenInput.length) {
            return;
        }

        // Parse current comma-separated value and populate the interface
        function renderFields() {
            container.empty();

            const fieldNames = hiddenInput.val().trim();
            const fields = fieldNames ? fieldNames.split(',').map(f => f.trim()).filter(f => f) : [];

            if (fields.length === 0) {
                container.html('<div class="anchorkit-no-fields-message">No ACF fields added yet. Click "Add ACF Field" to specify which fields to scan, or leave empty to scan all fields automatically.</div>');
                return;
            }

            fields.forEach(function (fieldName) {
                addFieldRow(fieldName);
            });
        }

        // Add a new field row to the interface
        function addFieldRow(fieldName = '') {
            const row = $('<div class="anchorkit-acf-field-row"></div>');

            row.html(`
                <input type="text" class="anchorkit-acf-field-input" placeholder="e.g., hero_content, modules_0_text" value="${escapeHtml(fieldName)}">
                <button type="button" class="anchorkit-remove-field-btn" title="Remove">×</button>
            `);

            // Remove empty message if it exists
            container.find('.anchorkit-no-fields-message').remove();
            container.append(row);

            // Auto-focus the input if field is empty
            if (!fieldName) {
                row.find('.anchorkit-acf-field-input').focus();
            }
        }

        // Update the hidden comma-separated field
        function updateHiddenField() {
            const fields = [];

            container.find('.anchorkit-acf-field-row').each(function () {
                const fieldName = $(this).find('.anchorkit-acf-field-input').val().trim();

                // Only add if field has a value
                if (fieldName) {
                    fields.push(fieldName);
                }
            });

            const commaSeparated = fields.join(', ');
            hiddenInput.val(commaSeparated);

            // Trigger change event so the AJAX handler saves it
            hiddenInput.trigger('change');
        }

        // Helper function to escape HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function (m) { return map[m]; });
        }

        // Event: Add new field
        addButton.on('click', function (e) {
            e.preventDefault();
            addFieldRow();
        });

        // Event: Remove field
        container.on('click', '.anchorkit-remove-field-btn', function (e) {
            e.preventDefault();
            $(this).closest('.anchorkit-acf-field-row').remove();

            // If no rows left, show empty message
            if (container.find('.anchorkit-acf-field-row').length === 0) {
                container.html('<div class="anchorkit-no-fields-message">No ACF fields added yet. Click "Add ACF Field" to specify which fields to scan, or leave empty to scan all fields automatically.</div>');
            }

            updateHiddenField();
        });

        // Event: Update hidden field when inputs change
        container.on('input blur', '.anchorkit-acf-field-input', function () {
            updateHiddenField();
        });

        // Initial render
        renderFields();

        // Expose renderFields globally so it can be called when resetting
        window.renderACFFields = renderFields;
    }

})(jQuery);

/**
 * CSS Classes - Dynamic Class List Interface
 */
(function ($) {
    'use strict';

    // Initialize the CSS classes interface when the page loads
    $(document).ready(function () {
        initCSSClassesInterface();
    });

    function initCSSClassesInterface() {
        const container = $('#anchorkit_css_classes_container');
        const hiddenInput = $('#anchorkit_toc_custom_class');
        const addButton = $('#anchorkit_add_css_class');

        if (!container.length || !hiddenInput.length) {
            return;
        }

        // Parse current space-separated value and populate the interface
        function renderClasses() {
            container.empty();

            const classNames = hiddenInput.val().trim();
            const classes = classNames ? classNames.split(/\s+/).map(c => c.trim()).filter(c => c) : [];

            if (classes.length === 0) {
                container.html('<div class="anchorkit-no-classes-message">No CSS classes added yet. Click "Add CSS Class" to add one.</div>');
                return;
            }

            classes.forEach(function (className) {
                addClassRow(className);
            });
        }

        // Add a new class row to the interface
        function addClassRow(className = '') {
            const row = $('<div class="anchorkit-css-class-row"></div>');

            row.html(`
                <input type="text" class="anchorkit-css-class-input" placeholder="e.g., my-toc or .my-toc" value="${escapeHtml(className)}">
                <button type="button" class="anchorkit-remove-class-btn" title="Remove">×</button>
            `);

            // Remove empty message if it exists
            container.find('.anchorkit-no-classes-message').remove();
            container.append(row);

            // Auto-focus the input if class is empty
            if (!className) {
                row.find('.anchorkit-css-class-input').focus();
            }
        }

        // Update the hidden space-separated field
        function updateHiddenField() {
            const classes = [];

            container.find('.anchorkit-css-class-row').each(function () {
                const className = $(this).find('.anchorkit-css-class-input').val().trim();

                // Only add if class has a value
                if (className) {
                    classes.push(className);
                }
            });

            const spaceSeparated = classes.join(' ');
            hiddenInput.val(spaceSeparated);

            // Trigger change event so the AJAX handler saves it
            hiddenInput.trigger('change');
        }

        // Helper function to escape HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function (m) { return map[m]; });
        }

        // Event: Add new class
        addButton.on('click', function (e) {
            e.preventDefault();
            addClassRow();
        });

        // Event: Remove class
        container.on('click', '.anchorkit-remove-class-btn', function (e) {
            e.preventDefault();
            $(this).closest('.anchorkit-css-class-row').remove();

            // If no rows left, show empty message
            if (container.find('.anchorkit-css-class-row').length === 0) {
                container.html('<div class="anchorkit-no-classes-message">No CSS classes added yet. Click "Add CSS Class" to add one.</div>');
            }

            updateHiddenField();
        });

        // Event: Update hidden field when inputs change
        container.on('input blur', '.anchorkit-css-class-input', function () {
            updateHiddenField();
        });

        // Initial render
        renderClasses();

        // Expose renderClasses globally so it can be called when resetting
        window.renderCSSClasses = renderClasses;
    }

    /**
     * Color Picker Enhancement
     * Adds hex value display next to color input fields
     */
    function initColorPickerEnhancement() {
        document.querySelectorAll('input[type="color"]').forEach(input => {
            const nextSibling = input.nextElementSibling;
            const hasColorValueSibling = nextSibling && nextSibling.classList && nextSibling.classList.contains('color-value');

            if (!hasColorValueSibling) {
                const valueDisplay = document.createElement('span');
                valueDisplay.className = 'color-value';
                valueDisplay.textContent = input.value.toUpperCase();
                input.parentNode.insertBefore(valueDisplay, input.nextSibling);
            }

            ['input', 'change'].forEach(event => {
                input.addEventListener(event, (e) => {
                    const container = e.target.closest('.input-container') || e.target.parentNode;
                    const valueDisplay = container.querySelector('.color-value');
                    if (valueDisplay) {
                        valueDisplay.textContent = e.target.value.toUpperCase();
                    }
                });
            });
        });
    }

    /**
     * Feature Toggle Status Updater
     * Updates "enabled/disabled" text when TOC feature is toggled
     */
    function initFeatureToggleStatus() {
        const featureToggle = document.querySelector('input[name="anchorkit_toc_enabled"]');
        const statusText = document.querySelector('.m3-switch-label .status-text');

        function updateStatus(isChecked) {
            if (statusText) {
                statusText.textContent = isChecked ? 'enabled' : 'disabled';
                statusText.style.color = isChecked ? '#4CAF50' : '#F44336';
            }
        }

        function updateCardDisabledStates(isFeatureEnabled) {
            const allCards = document.querySelectorAll('.anchorkit-card');
            allCards.forEach((card, index) => {
                if (index === 0) return;
                if (!isFeatureEnabled) {
                    card.classList.add('disabled-card');
                } else {
                    card.classList.remove('disabled-card');
                }
            });
        }

        if (featureToggle) {
            updateStatus(featureToggle.checked);
            featureToggle.addEventListener('change', function() {
                updateStatus(this.checked);
                updateCardDisabledStates(this.checked);
            });
            updateCardDisabledStates(featureToggle.checked);
        }
    }

    /**
     * FAQ Accordion Handler
     * Event delegation for FAQ toggles (used in Help and Pro tabs)
     */
    function initFaqAccordion() {
        document.addEventListener('click', function(e) {
            const header = e.target.closest('.faq-header[data-toggle="faq"]');
            if (!header) return;

            const item = header.closest('.faq-item');
            const answer = item.querySelector('.faq-answer');
            const toggle = header.querySelector('.faq-toggle');
            const isOpen = answer.classList.contains('open');

            // Close all other FAQs
            document.querySelectorAll('.faq-item').forEach(faq => {
                if (faq !== item) {
                    faq.querySelector('.faq-answer').classList.remove('open');
                    faq.querySelector('.faq-toggle').classList.remove('open');
                    faq.classList.remove('active');
                }
            });

            // Toggle current FAQ
            if (isOpen) {
                answer.classList.remove('open');
                toggle.classList.remove('open');
                item.classList.remove('active');
            } else {
                answer.classList.add('open');
                toggle.classList.add('open');
                item.classList.add('active');
            }
        });
    }

    // Initialize on DOM ready
    document.addEventListener('DOMContentLoaded', function() {
        initColorPickerEnhancement();
        initFeatureToggleStatus();
        initFaqAccordion();
    });

})(jQuery);
