/**
 * Modern Notification Slider System
 */

class NotificationSlider {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.config = {
            interval: options.interval || 3000,
            fadeSpeed: options.fadeSpeed || 600,
            pauseOnHover: options.pauseOnHover !== false,
            autoStart: options.autoStart !== false,
            randomOrder: options.randomOrder || false,
            ...options
        };
        
        this.notifications = [];
        this.currentIndex = 0;
        this.isPlaying = false;
        this.intervalId = null;
        this.isVisible = true;
        
        this.init();
    }
    
    /**
     * Initialize the slider
     */
    init() {
        if (!this.container) {
            return;
        }
        
        this.loadNotifications();
        this.setupEventListeners();
        
        if (this.config.autoStart && this.notifications.length > 0) {
            this.start();
        }
    }
    
    /**
     * Load notifications from data attribute or default data
     */
    loadNotifications() {
        const sliderElement = this.container.querySelector('.notification-slider');
        if (!sliderElement) return;
        
        try {
            const dataNotifications = sliderElement.dataset.notifications;
            if (dataNotifications) {
                const parsedData = JSON.parse(dataNotifications);
                this.notifications = parsedData.map(item => 
                    `Congrats! ${item.id}*** Got ${item.reward}`
                );
            }
        } catch (error) {
            this.notifications = [
                'Congrats! 628290*** Got Lone Destructor',
                'Congrats! 272388*** Got Serene Plume',
                'Congrats! 286373*** Got Psychic Harith'
            ];
        }
        
        if (this.config.randomOrder) {
            this.shuffleNotifications();
        }
    }
    
    /**
     * Shuffle notifications array
     */
    shuffleNotifications() {
        for (let i = this.notifications.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.notifications[i], this.notifications[j]] = [this.notifications[j], this.notifications[i]];
        }
    }
    
    /**
     * Setup event listeners
     */
    setupEventListeners() {
        if (this.config.pauseOnHover) {
            this.container.addEventListener('mouseenter', () => this.pause());
            this.container.addEventListener('mouseleave', () => this.resume());
        }
        
        // Page visibility API for better performance
        document.addEventListener('visibilitychange', () => {
            this.isVisible = !document.hidden;
            if (this.isVisible && this.isPlaying) {
                this.resume();
            } else {
                this.pause();
            }
        });
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', () => this.destroy());
    }
    
    /**
     * Start the slider
     */
    start() {
        if (this.isPlaying || this.notifications.length === 0) return;
        
        this.isPlaying = true;
        this.showCurrentNotification();
        this.scheduleNext();
    }
    
    /**
     * Stop the slider
     */
    stop() {
        this.isPlaying = false;
        this.clearSchedule();
    }
    
    /**
     * Pause the slider
     */
    pause() {
        if (!this.isPlaying) return;
        this.clearSchedule();
    }
    
    /**
     * Resume the slider
     */
    resume() {
        if (!this.isPlaying || !this.isVisible) return;
        this.scheduleNext();
    }
    
    /**
     * Show current notification with smooth transition
     */
    showCurrentNotification() {
        const sliderElement = this.container.querySelector('.notification-slider');
        if (!sliderElement) return;
        
        const currentNotification = this.notifications[this.currentIndex];
        
        // Create notification element
        const notificationElement = this.createNotificationElement(currentNotification);
        
        // Remove old notification with fade out
        const oldElement = sliderElement.querySelector('.slider-notification');
        if (oldElement) {
            oldElement.classList.add('fade-out');
            setTimeout(() => {
                if (oldElement.parentNode) {
                    oldElement.remove();
                }
            }, this.config.fadeSpeed / 2);
        }
        
        // Add new notification
        sliderElement.appendChild(notificationElement);
        
        // Trigger fade in
        requestAnimationFrame(() => {
            notificationElement.classList.add('active');
        });
        
        // Update aria-live region for screen readers
        this.container.setAttribute('aria-label', currentNotification);
    }
    
    /**
     * Create notification element
     */
    createNotificationElement(text) {
        const element = document.createElement('div');
        element.className = 'slider-notification';
        element.innerHTML = `<span class="notification-text">${this.escapeHtml(text)}</span>`;
        return element;
    }
    
    /**
     * Escape HTML to prevent XSS
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    /**
     * Schedule next notification
     */
    scheduleNext() {
        this.clearSchedule();
        this.intervalId = setTimeout(() => {
            this.next();
        }, this.config.interval);
    }
    
    /**
     * Clear current schedule
     */
    clearSchedule() {
        if (this.intervalId) {
            clearTimeout(this.intervalId);
            this.intervalId = null;
        }
    }
    
    /**
     * Move to next notification
     */
    next() {
        if (!this.isPlaying) return;
        
        this.currentIndex = (this.currentIndex + 1) % this.notifications.length;
        this.showCurrentNotification();
        this.scheduleNext();
    }
    
    /**
     * Move to previous notification
     */
    previous() {
        this.currentIndex = this.currentIndex === 0 ? 
            this.notifications.length - 1 : this.currentIndex - 1;
        this.showCurrentNotification();
    }
    
    /**
     * Go to specific notification
     */
    goTo(index) {
        if (index >= 0 && index < this.notifications.length) {
            this.currentIndex = index;
            this.showCurrentNotification();
        }
    }
    
    /**
     * Add new notification
     */
    addNotification(text) {
        this.notifications.push(text);
    }
    
    /**
     * Remove notification by index
     */
    removeNotification(index) {
        if (index >= 0 && index < this.notifications.length) {
            this.notifications.splice(index, 1);
            if (this.currentIndex >= this.notifications.length) {
                this.currentIndex = 0;
            }
        }
    }
    
    /**
     * Update configuration
     */
    updateConfig(newConfig) {
        this.config = { ...this.config, ...newConfig };
        if (this.isPlaying) {
            this.stop();
            this.start();
        }
    }
    
    /**
     * Get current status
     */
    getStatus() {
        return {
            isPlaying: this.isPlaying,
            currentIndex: this.currentIndex,
            totalNotifications: this.notifications.length,
            currentNotification: this.notifications[this.currentIndex]
        };
    }
    
    /**
     * Destroy the slider and cleanup
     */
    destroy() {
        this.stop();
        
        // Remove event listeners
        this.container.removeEventListener('mouseenter', () => this.pause());
        this.container.removeEventListener('mouseleave', () => this.resume());
        
        // Clear container
        const sliderElement = this.container.querySelector('.notification-slider');
        if (sliderElement) {
            sliderElement.innerHTML = '';
        }
    }
}

// Auto-initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    // Initialize notification slider
    const notificationSlider = new NotificationSlider('notification-container', {
        interval: 3000,        // 3 seconds between notifications
        fadeSpeed: 600,        // 600ms fade transition
        pauseOnHover: true,    // Pause when hovering
        autoStart: true,       // Start automatically
        randomOrder: false     // Keep original order
    });
    
    // Make it globally accessible for debugging
    window.notificationSlider = notificationSlider;
    
    // Optional: Add keyboard controls
    document.addEventListener('keydown', (event) => {
        if (event.ctrlKey || event.metaKey) {
            switch (event.key) {
                case 'ArrowLeft':
                    event.preventDefault();
                    notificationSlider.previous();
                    break;
                case 'ArrowRight':
                    event.preventDefault();
                    notificationSlider.next();
                    break;
                case ' ':
                    event.preventDefault();
                    if (notificationSlider.getStatus().isPlaying) {
                        notificationSlider.stop();
                    } else {
                        notificationSlider.start();
                    }
                    break;
            }
        }
    });
});

// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
    module.exports = NotificationSlider;
}
