class AdminChatSystem extends ChatSystem {
    constructor(config) {
        super(config);
        
        // Admin-specific properties
        this.conversations = new Map();
        this.activeConversationId = null;
        this.eventListenersSetup = false;
        this.typingTimeout = null;
        this.notificationAudio = null;
        
        // 🔥 ADD: Refresh state
        this.isRefreshing = false;
        
        // Initialize UI
        this.initUI();
    }
    
    initUI() {
        this.createChatLayout();
        this.loadConversations();
        
        if (!this.eventListenersSetup) {
            this.setupAdminEventListeners();
            this.eventListenersSetup = true;
        }
    }
    
    createChatLayout() {
        const chatContainer = document.createElement('div');
        chatContainer.className = 'admin-chat-container';
        chatContainer.innerHTML = `
            <div class="admin-chat-wrapper">
                <!-- Left Panel - Conversation List -->
                <div class="chat-left-panel">
                    <div class="panel-header">
                        <div class="user-info">
                            <div class="user-avatar">
                                ${this.config.userAvatar ? 
                                    `<img src="${this.config.userAvatar}" alt="${this.config.userName}">` :
                                    this.config.userName.charAt(0).toUpperCase()
                                }
                            </div>
                            <div class="user-details">
                                <h4>${this.config.userName}</h4>
                                <small class="online-status online">Online</small>
                            </div>
                        </div>
                        <div class="panel-actions">
                            <button class="btn-refresh" title="Refresh conversations">
                                <i class="fas fa-redo"></i>
                            </button>
                            <button class="btn-search" title="Search conversations">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="search-box" style="display: none;">
                        <div class="search-input-wrapper">
                            <i class="fas fa-search search-icon"></i>
                            <input type="text" class="search-input" placeholder="Search conversations...">
                            <button class="btn-close-search" title="Close search">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="conversation-list" id="conversationList">
                        <div class="loading-conversations">
                            <div class="spinner"></div>
                            <p>Loading conversations...</p>
                        </div>
                    </div>
                </div>
                
                <!-- Right Panel - Chat Area -->
                <div class="chat-right-panel">
                    <div class="empty-chat-state" id="emptyChatState">
                        <div class="empty-icon">
                            <i class="fas fa-comments"></i>
                        </div>
                        <h3>Select a conversation</h3>
                        <p>Choose a conversation from the list to start chatting</p>
                    </div>
                    
                    <div class="active-chat" id="activeChat" style="display: none;">
                        <!-- Chat header -->
                        <div class="chat-header" id="chatHeader"></div>
                        
                        <!-- Messages container -->
                        <div class="messages-container" id="messagesContainer">
                            <div class="loading-messages">
                                <div class="spinner"></div>
                                <p>Loading messages...</p>
                            </div>
                        </div>
                        
                        <!-- Typing indicator -->
                        <div class="typing-indicator" id="typingIndicator" style="display: none;">
                            <div class="typing-dots">
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                            <span class="typing-text">is typing...</span>
                        </div>
                        
                        <!-- Message input -->
                        <div class="message-input-container">
                            <div class="input-wrapper">
                                <textarea 
                                    class="message-input" 
                                    id="messageInput"
                                    placeholder="Type a message..."
                                    rows="1"></textarea>
                                <button class="btn-send" id="sendButton" title="Send message">
                                    <i class="fas fa-paper-plane"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        const targetContainer = document.getElementById('chatContainer') || document.body;
        targetContainer.appendChild(chatContainer);
        
        // Store references to DOM elements
        this.elements = {
            container: chatContainer,
            conversationList: document.getElementById('conversationList'),
            emptyChatState: document.getElementById('emptyChatState'),
            activeChat: document.getElementById('activeChat'),
            chatHeader: document.getElementById('chatHeader'),
            messagesContainer: document.getElementById('messagesContainer'),
            typingIndicator: document.getElementById('typingIndicator'),
            messageInput: document.getElementById('messageInput'),
            sendButton: document.getElementById('sendButton'),
            searchBox: chatContainer.querySelector('.search-box'),
            searchInput: chatContainer.querySelector('.search-input'),
            searchButton: chatContainer.querySelector('.btn-search'),
            closeSearchButton: chatContainer.querySelector('.btn-close-search'),
            refreshButton: chatContainer.querySelector('.btn-refresh')
        };
    }
    
    setupAdminEventListeners() {
        // Clone input and button to remove old listeners
        const newInput = this.elements.messageInput.cloneNode(true);
        this.elements.messageInput.parentNode.replaceChild(newInput, this.elements.messageInput);
        this.elements.messageInput = newInput;
        
        const newSendBtn = this.elements.sendButton.cloneNode(true);
        this.elements.sendButton.parentNode.replaceChild(newSendBtn, this.elements.sendButton);
        this.elements.sendButton = newSendBtn;
        
        // Send message on Enter (without Shift)
        this.elements.messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendActiveMessage();
            }
        });
        
        // Send button click
        this.elements.sendButton.addEventListener('click', () => {
            this.sendActiveMessage();
        }, { once: false });
        
        // Auto-resize textarea and handle typing
        this.elements.messageInput.addEventListener('input', () => {
            this.autoResizeTextarea(this.elements.messageInput);
            this.handleTyping();
        });
        
        // Search conversations
        this.elements.searchInput.addEventListener('input', (e) => {
            this.filterConversations(e.target.value);
        });
        
        // 🔥 FIXED: Refresh conversations
        this.elements.refreshButton.addEventListener('click', () => {
            this.refreshConversations();
        });
        
        // 🔥 NEW: Toggle search box
        this.elements.searchButton.addEventListener('click', () => {
            this.toggleSearchBox();
        });
        
        // Close search box
        this.elements.closeSearchButton.addEventListener('click', () => {
            this.closeSearchBox();
        });
        
        // Search on Enter key
        this.elements.searchInput.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeSearchBox();
            }
        });
        
        // Listen for auth success
        this.on('auth_success', () => {
            console.log('✅ [ADMIN] Authenticated - loading conversations');
            this.loadConversations();
        });
        
        // Listen for chat system events
        this.on('new_message', (message) => {
            const isOwnMessage = (
                message.from.type === this.config.userType && 
                parseInt(message.from.id) === parseInt(this.config.userId)
            );
            
            if (isOwnMessage) {
                return;
            }
            
            // Play sound for incoming messages
            this.playNotificationSound();
            
            // Check if from active conversation
            const isActiveConversation = (
                this.activeConversationId && 
                parseInt(message.from.id) === parseInt(this.activeConversationId)
            );
            
            if (isActiveConversation) {
                this.addMessageToUI(message, false);
                this.markConversationAsRead(message.from.id);
            } else {
                this.updateConversationUnread(message.from.id, true);
            }
            
            // Refresh conversation list to update preview
            this.loadConversations();
        });
        
        this.on('typing', (message) => {
            if (this.activeConversationId && 
                parseInt(message.from.id) === parseInt(this.activeConversationId)) {
                this.showTypingIndicator(message.from);
            }
        });
        
        this.on('user_online', (message) => {
            console.log('🟢 [ADMIN] User online:', message.user.id);
            this.updateConversationStatus(message.user.id, true);
        });
        
        this.on('user_offline', (message) => {
            console.log('🔴 [ADMIN] User offline:', message.user.id);
            this.updateConversationStatus(message.user.id, false);
        });
    }
    
    // 🔥 NEW: Refresh conversations with loading state
    async refreshConversations() {
        if (this.isRefreshing) {
            console.log('⚠️ Already refreshing...');
            return;
        }
        
        console.log('🔄 Refreshing conversations...');
        this.isRefreshing = true;
        
        // Add spinning animation
        const icon = this.elements.refreshButton.querySelector('i');
        icon.classList.add('fa-spin');
        this.elements.refreshButton.disabled = true;
        
        try {
            await this.loadConversations();
            console.log('✅ Conversations refreshed');
        } catch (error) {
            console.error('❌ Failed to refresh:', error);
        } finally {
            // Remove spinning animation
            setTimeout(() => {
                icon.classList.remove('fa-spin');
                this.elements.refreshButton.disabled = false;
                this.isRefreshing = false;
            }, 500);
        }
    }
    
    // 🔥 NEW: Toggle search box with animation
    toggleSearchBox() {
        const searchBox = this.elements.searchBox;
        const isVisible = searchBox.style.display !== 'none';
        
        if (isVisible) {
            this.closeSearchBox();
        } else {
            this.openSearchBox();
        }
    }
    
    // 🔥 NEW: Open search box
    openSearchBox() {
        const searchBox = this.elements.searchBox;
        const conversationList = this.elements.conversationList;
        
        // Show search box
        searchBox.style.display = 'block';
        searchBox.style.height = '0px';
        searchBox.style.opacity = '0';
        
        // Trigger reflow
        searchBox.offsetHeight;
        
        // Animate
        searchBox.style.transition = 'all 0.3s ease';
        searchBox.style.height = '60px';
        searchBox.style.opacity = '1';
        
        // Add active class to button
        this.elements.searchButton.classList.add('active');
        
        // Focus input after animation
        setTimeout(() => {
            this.elements.searchInput.focus();
        }, 300);
    }
    
    // 🔥 NEW: Close search box
    closeSearchBox() {
        const searchBox = this.elements.searchBox;
        
        // Animate out
        searchBox.style.transition = 'all 0.3s ease';
        searchBox.style.height = '0px';
        searchBox.style.opacity = '0';
        
        // Clear search and reset filter
        this.elements.searchInput.value = '';
        this.filterConversations('');
        
        // Remove active class
        this.elements.searchButton.classList.remove('active');
        
        // Hide after animation
        setTimeout(() => {
            searchBox.style.display = 'none';
        }, 300);
    }
    
    async loadConversations() {
        try {
            const url = `${this.config.apiUrl}/get_conversations`;
            
            const response = await fetch(url, {
                method: 'GET',
                credentials: 'same-origin'
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.status) {
                this.renderConversationList(data.conversations);
            }
        } catch (error) {
            console.error('Error loading conversations:', error);
        }
    }
    
    renderConversationList(conversations) {
        const listElement = this.elements.conversationList;
        listElement.innerHTML = '';
        
        if (conversations.length === 0) {
            listElement.innerHTML = `
                <div class="empty-conversations">
                    <i class="fas fa-comments"></i>
                    <p>No conversations yet</p>
                </div>
            `;
            return;
        }
        
        conversations.forEach(conversation => {
            const conversationElement = this.createConversationElement(conversation);
            listElement.appendChild(conversationElement);
            
            // Store in map
            this.conversations.set(conversation.id_penghuni, conversation);
        });
    }
    
    createConversationElement(conversation) {
        const element = document.createElement('div');
        element.className = 'conversation-item';
        element.dataset.userId = conversation.id_penghuni;
        
        if (this.activeConversationId && 
            parseInt(this.activeConversationId) === parseInt(conversation.id_penghuni)) {
            element.classList.add('active');
        }
        
        const lastMessage = conversation.last_message || 'No messages yet';
        const timeAgo = this.getTimeAgo(conversation.last_message_time);
        const unreadCount = conversation.unread_count || 0;
        const isOnline = conversation.is_online == 1;
        
        element.innerHTML = `
            <div class="conversation-avatar">
                ${conversation.foto ? 
                    `<img src="${conversation.foto}" alt="${conversation.nama_penghuni}">` :
                    conversation.nama_penghuni.charAt(0).toUpperCase()
                }
                ${isOnline ? '<span class="online-dot"></span>' : ''}
            </div>
            <div class="conversation-info">
                <div class="conversation-header">
                    <h5 class="conversation-name">${this.escapeHtml(conversation.nama_penghuni)}</h5>
                    <span class="conversation-time">${timeAgo}</span>
                </div>
                <div class="conversation-preview">
                    <p class="last-message">${this.escapeHtml(lastMessage)}</p>
                    ${unreadCount > 0 ? 
                        `<span class="unread-badge">${unreadCount > 9 ? '9+' : unreadCount}</span>` : 
                        ''
                    }
                </div>
                <div class="conversation-details">
                    <span class="room-info">Kamar ${conversation.kamar || 'N/A'}</span>
                </div>
            </div>
        `;
        
        // Click handler
        element.addEventListener('click', () => {
            this.openConversation(conversation.id_penghuni);
        }, { once: false });
        
        return element;
    }
    
    async openConversation(penghuniId) {
        const conversation = this.conversations.get(penghuniId);
        if (!conversation) return;
        
        // Stop typing from previous conversation
        this.stopTyping();
        
        // Update active state in list
        this.elements.conversationList.querySelectorAll('.conversation-item').forEach(item => {
            item.classList.remove('active');
        });
        const activeItem = this.elements.conversationList.querySelector(`[data-user-id="${penghuniId}"]`);
        if (activeItem) {
            activeItem.classList.add('active');
        }
        
        // Update active conversation
        this.activeConversationId = penghuniId;
        this.activeConversation = {
            type: 'penghuni',
            id: parseInt(penghuniId),
            name: conversation.nama_penghuni
        };
        
        // Update UI state
        this.elements.emptyChatState.style.display = 'none';
        this.elements.activeChat.style.display = 'flex';
        
        // Update chat header
        this.updateChatHeader(conversation);
        
        // Load messages
        await this.loadMessages(penghuniId);
        
        // Mark as read
        this.markConversationAsRead(penghuniId);
        
        // Focus input
        setTimeout(() => {
            this.elements.messageInput.focus();
        }, 100);
    }
    
    updateChatHeader(conversation) {
        const isOnline = conversation.is_online == 1;
        
        this.elements.chatHeader.innerHTML = `
            <div class="chat-user-info">
                <div class="chat-user-avatar">
                    ${conversation.foto ? 
                        `<img src="${conversation.foto}" alt="${conversation.nama_penghuni}">` :
                        conversation.nama_penghuni.charAt(0).toUpperCase()
                    }
                    ${isOnline ? '<span class="online-dot"></span>' : ''}
                </div>
                <div class="chat-user-details">
                    <h4>${this.escapeHtml(conversation.nama_penghuni)}</h4>
                    <small class="user-status ${isOnline ? 'online' : 'offline'}">
                        ${isOnline ? 'Online' : 'Offline'}
                    </small>
                </div>
            </div>
            <div class="chat-actions">
                <button class="btn-action" title="User info">
                    <i class="fas fa-info-circle"></i>
                </button>
                <button class="btn-action" title="More options">
                    <i class="fas fa-ellipsis-v"></i>
                </button>
            </div>
        `;
    }
    
    async loadMessages(penghuniId) {
        try {
            const url = `${this.config.apiUrl}/get_messages?penghuni_id=${penghuniId}`;
            
            const response = await fetch(url, {
                method: 'GET',
                credentials: 'same-origin'
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.status) {
                this.renderMessages(data.messages);
            }
        } catch (error) {
            console.error('Error loading messages:', error);
            this.elements.messagesContainer.innerHTML = `
                <div class="empty-messages">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>Failed to load messages</p>
                </div>
            `;
        }
    }
    
    renderMessages(messages) {
        const container = this.elements.messagesContainer;
        container.innerHTML = '';
        
        if (messages.length === 0) {
            container.innerHTML = `
                <div class="empty-messages">
                    <i class="fas fa-comments"></i>
                    <p>No messages yet</p>
                    <p>Start the conversation!</p>
                </div>
            `;
            return;
        }
        
        // Sort messages by date (oldest first)
        messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
        
        messages.forEach(message => {
            const messageElement = this.createMessageElement(message);
            container.appendChild(messageElement);
        });
        
        // Scroll to bottom
        setTimeout(() => {
            container.scrollTop = container.scrollHeight;
        }, 100);
    }
    
    createMessageElement(message) {
        const isOwnMessage = message.sender === 'admin';
        const time = this.formatTime(message.created_at);
        
        const element = document.createElement('div');
        element.className = `message ${isOwnMessage ? 'message-sent' : 'message-received'}`;
        element.dataset.messageId = message.id_chat;
        
        element.innerHTML = `
            <div class="message-content">
                <div class="message-text">${this.escapeHtml(message.message)}</div>
                <div class="message-meta">
                    <span class="message-time">${time}</span>
                    ${isOwnMessage ? 
                        `<span class="message-status">
                            ${message.is_read_penghuni ? '✓✓' : '✓'}
                        </span>` : 
                        ''
                    }
                </div>
            </div>
        `;
        
        return element;
    }
    
    sendActiveMessage() {
        if (!this.activeConversationId) {
            return;
        }
        
        const message = this.elements.messageInput.value.trim();
        if (!message) return;
        
        if (!this.isAuthenticated) {
            alert('Connection not established. Please wait...');
            return;
        }
        
        // Clear input BEFORE sending
        this.elements.messageInput.value = '';
        this.autoResizeTextarea(this.elements.messageInput);
        
        // Stop typing immediately
        this.stopTyping();
        
        // Send message via WebSocket
        this.sendMessage(
            {
                type: 'penghuni',
                id: parseInt(this.activeConversationId)
            },
            message
        );
    }
    
    handleTyping() {
        if (!this.activeConversationId) return;
        
        const message = this.elements.messageInput.value.trim();
        
        if (!message) {
            this.stopTyping();
            return;
        }
        
        const now = Date.now();
        
        if (now - this.lastTypingSent > 1000) {
            this.sendTypingIndicator(
                { type: 'penghuni', id: parseInt(this.activeConversationId) },
                true
            );
            this.lastTypingSent = now;
        }
        
        if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
        }
        
        this.typingTimeout = setTimeout(() => {
            this.stopTyping();
        }, 2000);
    }
    
    stopTyping() {
        if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
            this.typingTimeout = null;
        }
        
        if (this.activeConversationId) {
            this.sendTypingIndicator(
                { type: 'penghuni', id: parseInt(this.activeConversationId) },
                false
            );
        }
    }
    
    addMessageToUI(message, isOwnMessage) {
        const existingMsg = this.elements.messagesContainer.querySelector(
            `[data-message-id="${message.messageId}"]`
        );
        
        if (existingMsg) {
            return;
        }
        
        const messageElement = this.createMessageElementFromWS(message, isOwnMessage);
        this.elements.messagesContainer.appendChild(messageElement);
        
        setTimeout(() => {
            this.elements.messagesContainer.scrollTop = this.elements.messagesContainer.scrollHeight;
        }, 50);
    }
    
    createMessageElementFromWS(message, isOwnMessage) {
        const time = this.formatTime(message.timestamp);
        
        const element = document.createElement('div');
        element.className = `message ${isOwnMessage ? 'message-sent' : 'message-received'}`;
        element.dataset.messageId = message.messageId;
        
        element.innerHTML = `
            <div class="message-content">
                <div class="message-text">${this.escapeHtml(message.content)}</div>
                <div class="message-meta">
                    <span class="message-time">${time}</span>
                    ${isOwnMessage ? 
                        `<span class="message-status">
                            ${message.isDelivered ? '✓✓' : '✓'}
                        </span>` : 
                        ''
                    }
                </div>
            </div>
        `;
        
        return element;
    }
    
    updateMessageStatus(messageId, status) {
        const messageElement = this.elements.messagesContainer.querySelector(
            `[data-message-id="${messageId}"]`
        );
        
        if (messageElement) {
            const statusElement = messageElement.querySelector('.message-status');
            if (statusElement) {
                statusElement.textContent = status === 'read' ? '✓✓' : '✓✓';
            }
        }
    }
    
    showTypingIndicator(user) {
        this.elements.typingIndicator.style.display = 'flex';
        this.elements.typingIndicator.querySelector('.typing-text').textContent = 
            `${user.name || 'User'} is typing...`;
        
        setTimeout(() => {
            if (this.elements.typingIndicator.style.display === 'flex') {
                this.hideTypingIndicator();
            }
        }, 5000);
    }
    
    hideTypingIndicator(userId) {
        if (!userId || (this.activeConversationId && 
            parseInt(this.activeConversationId) === parseInt(userId))) {
            this.elements.typingIndicator.style.display = 'none';
        }
    }
    
    playNotificationSound() {
        try {
            const audioPath = '/sistemkos/asset/sounds/notification.mp3';
            
            if (!this.notificationAudio) {
                this.notificationAudio = new Audio(audioPath);
                this.notificationAudio.volume = 0.5;
            }
            
            this.notificationAudio.currentTime = 0;
            
            const playPromise = this.notificationAudio.play();
            
            if (playPromise !== undefined) {
                playPromise.catch(() => {
                    // Silently handle autoplay restrictions
                });
            }
        } catch (error) {
            // Silently handle errors
        }
    }
    
    updateUserStatus(user, isOnline) {
        const conversationItem = this.elements.conversationList.querySelector(
            `[data-user-id="${user.id}"]`
        );
        
        if (conversationItem) {
            let onlineDot = conversationItem.querySelector('.online-dot');
            
            if (isOnline) {
                if (!onlineDot) {
                    onlineDot = document.createElement('span');
                    onlineDot.className = 'online-dot';
                    conversationItem.querySelector('.conversation-avatar').appendChild(onlineDot);
                }
            } else if (onlineDot) {
                onlineDot.remove();
            }
        }
        
        if (this.activeConversationId && 
            parseInt(this.activeConversationId) === parseInt(user.id)) {
            const statusElement = this.elements.chatHeader.querySelector('.user-status');
            if (statusElement) {
                statusElement.textContent = isOnline ? 'Online' : 'Offline';
                statusElement.className = `user-status ${isOnline ? 'online' : 'offline'}`;
            }
            
            const headerDot = this.elements.chatHeader.querySelector('.online-dot');
            if (isOnline && !headerDot) {
                const dot = document.createElement('span');
                dot.className = 'online-dot';
                this.elements.chatHeader.querySelector('.chat-user-avatar').appendChild(dot);
            } else if (!isOnline && headerDot) {
                headerDot.remove();
            }
        }
    }
    
    incrementUnreadCount(userId) {
        this.updateConversationUnread(userId, true);
    }
    
    updateConversationUnread(userId, increment = false) {
        const conversationItem = this.elements.conversationList.querySelector(
            `[data-user-id="${userId}"]`
        );
        
        if (conversationItem) {
            let badge = conversationItem.querySelector('.unread-badge');
            let currentCount = 0;
            
            if (badge) {
                currentCount = parseInt(badge.textContent);
                if (badge.textContent === '9+') {
                    currentCount = 10;
                }
            }
            
            if (increment) {
                currentCount++;
            }
            
            if (currentCount > 0) {
                if (!badge) {
                    badge = document.createElement('span');
                    badge.className = 'unread-badge';
                    conversationItem.querySelector('.conversation-preview').appendChild(badge);
                }
                badge.textContent = currentCount > 9 ? '9+' : currentCount;
            } else if (badge) {
                badge.remove();
            }
        }
    }
    
    markConversationAsRead(userId) {
        this.updateConversationUnread(userId, false);
        
        const messageIds = Array.from(
            this.elements.messagesContainer.querySelectorAll('.message-received[data-message-id]')
        ).map(el => el.dataset.messageId);
        
        if (messageIds.length > 0) {
            this.markAsRead(messageIds);
        }
    }
    
    updateConversationStatus(userId, isOnline) {
        const conversationItem = this.elements.conversationList.querySelector(
            `[data-user-id="${userId}"]`
        );
        
        if (conversationItem) {
            let onlineDot = conversationItem.querySelector('.online-dot');
            
            if (isOnline) {
                if (!onlineDot) {
                    onlineDot = document.createElement('span');
                    onlineDot.className = 'online-dot';
                    conversationItem.querySelector('.conversation-avatar').appendChild(onlineDot);
                }
            } else if (onlineDot) {
                onlineDot.remove();
            }
        }
        
        // Update chat header if this is active conversation
        if (this.activeConversationId && 
            parseInt(this.activeConversationId) === parseInt(userId)) {
            const statusElement = this.elements.chatHeader.querySelector('.user-status');
            if (statusElement) {
                statusElement.textContent = isOnline ? 'Online' : 'Offline';
                statusElement.className = `user-status ${isOnline ? 'online' : 'offline'}`;
            }
            
            const headerDot = this.elements.chatHeader.querySelector('.online-dot');
            if (isOnline && !headerDot) {
                const dot = document.createElement('span');
                dot.className = 'online-dot';
                this.elements.chatHeader.querySelector('.chat-user-avatar').appendChild(dot);
            } else if (!isOnline && headerDot) {
                headerDot.remove();
            }
        }
    }
    
    filterConversations(searchTerm) {
        const items = this.elements.conversationList.querySelectorAll('.conversation-item');
        searchTerm = searchTerm.toLowerCase();
        
        items.forEach(item => {
            const name = item.querySelector('.conversation-name').textContent.toLowerCase();
            const room = item.querySelector('.room-info').textContent.toLowerCase();
            const message = item.querySelector('.last-message').textContent.toLowerCase();
            
            if (name.includes(searchTerm) || room.includes(searchTerm) || message.includes(searchTerm)) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    }
    
    autoResizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 100) + 'px';
    }
    
    getTimeAgo(timestamp) {
        if (!timestamp) return '';
        
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) return 'Just now';
        if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
        if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
        if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;
        
        return date.toLocaleDateString();
    }
}