class ChatApp {
    constructor() {
        this.socket = null;
        this.currentUser = null;
        this.typingTimer = null;
        this.isTyping = false;
        this.selectedFile = null;
        this.currentChatMode = 'public'; // 'public' or 'private'
        this.currentPrivateChat = null;
        this.privateChats = [];
        this.availableUsers = [];
        this.allOnlineUsers = [];
        this.allPrivateChats = [];
        
        this.initializeSplashScreen();
        this.initializeElements();
        this.checkAuthStatus();
        this.bindEvents();
        this.requestNotificationPermission();
    }
    
    initializeSplashScreen() {
        // Show splash screen for 2.5 seconds then check auth and transition
        setTimeout(() => {
            this.transitionFromSplash();
        }, 2500);
    }
    
    async transitionFromSplash() {
        const splashScreen = document.getElementById('splashScreen');
        
        if (splashScreen) {
            // Check auth status first
            try {
                const response = await fetch('/auth/status');
                const data = await response.json();
                
                // Fade out splash screen
                splashScreen.style.animation = 'splashFadeOut 0.8s ease-in-out forwards';
                
                // Transition to appropriate screen after splash fades out
                setTimeout(() => {
                    splashScreen.style.display = 'none';
                    
                    if (data.authenticated) {
                        this.currentUser = data.user;
                        this.showChatScreen();
                        this.initializeSocket();
                    } else {
                        this.showLoginScreen();
                    }
                }, 800);
            } catch (error) {
                console.error('Error checking auth status during splash:', error);
                // Fallback to login screen on error
                splashScreen.style.animation = 'splashFadeOut 0.8s ease-in-out forwards';
                setTimeout(() => {
                    splashScreen.style.display = 'none';
                    this.showLoginScreen();
                }, 800);
            }
        }
    }
    
    requestNotificationPermission() {
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }

