/**
 * RSL Announcements Component
 * Version: 1.0.0
 *
 * A two-mode announcement system with bar (collapsed) and panel (expanded) views.
 * Fully ADA compliant with WCAG 2.1 AA support.
 *
 * Features:
 * - Bar Mode: Single-line display with navigation controls
 * - Panel Mode: Expanded scannable list of all announcements
 * - Optional auto-rotation with pause controls
 * - FilterBus integration for filtering by category
 * - Full keyboard navigation
 * - Screen reader support with live regions
 * - Reduced motion support
 *
 * Data Attributes:
 * - data-rsl-announcements: Initialize component
 * - data-auto-rotate: Enable auto-rotation (default: false)
 * - data-interval: Rotation interval in seconds (default: 5)
 * - data-pause-on-hover: Pause on hover (default: true)
 * - data-expand-on-focus: Expand panel on focus (default: false)
 * - data-filter-key: FilterBus integration key
 * - data-variant: Color variant (info, success, warning, danger, neutral)
 *
 * Item Attributes:
 * - data-priority: Priority level (urgent, event, news, reminder)
 * - data-category: Category for filtering
 * - data-date: Date string (YYYY-MM-DD)
 * - data-new: Mark as new
 * - data-link: Link URL
 */

(function() {
    'use strict';

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

    // Track initialized instances
    const instances = new Set();

    /**
     * Announcements Component
     */
    window.RSL.Announcements = {

        // Default configuration
        defaults: {
            autoRotate: false,
            interval: 5,
            pauseOnHover: true,
            expandOnFocus: false,
            filterKey: null
        },

        /**
         * Initialize all announcement components on the page
         */
        init: function() {
            const components = document.querySelectorAll('[data-rsl-announcements]');
            components.forEach(function(el) {
                if (!instances.has(el)) {
                    RSL.Announcements.create(el);
                    instances.add(el);
                }
            });
        },

        /**
         * Create a single announcement component
         * @param {HTMLElement} container - The container element
         * @param {Object} options - Optional configuration overrides
         */
        create: function(container, options) {
            if (!container) return null;

            // Check if already initialized
            if (container._rslAnnouncements) {
                return container._rslAnnouncements;
            }

            // Parse configuration
            const config = Object.assign({}, RSL.Announcements.defaults, options || {}, {
                autoRotate: container.hasAttribute('data-auto-rotate')
                    ? container.getAttribute('data-auto-rotate') === 'true'
                    : (options && options.autoRotate) || RSL.Announcements.defaults.autoRotate,
                interval: parseInt(container.getAttribute('data-interval'), 10)
                    || (options && options.interval)
                    || RSL.Announcements.defaults.interval,
                pauseOnHover: container.hasAttribute('data-pause-on-hover')
                    ? container.getAttribute('data-pause-on-hover') !== 'false'
                    : (options && options.pauseOnHover !== undefined ? options.pauseOnHover : RSL.Announcements.defaults.pauseOnHover),
                expandOnFocus: container.hasAttribute('data-expand-on-focus')
                    ? container.getAttribute('data-expand-on-focus') === 'true'
                    : (options && options.expandOnFocus) || RSL.Announcements.defaults.expandOnFocus,
                filterKey: container.getAttribute('data-filter-key')
                    || (options && options.filterKey)
                    || RSL.Announcements.defaults.filterKey
            });

            // State
            const state = {
                currentIndex: 0,
                isPaused: !config.autoRotate,
                pausedByUser: false,
                isExpanded: false,
                items: [],
                rotationTimer: null,
                reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches
            };

            // Build the component structure
            const structure = buildStructure(container, config, state);

            // Store instance reference
            const instance = {
                container: container,
                config: config,
                state: state,
                structure: structure,
                next: function() { navigateNext(state, structure, config); },
                prev: function() { navigatePrev(state, structure, config); },
                goTo: function(index) { goToIndex(index, state, structure, config); },
                expand: function() { expandPanel(state, structure); },
                collapse: function() { collapsePanel(state, structure); },
                toggle: function() { togglePanel(state, structure); },
                pause: function() { pauseRotation(state, true, structure); },
                resume: function() { resumeRotation(state, config, structure); },
                refresh: function() { refreshItems(container, state, structure, config); },
                destroy: function() { destroyInstance(container, state, structure); }
            };

            container._rslAnnouncements = instance;

            // Setup event listeners
            setupEventListeners(container, config, state, structure);

            // Setup FilterBus integration
            if (config.filterKey && window.RSL.FilterBus) {
                setupFilterBus(container, config, state, structure);
            }

            // Start auto-rotation if enabled
            if (config.autoRotate && state.items.length > 1) {
                startRotation(state, config, structure);
            }

            return instance;
        },

        /**
         * Get instance by container element
         */
        getInstance: function(container) {
            return container && container._rslAnnouncements;
        },

        /**
         * Destroy instance
         */
        destroy: function(container) {
            const instance = this.getInstance(container);
            if (instance) {
                instance.destroy();
                instances.delete(container);
            }
        }
    };

    /**
     * Build the component HTML structure
     */
    function buildStructure(container, config, state) {
        // Parse existing items from container
        const existingItems = container.querySelectorAll('.rsl-announcement-item, [data-announcement]');

        existingItems.forEach(function(item, index) {
            state.items.push({
                id: item.id || 'announcement-' + index,
                title: item.textContent.trim() || item.getAttribute('data-title') || '',
                priority: item.getAttribute('data-priority') || 'normal',
                category: item.getAttribute('data-category') || '',
                date: item.getAttribute('data-date') || '',
                link: item.getAttribute('data-link') || item.querySelector('a')?.href || '',
                isNew: item.hasAttribute('data-new')
            });
        });

        // Clear existing content
        container.innerHTML = '';

        // Create bar
        const bar = document.createElement('div');
        bar.className = 'rsl-announcements-bar';
        bar.setAttribute('role', 'group');
        bar.setAttribute('aria-label', 'Announcements. Use left and right arrow keys to navigate announcements');

        // Label
        const label = document.createElement('div');
        label.className = 'rsl-announcements-label';
        label.innerHTML = '<i class="fas fa-bullhorn" aria-hidden="true"></i> <span>Announcements</span>';

        // Current announcement display - focusable for keyboard users
        const current = document.createElement('div');
        current.className = 'rsl-announcements-current';
        current.setAttribute('tabindex', '0');

        const textDisplay = document.createElement('span');
        textDisplay.className = 'rsl-announcements-text';
        current.appendChild(textDisplay);

        // Controls
        const controls = document.createElement('div');
        controls.className = 'rsl-announcements-controls';

        // Previous button (not tabbable - use arrow keys instead)
        const prevBtn = document.createElement('button');
        prevBtn.className = 'rsl-announcements-btn rsl-announcements-prev';
        prevBtn.setAttribute('type', 'button');
        prevBtn.setAttribute('tabindex', '-1');
        prevBtn.setAttribute('aria-label', 'Show previous announcement');
        prevBtn.innerHTML = '<i class="fas fa-chevron-left" aria-hidden="true"></i>';

        // Pause button (only if auto-rotate is enabled)
        let pauseBtn = null;
        if (config.autoRotate) {
            pauseBtn = document.createElement('button');
            pauseBtn.className = 'rsl-announcements-btn rsl-announcements-pause';
            pauseBtn.setAttribute('type', 'button');
            pauseBtn.setAttribute('aria-label', 'Pause auto-rotation');
            pauseBtn.setAttribute('aria-pressed', 'false');
            pauseBtn.innerHTML = '<i class="fas fa-pause" aria-hidden="true"></i>';
        }

        // Next button (not tabbable - use arrow keys instead)
        const nextBtn = document.createElement('button');
        nextBtn.className = 'rsl-announcements-btn rsl-announcements-next';
        nextBtn.setAttribute('type', 'button');
        nextBtn.setAttribute('tabindex', '-1');
        nextBtn.setAttribute('aria-label', 'Show next announcement');
        nextBtn.innerHTML = '<i class="fas fa-chevron-right" aria-hidden="true"></i>';

        // Counter
        const counter = document.createElement('span');
        counter.className = 'rsl-announcements-counter';
        counter.setAttribute('aria-hidden', 'true');

        // Expand button
        const expandBtn = document.createElement('button');
        expandBtn.className = 'rsl-announcements-btn rsl-announcements-expand';
        expandBtn.setAttribute('type', 'button');
        expandBtn.setAttribute('aria-label', 'View all announcements');
        expandBtn.setAttribute('aria-expanded', 'false');
        expandBtn.innerHTML = '<i class="fas fa-chevron-down" aria-hidden="true"></i>';

        // Assemble controls
        controls.appendChild(prevBtn);
        if (pauseBtn) controls.appendChild(pauseBtn);
        controls.appendChild(nextBtn);
        controls.appendChild(counter);
        controls.appendChild(expandBtn);

        // Navigation hint tooltip (shown on focus for non-screen reader users)
        const navHint = document.createElement('div');
        navHint.className = 'rsl-announcements-nav-hint';
        navHint.textContent = 'Use left and right arrow keys to navigate announcements';
        navHint.setAttribute('aria-hidden', 'true');

        // Assemble bar
        bar.appendChild(label);
        bar.appendChild(current);
        bar.appendChild(navHint);
        bar.appendChild(controls);

        // Create panel
        const panel = document.createElement('div');
        panel.className = 'rsl-announcements-panel';
        panel.setAttribute('role', 'dialog');
        panel.setAttribute('aria-label', 'All announcements');
        panel.setAttribute('aria-hidden', 'true');

        // Panel header
        const panelHeader = document.createElement('div');
        panelHeader.className = 'rsl-announcements-panel-header';

        const panelTitle = document.createElement('h2');
        panelTitle.className = 'rsl-announcements-panel-title';
        panelTitle.textContent = 'All Announcements';
        panelTitle.id = 'announcements-panel-title-' + Math.random().toString(36).substr(2, 9);

        const closeBtn = document.createElement('button');
        closeBtn.className = 'rsl-announcements-panel-close';
        closeBtn.setAttribute('type', 'button');
        closeBtn.setAttribute('aria-label', 'Close announcements panel');
        closeBtn.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i>';

        panelHeader.appendChild(panelTitle);
        panelHeader.appendChild(closeBtn);

        // Panel list
        const list = document.createElement('ul');
        list.className = 'rsl-announcements-list';
        list.setAttribute('role', 'list');

        // Populate list
        state.items.forEach(function(item, index) {
            const li = createListItem(item, index);
            list.appendChild(li);
        });

        // Empty state
        if (state.items.length === 0) {
            const empty = document.createElement('div');
            empty.className = 'rsl-announcements-empty';
            empty.innerHTML = '<i class="fas fa-inbox" aria-hidden="true"></i><p>No announcements at this time.</p>';
            list.appendChild(empty);
        }

        panel.appendChild(panelHeader);
        panel.appendChild(list);

        // Set aria-labelledby for panel
        panel.setAttribute('aria-labelledby', panelTitle.id);

        // Live region for announcing changes when using arrow keys
        const liveRegion = document.createElement('div');
        liveRegion.className = 'rsl-announcements-live';
        liveRegion.setAttribute('aria-live', 'assertive');
        liveRegion.setAttribute('aria-atomic', 'true');
        liveRegion.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);';

        // Assemble container
        container.appendChild(bar);
        container.appendChild(panel);
        container.appendChild(liveRegion);

        // Update display
        const structure = {
            bar: bar,
            label: label,
            current: current,
            textDisplay: textDisplay,
            navHint: navHint,
            controls: controls,
            prevBtn: prevBtn,
            pauseBtn: pauseBtn,
            nextBtn: nextBtn,
            counter: counter,
            expandBtn: expandBtn,
            panel: panel,
            panelHeader: panelHeader,
            panelTitle: panelTitle,
            closeBtn: closeBtn,
            list: list,
            liveRegion: liveRegion
        };

        updateDisplay(state, structure);

        return structure;
    }

    /**
     * Create a list item for the panel
     */
    function createListItem(item, index) {
        const li = document.createElement('li');
        li.className = 'rsl-announcements-item';
        li.setAttribute('data-index', index);
        if (item.category) {
            li.setAttribute('data-category', item.category);
        }

        // Badges container
        const badges = document.createElement('div');
        badges.className = 'rsl-announcements-item-badges';

        // Priority badge
        if (item.priority && item.priority !== 'normal') {
            const priorityBadge = document.createElement('span');
            priorityBadge.className = 'rsl-announcements-badge';
            priorityBadge.setAttribute('data-priority', item.priority);
            priorityBadge.textContent = item.priority.charAt(0).toUpperCase() + item.priority.slice(1);
            badges.appendChild(priorityBadge);
        }

        // New badge
        if (item.isNew) {
            const newBadge = document.createElement('span');
            newBadge.className = 'rsl-announcements-new';
            newBadge.textContent = 'New';
            badges.appendChild(newBadge);
        }

        // Content container
        const content = document.createElement('div');
        content.className = 'rsl-announcements-item-content';

        // Title
        const title = document.createElement('p');
        title.className = 'rsl-announcements-item-title';

        if (item.link) {
            const link = document.createElement('a');
            link.href = item.link;
            link.textContent = item.title;
            title.appendChild(link);
        } else {
            title.textContent = item.title;
        }

        content.appendChild(title);

        // Meta (date)
        if (item.date) {
            const meta = document.createElement('div');
            meta.className = 'rsl-announcements-item-meta';

            const dateSpan = document.createElement('span');
            dateSpan.className = 'rsl-announcements-item-date';
            dateSpan.innerHTML = '<i class="fas fa-calendar-alt" aria-hidden="true"></i> ' + formatDate(item.date);
            meta.appendChild(dateSpan);

            content.appendChild(meta);
        }

        li.appendChild(badges);
        li.appendChild(content);

        return li;
    }

    /**
     * Format date for display
     */
    function formatDate(dateStr) {
        try {
            const date = new Date(dateStr);
            return date.toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric'
            });
        } catch (e) {
            return dateStr;
        }
    }

    /**
     * Update the display to show current announcement
     */
    function updateDisplay(state, structure) {
        if (state.items.length === 0) {
            structure.textDisplay.textContent = 'No announcements';
            structure.counter.textContent = '';
            structure.prevBtn.disabled = true;
            structure.nextBtn.disabled = true;
            return;
        }

        const item = state.items[state.currentIndex];

        // Build text content
        let text = '';

        // Add badge info for accessibility
        const badgeText = [];
        if (item.priority && item.priority !== 'normal') {
            badgeText.push(item.priority);
        }
        if (item.isNew) {
            badgeText.push('new');
        }

        // Create text element
        if (item.link) {
            const link = document.createElement('a');
            link.href = item.link;
            link.textContent = item.title;

            // Build aria-label that matches visible text (badge + title)
            // e.g., "Urgent Flash sale! 50% off all items today only"
            let ariaLabel = '';
            if (item.priority && item.priority !== 'normal') {
                ariaLabel += item.priority.charAt(0).toUpperCase() + item.priority.slice(1) + ' ';
            }
            if (item.isNew) {
                ariaLabel += 'New ';
            }
            ariaLabel += item.title;
            link.setAttribute('aria-label', ariaLabel);

            structure.textDisplay.innerHTML = '';

            // Add visible badges
            if (item.priority && item.priority !== 'normal') {
                const badge = document.createElement('span');
                badge.className = 'rsl-announcements-badge';
                badge.setAttribute('data-priority', item.priority);
                badge.textContent = item.priority.charAt(0).toUpperCase() + item.priority.slice(1);
                badge.setAttribute('aria-hidden', 'true');
                structure.textDisplay.appendChild(badge);
                structure.textDisplay.appendChild(document.createTextNode(' '));
            }

            if (item.isNew) {
                const newBadge = document.createElement('span');
                newBadge.className = 'rsl-announcements-new';
                newBadge.textContent = 'New';
                newBadge.setAttribute('aria-hidden', 'true');
                structure.textDisplay.appendChild(newBadge);
                structure.textDisplay.appendChild(document.createTextNode(' '));
            }

            structure.textDisplay.appendChild(link);
        } else {
            structure.textDisplay.innerHTML = '';

            // Add visible badges
            if (item.priority && item.priority !== 'normal') {
                const badge = document.createElement('span');
                badge.className = 'rsl-announcements-badge';
                badge.setAttribute('data-priority', item.priority);
                badge.textContent = item.priority.charAt(0).toUpperCase() + item.priority.slice(1);
                badge.setAttribute('aria-hidden', 'true');
                structure.textDisplay.appendChild(badge);
                structure.textDisplay.appendChild(document.createTextNode(' '));
            }

            if (item.isNew) {
                const newBadge = document.createElement('span');
                newBadge.className = 'rsl-announcements-new';
                newBadge.textContent = 'New';
                newBadge.setAttribute('aria-hidden', 'true');
                structure.textDisplay.appendChild(newBadge);
                structure.textDisplay.appendChild(document.createTextNode(' '));
            }

            structure.textDisplay.appendChild(document.createTextNode(item.title));
        }

        // Update counter
        structure.counter.textContent = (state.currentIndex + 1) + ' of ' + state.items.length;

        // Build the current announcement text for aria-label on announcement area
        let currentAnnouncementText = '';
        if (item.priority && item.priority !== 'normal') {
            currentAnnouncementText += item.priority.charAt(0).toUpperCase() + item.priority.slice(1) + ' ';
        }
        if (item.isNew) {
            currentAnnouncementText += 'New ';
        }
        currentAnnouncementText += item.title;

        // Update aria-label on current announcement area only
        let ariaLabel = 'Announcement ' + (state.currentIndex + 1) + ' of ' + state.items.length + ': ' + currentAnnouncementText;
        if (item.link) {
            ariaLabel += '. Press Enter to open link.';
        }
        structure.current.setAttribute('aria-label', ariaLabel);

        // Update button states (no infinite loop - stop at boundaries)
        structure.prevBtn.disabled = state.currentIndex === 0;
        structure.nextBtn.disabled = state.currentIndex === state.items.length - 1;

        // Build expand button aria-label with all announcements
        let allAnnouncementsText = 'View all ' + state.items.length + ' announcements: ';
        state.items.forEach(function(item, index) {
            let itemText = '';
            if (item.priority && item.priority !== 'normal') {
                itemText += item.priority.charAt(0).toUpperCase() + item.priority.slice(1) + ' ';
            }
            if (item.isNew) {
                itemText += 'New ';
            }
            itemText += item.title;
            allAnnouncementsText += (index + 1) + ': ' + itemText;
            if (index < state.items.length - 1) {
                allAnnouncementsText += '. ';
            }
        });
        structure.expandBtn.setAttribute('aria-label', allAnnouncementsText);
    }

    /**
     * Navigate to next announcement
     */
    function navigateNext(state, structure, config) {
        if (state.currentIndex < state.items.length - 1) {
            state.currentIndex++;
            updateDisplay(state, structure);
            // Announce the new announcement via live region
            announceCurrentItem(state, structure);
        }
    }

    /**
     * Navigate to previous announcement
     */
    function navigatePrev(state, structure, config) {
        if (state.currentIndex > 0) {
            state.currentIndex--;
            updateDisplay(state, structure);
            // Announce the new announcement via live region
            announceCurrentItem(state, structure);
        }
    }

    /**
     * Announce current item via live region (for arrow key navigation)
     */
    function announceCurrentItem(state, structure) {
        const item = state.items[state.currentIndex];
        let message = 'Announcement ' + (state.currentIndex + 1) + ' of ' + state.items.length + ': ';
        if (item.priority && item.priority !== 'normal') {
            message += item.priority.charAt(0).toUpperCase() + item.priority.slice(1) + ' ';
        }
        if (item.isNew) {
            message += 'New ';
        }
        message += item.title;
        if (item.link) {
            message += '. Press Enter to open link.';
        }

        // Cancel any pending announcement
        if (state.announceTimeout) {
            clearTimeout(state.announceTimeout);
        }

        // Clear and set new content after brief delay
        structure.liveRegion.textContent = '';

        state.announceTimeout = setTimeout(function() {
            structure.liveRegion.textContent = message;
        }, 100);
    }

    /**
     * Go to specific index
     */
    function goToIndex(index, state, structure, config) {
        if (index >= 0 && index < state.items.length) {
            state.currentIndex = index;
            updateDisplay(state, structure);
        }
    }

    /**
     * Start auto-rotation
     */
    function startRotation(state, config, structure) {
        if (state.rotationTimer) {
            clearInterval(state.rotationTimer);
        }

        state.isPaused = false;
        updatePauseButton(state, structure);

        state.rotationTimer = setInterval(function() {
            if (!state.isPaused && !state.isExpanded) {
                // Wrap around for auto-rotation
                state.currentIndex = (state.currentIndex + 1) % state.items.length;
                updateDisplay(state, structure);
                // Re-enable buttons for auto-rotate wrap-around navigation
                structure.prevBtn.disabled = false;
                structure.nextBtn.disabled = false;
            }
        }, config.interval * 1000);
    }

    /**
     * Pause rotation
     */
    function pauseRotation(state, byUser, structure) {
        state.isPaused = true;
        if (byUser) {
            state.pausedByUser = true;
        }
        if (structure) {
            updatePauseButton(state, structure);
        }
    }

    /**
     * Resume rotation
     */
    function resumeRotation(state, config, structure) {
        state.isPaused = false;
        state.pausedByUser = false;
        updatePauseButton(state, structure);
    }

    /**
     * Update pause button state
     */
    function updatePauseButton(state, structure) {
        if (!structure.pauseBtn) return;

        const icon = structure.pauseBtn.querySelector('i');
        if (state.isPaused) {
            structure.pauseBtn.setAttribute('aria-label', 'Resume auto-rotation');
            structure.pauseBtn.setAttribute('aria-pressed', 'true');
            icon.className = 'fas fa-play';
        } else {
            structure.pauseBtn.setAttribute('aria-label', 'Pause auto-rotation');
            structure.pauseBtn.setAttribute('aria-pressed', 'false');
            icon.className = 'fas fa-pause';
        }
    }

    /**
     * Expand the panel
     * @param {boolean} moveFocus - Whether to move focus to close button (default: true)
     */
    function expandPanel(state, structure, moveFocus) {
        state.isExpanded = true;
        structure.panel.setAttribute('aria-hidden', 'false');
        structure.expandBtn.setAttribute('aria-expanded', 'true');
        structure.expandBtn.querySelector('i').className = 'fas fa-chevron-up';

        // Add expanded class
        structure.panel.closest('.rsl-announcements').classList.add('is-expanded');

        // Focus the close button (unless moveFocus is false)
        if (moveFocus !== false) {
            setTimeout(function() {
                structure.closeBtn.focus();
            }, 100);
        }
    }

    /**
     * Collapse the panel
     * @param {boolean} moveFocus - Whether to move focus to expand button (default: true)
     */
    function collapsePanel(state, structure, moveFocus) {
        state.isExpanded = false;
        structure.panel.setAttribute('aria-hidden', 'true');
        structure.expandBtn.setAttribute('aria-expanded', 'false');
        structure.expandBtn.querySelector('i').className = 'fas fa-chevron-down';

        // Remove expanded class
        structure.panel.closest('.rsl-announcements').classList.remove('is-expanded');

        // Return focus to expand button (unless moveFocus is false)
        if (moveFocus !== false) {
            structure.expandBtn.focus();
        }
    }

    /**
     * Toggle panel
     */
    function togglePanel(state, structure) {
        if (state.isExpanded) {
            collapsePanel(state, structure);
        } else {
            expandPanel(state, structure);
        }
    }

    /**
     * Setup event listeners
     */
    function setupEventListeners(container, config, state, structure) {
        // Previous button
        structure.prevBtn.addEventListener('click', function() {
            navigatePrev(state, structure, config);
        });

        // Next button
        structure.nextBtn.addEventListener('click', function() {
            navigateNext(state, structure, config);
        });

        // Pause button
        if (structure.pauseBtn) {
            structure.pauseBtn.addEventListener('click', function(e) {
                e.stopPropagation(); // Prevent event bubbling

                // Toggle based on pausedByUser state, not isPaused
                // (isPaused may be true from hover, but user hasn't explicitly paused)
                if (state.pausedByUser) {
                    // User had explicitly paused, now resume
                    resumeRotation(state, config, structure);
                } else {
                    // User is explicitly pausing
                    pauseRotation(state, true, structure);
                }
            });
        }

        // Expand button
        structure.expandBtn.addEventListener('click', function() {
            togglePanel(state, structure);
        });

        // Close button
        structure.closeBtn.addEventListener('click', function() {
            collapsePanel(state, structure);
        });

        // Pause on hover - only for readable area (label + current text), not controls
        if (config.pauseOnHover && config.autoRotate) {
            // Helper to update icon for hover pause state
            function setHoverPauseIcon(paused) {
                if (structure.pauseBtn && !state.pausedByUser) {
                    const icon = structure.pauseBtn.querySelector('i');
                    icon.className = paused ? 'fas fa-play' : 'fas fa-pause';
                }
            }

            // Hover over label pauses
            structure.label.addEventListener('mouseenter', function() {
                if (!state.pausedByUser) {
                    pauseRotation(state, false, null);
                    setHoverPauseIcon(true);
                }
            });
            structure.label.addEventListener('mouseleave', function(e) {
                // Only resume if not moving to another pause zone
                if (!state.pausedByUser && !state.isExpanded &&
                    !structure.current.contains(e.relatedTarget)) {
                    state.isPaused = false;
                    setHoverPauseIcon(false);
                }
            });

            // Hover over current announcement text pauses
            structure.current.addEventListener('mouseenter', function() {
                if (!state.pausedByUser) {
                    pauseRotation(state, false, null);
                    setHoverPauseIcon(true);
                }
            });
            structure.current.addEventListener('mouseleave', function(e) {
                // Only resume if not moving to another pause zone
                if (!state.pausedByUser && !state.isExpanded &&
                    !structure.label.contains(e.relatedTarget)) {
                    state.isPaused = false;
                    setHoverPauseIcon(false);
                }
            });
        }

        // Focus handling:
        // - Any focus on bar = pause slideshow, disable pause button
        // - Focus leaves bar = resume slideshow, enable pause button
        // - Arrow keys navigate announcements and read the new one
        // - Only the visible announcement is read

        structure.bar.addEventListener('focusin', function() {
            state.isPaused = true;
            // Disable pause button while in keyboard focus
            if (structure.pauseBtn) {
                structure.pauseBtn.disabled = true;
                const icon = structure.pauseBtn.querySelector('i');
                icon.className = 'fas fa-play';
            }
        });

        structure.bar.addEventListener('focusout', function(e) {
            // Only act if focus leaves the entire bar
            if (!structure.bar.contains(e.relatedTarget)) {
                // Re-enable pause button
                if (structure.pauseBtn) {
                    structure.pauseBtn.disabled = false;
                }
                // Resume if user hasn't explicitly paused
                if (!state.pausedByUser && !state.isExpanded) {
                    state.isPaused = false;
                    if (structure.pauseBtn) {
                        const icon = structure.pauseBtn.querySelector('i');
                        icon.className = 'fas fa-pause';
                    }
                }
            }
        });

        // Show navigation hint when current announcement area is focused
        structure.current.addEventListener('focus', function() {
            structure.navHint.classList.add('visible');
        });

        structure.current.addEventListener('blur', function() {
            structure.navHint.classList.remove('visible');
        });

        // Arrow keys and Enter on current announcement area
        structure.current.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                e.preventDefault();
                e.stopPropagation();
                navigateNext(state, structure, config);
                return false;
            } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                e.preventDefault();
                e.stopPropagation();
                navigatePrev(state, structure, config);
                return false;
            } else if (e.key === 'Enter') {
                // Open the link if current announcement has one
                const item = state.items[state.currentIndex];
                if (item && item.link) {
                    window.location.href = item.link;
                }
            }
        });

        // Keyboard navigation for container (Escape to close panel)
        container.addEventListener('keydown', function(e) {
            // Escape closes panel
            if (e.key === 'Escape' && state.isExpanded) {
                e.preventDefault();
                collapsePanel(state, structure);
            }
        });

        // Focus trap in panel
        structure.panel.addEventListener('keydown', function(e) {
            if (e.key === 'Tab' && state.isExpanded) {
                const focusable = structure.panel.querySelectorAll(
                    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                );
                const first = focusable[0];
                const last = focusable[focusable.length - 1];

                if (e.shiftKey && document.activeElement === first) {
                    e.preventDefault();
                    last.focus();
                } else if (!e.shiftKey && document.activeElement === last) {
                    e.preventDefault();
                    first.focus();
                }
            }
        });

        // Click on list items
        structure.list.addEventListener('click', function(e) {
            const item = e.target.closest('.rsl-announcements-item');
            if (item) {
                const index = parseInt(item.getAttribute('data-index'), 10);
                goToIndex(index, state, structure, config);
                collapsePanel(state, structure);
            }
        });

        // Reduced motion listener
        const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
        motionQuery.addEventListener('change', function(e) {
            state.reducedMotion = e.matches;
        });
    }

    /**
     * Setup FilterBus integration
     */
    function setupFilterBus(container, config, state, structure) {
        if (!window.RSL.FilterBus) return;

        // Store original items for filtering
        state.allItems = state.items.slice();
        state.filterBusId = 'announcements-' + (container.id || Date.now());

        // Subscribe to filter changes
        window.RSL.FilterBus.subscribe(state.filterBusId, function(filters) {
            const filterValue = filters[config.filterKey];

            if (!filterValue || filterValue.toString().toLowerCase() === 'all' || filterValue === '') {
                // Show all items - restore from allItems
                state.items = state.allItems.slice();

                // Update panel list visibility
                structure.list.querySelectorAll('.rsl-announcements-item').forEach(function(item) {
                    item.classList.remove('filterbus-hidden');
                    item.removeAttribute('data-filter-hidden');
                });

                // Show the bar if it was hidden
                structure.bar.style.display = '';

                // Announce restoration
                structure.liveRegion.textContent = 'Showing all ' + state.items.length + ' announcements.';
            } else {
                // Filter items - support multiple values (comma-separated or array)
                const filterValues = Array.isArray(filterValue)
                    ? filterValue
                    : filterValue.toString().split(',').map(function(v) { return v.trim().toLowerCase(); });

                // Filter state.items to only matching ones
                state.items = state.allItems.filter(function(item) {
                    const itemCategory = (item.category || '').toLowerCase();
                    const itemPriority = (item.priority || '').toLowerCase();

                    // Match against category OR priority
                    return filterValues.some(function(fv) {
                        return itemCategory === fv || itemPriority === fv;
                    });
                });

                // Update panel list visibility
                structure.list.querySelectorAll('.rsl-announcements-item').forEach(function(item, index) {
                    const itemCategory = (item.getAttribute('data-category') || '').toLowerCase();
                    const itemPriority = (item.getAttribute('data-priority') || '').toLowerCase();

                    const matches = filterValues.some(function(fv) {
                        return itemCategory === fv || itemPriority === fv;
                    });

                    if (matches) {
                        item.classList.remove('filterbus-hidden');
                        item.removeAttribute('data-filter-hidden');
                    } else {
                        item.classList.add('filterbus-hidden');
                        item.setAttribute('data-filter-hidden', 'true');
                    }
                });

                // Handle case where no items match
                if (state.items.length === 0) {
                    structure.bar.style.display = 'none';
                    structure.liveRegion.textContent = 'No announcements match the current filter.';
                } else {
                    structure.bar.style.display = '';
                    structure.liveRegion.textContent = 'Showing ' + state.items.length + ' of ' + state.allItems.length + ' announcements.';
                }
            }

            // Reset to first item and update display
            state.currentIndex = 0;
            if (state.items.length > 0) {
                updateDisplay(state, structure, config);
                updateNavigation(state, structure);
            }

        }, { keys: [config.filterKey] });

        // Apply any existing FilterBus state on init
        var currentState = window.RSL.FilterBus.getState();
        if (currentState && currentState[config.filterKey]) {
            // Trigger the filter handler with current state
            var initialFilters = {};
            initialFilters[config.filterKey] = currentState[config.filterKey];
            window.RSL.FilterBus.publish(config.filterKey, currentState[config.filterKey], { source: 'init' });
        }
    }

    /**
     * Refresh items from container
     */
    function refreshItems(container, state, structure, config) {
        // Re-parse items
        const existingItems = container.querySelectorAll('.rsl-announcement-item, [data-announcement]');
        state.items = [];

        existingItems.forEach(function(item, index) {
            state.items.push({
                id: item.id || 'announcement-' + index,
                title: item.textContent.trim() || item.getAttribute('data-title') || '',
                priority: item.getAttribute('data-priority') || 'normal',
                category: item.getAttribute('data-category') || '',
                date: item.getAttribute('data-date') || '',
                link: item.getAttribute('data-link') || item.querySelector('a')?.href || '',
                isNew: item.hasAttribute('data-new')
            });
        });

        // Rebuild list
        structure.list.innerHTML = '';
        state.items.forEach(function(item, index) {
            const li = createListItem(item, index);
            structure.list.appendChild(li);
        });

        // Reset index if needed
        if (state.currentIndex >= state.items.length) {
            state.currentIndex = 0;
        }

        updateDisplay(state, structure);
    }

    /**
     * Destroy instance and clean up
     */
    function destroyInstance(container, state, structure) {
        // Clear timer
        if (state.rotationTimer) {
            clearInterval(state.rotationTimer);
        }

        // Unsubscribe from FilterBus
        if (state.filterBusId && window.RSL.FilterBus) {
            window.RSL.FilterBus.unsubscribe(state.filterBusId);
        }

        // Remove instance reference
        delete container._rslAnnouncements;

        // Clear container
        container.innerHTML = '';
    }

    // Auto-initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            RSL.Announcements.init();
        });
    } else {
        RSL.Announcements.init();
    }

})();
