/**
 * RSL Accessibility Widget v1.5.0
 * A comprehensive accessibility overlay for any website using RSL
 * Provides users with controls for text, visual, navigation, and motion preferences
 *
 * Features:
 * - Text: Font size, line height, letter spacing, word spacing, font family, alignment
 * - Visual: High contrast, invert colors, grayscale, saturation, highlight links/headings
 * - Navigation: Focus indicators, big cursor, reading guide, keyboard navigation
 * - Motion: Stop animations, reduce motion
 * - Cognitive: Hide images, reading mask
 * - Text-to-Speech: Read page content aloud with word highlighting
 * - Page Zoom: Scale the entire page up to 400%
 * - Settings: Save to localStorage, reset to defaults
 *
 * Configuration (via data attributes on script tag):
 * - data-position: Widget position (bottom-left, bottom-right, top-left, top-right)
 * - data-primary: Primary brand color (e.g., "#8B1538")
 * - data-secondary: Secondary/gradient end color (e.g., "#6B1028")
 * - data-button-icon: Button icon color (default: "#ffffff")
 * - data-header-text: Header text color (default: "#ffffff")
 *
 * Example:
 * <script src="accessibility-widget.js"
 *         data-position="bottom-right"
 *         data-primary="#8B1538"
 *         data-secondary="#6B1028"></script>
 */

