// Initialize chat system based on user type
document.addEventListener('DOMContentLoaded', function() {
    // Get user info from page data attributes
    const userType = document.body.dataset.userType;
    const userId = parseInt(document.body.dataset.userId);
    const userName = document.body.dataset.userName;
    const userAvatar = document.body.dataset.userAvatar;
    
    // WebSocket URL
    const wsUrl = document.body.dataset.wsUrl || 'ws://localhost:3001';
    const apiUrl = document.body.dataset.apiUrl || '/api/chat';
    
    if (!userType || !userId) {
        console.error('User information not found');
        return;
    }
    
    // Initialize based on user type
    if (userType === 'admin') {
        initAdminChat();
    } else if (userType === 'penghuni') {
        initUserChat();
    }
    
    function initAdminChat() {
        const config = {
            wsUrl: wsUrl,
            apiUrl: apiUrl,
            userType: 'admin',
            userId: userId,
            userName: userName,
            userAvatar: userAvatar,
            autoReconnect: true,
            reconnectDelay: 3000,
            maxReconnectAttempts: 10
        };
        
        // Initialize admin chat system
        window.chatSystem = new AdminChatSystem(config);
        
        console.log('Admin chat system initialized');
    }
    
    function initUserChat() {
        // Get admin info from page
        const adminId = parseInt(document.body.dataset.adminId);
        const adminName = document.body.dataset.adminName;
        const adminAvatar = document.body.dataset.adminAvatar;
        
        if (!adminId) {
            console.error('Admin information not found');
            return;
        }
        
        const config = {
            wsUrl: wsUrl,
            apiUrl: apiUrl,
            userType: 'penghuni',
            userId: userId,
            userName: userName,
            userAvatar: userAvatar,
            adminInfo: {
                id: adminId,
                name: adminName,
                avatar: adminAvatar
            },
            autoReconnect: true,
            reconnectDelay: 3000,
            maxReconnectAttempts: 10
        };
        
        // Initialize user chat system
        window.chatSystem = new UserChatSystem(config);
        
        console.log('User chat system initialized');
    }
    
    // Global error handling for WebSocket
    window.addEventListener('unhandledrejection', function(event) {
        if (event.reason && event.reason.message && event.reason.message.includes('WebSocket')) {
            console.error('WebSocket error:', event.reason);
            event.preventDefault();
        }
    });
});