    initializeElements() {
        // Screens
        this.splashScreen = document.getElementById('splashScreen');
        this.loginScreen = document.getElementById('loginScreen');
        this.chatScreen = document.getElementById('chatScreen');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        
        // Login elements
        this.googleLoginBtn = document.getElementById('googleLoginBtn');
        
        // Chat elements
        this.messagesContainer = document.getElementById('messagesContainer');
        this.messageInput = document.getElementById('messageInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.attachBtn = document.getElementById('attachBtn');
        this.fileInput = document.getElementById('fileInput');
        this.filePreview = document.getElementById('filePreview');
        this.fileName = document.getElementById('fileName');
        this.removeFileBtn = document.getElementById('removeFile');
        this.onlineUsers = document.getElementById('onlineUsers');
        this.onlineCount = document.getElementById('onlineCount');
        this.typingIndicator = document.getElementById('typingIndicator');
        this.typingText = document.getElementById('typingText');
        
        // User info elements
        this.userAvatar = document.getElementById('userAvatar');
        this.userName = document.getElementById('userName');
        this.logoutBtn = document.getElementById('logoutBtn');
        
        // Private chat elements
        this.publicChatTab = document.getElementById('publicChatTab');
        this.privateChatTab = document.getElementById('privateChatTab');
        this.publicChatContent = document.getElementById('publicChatContent');
        this.privateChatContent = document.getElementById('privateChatContent');
        this.newChatBtn = document.getElementById('newChatBtn');
        this.privateChatsList = document.getElementById('privateChatsList');
        this.chatModeIndicator = document.getElementById('chatModeIndicator');
        this.chatModeName = document.getElementById('chatModeName');
        this.backToPublicBtn = document.getElementById('backToPublicBtn');
        
        // Modal elements
        this.newChatModal = document.getElementById('newChatModal');
        this.closeModalBtn = document.getElementById('closeModalBtn');
        this.userSearchInput = document.getElementById('userSearchInput');
        this.onlineUserSearchInput = document.getElementById('onlineUserSearchInput');
        this.privateChatSearchInput = document.getElementById('privateChatSearchInput');
        this.availableUsersList = document.getElementById('availableUsersList');
        
        // Mobile navigation elements
        this.mobileMenuBtn = document.getElementById('mobileMenuBtn');
        this.sidebar = document.getElementById('sidebar');
        this.sidebarOverlay = document.getElementById('sidebarOverlay');
        this.mobilePublicChatBtn = document.getElementById('mobilePublicChatBtn');
        this.mobilePrivateChatBtn = document.getElementById('mobilePrivateChatBtn');
        this.mobileUsersBtn = document.getElementById('mobileUsersBtn');
    }

    bindEvents() {
        // Login
        this.googleLoginBtn.addEventListener('click', () => this.loginWithGoogle());
        
        // Logout
        this.logoutBtn.addEventListener('click', () => this.logout());
        
        // Message sending
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.sendMessage();
            } else {
                this.handleTyping();
            }
        });
        
        // File upload event listeners
        this.attachBtn.addEventListener('click', () => this.fileInput.click());
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        this.removeFileBtn.addEventListener('click', () => this.removeSelectedFile());
        
        // Stop typing when input loses focus
        this.messageInput.addEventListener('blur', () => this.stopTyping());
        
        // Mobile navigation event listeners
        this.mobileMenuBtn.addEventListener('click', () => this.toggleMobileSidebar());
        this.sidebarOverlay.addEventListener('click', () => this.closeMobileSidebar());
        
        // Close mobile sidebar when clicking on sidebar links
        this.publicChatTab.addEventListener('click', () => this.closeMobileSidebar());
        this.privateChatTab.addEventListener('click', () => this.closeMobileSidebar());
        
        // Handle window resize to close mobile sidebar on desktop
        window.addEventListener('resize', () => {
            if (window.innerWidth > 768) {
                this.closeMobileSidebar();
            }
        });
        
        // Mobile chat navigation event listeners
        this.mobilePublicChatBtn.addEventListener('click', () => this.switchToMobilePublicChat());
        this.mobilePrivateChatBtn.addEventListener('click', () => this.switchToMobilePrivateChat());
        this.mobileUsersBtn.addEventListener('click', () => this.showMobileUsers());
        
        // Private chat event listeners
        this.publicChatTab.addEventListener('click', () => this.switchToPublicChat());
        this.privateChatTab.addEventListener('click', () => {
            this.currentChatMode = 'private';
            
            // Update tab appearance
            this.publicChatTab.classList.remove('active');
            this.privateChatTab.classList.add('active');
            
            // Update content visibility
            this.publicChatContent.classList.remove('active');
            this.privateChatContent.classList.add('active');
            
            // Clear search input
            this.privateChatSearchInput.value = '';
            
            // Load private chats
            this.loadPrivateChats();
        });
        this.newChatBtn.addEventListener('click', () => this.showNewChatModal());
        this.backToPublicBtn.addEventListener('click', () => this.switchToPublicChat());
        
        // Modal event listeners
        this.closeModalBtn.addEventListener('click', () => this.hideNewChatModal());
        this.newChatModal.addEventListener('click', (e) => {
            if (e.target === this.newChatModal) {
                this.hideNewChatModal();
            }
        });
        this.userSearchInput.addEventListener('input', (e) => this.filterUsers(e.target.value));
        this.onlineUserSearchInput.addEventListener('input', (e) => this.filterOnlineUsers(e.target.value));
        this.privateChatSearchInput.addEventListener('input', (e) => this.filterPrivateChats(e.target.value));
    }

    async checkAuthStatus() {
        // Skip auth check if splash screen is still visible (will be handled by splash transition)
        const splashScreen = document.getElementById('splashScreen');
        if (splashScreen && splashScreen.style.display !== 'none') {
            return;
        }
        
        try {
            const response = await fetch('/auth/status');
            const data = await response.json();
            
            if (data.authenticated) {
                this.currentUser = data.user;
                this.showChatScreen();
                this.initializeSocket();
            } else {
                this.showLoginScreen();
            }
        } catch (error) {
            console.error('Error checking auth status:', error);
            this.showLoginScreen();
        }
    }

    loginWithGoogle() {
        window.location.href = '/auth/google';
    }

    logout() {
        window.location.href = '/auth/logout';
    }

    showLoginScreen() {
        this.loginScreen.classList.remove('hidden');
        this.chatScreen.classList.add('hidden');
        this.loadingOverlay.classList.add('hidden');
    }

    showChatScreen() {
        this.loginScreen.classList.add('hidden');
        this.chatScreen.classList.remove('hidden');
        this.loadingOverlay.classList.add('hidden');
        
        // Update user info
        this.userAvatar.src = this.currentUser.avatar || '/default-avatar.svg';
        this.userAvatar.onerror = () => { this.userAvatar.src = '/default-avatar.svg'; };
        this.userName.textContent = this.currentUser.name;
    }

    showLoading() {
        this.loadingOverlay.classList.remove('hidden');
    }

    hideLoading() {
        this.loadingOverlay.classList.add('hidden');
    }

    initializeSocket() {
        this.showLoading();
        
        this.socket = io();
        
        this.socket.on('connect', () => {
            console.log('Connected to server');
            this.socket.emit('authenticate', this.currentUser.id);
            this.loadRecentMessages();
            this.hideLoading();
        });
        
        this.socket.on('disconnect', () => {
            console.log('Disconnected from server');
        });
        
        this.socket.on('new_message', (message) => {
            if (this.currentChatMode === 'public') {
                this.displayMessage(message);
            }
        });
        
        this.socket.on('user_online', (user) => {
            this.addOnlineUser(user);
        });
        
        this.socket.on('user_offline', (user) => {
            this.removeOnlineUser(user.userId);
        });
        
        this.socket.on('online_users', (users) => {
            this.updateOnlineUsers(users);
        });
        
        this.socket.on('user_typing', (data) => {
            if (this.currentChatMode === 'public') {
                this.showTypingIndicator(data);
            }
        });
        
        // Private chat socket events
        this.socket.on('private_message', (data) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                data.privateChatId === this.currentPrivateChat.id) {
                this.displayMessage(data);
            }
        });
        
        this.socket.on('new_private_message', (message) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                message.privateChatId === this.currentPrivateChat.id) {
                // Display message if we're in the same chat
                this.displayMessage(message);
                // Mark messages as read
                this.markMessagesAsRead();
            } else {
                // Show notification for new private message
                this.showPrivateMessageNotification(message);
            }
            
            // Always refresh private chats list to update last message
            setTimeout(() => {
                this.loadPrivateChats();
            }, 100);
        });
        
        // Typing indicators for private chat
        this.socket.on('user_typing', (data) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                data.privateChatId === this.currentPrivateChat.id) {
                this.showPrivateTypingIndicator(data);
            }
        });
        
        this.socket.on('user_stop_typing', (data) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                data.privateChatId === this.currentPrivateChat.id) {
                this.hidePrivateTypingIndicator();
            }
        });
        
        // Message status events
        this.socket.on('private_message_sent', (message) => {
            this.updateMessageStatus(message.id, message.status);
        });
        
        this.socket.on('messages_read', (data) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                data.privateChatId === this.currentPrivateChat.id) {
                this.updateMessagesReadStatus();
            }
        });
        
        this.socket.on('private_file_uploaded', (data) => {
            if (this.currentChatMode === 'private' && 
                this.currentPrivateChat && 
                data.privateChatId === this.currentPrivateChat.id) {
                this.displayMessage(data);
            }
        });
    }

    async loadRecentMessages() {
        try {
            const response = await fetch('/api/chat/messages');
            const messages = await response.json();
            
            this.messagesContainer.innerHTML = '';
            messages.forEach(message => this.displayMessage(message, false));
            this.scrollToBottom();
        } catch (error) {
            console.error('Error loading messages:', error);
        }
    }

    async sendMessage() {
        const message = this.messageInput.value.trim();
        
        if (this.selectedFile) {
            // Send file
            await this.uploadFile();
        } else if (message && this.socket) {
            if (this.currentChatMode === 'private' && this.currentPrivateChat) {
                // Send private message
                this.socket.emit('send_private_message', {
                    message: message,
                    privateChatId: this.currentPrivateChat.id,
                    otherUserId: this.currentPrivateChat.otherUserId,
                    messageType: 'text'
                });
            } else {
                // Send public message
                this.socket.emit('send_message', { 
                    message,
                    messageType: 'text'
                });
            }
            this.messageInput.value = '';
            this.stopTyping();
        }
    }

    displayMessage(message, animate = true) {
        const messageEl = document.createElement('div');
        messageEl.className = `message ${message.user.id === this.currentUser.id ? 'own' : ''}`;
        messageEl.setAttribute('data-message-id', message.id);
        
        if (message.messageType === 'file') {
            messageEl.classList.add('file-message');
        }
        
        const timestamp = new Date(message.timestamp).toLocaleTimeString('id-ID', {
            hour: '2-digit',
            minute: '2-digit'
        });
        
        let contentHtml = '';
        if (message.messageType === 'file' && message.files && message.files.length > 0) {
            contentHtml = this.renderFileAttachments(message.files);
        } else {
            contentHtml = `<div class="message-text">${this.escapeHtml(message.content || '')}</div>`;
        }
        
        // Add status indicator for own messages in private chat
        let statusHtml = '';
        if (message.user.id === this.currentUser.id && this.currentChatMode === 'private') {
            const status = message.status || 'sent';
            statusHtml = `<span class="message-status status-${status}">${this.getStatusText(status)}</span>`;
        }
        
        messageEl.innerHTML = `
            <img src="${message.user.avatar || '/default-avatar.svg'}" alt="${message.user.name}" class="message-avatar" onerror="this.src='/default-avatar.svg'">
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">${message.user.name}</span>
                    <span class="message-time">${timestamp}</span>
                    ${statusHtml}
                </div>
                ${contentHtml}
            </div>
        `;
        
        if (!animate) {
            messageEl.style.animation = 'none';
        }
        
        this.messagesContainer.appendChild(messageEl);
        this.scrollToBottom();
    }

    updateOnlineUsers(users) {
        // Filter out current user and store all online users
        this.allOnlineUsers = users.filter(user => user.id !== this.currentUser.id);
        
        this.renderOnlineUsers();
    }
    
    renderOnlineUsers(filteredUsers = null) {
        this.onlineUsers.innerHTML = '';
        
        const usersToShow = filteredUsers || this.allOnlineUsers;
        
        usersToShow.forEach(user => {
            this.addOnlineUser(user, false);
        });
        
        this.onlineCount.textContent = usersToShow.length;
    }

    addOnlineUser(user, updateCount = true) {
        // Check if user already exists
        const existingUser = document.querySelector(`[data-user-id="${user.userId || user.id}"]`);
        if (existingUser) return;
        
        // Don't add current user to online list
        if ((user.userId || user.id) === this.currentUser.id) return;
        
        const userEl = document.createElement('div');
        userEl.className = 'online-user';
        userEl.setAttribute('data-user-id', user.userId || user.id);
        userEl.setAttribute('data-user-name', user.name);
        userEl.setAttribute('data-user-avatar', user.avatar);
        
        userEl.innerHTML = `
            <img src="${user.avatar || '/default-avatar.svg'}" alt="${user.name}" onerror="this.src='/default-avatar.svg'">
            <span>${user.name}</span>
        `;
        
        // Add click event for private chat
        userEl.addEventListener('click', () => {
            this.showPrivateChatModal(user);
        });
        
        this.onlineUsers.appendChild(userEl);
        
        if (updateCount) {
            const currentCount = parseInt(this.onlineCount.textContent);
            this.onlineCount.textContent = currentCount + 1;
        }
    }

    removeOnlineUser(userId) {
        const userEl = document.querySelector(`[data-user-id="${userId}"]`);
        if (userEl) {
            userEl.remove();
            const currentCount = parseInt(this.onlineCount.textContent);
            this.onlineCount.textContent = Math.max(0, currentCount - 1);
        }
    }

    handleTyping() {
        if (!this.isTyping) {
            this.isTyping = true;
            if (this.currentChatMode === 'private' && this.currentPrivateChat) {
                this.socket.emit('typing_start', {
                    privateChatId: this.currentPrivateChat.id,
                    otherUserId: this.currentPrivateChat.otherUserId
                });
            } else {
                this.socket.emit('typing', { isTyping: true });
            }
        }
        
        clearTimeout(this.typingTimer);
        this.typingTimer = setTimeout(() => {
            this.stopTyping();
        }, 1000);
    }

    stopTyping() {
        if (this.isTyping) {
            this.isTyping = false;
            if (this.currentChatMode === 'private' && this.currentPrivateChat) {
                this.socket.emit('typing_stop', {
                    privateChatId: this.currentPrivateChat.id,
                    otherUserId: this.currentPrivateChat.otherUserId
                });
            } else {
                this.socket.emit('typing', { isTyping: false });
            }
        }
        clearTimeout(this.typingTimer);
    }

    showTypingIndicator(data) {
        if (data.isTyping) {
            this.typingText.textContent = `${data.name} sedang mengetik...`;
            this.typingIndicator.classList.remove('hidden');
        } else {
            this.typingIndicator.classList.add('hidden');
        }
    }

    scrollToBottom() {
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }
    
    showPrivateTypingIndicator(data) {
        this.typingText.textContent = `${data.userName} sedang mengetik...`;
        this.typingIndicator.classList.remove('hidden');
    }
    
    hidePrivateTypingIndicator() {
        this.typingIndicator.classList.add('hidden');
    }
    
    markMessagesAsRead() {
        if (this.currentChatMode === 'private' && this.currentPrivateChat) {
            this.socket.emit('mark_messages_read', {
                privateChatId: this.currentPrivateChat.id,
                otherUserId: this.currentPrivateChat.otherUserId
            });
        }
    }
    
    updateMessageStatus(messageId, status) {
        const messageEl = document.querySelector(`[data-message-id="${messageId}"]`);
        if (messageEl) {
            const statusEl = messageEl.querySelector('.message-status');
            if (statusEl) {
                statusEl.textContent = this.getStatusText(status);
                statusEl.className = `message-status status-${status}`;
            }
        }
    }
    
    updateMessagesReadStatus() {
        const messageElements = this.messagesContainer.querySelectorAll('.message.own');
        messageElements.forEach(messageEl => {
            const statusEl = messageEl.querySelector('.message-status');
            if (statusEl && !statusEl.classList.contains('status-read')) {
                statusEl.textContent = this.getStatusText('read');
                statusEl.className = 'message-status status-read';
            }
        });
    }
    
    getStatusText(status) {
        switch (status) {
            case 'sent': return '✓';
            case 'delivered': return '✓✓';
            case 'read': return '✓✓';
            default: return '';
        }
    }
    
    showPrivateMessageNotification(message) {
        // Add notification dot to private chat icon
        const privateChatTab = this.privateChatTab;
        const icon = privateChatTab.querySelector('i.fas.fa-comments');
        let dot = privateChatTab.querySelector('.notification-dot');
        
        if (!dot && icon) {
            dot = document.createElement('span');
            dot.className = 'notification-dot';
            icon.style.position = 'relative';
            icon.appendChild(dot);
        }
        
        // Show browser notification if permission granted
        if (Notification.permission === 'granted') {
            new Notification(`Pesan baru dari ${message.user.name}`, {
                body: message.content,
                icon: message.user.avatar || '/default-avatar.png'
            });
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    handleFileSelect(event) {
        const file = event.target.files[0];
        if (!file) return;
        
        // Check file size (max 10MB)
        if (file.size > 10 * 1024 * 1024) {
            alert('File terlalu besar. Maksimal 10MB.');
            return;
        }
        
        this.selectedFile = file;
        this.fileName.textContent = file.name;
        this.filePreview.classList.remove('hidden');
    }
    
    removeSelectedFile() {
        this.selectedFile = null;
        this.fileInput.value = '';
        this.filePreview.classList.add('hidden');
    }
    
    async uploadFile() {
        if (!this.selectedFile) return;
        
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        formData.append('message', this.messageInput.value.trim());
        
        // Add private chat info if in private mode
        if (this.currentChatMode === 'private' && this.currentPrivateChat) {
            formData.append('privateChatId', this.currentPrivateChat.id);
            formData.append('recipientId', this.currentPrivateChat.otherUserId);
        }
        
        try {
            const endpoint = this.currentChatMode === 'private' ? '/api/chat/private-upload' : '/api/chat/upload';
            const response = await fetch(endpoint, {
                method: 'POST',
                body: formData
            });
            
            if (response.ok) {
                const result = await response.json();
                
                // Emit file message via socket
                if (this.currentChatMode === 'private') {
                    this.socket.emit('private_file_uploaded', {
                        ...result.message,
                        privateChatId: this.currentPrivateChat.id,
                        recipientId: this.currentPrivateChat.otherUserId
                    });
                } else {
                    this.socket.emit('file_uploaded', result.message);
                }
                
                // Clear input and file
                this.messageInput.value = '';
                this.removeSelectedFile();
                this.stopTyping();
            } else {
                alert('Gagal mengunggah file.');
            }
        } catch (error) {
            console.error('Upload error:', error);
            alert('Terjadi kesalahan saat mengunggah file.');
        }
    }
    
    renderFileAttachments(files) {
        return files.map(file => {
            const isImage = file.mime_type && file.mime_type.startsWith('image/');
            const fileIcon = this.getFileIcon(file.mime_type);
            const fileSize = this.formatFileSize(file.file_size);
            
            let attachmentHtml = `
                <div class="file-attachment">
                    <div class="file-attachment-info">
                        <i class="${fileIcon}"></i>
                        <div class="file-details">
                            <div class="file-name">${this.escapeHtml(file.original_name)}</div>
                            <div class="file-size">${fileSize}</div>
                        </div>
                        <a href="/api/chat/download/${file.filename}" download="${file.original_name}" class="download-btn">
                            <i class="fas fa-download"></i> Download
                        </a>
                    </div>
            `;
            
            if (isImage) {
                attachmentHtml += `
                    <img src="/uploads/${file.filename}" alt="${this.escapeHtml(file.original_name)}" class="image-preview" onclick="window.open('/uploads/${file.filename}', '_blank')">
                `;
            }
            
            attachmentHtml += '</div>';
            return attachmentHtml;
        }).join('');
    }
    
    getFileIcon(mimeType) {
        if (!mimeType) return 'fas fa-file';
        
        if (mimeType.startsWith('image/')) return 'fas fa-image';
        if (mimeType.includes('pdf')) return 'fas fa-file-pdf';
        if (mimeType.includes('word') || mimeType.includes('document')) return 'fas fa-file-word';
        if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return 'fas fa-file-excel';
        if (mimeType.includes('text')) return 'fas fa-file-alt';
        
        return 'fas fa-file';
    }
    
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // Private Chat Methods
    switchToPublicChat() {
        this.currentChatMode = 'public';
        this.currentPrivateChat = null;
        
        // Update UI
        this.publicChatTab.classList.add('active');
        this.privateChatTab.classList.remove('active');
        this.publicChatContent.classList.add('active');
        this.privateChatContent.classList.remove('active');
        
        // Update mobile navigation
        if (window.innerWidth <= 768) {
            this.updateMobileNavButtons('public');
        }
        
        // Update chat header
        this.chatModeIndicator.innerHTML = '<i class="fas fa-users"></i><span>Public Chat</span>';
        this.backToPublicBtn.classList.add('hidden');
        
        // Clear private chat selection
        document.querySelectorAll('.private-chat-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // Clear search inputs
        this.onlineUserSearchInput.value = '';
        this.renderOnlineUsers();
        
        // Load public messages
        this.loadRecentMessages();
    }
    
    switchToPrivateChat() {
        this.publicChatTab.classList.remove('active');
        this.privateChatTab.classList.add('active');
        this.publicChatContent.classList.remove('active');
        this.privateChatContent.classList.add('active');
        
        // Clear notification badge
        this.clearPrivateNotificationBadge();
        
        // Load private chats
        this.loadPrivateChats();
    }
    
    clearPrivateNotificationBadge() {
        const dot = this.privateChatTab.querySelector('.notification-dot');
        if (dot) {
            dot.remove();
        }
    }
    
    async loadPrivateChats() {
        try {
            const response = await fetch('/api/chat/private-chats');
            const data = await response.json();
            
            this.privateChats = data.privateChats || [];
            this.allPrivateChats = this.privateChats;
            this.renderPrivateChats();
        } catch (error) {
            console.error('Error loading private chats:', error);
        }
    }
    
    renderPrivateChats(filteredChats = null) {
        const chatsToShow = filteredChats || this.privateChats;
        
        if (chatsToShow.length === 0) {
            this.privateChatsList.innerHTML = '<div class="no-chats">No private chats yet. Click + to start a new chat.</div>';
            return;
        }
        
        const currentChatId = this.currentPrivateChat ? this.currentPrivateChat.id : null;
        
        this.privateChatsList.innerHTML = chatsToShow.map(chat => {
            const lastMessageTime = chat.last_message_time ? 
                new Date(chat.last_message_time).toLocaleTimeString('id-ID', {
                    hour: '2-digit',
                    minute: '2-digit'
                }) : '';
            
            const lastMessagePreview = chat.last_message ? 
                (chat.last_message.length > 30 ? 
                    this.escapeHtml(chat.last_message.substring(0, 30)) + '...' : 
                    this.escapeHtml(chat.last_message)
                ) : 'No messages yet';
            
            return `
                <div class="private-chat-item ${currentChatId == chat.id ? 'active' : ''}" data-chat-id="${chat.id}" data-other-user-id="${chat.other_user_id}">
                    <img src="${chat.other_user_avatar || '/default-avatar.svg'}" alt="${this.escapeHtml(chat.other_user_name)}" class="private-chat-avatar" onerror="this.src='/default-avatar.svg'">
                    <div class="private-chat-info">
                        <div class="private-chat-header">
                            <div class="private-chat-name">${this.escapeHtml(chat.other_user_name)}</div>
                            ${lastMessageTime ? `<div class="private-chat-time">${lastMessageTime}</div>` : ''}
                        </div>
                        <div class="private-chat-last-message">${lastMessagePreview}</div>
                    </div>
                </div>
            `;
        }).join('');
        
        // Add click listeners
        document.querySelectorAll('.private-chat-item').forEach(item => {
            item.addEventListener('click', () => this.openPrivateChat(item));
        });
    }
    
    async openPrivateChat(chatElement) {
        const chatId = chatElement.dataset.chatId;
        const otherUserId = chatElement.dataset.otherUsererId;
        
        console.log('Opening private chat:', { chatId, otherUserId, chatElement });
        
        // Update UI
        document.querySelectorAll('.private-chat-item').forEach(item => {
            item.classList.remove('active');
        });
        chatElement.classList.add('active');
        
        // Set current private chat
        this.currentChatMode = 'private';
        this.currentPrivateChat = {
            id: chatId,
            otherUserId: otherUserId,
            otherUserName: chatElement.querySelector('.private-chat-name').textContent
        };
        
        // Update mobile navigation
        if (window.innerWidth <= 768) {
            this.updateMobileNavButtons('private');
        }
        
        // Update chat header
        this.chatModeIndicator.innerHTML = `<i class="fas fa-user"></i><span>Chat with ${this.currentPrivateChat.otherUserName}</span>`;
        this.backToPublicBtn.classList.remove('hidden');
        
        // Load private chat messages
        await this.loadPrivateChatMessages(chatId);
        
        // Mark messages as read
        this.markMessagesAsRead();
    }
    
    async loadPrivateChatMessages(chatId) {
        try {
            console.log('Loading private chat messages for chat ID:', chatId);
            const response = await fetch(`/api/chat/private-chat/${chatId}/messages`);
            const data = await response.json();
            
            console.log('Private chat messages data:', data);
            this.messagesContainer.innerHTML = '';
            
            if (data.messages && data.messages.length > 0) {
                data.messages.forEach(message => {
                    // Convert database message format to display format
                    const displayMessage = {
                        id: message.id,
                        content: message.content,
                        timestamp: message.timestamp,
                        messageType: message.message_type,
                        files: message.files || [],
                        user: {
                            id: message.user_id,
                            name: message.name,
                            avatar: message.avatar
                        }
                    };
                    this.displayMessage(displayMessage);
                });
            } else {
                // Show empty chat placeholder
                this.messagesContainer.innerHTML = `
                    <div class="empty-chat-placeholder">
                        <div class="empty-chat-icon">
                            <i class="fas fa-comments"></i>
                        </div>
                        <h3>Mulai percakapan</h3>
                        <p>Belum ada pesan dalam chat ini. Kirim pesan pertama untuk memulai percakapan dengan ${this.currentPrivateChat.otherUserName}.</p>
                    </div>
                `;
            }
            
            this.scrollToBottom();
        } catch (error) {
            console.error('Error loading private chat messages:', error);
        }
    }
    
    async showNewChatModal() {
        try {
            const response = await fetch('/api/chat/users');
            const data = await response.json();
            
            this.availableUsers = data.users || [];
            this.renderAvailableUsers();
            this.newChatModal.classList.remove('hidden');
            this.userSearchInput.value = '';
            this.userSearchInput.focus();
        } catch (error) {
            console.error('Error loading users:', error);
        }
    }
    
    hideNewChatModal() {
        this.newChatModal.classList.add('hidden');
    }
    
    renderAvailableUsers(filteredUsers = null) {
        const users = filteredUsers || this.availableUsers;
        
        if (users.length === 0) {
            this.availableUsersList.innerHTML = '<div class="no-users">No users found.</div>';
            return;
        }
        
        this.availableUsersList.innerHTML = users.map(user => `
            <div class="available-user-item" data-user-id="${user.id}">
                <img src="${user.avatar || '/default-avatar.svg'}" alt="${this.escapeHtml(user.name)}" class="available-user-avatar" onerror="this.src='/default-avatar.svg'">
                <div class="available-user-info">
                    <div class="available-user-name">${this.escapeHtml(user.name)}</div>
                    <div class="available-user-email">${this.escapeHtml(user.email)}</div>
                </div>
            </div>
        `).join('');
        
        // Add click listeners
        document.querySelectorAll('.available-user-item').forEach(item => {
            item.addEventListener('click', () => this.startPrivateChat(item));
        });
    }
    
    filterUsers(searchTerm) {
        if (!searchTerm.trim()) {
            this.renderAvailableUsers();
            return;
        }
        
        const filtered = this.availableUsers.filter(user => 
            user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            user.email.toLowerCase().includes(searchTerm.toLowerCase())
        );
        
        this.renderAvailableUsers(filtered);
    }
    
    filterOnlineUsers(searchTerm) {
        if (!searchTerm.trim()) {
            this.renderOnlineUsers();
            return;
        }
        
        const filtered = this.allOnlineUsers.filter(user => 
            user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (user.email && user.email.toLowerCase().includes(searchTerm.toLowerCase()))
        );
        
        this.renderOnlineUsers(filtered);
    }
    
    filterPrivateChats(searchTerm) {
        if (!searchTerm.trim()) {
            this.renderPrivateChats();
            return;
        }
        
        const filtered = this.allPrivateChats.filter(chat => 
            chat.other_user_name.toLowerCase().includes(searchTerm.toLowerCase())
        );
        
        this.renderPrivateChats(filtered);
    }
    
    showPrivateChatModal(user) {
        // Create modal if it doesn't exist
        if (!document.getElementById('privateChatModal')) {
            this.createPrivateChatModal();
        }
        
        const modal = document.getElementById('privateChatModal');
        const userInfo = modal.querySelector('.modal-user-info');
        
        userInfo.innerHTML = `
            <img src="${user.avatar || '/default-avatar.svg'}" alt="${user.name}" class="modal-user-avatar" onerror="this.src='/default-avatar.svg'">
            <div class="modal-user-details">
                <h3>${this.escapeHtml(user.name)}</h3>
                <p>Start a private conversation</p>
            </div>
        `;
        
        // Store user data for later use
        modal.setAttribute('data-user-id', user.userId || user.id);
        modal.setAttribute('data-user-name', user.name);
        modal.setAttribute('data-user-avatar', user.avatar);
        
        modal.classList.remove('hidden');
    }
    
    createPrivateChatModal() {
        const modal = document.createElement('div');
        modal.id = 'privateChatModal';
        modal.className = 'modal hidden';
        
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Start Private Chat</h2>
                    <button class="modal-close-btn">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="modal-user-info">
                        <!-- User info will be populated here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" id="cancelPrivateChat">Cancel</button>
                    <button class="btn btn-primary" id="startPrivateChat">
                        <i class="fas fa-comments"></i> Start Chat
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // Add event listeners
        modal.querySelector('.modal-close-btn').addEventListener('click', () => {
            modal.classList.add('hidden');
        });
        
        modal.querySelector('.modal-overlay').addEventListener('click', () => {
            modal.classList.add('hidden');
        });
        
        modal.querySelector('#cancelPrivateChat').addEventListener('click', () => {
            modal.classList.add('hidden');
        });
        
        modal.querySelector('#startPrivateChat').addEventListener('click', () => {
            this.startPrivateChatFromModal(modal);
        });
    }
    
    async startPrivateChatFromModal(modal) {
        const otherUserId = modal.getAttribute('data-user-id');
        const otherUserName = modal.getAttribute('data-user-name');
        const otherUserAvatar = modal.getAttribute('data-user-avatar');
        
        try {
            const response = await fetch('/api/chat/private-chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    otherUserId: otherUserId
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Hide modal
                modal.classList.add('hidden');
                
                // Switch to private chat tab
                this.switchToPrivateChat();
                
                // Wait a bit for the tab to switch, then open the chat
                setTimeout(() => {
                    // Create a temporary element to simulate clicking on the chat
                    const tempChatElement = document.createElement('div');
                    tempChatElement.dataset.chatId = data.chatId;
                    tempChatElement.dataset.otherUserId = otherUserId;
                    tempChatElement.innerHTML = `<div class="private-chat-name">${otherUserName}</div>`;
                    
                    this.openPrivateChat(tempChatElement);
                }, 100);
            } else {
                alert('Failed to start private chat: ' + (data.message || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error starting private chat:', error);
            alert('Failed to start private chat. Please try again.');
        }
    }

    async startPrivateChat(userElement) {
        const otherUserId = userElement.dataset.userId;
        
        try {
            const response = await fetch('/api/chat/private-chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ otherUserId })
            });
            
            const data = await response.json();
            
            if (data.privateChat) {
                this.hideNewChatModal();
                
                // Reload private chats and open the new one
                await this.loadPrivateChats();
                
                // Find and open the chat
                const chatElement = document.querySelector(`[data-chat-id="${data.privateChat.id}"]`);
                if (chatElement) {
                    this.openPrivateChat(chatElement);
                }
            }
        } catch (error) {
            console.error('Error starting private chat:', error);
        }
    }
    
    // Mobile Navigation Methods
    toggleMobileSidebar() {
        if (this.sidebar.classList.contains('mobile-open')) {
            this.closeMobileSidebar();
        } else {
            this.openMobileSidebar();
        }
    }
    
    openMobileSidebar() {
        this.sidebar.classList.add('mobile-open');
        this.sidebarOverlay.classList.add('active');
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
    }
    
    closeMobileSidebar() {
        this.sidebar.classList.remove('mobile-open');
        this.sidebarOverlay.classList.remove('active');
        document.body.style.overflow = ''; // Restore scrolling
    }
    
    // Mobile Chat Navigation Methods
    switchToMobilePublicChat() {
        // Update mobile nav buttons
        this.updateMobileNavButtons('public');
        
        // Switch to public chat
        this.switchToPublicChat();
    }
    
    switchToMobilePrivateChat() {
        // Update mobile nav buttons
        this.updateMobileNavButtons('private');
        
        // Switch to private chat tab
        this.currentChatMode = 'private';
        
        // Update tab appearance
        this.publicChatTab.classList.remove('active');
        this.privateChatTab.classList.add('active');
        
        // Update content visibility
        this.publicChatContent.classList.remove('active');
        this.privateChatContent.classList.add('active');
        
        // Load private chats if not loaded
        if (!this.privateChatsLoaded) {
            this.loadPrivateChats();
        }
    }
    
    showMobileUsers() {
        // Update mobile nav buttons
        this.updateMobileNavButtons('users');
        
        // Open sidebar to show users
        this.openMobileSidebar();
        
        // Make sure we're on public chat tab to show online users
        if (this.currentChatMode !== 'public') {
            this.switchToPublicChat();
        }
    }
    
    updateMobileNavButtons(activeButton) {
        // Remove active class from all buttons
        this.mobilePublicChatBtn.classList.remove('active');
        this.mobilePrivateChatBtn.classList.remove('active');
        this.mobileUsersBtn.classList.remove('active');
        
        // Add active class to selected button
        switch(activeButton) {
            case 'public':
                this.mobilePublicChatBtn.classList.add('active');
                break;
            case 'private':
                this.mobilePrivateChatBtn.classList.add('active');
                break;
            case 'users':
                this.mobileUsersBtn.classList.add('active');
                break;
        }
    }
}

// Initialize TChat when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new ChatApp();
});

// Handle page visibility for better UX
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        // Page is hidden, could pause some activities
    } else {
        // Page is visible, resume activities
    }
});