// Badge Controller System
// Manages notification and tournament badge numbers with localStorage persistence

class BadgeController {
    constructor() {
        this.STORAGE_KEY = 'badge_numbers';
        this.notificationBadge = document.querySelector('.notification-badge');
        this.tournamentBadge = document.querySelector('.tournament-badge');
        this.marketBadge = document.querySelector('.market-badge');
        
        this.notificationInput = document.getElementById('notification-badge-input');
        this.tournamentInput = document.getElementById('tournament-badge-input');
        this.marketInput = document.getElementById('market-badge-input');
        
        this.updateButton = document.getElementById('badge-update-button');
        this.statusElement = document.getElementById('badge-status');

        this.init();
    }

    init() {
        // Load saved badge numbers from localStorage
        this.loadBadgeNumbers();

        // Set up event listeners
        this.setupEventListeners();
    }

    setupEventListeners() {
        // Update button click handler
        this.updateButton?.addEventListener('click', () => {
            this.updateBadges();
        });

        // Enter key handler for inputs
        [this.notificationInput, this.tournamentInput, this.marketInput].forEach(input => {
            input?.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.updateBadges();
                }
            });
        });
    }

    loadBadgeNumbers() {
        try {
            const saved = localStorage.getItem(this.STORAGE_KEY);
            if (saved) {
                const data = JSON.parse(saved);
                
                // Update notification badge
                if (data.notification !== undefined) {
                    this.updateNotificationBadge(data.notification);
                    if (this.notificationInput) {
                        this.notificationInput.value = data.notification;
                    }
                }

                // Update tournament badge
                if (data.tournament !== undefined) {
                    this.updateTournamentBadge(data.tournament);
                    if (this.tournamentInput) {
                        this.tournamentInput.value = data.tournament;
                    }
                }

                // Update market badge
                if (data.market !== undefined) {
                    this.updateMarketBadge(data.market);
                    if (this.marketInput) {
                        this.marketInput.value = data.market;
                    }
                }
            } else {
                // Set default values if no saved data
                if (this.notificationInput) this.notificationInput.value = 2;
                if (this.tournamentInput) this.tournamentInput.value = 5;
                if (this.marketInput) this.marketInput.value = 5;
                
                // Trigger initial update to sync UI
                this.updateMarketBadge(5);
            }
        } catch (error) {
            console.error('Error loading badge numbers:', error);
        }
    }

    updateBadges() {
        const notificationValue = parseInt(this.notificationInput?.value) || 0;
        const tournamentValue = parseInt(this.tournamentInput?.value) || 0;
        const marketValue = parseInt(this.marketInput?.value) || 0;

        // Validate input (0-99)
        const inputs = [
            { val: notificationValue, name: 'Notification' },
            { val: tournamentValue, name: 'Tournament' },
            { val: marketValue, name: 'Market' }
        ];

        for (const item of inputs) {
            if (item.val < 0 || item.val > 99) {
                this.showStatus('Badge numbers must be between 0 and 99', 'error');
                return;
            }
        }

        // Update badges
        this.updateNotificationBadge(notificationValue);
        this.updateTournamentBadge(tournamentValue);
        this.updateMarketBadge(marketValue);

        // Save to localStorage
        this.saveBadgeNumbers(notificationValue, tournamentValue, marketValue);

        // Show success message
        this.showStatus('Badges updated successfully!', 'success');
    }

    updateNotificationBadge(value) {
        if (this.notificationBadge) {
            this.notificationBadge.textContent = value;
            this.notificationBadge.style.display = value === 0 ? 'none' : 'flex';
        }
    }

    updateTournamentBadge(value) {
        if (this.tournamentBadge) {
            this.tournamentBadge.textContent = value;
            this.tournamentBadge.style.display = value === 0 ? 'none' : 'flex';
        }
    }

    updateMarketBadge(value) {
        if (this.marketBadge) {
            this.marketBadge.textContent = value;
            this.marketBadge.style.display = value === 0 ? 'none' : 'flex';
        }
    }

    saveBadgeNumbers(notification, tournament, market) {
        try {
            const data = {
                notification: notification,
                tournament: tournament,
                market: market,
                timestamp: Date.now()
            };
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(data));
        } catch (error) {
            console.error('Error saving badge numbers:', error);
        }
    }

    showStatus(message, type = 'success') {
        if (!this.statusElement) return;

        this.statusElement.textContent = message;
        this.statusElement.className = `badge-status ${type}`;
        this.statusElement.style.display = 'block';

        // Hide status after 3 seconds
        setTimeout(() => {
            this.statusElement.style.display = 'none';
        }, 3000);
    }
}

// Initialize badge controller when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.badgeController = new BadgeController();
});