(function() {
    'use strict';

    // Prevent double initialization
    if (window.RSL && window.RSL.AccessibilityWidget) {
        return;
    }

    window.RSL = window.RSL || {};

    // Widget configuration
    const config = {
        position: 'bottom-left', // Default position
        // Color theming (null = use CSS defaults)
        primaryColor: null,
        secondaryColor: null,
        buttonIconColor: null,
        headerTextColor: null
    };

    // Valid positions
    const VALID_POSITIONS = ['bottom-left', 'bottom-right', 'top-left', 'top-right'];

    // Default settings
    const DEFAULT_SETTINGS = {
        // Text settings
        fontSize: 100,
        lineHeight: 100,
        letterSpacing: 0,
        wordSpacing: 0,
        fontFamily: 'default',
        textAlign: 'default',

        // Visual settings
        highContrast: false,
        invertColors: false,
        grayscale: false,
        lowSaturation: false,
        highSaturation: false,
        highlightLinks: false,
        highlightHeadings: false,

        // Navigation settings
        bigCursor: false,
        readingGuide: false,
        focusIndicator: false,

        // Motion settings
        stopAnimations: false,

        // Cognitive settings
        hideImages: false,
        readingMask: false,

        // Text-to-Speech settings
        ttsEnabled: false,
        ttsRate: 1.0,

        // Page zoom
        pageZoom: 100,

        // Widget state
        widgetOpen: false
    };

    // Storage key
    const STORAGE_KEY = 'rsl-accessibility-settings';

    // Current settings
    let settings = { ...DEFAULT_SETTINGS };

    // Widget elements
    let widgetButton = null;
    let widgetPanel = null;
    let readingGuideElement = null;
    let readingMaskElement = null;

    // Text-to-Speech state
    let ttsUtterance = null;
    let ttsIsPaused = false;
    let ttsIsPlaying = false;
    let ttsCurrentElement = null;
    let ttsHighlightedElements = [];

    /**
     * Read configuration from script tag data attributes
     */
    function readConfig() {
        const scripts = document.querySelectorAll('script[src*="accessibility-widget"]');
        const script = scripts[scripts.length - 1]; // Get the last matching script

        if (script) {
            // Read position
            const position = script.getAttribute('data-position');
            if (position && VALID_POSITIONS.includes(position)) {
                config.position = position;
            }

            // Read color theming
            const primary = script.getAttribute('data-primary');
            if (primary) {
                config.primaryColor = primary;
            }

            const secondary = script.getAttribute('data-secondary');
            if (secondary) {
                config.secondaryColor = secondary;
            }

            const buttonIcon = script.getAttribute('data-button-icon');
            if (buttonIcon) {
                config.buttonIconColor = buttonIcon;
            }

            const headerText = script.getAttribute('data-header-text');
            if (headerText) {
                config.headerTextColor = headerText;
            }
        }
    }

    /**
     * Apply custom colors via CSS custom properties
     * Sets colors on :root so they override defaults
     */
    function applyCustomColors() {
        if (!config.primaryColor && !config.secondaryColor) {
            return; // No custom colors configured
        }

        const root = document.documentElement;
        const primary = config.primaryColor || '#667eea';
        const secondary = config.secondaryColor || config.primaryColor || '#764ba2';

        // Set CSS custom properties
        root.style.setProperty('--rsl-a11y-primary', primary);
        root.style.setProperty('--rsl-a11y-secondary', secondary);
        root.style.setProperty('--rsl-a11y-button-gradient',
            `linear-gradient(135deg, ${primary} 0%, ${secondary} 100%)`);
        root.style.setProperty('--rsl-a11y-header-gradient',
            `linear-gradient(135deg, ${primary} 0%, ${secondary} 100%)`);
        root.style.setProperty('--rsl-a11y-toggle-gradient',
            `linear-gradient(135deg, ${primary} 0%, ${secondary} 100%)`);

        // Calculate shadow color from primary (with transparency)
        root.style.setProperty('--rsl-a11y-button-shadow',
            `0 4px 16px ${hexToRgba(primary, 0.4)}`);

        if (config.buttonIconColor) {
            root.style.setProperty('--rsl-a11y-button-icon', config.buttonIconColor);
        }

        if (config.headerTextColor) {
            root.style.setProperty('--rsl-a11y-header-text', config.headerTextColor);
        }
    }

    /**
     * Convert hex color to rgba
     * @param {string} hex - Hex color code
     * @param {number} alpha - Alpha value (0-1)
     * @returns {string} RGBA color string
     */
    function hexToRgba(hex, alpha) {
        // Remove # if present
        hex = hex.replace('#', '');

        // Handle short hex (e.g., #FFF)
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }

        const r = parseInt(hex.substring(0, 2), 16);
        const g = parseInt(hex.substring(2, 4), 16);
        const b = parseInt(hex.substring(4, 6), 16);

        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }

    /**
     * Apply position to widget elements
     */
    function applyPosition(position) {
        if (!VALID_POSITIONS.includes(position)) {
            console.warn('Invalid position:', position, '. Valid options:', VALID_POSITIONS.join(', '));
            return;
        }

        config.position = position;

        // Remove existing position classes
        VALID_POSITIONS.forEach(pos => {
            if (widgetButton) {
                widgetButton.classList.remove('rsl-a11y-pos-' + pos);
            }
            if (widgetPanel) {
                widgetPanel.classList.remove('rsl-a11y-pos-' + pos);
            }
        });

        // Add new position class (only if not default bottom-left)
        if (position !== 'bottom-left') {
            if (widgetButton) {
                widgetButton.classList.add('rsl-a11y-pos-' + position);
            }
            if (widgetPanel) {
                widgetPanel.classList.add('rsl-a11y-pos-' + position);
            }
        }
    }

    /**
     * Initialize the accessibility widget
     * @param {Object} options - Optional configuration options
     * @param {string} options.position - Widget position (bottom-left, bottom-right, top-left, top-right)
     * @param {string} options.primaryColor - Primary brand color
     * @param {string} options.secondaryColor - Secondary/gradient end color
     */
    function init(options) {
        // Read config from data attributes first
        readConfig();

        // Override with passed options
        if (options) {
            if (options.position && VALID_POSITIONS.includes(options.position)) {
                config.position = options.position;
            }
            if (options.primaryColor) {
                config.primaryColor = options.primaryColor;
            }
            if (options.secondaryColor) {
                config.secondaryColor = options.secondaryColor;
            }
            if (options.buttonIconColor) {
                config.buttonIconColor = options.buttonIconColor;
            }
            if (options.headerTextColor) {
                config.headerTextColor = options.headerTextColor;
            }
        }

        // Apply custom colors before creating UI
        applyCustomColors();

        // Load saved settings
        loadSettings();

        // Create widget UI
        createWidgetButton();
        createWidgetPanel();
        createReadingGuide();
        createReadingMask();

        // Apply position
        applyPosition(config.position);

        // Apply saved settings
        applyAllSettings();

        // Add keyboard shortcut (Alt + A)
        document.addEventListener('keydown', handleKeyboardShortcut);

        // Handle escape key to close panel
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && settings.widgetOpen) {
                closePanel();
            }
        });

        // Restore panel open state if it was open before page load/refresh
        if (settings.widgetOpen) {
            // Use setTimeout to ensure DOM is fully ready
            setTimeout(function() {
                widgetPanel.classList.add('open');
                widgetButton.classList.add('active');
                widgetButton.setAttribute('aria-expanded', 'true');
            }, 100);
        }

        console.log('RSL Accessibility Widget initialized at position:', config.position);
    }

    /**
     * Load settings from localStorage
     */
    function loadSettings() {
        try {
            const saved = localStorage.getItem(STORAGE_KEY);
            if (saved) {
                const parsed = JSON.parse(saved);
                settings = { ...DEFAULT_SETTINGS, ...parsed };
                // widgetOpen state is preserved to restore panel state on page load
            }
        } catch (e) {
            console.warn('Could not load accessibility settings:', e);
        }
    }

    /**
     * Save settings to localStorage
     */
    function saveSettings() {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
        } catch (e) {
            console.warn('Could not save accessibility settings:', e);
        }
    }

    /**
     * Reset all settings to defaults
     */
    function resetSettings() {
        // Stop TTS if playing
        ttsStop();

        settings = { ...DEFAULT_SETTINGS };
        saveSettings();
        applyAllSettings();
        updatePanelControls();

        // Show confirmation
        showToast('Settings reset to defaults');
    }

    /**
     * Create the floating widget button
     */
    function createWidgetButton() {
        widgetButton = document.createElement('button');
        widgetButton.className = 'rsl-a11y-widget-button';
        widgetButton.setAttribute('aria-label', 'Open accessibility settings');
        widgetButton.setAttribute('title', 'Accessibility Options (Alt+A)');
        widgetButton.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="28" height="28">
                <path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9H15V22H13V16H11V22H9V9H3V7H21V9Z"/>
            </svg>
        `;

        widgetButton.addEventListener('click', togglePanel);
        document.body.appendChild(widgetButton);
    }

    /**
     * Create the settings panel
     */
    function createWidgetPanel() {
        widgetPanel = document.createElement('div');
        widgetPanel.className = 'rsl-a11y-widget-panel';
        widgetPanel.setAttribute('role', 'dialog');
        widgetPanel.setAttribute('aria-label', 'Accessibility Settings');
        widgetPanel.setAttribute('aria-modal', 'true');
        widgetPanel.innerHTML = generatePanelHTML();

        document.body.appendChild(widgetPanel);

        // Attach event listeners to controls
        attachPanelListeners();
    }

    /**
     * Generate the panel HTML
     */
    function generatePanelHTML() {
        return `
            <div class="rsl-a11y-panel-header">
                <h2 class="rsl-a11y-panel-title">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                        <path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9H15V22H13V16H11V22H9V9H3V7H21V9Z"/>
                    </svg>
                    Accessibility Settings
                </h2>
                <button class="rsl-a11y-close-btn" aria-label="Close accessibility settings">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
                        <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                    </svg>
                </button>
            </div>

            <div class="rsl-a11y-panel-body">
                <!-- Text Adjustments Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M9.93 13.5h4.14L12 7.98zM20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-4.05 16.5l-1.14-3H9.17l-1.12 3H5.96l5.11-13h1.86l5.11 13h-2.09z"/>
                        </svg>
                        Text Adjustments
                    </h3>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label" for="a11y-fontSize">Font Size: <span id="a11y-fontSize-value">${settings.fontSize}%</span></label>
                        <div class="rsl-a11y-slider-group">
                            <button class="rsl-a11y-btn-small" data-action="fontSize" data-value="-10" aria-label="Decrease font size">-</button>
                            <input type="range" id="a11y-fontSize" min="50" max="200" value="${settings.fontSize}" class="rsl-a11y-slider">
                            <button class="rsl-a11y-btn-small" data-action="fontSize" data-value="10" aria-label="Increase font size">+</button>
                        </div>
                    </div>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label" for="a11y-lineHeight">Line Height: <span id="a11y-lineHeight-value">${settings.lineHeight}%</span></label>
                        <div class="rsl-a11y-slider-group">
                            <button class="rsl-a11y-btn-small" data-action="lineHeight" data-value="-10" aria-label="Decrease line height">-</button>
                            <input type="range" id="a11y-lineHeight" min="100" max="200" value="${settings.lineHeight}" class="rsl-a11y-slider">
                            <button class="rsl-a11y-btn-small" data-action="lineHeight" data-value="10" aria-label="Increase line height">+</button>
                        </div>
                    </div>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label" for="a11y-letterSpacing">Letter Spacing: <span id="a11y-letterSpacing-value">${settings.letterSpacing}px</span></label>
                        <div class="rsl-a11y-slider-group">
                            <button class="rsl-a11y-btn-small" data-action="letterSpacing" data-value="-1" aria-label="Decrease letter spacing">-</button>
                            <input type="range" id="a11y-letterSpacing" min="0" max="10" value="${settings.letterSpacing}" class="rsl-a11y-slider">
                            <button class="rsl-a11y-btn-small" data-action="letterSpacing" data-value="1" aria-label="Increase letter spacing">+</button>
                        </div>
                    </div>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label" for="a11y-wordSpacing">Word Spacing: <span id="a11y-wordSpacing-value">${settings.wordSpacing}px</span></label>
                        <div class="rsl-a11y-slider-group">
                            <button class="rsl-a11y-btn-small" data-action="wordSpacing" data-value="-2" aria-label="Decrease word spacing">-</button>
                            <input type="range" id="a11y-wordSpacing" min="0" max="20" value="${settings.wordSpacing}" class="rsl-a11y-slider">
                            <button class="rsl-a11y-btn-small" data-action="wordSpacing" data-value="2" aria-label="Increase word spacing">+</button>
                        </div>
                    </div>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label">Font Family</label>
                        <select id="a11y-fontFamily" class="rsl-a11y-select">
                            <option value="default" ${settings.fontFamily === 'default' ? 'selected' : ''}>Default</option>
                            <option value="arial" ${settings.fontFamily === 'arial' ? 'selected' : ''}>Arial</option>
                            <option value="verdana" ${settings.fontFamily === 'verdana' ? 'selected' : ''}>Verdana</option>
                            <option value="georgia" ${settings.fontFamily === 'georgia' ? 'selected' : ''}>Georgia</option>
                            <option value="times" ${settings.fontFamily === 'times' ? 'selected' : ''}>Times New Roman</option>
                            <option value="courier" ${settings.fontFamily === 'courier' ? 'selected' : ''}>Courier New</option>
                            <option value="opendyslexic" ${settings.fontFamily === 'opendyslexic' ? 'selected' : ''}>OpenDyslexic</option>
                        </select>
                    </div>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label">Text Alignment</label>
                        <div class="rsl-a11y-btn-group">
                            <button class="rsl-a11y-btn-icon ${settings.textAlign === 'left' ? 'active' : ''}" data-action="textAlign" data-value="left" aria-label="Align left" title="Left">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M15 15H3v2h12v-2zm0-8H3v2h12V7zM3 13h18v-2H3v2zm0 8h18v-2H3v2zM3 3v2h18V3H3z"/></svg>
                            </button>
                            <button class="rsl-a11y-btn-icon ${settings.textAlign === 'center' ? 'active' : ''}" data-action="textAlign" data-value="center" aria-label="Align center" title="Center">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/></svg>
                            </button>
                            <button class="rsl-a11y-btn-icon ${settings.textAlign === 'right' ? 'active' : ''}" data-action="textAlign" data-value="right" aria-label="Align right" title="Right">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"/></svg>
                            </button>
                            <button class="rsl-a11y-btn-icon ${settings.textAlign === 'default' ? 'active' : ''}" data-action="textAlign" data-value="default" aria-label="Default alignment" title="Default">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/></svg>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Page Zoom Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                            <path d="M12 10h-2v2H9v-2H7V9h2V7h1v2h2v1z"/>
                        </svg>
                        Page Zoom
                    </h3>

                    <div class="rsl-a11y-control">
                        <label class="rsl-a11y-label" for="a11y-pageZoom">Zoom Level: <span id="a11y-pageZoom-value">${settings.pageZoom}%</span></label>
                        <div class="rsl-a11y-slider-group">
                            <button class="rsl-a11y-btn-small" data-action="pageZoom" data-value="-25" aria-label="Zoom out">−</button>
                            <input type="range" id="a11y-pageZoom" min="100" max="400" step="25" value="${settings.pageZoom}" class="rsl-a11y-slider">
                            <button class="rsl-a11y-btn-small" data-action="pageZoom" data-value="25" aria-label="Zoom in">+</button>
                        </div>
                        <div class="rsl-a11y-zoom-presets">
                            <button class="rsl-a11y-zoom-preset ${settings.pageZoom === 100 ? 'active' : ''}" data-zoom="100">100%</button>
                            <button class="rsl-a11y-zoom-preset ${settings.pageZoom === 150 ? 'active' : ''}" data-zoom="150">150%</button>
                            <button class="rsl-a11y-zoom-preset ${settings.pageZoom === 200 ? 'active' : ''}" data-zoom="200">200%</button>
                            <button class="rsl-a11y-zoom-preset ${settings.pageZoom === 300 ? 'active' : ''}" data-zoom="300">300%</button>
                            <button class="rsl-a11y-zoom-preset ${settings.pageZoom === 400 ? 'active' : ''}" data-zoom="400">400%</button>
                        </div>
                    </div>
                </div>

                <!-- Visual Adjustments Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                        </svg>
                        Visual Adjustments
                    </h3>

                    <div class="rsl-a11y-toggle-grid">
                        <button class="rsl-a11y-toggle ${settings.highContrast ? 'active' : ''}" data-setting="highContrast" aria-pressed="${settings.highContrast}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18V4c4.41 0 8 3.59 8 8s-3.59 8-8 8z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">High Contrast</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.invertColors ? 'active' : ''}" data-setting="invertColors" aria-pressed="${settings.invertColors}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58s4.1-.78 5.66-2.34c3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Invert Colors</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.grayscale ? 'active' : ''}" data-setting="grayscale" aria-pressed="${settings.grayscale}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zm-7-2h2v-4h4v-2h-4V7h-2v4H8v2h4z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Grayscale</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.lowSaturation ? 'active' : ''}" data-setting="lowSaturation" aria-pressed="${settings.lowSaturation}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Low Saturation</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.highSaturation ? 'active' : ''}" data-setting="highSaturation" aria-pressed="${settings.highSaturation}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">High Saturation</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.highlightLinks ? 'active' : ''}" data-setting="highlightLinks" aria-pressed="${settings.highlightLinks}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Highlight Links</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.highlightHeadings ? 'active' : ''}" data-setting="highlightHeadings" aria-pressed="${settings.highlightHeadings}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M5 4v3h5.5v12h3V7H19V4z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Highlight Headings</span>
                        </button>
                    </div>
                </div>

                <!-- Navigation Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                        </svg>
                        Navigation & Focus
                    </h3>

                    <div class="rsl-a11y-toggle-grid">
                        <button class="rsl-a11y-toggle ${settings.bigCursor ? 'active' : ''}" data-setting="bigCursor" aria-pressed="${settings.bigCursor}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M13.64 21.97C13.14 22.21 12.54 22 12.31 21.5L10.13 16.76L7.62 18.78C7.45 18.92 7.24 19 7.02 19C6.44 19 6 18.55 6 18V3C6 2.44 6.46 2 7.03 2C7.25 2 7.46 2.08 7.64 2.23L19.75 12.75C20.21 13.15 20.19 13.86 19.7 14.23L16.05 16.86L18.22 21.59C18.45 22.09 18.22 22.68 17.71 22.91L16.34 23.53C15.83 23.76 15.24 23.54 15 23.04L12.95 18.55L13.64 21.97Z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Big Cursor</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.readingGuide ? 'active' : ''}" data-setting="readingGuide" aria-pressed="${settings.readingGuide}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM5 15h14v3H5z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Reading Guide</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.focusIndicator ? 'active' : ''}" data-setting="focusIndicator" aria-pressed="${settings.focusIndicator}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Focus Indicator</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.readingMask ? 'active' : ''}" data-setting="readingMask" aria-pressed="${settings.readingMask}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Reading Mask</span>
                        </button>
                    </div>
                </div>

                <!-- Motion & Content Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M15 1H9v2h6V1zm-4 13h2V8h-2v6zm8.03-6.61l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
                        </svg>
                        Motion & Content
                    </h3>

                    <div class="rsl-a11y-toggle-grid">
                        <button class="rsl-a11y-toggle ${settings.stopAnimations ? 'active' : ''}" data-setting="stopAnimations" aria-pressed="${settings.stopAnimations}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Stop Animations</span>
                        </button>

                        <button class="rsl-a11y-toggle ${settings.hideImages ? 'active' : ''}" data-setting="hideImages" aria-pressed="${settings.hideImages}">
                            <span class="rsl-a11y-toggle-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/><path d="M2.5 4.27l1.48 1.48A1.996 1.996 0 003 7v14c0 1.1.9 2 2 2h14c.55 0 1.05-.22 1.41-.59l1.31 1.31 1.41-1.41L3.91 2.86 2.5 4.27z"/></svg>
                            </span>
                            <span class="rsl-a11y-toggle-label">Hide Images</span>
                        </button>
                    </div>
                </div>

                <!-- Text-to-Speech Section -->
                <div class="rsl-a11y-section">
                    <h3 class="rsl-a11y-section-title">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
                            <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
                        </svg>
                        Text-to-Speech
                    </h3>

                    <div class="rsl-a11y-tts-container">
                        <div class="rsl-a11y-tts-toggle-row">
                            <button class="rsl-a11y-toggle rsl-a11y-tts-main-toggle ${settings.ttsEnabled ? 'active' : ''}" data-setting="ttsEnabled" aria-pressed="${settings.ttsEnabled}">
                                <span class="rsl-a11y-toggle-icon">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                        <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/>
                                    </svg>
                                </span>
                                <span class="rsl-a11y-toggle-label">Enable Read Aloud</span>
                            </button>
                        </div>

                        <div class="rsl-a11y-tts-controls ${settings.ttsEnabled ? 'active' : ''}" id="a11y-tts-controls">
                            <div class="rsl-a11y-tts-buttons">
                                <button class="rsl-a11y-tts-btn" id="a11y-tts-play" aria-label="Read page content" title="Read Page">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
                                        <path d="M8 5v14l11-7z"/>
                                    </svg>
                                </button>
                                <button class="rsl-a11y-tts-btn" id="a11y-tts-pause" aria-label="Pause reading" title="Pause" disabled>
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
                                        <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
                                    </svg>
                                </button>
                                <button class="rsl-a11y-tts-btn" id="a11y-tts-stop" aria-label="Stop reading" title="Stop" disabled>
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
                                        <path d="M6 6h12v12H6z"/>
                                    </svg>
                                </button>
                            </div>

                            <div class="rsl-a11y-control rsl-a11y-tts-speed">
                                <label class="rsl-a11y-label" for="a11y-ttsRate">Speed: <span id="a11y-ttsRate-value">${settings.ttsRate}x</span></label>
                                <div class="rsl-a11y-slider-group">
                                    <span class="rsl-a11y-speed-label">Slow</span>
                                    <input type="range" id="a11y-ttsRate" min="0.5" max="2" step="0.25" value="${settings.ttsRate}" class="rsl-a11y-slider">
                                    <span class="rsl-a11y-speed-label">Fast</span>
                                </div>
                            </div>

                            <p class="rsl-a11y-tts-hint">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="14" height="14">
                                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
                                </svg>
                                Click any text on the page to read it aloud
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="rsl-a11y-panel-footer">
                <button class="rsl-a11y-btn rsl-a11y-btn-reset" id="a11y-reset">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/></svg>
                    Reset All
                </button>
                <div class="rsl-a11y-saved-indicator" id="a11y-saved">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
                    Settings saved
                </div>
            </div>
        `;
    }

    /**
     * Attach event listeners to panel controls
     */
    function attachPanelListeners() {
        // Close button
        const closeBtn = widgetPanel.querySelector('.rsl-a11y-close-btn');
        closeBtn.addEventListener('click', closePanel);

        // Reset button
        const resetBtn = widgetPanel.querySelector('#a11y-reset');
        resetBtn.addEventListener('click', resetSettings);

        // Slider controls
        const sliders = widgetPanel.querySelectorAll('.rsl-a11y-slider');
        sliders.forEach(slider => {
            slider.addEventListener('input', handleSliderChange);
        });

        // Increment/decrement buttons
        const adjustBtns = widgetPanel.querySelectorAll('[data-action]');
        adjustBtns.forEach(btn => {
            btn.addEventListener('click', handleAdjustClick);
        });

        // Toggle buttons
        const toggles = widgetPanel.querySelectorAll('.rsl-a11y-toggle[data-setting]');
        toggles.forEach(toggle => {
            toggle.addEventListener('click', handleToggleClick);
        });

        // Select controls
        const selects = widgetPanel.querySelectorAll('.rsl-a11y-select');
        selects.forEach(select => {
            select.addEventListener('change', handleSelectChange);
        });

        // Text align buttons
        const alignBtns = widgetPanel.querySelectorAll('[data-action="textAlign"]');
        alignBtns.forEach(btn => {
            btn.addEventListener('click', handleAlignClick);
        });

        // TTS controls
        const ttsPlayBtn = widgetPanel.querySelector('#a11y-tts-play');
        const ttsPauseBtn = widgetPanel.querySelector('#a11y-tts-pause');
        const ttsStopBtn = widgetPanel.querySelector('#a11y-tts-stop');
        const ttsRateSlider = widgetPanel.querySelector('#a11y-ttsRate');

        if (ttsPlayBtn) ttsPlayBtn.addEventListener('click', ttsPlay);
        if (ttsPauseBtn) ttsPauseBtn.addEventListener('click', ttsPauseResume);
        if (ttsStopBtn) ttsStopBtn.addEventListener('click', ttsStop);
        if (ttsRateSlider) ttsRateSlider.addEventListener('input', handleTtsRateChange);

        // Page zoom presets
        const zoomPresets = widgetPanel.querySelectorAll('.rsl-a11y-zoom-preset');
        zoomPresets.forEach(btn => {
            btn.addEventListener('click', handleZoomPresetClick);
        });
    }

    /**
     * Handle slider changes
     */
    function handleSliderChange(e) {
        const slider = e.target;
        const setting = slider.id.replace('a11y-', '');
        const value = parseInt(slider.value);

        settings[setting] = value;

        // Update display value
        const valueDisplay = widgetPanel.querySelector(`#a11y-${setting}-value`);
        if (valueDisplay) {
            let unit = 'px';
            if (setting === 'fontSize' || setting === 'lineHeight' || setting === 'pageZoom') {
                unit = '%';
            }
            valueDisplay.textContent = value + unit;
        }

        // Update zoom presets if this is the page zoom slider
        if (setting === 'pageZoom') {
            const presets = widgetPanel.querySelectorAll('.rsl-a11y-zoom-preset');
            presets.forEach(p => {
                p.classList.toggle('active', parseInt(p.dataset.zoom) === value);
            });
        }

        applySetting(setting, value);
        saveSettings();
        showSavedIndicator();
    }

    /**
     * Handle adjustment button clicks (+/-)
     */
    function handleAdjustClick(e) {
        const btn = e.currentTarget;
        const action = btn.dataset.action;
        const change = parseInt(btn.dataset.value);
        const slider = widgetPanel.querySelector(`#a11y-${action}`);

        if (slider) {
            let newValue = parseInt(slider.value) + change;
            newValue = Math.max(parseInt(slider.min), Math.min(parseInt(slider.max), newValue));
            slider.value = newValue;
            slider.dispatchEvent(new Event('input'));
        }
    }

    /**
     * Handle toggle button clicks
     */
    function handleToggleClick(e) {
        const toggle = e.currentTarget;
        const setting = toggle.dataset.setting;

        settings[setting] = !settings[setting];
        toggle.classList.toggle('active');
        toggle.setAttribute('aria-pressed', settings[setting]);

        applySetting(setting, settings[setting]);
        saveSettings();
        showSavedIndicator();
    }

    /**
     * Handle select changes
     */
    function handleSelectChange(e) {
        const select = e.target;
        const setting = select.id.replace('a11y-', '');
        const value = select.value;

        settings[setting] = value;
        applySetting(setting, value);
        saveSettings();
        showSavedIndicator();
    }

    /**
     * Handle text alignment clicks
     */
    function handleAlignClick(e) {
        const btn = e.currentTarget;
        const value = btn.dataset.value;

        // Update button states
        const alignBtns = widgetPanel.querySelectorAll('[data-action="textAlign"]');
        alignBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');

        settings.textAlign = value;
        applySetting('textAlign', value);
        saveSettings();
        showSavedIndicator();
    }

    /**
     * Handle zoom preset button clicks
     */
    function handleZoomPresetClick(e) {
        const btn = e.currentTarget;
        const zoom = parseInt(btn.dataset.zoom);

        // Update slider
        const slider = widgetPanel.querySelector('#a11y-pageZoom');
        if (slider) {
            slider.value = zoom;
        }

        // Update display
        const valueDisplay = widgetPanel.querySelector('#a11y-pageZoom-value');
        if (valueDisplay) {
            valueDisplay.textContent = zoom + '%';
        }

        // Update preset button states
        const presets = widgetPanel.querySelectorAll('.rsl-a11y-zoom-preset');
        presets.forEach(p => p.classList.remove('active'));
        btn.classList.add('active');

        settings.pageZoom = zoom;
        applySetting('pageZoom', zoom);
        saveSettings();
        showSavedIndicator();
    }

    /**
     * Apply a specific setting
     */
    function applySetting(setting, value) {
        const html = document.documentElement;
        const body = document.body;

        switch (setting) {
            case 'fontSize':
                html.style.setProperty('--rsl-a11y-font-scale', value / 100);
                body.style.fontSize = (value / 100) + 'em';
                break;

            case 'lineHeight':
                html.style.setProperty('--rsl-a11y-line-height', value / 100);
                body.style.lineHeight = (value / 100 * 1.6);
                break;

            case 'letterSpacing':
                html.style.setProperty('--rsl-a11y-letter-spacing', value + 'px');
                body.style.letterSpacing = value + 'px';
                break;

            case 'wordSpacing':
                html.style.setProperty('--rsl-a11y-word-spacing', value + 'px');
                body.style.wordSpacing = value + 'px';
                break;

            case 'fontFamily':
                applyFontFamily(value);
                break;

            case 'textAlign':
                applyTextAlign(value);
                break;

            case 'highContrast':
                html.classList.toggle('rsl-a11y-high-contrast', value);
                break;

            case 'invertColors':
                html.classList.toggle('rsl-a11y-invert', value);
                break;

            case 'grayscale':
                html.classList.toggle('rsl-a11y-grayscale', value);
                break;

            case 'lowSaturation':
                html.classList.toggle('rsl-a11y-low-saturation', value);
                if (value) settings.highSaturation = false;
                break;

            case 'highSaturation':
                html.classList.toggle('rsl-a11y-high-saturation', value);
                if (value) settings.lowSaturation = false;
                break;

            case 'highlightLinks':
                html.classList.toggle('rsl-a11y-highlight-links', value);
                break;

            case 'highlightHeadings':
                html.classList.toggle('rsl-a11y-highlight-headings', value);
                break;

            case 'bigCursor':
                html.classList.toggle('rsl-a11y-big-cursor', value);
                break;

            case 'readingGuide':
                toggleReadingGuide(value);
                break;

            case 'focusIndicator':
                html.classList.toggle('rsl-a11y-focus-indicator', value);
                break;

            case 'readingMask':
                toggleReadingMask(value);
                break;

            case 'stopAnimations':
                html.classList.toggle('rsl-a11y-stop-animations', value);
                break;

            case 'hideImages':
                html.classList.toggle('rsl-a11y-hide-images', value);
                break;

            case 'ttsEnabled':
                toggleTts(value);
                break;

            case 'ttsRate':
                settings.ttsRate = value;
                if (ttsUtterance) {
                    ttsUtterance.rate = value;
                }
                break;

            case 'pageZoom':
                applyPageZoom(value);
                break;
        }
    }

    /**
     * Apply page zoom using CSS zoom property
     * CSS zoom behaves like browser zoom (Ctrl+/-) and doesn't break fixed positioning
     */
    function applyPageZoom(zoomLevel) {
        const html = document.documentElement;

        if (zoomLevel === 100) {
            // Reset zoom
            html.style.zoom = '';
        } else {
            // Apply zoom to html element - this behaves like browser zoom
            // and doesn't break fixed positioning like transform: scale() does
            html.style.zoom = (zoomLevel / 100);
        }

        // Apply counter-zoom to widget panel and button so they stay at normal size
        const counterZoom = zoomLevel === 100 ? '' : (100 / zoomLevel);
        if (widgetPanel) {
            widgetPanel.style.zoom = counterZoom;
        }
        if (widgetButton) {
            widgetButton.style.zoom = counterZoom;
        }

        // Update preset button states
        if (widgetPanel) {
            const presets = widgetPanel.querySelectorAll('.rsl-a11y-zoom-preset');
            presets.forEach(p => {
                p.classList.toggle('active', parseInt(p.dataset.zoom) === zoomLevel);
            });
        }
    }

    /**
     * Apply font family
     */
    function applyFontFamily(value) {
        const body = document.body;

        const fontMap = {
            'default': '',
            'arial': 'Arial, Helvetica, sans-serif',
            'verdana': 'Verdana, Geneva, sans-serif',
            'georgia': 'Georgia, serif',
            'times': '"Times New Roman", Times, serif',
            'courier': '"Courier New", Courier, monospace',
            'opendyslexic': 'OpenDyslexic, sans-serif'
        };

        if (fontMap[value]) {
            body.style.fontFamily = fontMap[value];
        } else {
            body.style.fontFamily = '';
        }
    }

    /**
     * Apply text alignment
     */
    function applyTextAlign(value) {
        const html = document.documentElement;

        html.classList.remove('rsl-a11y-text-left', 'rsl-a11y-text-center', 'rsl-a11y-text-right');

        if (value !== 'default') {
            html.classList.add(`rsl-a11y-text-${value}`);
        }
    }

    /**
     * Apply all settings
     */
    function applyAllSettings() {
        Object.keys(settings).forEach(key => {
            if (key !== 'widgetOpen') {
                applySetting(key, settings[key]);
            }
        });
    }

    /**
     * Update panel controls to match current settings
     */
    function updatePanelControls() {
        // Update sliders
        ['fontSize', 'lineHeight', 'letterSpacing', 'wordSpacing'].forEach(setting => {
            const slider = widgetPanel.querySelector(`#a11y-${setting}`);
            const valueDisplay = widgetPanel.querySelector(`#a11y-${setting}-value`);
            if (slider) {
                slider.value = settings[setting];
                const unit = (setting === 'fontSize' || setting === 'lineHeight') ? '%' : 'px';
                if (valueDisplay) valueDisplay.textContent = settings[setting] + unit;
            }
        });

        // Update select
        const fontSelect = widgetPanel.querySelector('#a11y-fontFamily');
        if (fontSelect) fontSelect.value = settings.fontFamily;

        // Update toggles
        const toggles = widgetPanel.querySelectorAll('.rsl-a11y-toggle[data-setting]');
        toggles.forEach(toggle => {
            const setting = toggle.dataset.setting;
            toggle.classList.toggle('active', settings[setting]);
            toggle.setAttribute('aria-pressed', settings[setting]);
        });

        // Update text align buttons
        const alignBtns = widgetPanel.querySelectorAll('[data-action="textAlign"]');
        alignBtns.forEach(btn => {
            btn.classList.toggle('active', btn.dataset.value === settings.textAlign);
        });

        // Update TTS controls
        const ttsRateSlider = widgetPanel.querySelector('#a11y-ttsRate');
        const ttsRateDisplay = widgetPanel.querySelector('#a11y-ttsRate-value');
        const ttsControls = widgetPanel.querySelector('#a11y-tts-controls');

        if (ttsRateSlider) ttsRateSlider.value = settings.ttsRate;
        if (ttsRateDisplay) ttsRateDisplay.textContent = settings.ttsRate + 'x';
        if (ttsControls) ttsControls.classList.toggle('active', settings.ttsEnabled);

        // Update TTS toggle button
        const ttsToggle = widgetPanel.querySelector('.rsl-a11y-tts-main-toggle');
        if (ttsToggle) {
            ttsToggle.classList.toggle('active', settings.ttsEnabled);
            ttsToggle.setAttribute('aria-pressed', settings.ttsEnabled);
        }

        updateTtsButtonStates();

        // Update page zoom controls
        const zoomSlider = widgetPanel.querySelector('#a11y-pageZoom');
        const zoomDisplay = widgetPanel.querySelector('#a11y-pageZoom-value');
        const zoomPresets = widgetPanel.querySelectorAll('.rsl-a11y-zoom-preset');

        if (zoomSlider) zoomSlider.value = settings.pageZoom;
        if (zoomDisplay) zoomDisplay.textContent = settings.pageZoom + '%';
        zoomPresets.forEach(p => {
            p.classList.toggle('active', parseInt(p.dataset.zoom) === settings.pageZoom);
        });
    }

    /**
     * Create reading guide element
     */
    function createReadingGuide() {
        readingGuideElement = document.createElement('div');
        readingGuideElement.className = 'rsl-a11y-reading-guide';
        readingGuideElement.setAttribute('aria-hidden', 'true');
        document.body.appendChild(readingGuideElement);

        document.addEventListener('mousemove', updateReadingGuide);
    }

    /**
     * Update reading guide position
     */
    function updateReadingGuide(e) {
        if (settings.readingGuide && readingGuideElement) {
            readingGuideElement.style.top = (e.clientY - 15) + 'px';
        }
    }

    /**
     * Toggle reading guide
     */
    function toggleReadingGuide(enabled) {
        if (readingGuideElement) {
            readingGuideElement.classList.toggle('active', enabled);
        }
    }

    /**
     * Create reading mask element
     */
    function createReadingMask() {
        readingMaskElement = document.createElement('div');
        readingMaskElement.className = 'rsl-a11y-reading-mask';
        readingMaskElement.setAttribute('aria-hidden', 'true');
        readingMaskElement.innerHTML = `
            <div class="rsl-a11y-mask-top"></div>
            <div class="rsl-a11y-mask-bottom"></div>
        `;
        document.body.appendChild(readingMaskElement);

        document.addEventListener('mousemove', updateReadingMask);
    }

    /**
     * Update reading mask position
     */
    function updateReadingMask(e) {
        if (settings.readingMask && readingMaskElement) {
            const viewportHeight = window.innerHeight;
            const maskHeight = 100; // Height of visible area
            const top = Math.max(0, e.clientY - maskHeight / 2);

            readingMaskElement.querySelector('.rsl-a11y-mask-top').style.height = top + 'px';
            readingMaskElement.querySelector('.rsl-a11y-mask-bottom').style.top = (top + maskHeight) + 'px';
        }
    }

    /**
     * Toggle reading mask
     */
    function toggleReadingMask(enabled) {
        if (readingMaskElement) {
            readingMaskElement.classList.toggle('active', enabled);
        }
    }

    // ==========================================
    // TEXT-TO-SPEECH FUNCTIONS
    // ==========================================

    /**
     * Check if browser supports Speech Synthesis
     */
    function ttsSupported() {
        return 'speechSynthesis' in window;
    }

    /**
     * Toggle TTS feature on/off
     */
    function toggleTts(enabled) {
        const html = document.documentElement;
        const ttsControls = widgetPanel ? widgetPanel.querySelector('#a11y-tts-controls') : null;

        if (enabled) {
            html.classList.add('rsl-a11y-tts-enabled');
            if (ttsControls) ttsControls.classList.add('active');

            // Add click listener for click-to-read
            document.addEventListener('click', handleTtsClick);
        } else {
            html.classList.remove('rsl-a11y-tts-enabled');
            if (ttsControls) ttsControls.classList.remove('active');

            // Stop any current speech
            ttsStop();

            // Remove click listener
            document.removeEventListener('click', handleTtsClick);
        }
    }

    /**
     * Handle click on text to read it
     */
    function handleTtsClick(e) {
        // Don't read if clicking on widget panel or button
        if (widgetPanel && (widgetPanel.contains(e.target) || widgetButton.contains(e.target))) {
            return;
        }

        // Don't read if clicking on interactive elements
        const interactiveElements = ['BUTTON', 'A', 'INPUT', 'SELECT', 'TEXTAREA'];
        if (interactiveElements.includes(e.target.tagName)) {
            return;
        }

        // Get the text content of the clicked element
        const element = e.target.closest('p, h1, h2, h3, h4, h5, h6, li, td, th, span, div, label');
        if (element && element.textContent.trim()) {
            ttsReadElement(element);
        }
    }

    /**
     * Read a specific element
     */
    function ttsReadElement(element) {
        if (!ttsSupported()) {
            showToast('Text-to-speech is not supported in your browser');
            return;
        }

        // Stop any current speech
        window.speechSynthesis.cancel();
        clearTtsHighlight();

        const text = element.textContent.trim();
        if (!text) return;

        ttsCurrentElement = element;
        ttsUtterance = new SpeechSynthesisUtterance(text);
        ttsUtterance.rate = settings.ttsRate;
        ttsUtterance.lang = document.documentElement.lang || 'en-US';

        // Highlight the element being read
        element.classList.add('rsl-a11y-tts-reading');
        ttsHighlightedElements.push(element);

        // Handle events
        ttsUtterance.onstart = function() {
            ttsIsPlaying = true;
            ttsIsPaused = false;
            updateTtsButtonStates();
        };

        ttsUtterance.onend = function() {
            ttsIsPlaying = false;
            ttsIsPaused = false;
            clearTtsHighlight();
            updateTtsButtonStates();
        };

        ttsUtterance.onerror = function(e) {
            console.warn('TTS error:', e);
            ttsIsPlaying = false;
            ttsIsPaused = false;
            clearTtsHighlight();
            updateTtsButtonStates();
        };

        window.speechSynthesis.speak(ttsUtterance);
    }

    /**
     * Read the entire page content
     */
    function ttsPlay() {
        if (!ttsSupported()) {
            showToast('Text-to-speech is not supported in your browser');
            return;
        }

        // If paused, resume
        if (ttsIsPaused) {
            window.speechSynthesis.resume();
            ttsIsPaused = false;
            ttsIsPlaying = true;
            updateTtsButtonStates();
            return;
        }

        // Stop any current speech
        window.speechSynthesis.cancel();
        clearTtsHighlight();

        // Get readable content from the page
        const content = getReadableContent();
        if (!content) {
            showToast('No readable content found on this page');
            return;
        }

        ttsUtterance = new SpeechSynthesisUtterance(content);
        ttsUtterance.rate = settings.ttsRate;
        ttsUtterance.lang = document.documentElement.lang || 'en-US';

        ttsUtterance.onstart = function() {
            ttsIsPlaying = true;
            ttsIsPaused = false;
            updateTtsButtonStates();
        };

        ttsUtterance.onend = function() {
            ttsIsPlaying = false;
            ttsIsPaused = false;
            updateTtsButtonStates();
        };

        ttsUtterance.onerror = function(e) {
            if (e.error !== 'canceled') {
                console.warn('TTS error:', e);
            }
            ttsIsPlaying = false;
            ttsIsPaused = false;
            updateTtsButtonStates();
        };

        window.speechSynthesis.speak(ttsUtterance);
    }

    /**
     * Pause or resume speech
     */
    function ttsPauseResume() {
        if (!ttsSupported()) return;

        if (ttsIsPaused) {
            window.speechSynthesis.resume();
            ttsIsPaused = false;
            ttsIsPlaying = true;
        } else if (ttsIsPlaying) {
            window.speechSynthesis.pause();
            ttsIsPaused = true;
            ttsIsPlaying = false;
        }
        updateTtsButtonStates();
    }

    /**
     * Stop speech completely
     */
    function ttsStop() {
        if (!ttsSupported()) return;

        window.speechSynthesis.cancel();
        ttsIsPlaying = false;
        ttsIsPaused = false;
        ttsUtterance = null;
        clearTtsHighlight();
        updateTtsButtonStates();
    }

    /**
     * Handle TTS rate slider change
     */
    function handleTtsRateChange(e) {
        const rate = parseFloat(e.target.value);
        settings.ttsRate = rate;

        // Update display
        const rateDisplay = widgetPanel.querySelector('#a11y-ttsRate-value');
        if (rateDisplay) {
            rateDisplay.textContent = rate + 'x';
        }

        // Update current utterance if speaking
        if (ttsUtterance && ttsIsPlaying) {
            // Need to restart speech with new rate
            const wasPlaying = ttsIsPlaying;
            ttsStop();
            if (wasPlaying) {
                ttsPlay();
            }
        }

        saveSettings();
        showSavedIndicator();
    }

    /**
     * Update TTS button states
     */
    function updateTtsButtonStates() {
        const playBtn = widgetPanel ? widgetPanel.querySelector('#a11y-tts-play') : null;
        const pauseBtn = widgetPanel ? widgetPanel.querySelector('#a11y-tts-pause') : null;
        const stopBtn = widgetPanel ? widgetPanel.querySelector('#a11y-tts-stop') : null;

        if (playBtn) {
            playBtn.disabled = ttsIsPlaying && !ttsIsPaused;
            playBtn.classList.toggle('active', ttsIsPlaying && !ttsIsPaused);
        }

        if (pauseBtn) {
            pauseBtn.disabled = !ttsIsPlaying && !ttsIsPaused;
            pauseBtn.classList.toggle('active', ttsIsPaused);
            // Change icon/label based on state
            pauseBtn.setAttribute('aria-label', ttsIsPaused ? 'Resume reading' : 'Pause reading');
            pauseBtn.setAttribute('title', ttsIsPaused ? 'Resume' : 'Pause');
        }

        if (stopBtn) {
            stopBtn.disabled = !ttsIsPlaying && !ttsIsPaused;
        }
    }

    /**
     * Clear TTS highlight from elements
     */
    function clearTtsHighlight() {
        ttsHighlightedElements.forEach(el => {
            el.classList.remove('rsl-a11y-tts-reading');
        });
        ttsHighlightedElements = [];
        ttsCurrentElement = null;
    }

    /**
     * Get readable content from the page
     */
    function getReadableContent() {
        // Try to find main content area
        const mainContent = document.querySelector('main, article, [role="main"], .content, .container');
        const contentArea = mainContent || document.body;

        // Get all readable elements
        const elements = contentArea.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, td, th, figcaption, blockquote');

        let content = '';
        elements.forEach(el => {
            // Skip if inside widget panel, nav, footer, or hidden
            if (widgetPanel && widgetPanel.contains(el)) return;
            if (el.closest('nav, footer, .rsl-a11y-widget-panel, .rsl-navbar, script, style, noscript')) return;
            if (el.offsetParent === null) return; // Hidden element

            const text = el.textContent.trim();
            if (text) {
                content += text + '. ';
            }
        });

        return content.trim();
    }

    /**
     * Toggle the settings panel
     */
    function togglePanel() {
        if (settings.widgetOpen) {
            closePanel();
        } else {
            openPanel();
        }
    }

    /**
     * Open the settings panel
     */
    function openPanel() {
        settings.widgetOpen = true;
        widgetPanel.classList.add('open');
        widgetButton.classList.add('active');
        widgetButton.setAttribute('aria-expanded', 'true');

        // Focus the close button for keyboard users
        setTimeout(() => {
            widgetPanel.querySelector('.rsl-a11y-close-btn').focus();
        }, 100);
    }

    /**
     * Close the settings panel
     */
    function closePanel() {
        settings.widgetOpen = false;
        widgetPanel.classList.remove('open');
        widgetButton.classList.remove('active');
        widgetButton.setAttribute('aria-expanded', 'false');

        // Return focus to widget button
        widgetButton.focus();
    }

    /**
     * Handle keyboard shortcuts
     */
    function handleKeyboardShortcut(e) {
        // Alt + A to toggle panel
        if (e.altKey && e.key.toLowerCase() === 'a') {
            e.preventDefault();
            togglePanel();
        }

        // Cmd+0 (Mac) / Ctrl+0 (Windows/Linux) to reset zoom to 100%
        if ((e.metaKey || e.ctrlKey) && e.key === '0') {
            if (settings.pageZoom !== 100) {
                e.preventDefault();
                settings.pageZoom = 100;
                applySetting('pageZoom', 100);
                saveSettings();
                updatePanelControls();
                showToast('Zoom reset to 100%');
            }
        }
    }

    /**
     * Show saved indicator
     */
    function showSavedIndicator() {
        const indicator = widgetPanel.querySelector('#a11y-saved');
        if (indicator) {
            indicator.classList.add('show');
            setTimeout(() => {
                indicator.classList.remove('show');
            }, 2000);
        }
    }

    /**
     * Show toast notification
     */
    function showToast(message) {
        // Use RSL Toast if available
        if (window.RSL && window.RSL.Toast && window.RSL.Toast.show) {
            window.RSL.Toast.show({
                header: 'Accessibility',
                body: message,
                position: 'bottom-center',
                autoHide: true,
                delay: 3000
            });
        } else {
            // Fallback toast
            const toast = document.createElement('div');
            toast.className = 'rsl-a11y-toast';
            toast.textContent = message;
            document.body.appendChild(toast);

            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }
    }

    // Public API
    window.RSL.AccessibilityWidget = {
        init: init,
        open: openPanel,
        close: closePanel,
        toggle: togglePanel,
        reset: resetSettings,
        getSetting: function(key) { return settings[key]; },
        setSetting: function(key, value) {
            if (key in settings) {
                settings[key] = value;
                applySetting(key, value);
                saveSettings();
                updatePanelControls();
            }
        },
        /**
         * Get current widget position
         * @returns {string} Current position (bottom-left, bottom-right, top-left, top-right)
         */
        getPosition: function() { return config.position; },
        /**
         * Set widget position dynamically
         * @param {string} position - Position (bottom-left, bottom-right, top-left, top-right)
         */
        setPosition: applyPosition,
        /**
         * Get available positions
         * @returns {Array} Array of valid position strings
         */
        getValidPositions: function() { return [...VALID_POSITIONS]; },

        // Text-to-Speech API
        /**
         * Start reading page content aloud
         */
        ttsPlay: ttsPlay,
        /**
         * Pause or resume speech
         */
        ttsPauseResume: ttsPauseResume,
        /**
         * Stop speech completely
         */
        ttsStop: ttsStop,
        /**
         * Read a specific element aloud
         * @param {HTMLElement} element - Element to read
         */
        ttsReadElement: ttsReadElement,
        /**
         * Check if TTS is supported in the browser
         * @returns {boolean}
         */
        ttsSupported: ttsSupported
    };

    // Auto-initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
