// Core Dodgers Stream Application
// Configuration and module loading

const AppConfig = {
    // API configuration
    api: {
        baseUrl: '',
        heartbeatInterval: 5000,
        chatPollInterval: 2000,
        maxRetries: 3,
        retryDelay: 1000
    },
    // Video player configuration
    video: {
        defaultVolume: 0.3,
        maxRetries: 3,
        recoveryTimeout: 10000,
        streamMonitoringInterval: 10000,
        recoveryCheckCount: 5,
        recoveryCheckInterval: 2000
    },
    // UI configuration
    ui: {
        animationDuration: 300,
        mobileBreakpoint: 768,
        toastDuration: 3000
    },
    // Chat configuration
    chat: {
        maxMessages: 100,
        maxMessageLength: 1000,
        maxNicknameLength: 20,
        typingTimeout: 1000
    }
};

// Global application state
const AppState = {
    player: null,
    userId: '',
    nickname: '',
    isAdmin: false,
    streamMode: 'live', // 'live' or 'placeholder'
    chatCollapsed: false,
    unreadCount: 0,
    soundEnabled: true,
    lastMessageId: '',
    allMessages: [],
    viewerCount: 0,
    errorRetryCount: 0,
    isRetrying: false,
    isRecovering: false,
    recoveryInterval: null,
    typingTimer: null,
    isTyping: false
};

// Global error handling and logging
const AppLogger = {
    log: (message, ...args) => {
        console.log(`[${new Date().toLocaleTimeString()}] ${message}`, ...args);
    },
    error: (message, ...args) => {
        console.error(`[${new Date().toLocaleTimeString()}] ERROR: ${message}`, ...args);
    },
    warn: (message, ...args) => {
        console.warn(`[${new Date().toLocaleTimeString()}] WARNING: ${message}`, ...args);
    }
};

// Module registry for dependencies
const AppModules = {
    loaded: new Set(),

    register: function(name) {
        this.loaded.add(name);
        AppLogger.log(`Module '${name}' registered`);
    },

    isLoaded: function(name) {
        return this.loaded.has(name);
    },

    require: function(...names) {
        for (const name of names) {
            if (!this.isLoaded(name)) {
                throw new Error(`Required module '${name}' is not loaded`);
            }
        }
    }
};

// Global error handler
window.addEventListener('unhandledrejection', (event) => {
    AppLogger.error('Unhandled promise rejection:', event.reason);
});

window.addEventListener('error', (event) => {
    AppLogger.error('Unhandled error:', event.error);
});

// Initialize application
document.addEventListener('DOMContentLoaded', () => {
    AppLogger.log('Dodgers Stream Theater initializing...');

    // Start with basic UI setup
    const nicknameInput = document.getElementById('nickname');
    if (nicknameInput && localStorage.getItem('chatNickname')) {
        nicknameInput.value = localStorage.getItem('chatNickname');
        AppState.nickname = nicknameInput.value;
    }

    AppLogger.log('Core application initialized');
});

AppLogger.log('Core app.js loaded');
