<main class="<?php echo $isMobile ? 'col-md-9 ms-sm-auto col-lg-10' : 'col-12'; ?> px-md-4" style="<?php echo $isMobile ? 'padding-bottom: 100px;' : ''; ?>">
<?php
$userPhoto = '/assets/images/default-avatar.png'; // Replace with actual user photo logic
?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">
            <i class="fas fa-envelope"></i> Messages
            <span id="total-unread-badge" class="badge bg-danger ms-2" style="display: none;">0</span>
        </h1>
        <div class="btn-toolbar">
            <button id="new-chat-btn" class="btn btn-primary">
                <i class="fas fa-plus"></i> New Message
            </button>
            <button id="refresh-btn" class="btn btn-outline-secondary ms-2">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <div id="alert-container"></div>

    <div class="row">
        <!-- Chat List -->
        <div class="col-md-4 col-lg-3">
            <div class="card shadow">
                <div class="card-header">
                    <h6 class="mb-0 text-dark">Conversations</h6>
                </div>
                <div id="chat-list" class="list-group list-group-flush" style="max-height: 600px; overflow-y: auto;">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3 small">Loading conversations...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chat Messages -->
        <div class="col-md-8 col-lg-9">
            <div id="chat-container" class="card shadow">
                <div class="card-header">
                    <h6 id="chat-header" class="mb-0 text-dark fw-bold">Select a conversation</h6>
                </div>
                <div id="messages-area" class="card-body text-center py-5" style="max-height: 400px; overflow-y: auto;">
                    <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                    <h5>Select a conversation</h5>
                    <p class="text-muted">Choose a conversation from the list or start a new one</p>
                    <button id="start-new-chat-btn" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Start New Conversation
                    </button>
                </div>
            </div>
            <div id="send-box" class="mt-3" style="display: none;">
                <!-- Send box will be populated here -->
            </div>
        </div>
    </div>

    <script>
    // Chat Manager
const ChatManager = {
    currentRoomId: null,
    currentRoomName: '',
    chatRooms: [],
    messages: [],
    lastMessageId: null,
    autoRefreshInterval: null,
    messageRefreshInterval: null,
    
    init() {
        this.loadChatRooms();
        this.setupEventListeners();
        this.startAutoRefresh();
    },
    
    setupEventListeners() {
            // New chat buttons
            document.getElementById('new-chat-btn').addEventListener('click', () => {
                this.showNewChatModal();
            });
            
            document.getElementById('start-new-chat-btn').addEventListener('click', () => {
                this.showNewChatModal();
            });
            
            // Send new message
            document.getElementById('send-new-message-btn').addEventListener('click', () => {
                this.sendNewMessage();
            });
            
            // Refresh button
            document.getElementById('refresh-btn').addEventListener('click', () => {
                this.loadChatRooms();
            });
            
            // Enter key in message input
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    const messageInput = document.getElementById('message-input');
                    if (messageInput && messageInput === document.activeElement) {
                        e.preventDefault();
                        this.sendMessage();
                    }
                }
            });
    },
    
    async loadChatRooms() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php?action=get_rooms');
            const data = await response.json();
            
            if (data.success) {
                this.chatRooms = data.rooms || [];
                this.renderChatList();
                this.updateUnreadBadge();
            } else {
                this.showAlert('Error loading conversations', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to load conversations', 'danger');
        }
    },
    
    renderChatList() {
        const container = document.getElementById('chat-list');
        
        if (this.chatRooms.length === 0) {
            container.innerHTML = `
                <div class="list-group-item text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-2"></i>
                    <p class="mb-0 small">No conversations yet</p>
                    <button class="btn btn-sm btn-primary mt-2" onclick="ChatManager.showNewChatModal()">
                        <i class="fas fa-plus"></i> Start One
                    </button>
                </div>
            `;
            return;
        }
        
        const html = this.chatRooms.map(room => {
            const isGroup = room.participants && room.participants.length > 1;
            const participantNames = isGroup ? 
                room.participants.map(p => p.first_name + ' ' + p.last_name).join(', ') : 
                (room.participants && room.participants.length > 0 ? 
                    room.participants[0].first_name + ' ' + room.participants[0].last_name : 
                    'Unknown');
            
            return `
            <a href="#" class="list-group-item list-group-item-action ${this.currentRoomId == room.id ? 'active' : ''}"
               onclick="ChatManager.selectRoom(${room.id}, '${JSON.stringify(room.name || (isGroup ? 'Group Chat' : participantNames)).slice(1, -1).replace(/'/g, '\\\\\'')}')">
                <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">
                        ${this.escapeHtml(room.name || (isGroup ? 'Group Chat' : participantNames))}
                        ${room.unread_count > 0 ? `<span class="badge bg-danger ms-2">${room.unread_count}</span>` : ''}
                        ${isGroup ? `<i class="fas fa-users text-muted ms-1" title="${JSON.stringify(participantNames).slice(1, -1).replace(/"/g, '&quot;')}"></i>` : ''}
                    </h6>
                    <small class="text-muted">${room.last_message_time ? this.timeAgo(room.last_message_time) : ''}</small>
                </div>
                <p class="mb-0 small text-truncate">
                    ${this.escapeHtml(room.last_message || 'No messages')}
                </p>
                ${isGroup ? `<small class="text-muted">${room.participants.length} participants</small>` : ''}
            </a>
            `;
        }).join('');
        
        container.innerHTML = html;
    },
    
    updateUnreadBadge() {
        const totalUnread = this.chatRooms.reduce((sum, room) => sum + (room.unread_count || 0), 0);
        const badge = document.getElementById('total-unread-badge');
        
        if (totalUnread > 0) {
            badge.textContent = totalUnread;
            badge.style.display = 'inline-block';
        } else {
            badge.style.display = 'none';
        }
    },
    
    async selectRoom(roomId, roomName) {
        this.currentRoomId = roomId;
        this.currentRoomName = roomName;
        
        // Update active state
        document.querySelectorAll('#chat-list .list-group-item').forEach(item => {
            item.classList.remove('active');
        });
        event.target.closest('.list-group-item').classList.add('active');
        
        // Show skeleton loader
        const messagesArea = document.getElementById('messages-area');
        messagesArea.innerHTML = `
            <div class="card-header d-flex justify-content-between align-items-center">
                <div class="skeleton skeleton-text" style="width: 200px; height: 24px;"></div>
                <div class="btn-group">
                    <div class="skeleton skeleton-button" style="width: 32px; height: 32px;"></div>
                    <div class="skeleton skeleton-button" style="width: 32px; height: 32px;"></div>
                </div>
            </div>
            <div style="height: 400px; overflow-y: auto; padding: 1.5rem 1rem 1rem 1rem;" id="messageContainer">
                <div class="skeleton-message mb-3">
                    <div class="skeleton skeleton-avatar"></div>
                    <div class="skeleton skeleton-text" style="width: 150px; height: 16px;"></div>
                    <div class="skeleton skeleton-text" style="width: 250px; height: 40px;"></div>
                    <div class="skeleton skeleton-text" style="width: 60px; height: 12px;"></div>
                </div>
                <div class="skeleton-message mb-3 text-end">
                    <div class="skeleton skeleton-text" style="width: 60px; height: 12px;"></div>
                    <div class="skeleton skeleton-text" style="width: 200px; height: 40px;"></div>
                </div>
                <div class="skeleton-message mb-3">
                    <div class="skeleton skeleton-avatar"></div>
                    <div class="skeleton skeleton-text" style="width: 120px; height: 16px;"></div>
                    <div class="skeleton skeleton-text" style="width: 180px; height: 40px;"></div>
                    <div class="skeleton skeleton-text" style="width: 60px; height: 12px;"></div>
                </div>
            </div>
        `;
        
        // Load messages
        await this.loadMessages();
        
        // Show send box
        const sendBox = document.getElementById('send-box');
        if (sendBox) {
            sendBox.innerHTML = `
                <div class="d-flex gap-2">
                    <input type="text" id="message-input" class="form-control" placeholder="Type your message..." maxlength="1000">
                    <button id="send-btn" class="btn btn-primary" onclick="ChatManager.sendMessage()">
                        <i class="fas fa-paper-plane"></i> Send
                    </button>
                </div>
            `;
            sendBox.style.display = 'block';
            
            // Focus input
            document.getElementById('message-input').focus();
        }
        
        // Start message auto-refresh
        this.startMessageRefresh();
    },
    
    async loadMessages(append = false) {
        if (!this.currentRoomId) return;
        
        try {
            const since = append && this.lastMessageId ? `&since_id=${this.lastMessageId}` : '';
            const response = await fetch(`<?php echo SITE_URL; ?>/api/chat.php?action=get_messages&room_id=${this.currentRoomId}&limit=100${since}`);
            const data = await response.json();
            
            if (data.success) {
                const newMessages = data.messages || [];
                
                if (append) {
                    // Append new messages
                    this.messages.push(...newMessages);
                    this.messages.sort((a, b) => a.id - b.id); // Ensure sorted by ID ASC
                    this.appendMessages(newMessages.sort((a, b) => a.id - b.id)); // Sort and append
                } else {
                    // Replace all messages
                    this.messages = newMessages; // API returns ASC
                    this.renderChat();
                }
                
                // Update last message ID
                if (this.messages.length > 0) {
                    this.lastMessageId = Math.max(...this.messages.map(m => m.id));
                }
                
                // Mark as read
                await this.markRoomAsRead();
            } else {
                this.showAlert('Error loading messages', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to load messages', 'danger');
        }
    },
    
    appendMessages(newMessages) {
        if (newMessages.length === 0) return;
        
        const messageContainer = document.getElementById('messageContainer');
        if (!messageContainer) return;
        
        const fragment = document.createDocumentFragment();
        
        newMessages.forEach(msg => { // Messages are already sorted ASC
            const messageElement = this.createMessageElement(msg);
            fragment.appendChild(messageElement);
        });
        
        messageContainer.appendChild(fragment);
        
        // Scroll to bottom
        this.scrollToBottom();
    },
    
    createMessageElement(msg) {
        // Handle system messages
        if (msg.is_system || msg.sender_id == 0 || msg.message.startsWith('[SYSTEM]')) {
            const div = document.createElement('div');
            div.className = 'mb-3 text-center';
            const cleanMessage = msg.message.replace('[SYSTEM] ', '');
            div.innerHTML = `
                <div class="d-inline-block bg-light text-muted px-3 py-2 rounded-pill small">
                    <i class="fas fa-info-circle me-1"></i>
                    ${this.processSystemMessage(cleanMessage)}
                </div>
            `;
            return div;
        }
        
        const isSent = msg.sender_id == <?php echo $userId; ?>;
        
        const div = document.createElement('div');
        div.className = 'mb-3 message-new';
        
        if (isSent) {
            div.classList.add('text-end');
            div.innerHTML = `
                <div class="d-inline-block" style="max-width: 70%;">
                    <div class="d-flex align-items-end">
                        <div class="bg-primary text-white p-3 rounded me-2">
                            ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                        </div>
                        <small class="text-muted">${this.formatTime(msg.created_at)}</small>
                    </div>
                </div>
            `;
        } else {
            const avatarHtml = msg.sender_photo ? 
                `<img src="${msg.sender_photo}" class="rounded-circle me-2" style="width: 40px; height: 40px;" alt="${this.escapeHtml(msg.sender_name)}">` :
                `<div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px; font-size: 14px; font-weight: bold;">${this.getInitials(msg.sender_name)}</div>`;
            
            div.innerHTML = `
                <div class="d-flex align-items-start">
                    ${avatarHtml}
                    <div class="flex-grow-1">
                        <small class="text-muted d-block mb-1">
                            ${this.escapeHtml(msg.sender_name)}
                        </small>
                        <div class="d-flex align-items-end">
                            <div class="bg-light p-3 rounded flex-grow-1">
                                ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                            </div>
                            <small class="text-muted ms-2">${this.formatTime(msg.created_at)}</small>
                        </div>
                        </div>
                    </div>
                `;
            }
            
            return div;
    },
    
    renderChat() {
        const messagesArea = document.getElementById('messages-area');
        const sendBox = document.getElementById('send-box');
        
        if (!this.currentRoomId) {
            messagesArea.innerHTML = `
                <div class="text-center py-5">
                    <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                    <h5>Select a conversation</h5>
                    <p class="text-muted">Choose a conversation from the list or start a new one</p>
                    <button class="btn btn-primary" onclick="ChatManager.showNewChatModal()">
                        <i class="fas fa-plus"></i> Start New Conversation
                    </button>
                </div>
            `;
            if (sendBox) sendBox.style.display = 'none';
            return;
        }
        
        const messagesHtml = this.messages.length === 0 ? `
            <div class="text-center text-muted py-5">
                <i class="fas fa-comments fa-3x mb-3"></i>
                <p>No messages yet. Start the conversation!</p>
            </div>
        ` : this.messages.map(msg => {
            // Handle system messages
            if (msg.is_system || msg.sender_id == 0 || msg.message.startsWith('[SYSTEM]')) {
                const cleanMessage = msg.message.replace('[SYSTEM] ', '');
                return `
                    <div class="mb-3 text-center">
                        <div class="d-inline-block bg-light text-muted px-3 py-2 rounded-pill small">
                            <i class="fas fa-info-circle me-1"></i>
                            ${this.processSystemMessage(cleanMessage)}
                        </div>
                    </div>
                `;
            }
            
            const isSent = msg.sender_id == <?php echo $userId; ?>;
            if (isSent) {
                return `
                    <div class="d-flex justify-content-end mb-3">
                        <div class="d-inline-block" style="max-width: 70%;">
                            <div class="d-flex align-items-end">
                                <div class="bg-primary text-white p-3 rounded me-2">
                                    ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                                </div>
                                <small class="text-muted">${this.formatTime(msg.created_at)}</small>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                const avatarHtml = msg.sender_photo ? 
                    `<img src="${msg.sender_photo}" class="rounded-circle me-2" style="width: 40px; height: 40px;" alt="${this.escapeHtml(msg.sender_name)}">` :
                    `<div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px; font-size: 14px; font-weight: bold;">${this.getInitials(msg.sender_name)}</div>`;
                
                return `
                    <div class="mb-3">
                        <div class="d-flex align-items-center mb-2">
                            ${avatarHtml}
                            <small class="text-muted">${this.escapeHtml(msg.sender_name)}</small>
                        </div>
                        <div class="d-flex justify-content-between align-items-end mb-1">
                            <div class="bg-light p-3 rounded flex-grow-1 me-2">
                                ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                            </div>
                            <small class="text-muted">${this.formatTime(msg.created_at)}</small>
                        </div>
                    </div>
                `;
            }
        }).join('');
        
        messagesArea.innerHTML = `
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0">${this.escapeHtml(this.currentRoomName)}</h6>
                <div class="btn-group">
                    <button class="btn btn-sm btn-outline-primary" onclick="ChatManager.showAddParticipantsModal()">
                        <i class="fas fa-user-plus"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="ChatManager.showRoomInfo()">
                        <i class="fas fa-info-circle"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="ChatManager.leaveRoom()">
                        <i class="fas fa-sign-out-alt"></i>
                    </button>
                </div>
            </div>
            <div style="height: 400px; overflow-y: auto; padding: 1.5rem 1rem 1rem 1rem;" id="messageContainer">
                ${messagesHtml}
            </div>
        `;
        
        // Scroll to bottom
        this.scrollToBottom();
    },
    
    async sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        
        if (!message || !this.currentRoomId) return;
        
        // Clear input immediately for better UX
        input.value = '';
        
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'send_message',
                    room_id: this.currentRoomId,
                    message: message
            })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            let data;
            try {
                data = await response.json();
            } catch (parseError) {
                console.error('JSON parse error:', parseError);
                throw new Error('Invalid response format');
            }
            
            if (data.success) {
                // Message sent successfully, refresh messages to show the new one
                await this.loadMessages(true); // This will append the new message from server
                
                // Scroll to bottom
                setTimeout(() => this.scrollToBottom(), 100);
                
                // Close any open mobile menus/overlays
                this.closeMobileMenus();
            } else {
                // Restore the message if sending failed
                input.value = message;
                this.showAlert('Failed to send message', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            // Restore the message if sending failed
            input.value = message;
            this.showAlert('Failed to send message', 'danger');
        }
    },
        
        async markRoomAsRead() {
            if (!this.currentRoomId) return;
            
            try {
                await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'mark_read',
                        room_id: this.currentRoomId
                    })
                });
                
                // Update local data
                this.chatRooms.forEach(room => {
                    if (room.id == this.currentRoomId) {
                        room.unread_count = 0;
                    }
                });
                this.renderChatList();
                this.updateUnreadBadge();
            } catch (error) {
                console.error('Error marking as read:', error);
            }
        },
        
        showNewChatModal(targetUserId = null) {
            const modal = new bootstrap.Modal(document.getElementById('newChatModal'));
            modal.show();
            this.loadResearchers(targetUserId);
        },
        
        async loadResearchers(targetUserId = null) {
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/search.php?q=&type=researchers&limit=100');
                const data = await response.json();
                
                const select = document.getElementById('researcher-select');
                if (data.success && data.results) {
                    select.innerHTML = '<option value="">Select a researcher...</option>' +
                        data.results.map(user => 
                            `<option value="${user.id}" ${targetUserId == user.id ? 'selected' : ''}>${this.escapeHtml(user.first_name + ' ' + user.last_name)}</option>`
                        ).join('');
                } else {
                    select.innerHTML = '<option value="">No researchers available</option>';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('researcher-select').innerHTML = '<option value="">Error loading researchers</option>';
            }
        },
        
        showAddParticipantsModal() {
            if (!this.currentRoomId) return;
            const modal = new bootstrap.Modal(document.getElementById('addParticipantsModal'));
            modal.show();
            this.loadResearchersForAdding();
        },
        
        async loadResearchersForAdding() {
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/search.php?q=&type=researchers&limit=100');
                const data = await response.json();
                
                const select = document.getElementById('add-participant-select');
                if (data.success && data.results) {
                    // Filter out users already in the current room
                    const currentParticipants = this.chatRooms.find(room => room.id == this.currentRoomId)?.participants || [];
                    const currentUserIds = currentParticipants.map(p => p.id);
                    
                    const availableUsers = data.results.filter(user => !currentUserIds.includes(user.id));
                    
                    select.innerHTML = '<option value="">Select a researcher to add...</option>' +
                        availableUsers.map(user => 
                            `<option value="${user.id}">${this.escapeHtml(user.first_name + ' ' + user.last_name)}</option>`
                        ).join('');
                } else {
                    select.innerHTML = '<option value="">No researchers available</option>';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('add-participant-select').innerHTML = '<option value="">Error loading researchers</option>';
            }
        },
        
        leaveRoom() {
            if (!this.currentRoomId) return;
            
            if (confirm('Are you sure you want to leave this conversation?')) {
                // For now, just close the current room view
                this.currentRoomId = null;
                this.currentRoomName = '';
                this.messages = [];
                this.renderChat();
                this.renderChatList();
                this.showAlert('You have left the conversation', 'info');
            }
        },
        
        async sendNewMessage() {
            const researcherId = document.getElementById('researcher-select').value;
            const message = document.getElementById('initial-message').value.trim();
            
            if (!researcherId || !message) {
                this.showAlert('Please select a researcher and enter a message', 'warning');
                return;
            }
            
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'start_conversation',
                        user_id: researcherId,
                        message: message
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('newChatModal'));
                    if (modal) {
                        modal.hide();
                    }
                    // Remove any remaining modal backdrops
                    document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
                    document.getElementById('initial-message').value = '';
                    this.showAlert('Message sent successfully!', 'success');
                    this.loadChatRooms(); // Refresh chat list
                } else {
                    this.showAlert(data.message || 'Failed to send message', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                this.showAlert('Failed to send message', 'danger');
            }
        },
        
        async addParticipant() {
            const researcherId = document.getElementById('add-participant-select').value;
            
            if (!researcherId) {
                this.showAlert('Please select a researcher to add', 'warning');
                return;
            }
            
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'add_participant',
                        room_id: this.currentRoomId,
                        user_id: researcherId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('addParticipantsModal')).hide();
                    // Remove any remaining modal backdrops
                    document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
                    document.getElementById('add-participant-select').value = '';
                    
                    // Send system message about the new participant
                    await this.sendSystemMessage(`[SYSTEM] ${data.participant_name}|${researcherId} was added to the conversation`);
                    
                    this.showAlert('Participant added successfully!', 'success');
                    this.loadChatRooms(); // Refresh chat list to show updated participants
                } else {
                    this.showAlert(data.message || 'Failed to add participant', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                this.showAlert('Failed to add participant', 'danger');
            }
        },
        
        async sendSystemMessage(message) {
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'send_message',
                        room_id: this.currentRoomId,
                        message: message
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // Add system message locally
                    const messageId = data.message_id || Date.now();
                    const systemMsg = {
                        id: messageId,
                        sender_id: 0, // System sender
                        sender_name: 'System',
                        sender_photo: null,
                        message: message,
                        created_at: new Date().toISOString(),
                        is_system: true
                    };
                    
                    this.messages.push(systemMsg);
                    this.messages.sort((a, b) => a.id - b.id);
                    this.lastMessageId = Math.max(this.lastMessageId, messageId);
                    
                    // Re-render to show the system message
                    this.renderChat();
                    setTimeout(() => this.scrollToBottom(), 100);
                }
            } catch (error) {
                console.error('Error sending system message:', error);
            }
        },
        
        startAutoRefresh() {
            // Refresh chat list every 30 seconds
            this.autoRefreshInterval = setInterval(() => {
                this.loadChatRooms();
            }, 30000);
        },
        
        startMessageRefresh() {
            // Stop previous interval
            if (this.messageRefreshInterval) {
                clearInterval(this.messageRefreshInterval);
            }
            
            // Refresh messages every 10 seconds when a room is selected
            this.messageRefreshInterval = setInterval(() => {
                if (this.currentRoomId) {
                    this.loadMessages(true); // Append new messages
                }
            }, 10000);
    },
    
    closeMobileMenus() {
            // Close mobile search if open
            const searchContainer = document.getElementById('mobile-search-container');
            if (searchContainer && searchContainer.classList.contains('show')) {
                searchContainer.classList.remove('show');
                document.body.style.paddingTop = '60px';
            }
            
            // Close Bootstrap offcanvas menus
            const offcanvasElements = document.querySelectorAll('.offcanvas.show');
            offcanvasElements.forEach(offcanvas => {
                const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvas);
                if (bsOffcanvas) {
                    bsOffcanvas.hide();
                }
            });
            
            // Close Bootstrap modals (if any are open)
            const modalElements = document.querySelectorAll('.modal.show');
            modalElements.forEach(modal => {
                const bsModal = bootstrap.Modal.getInstance(modal);
                if (bsModal) {
                    bsModal.hide();
                }
            });
            
            // Remove any remaining modal backdrops
            document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
            
            // Close mobile conversation list if on mobile and chat view is active
            if (window.innerWidth <= 768) {
                const conversationListView = document.getElementById('conversationListView');
                const chatView = document.getElementById('chatView');
                
                if (conversationListView && chatView && chatView.classList.contains('active')) {
                    conversationListView.classList.add('hidden');
                }
            }
        },
        
        scrollToBottom() {
            const container = document.getElementById('messageContainer');
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        },
        
        processSystemMessage(message) {
            // Handle system messages like "John Doe|123 was added to the conversation"
            if (message.includes('was added to the conversation')) {
                const nameWithId = message.replace(' was added to the conversation', '');
                const [name, id] = nameWithId.split('|');
                if (id) {
                    return `<a href="<?php echo SITE_URL; ?>/public/researcher-profile.php?id=${id}" class="text-decoration-none fw-bold">${this.escapeHtml(name)}</a> was added to the conversation`;
                } else {
                    return `<span class="fw-bold">${this.escapeHtml(name)}</span> was added to the conversation`;
                }
            }
            return this.escapeHtml(message);
        },
        
        getUserIdByName(name) {
            // Find user ID by name from current room participants
            const room = this.chatRooms.find(r => r.id == this.currentRoomId);
            if (room && room.participants) {
                const participant = room.participants.find(p => `${p.first_name} ${p.last_name}` === name);
                return participant ? participant.id : '';
            }
            return '';
        },
        
        showAlert(message, type = 'info') {
            const container = document.getElementById('alert-container');
            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show`;
            alert.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            container.appendChild(alert);
            
            // Auto-dismiss after 3 seconds
            setTimeout(() => {
                alert.remove();
            }, 3000);
        },
        
        escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        },
        
        getInitials(name) {
            if (!name) return '?';
            const parts = name.trim().split(' ');
            if (parts.length >= 2) {
                return (parts[0][0] + parts[1][0]).toUpperCase();
            } else if (parts.length === 1) {
                return parts[0][0].toUpperCase();
            }
            return '?';
        },
        
        timeAgo(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const seconds = Math.floor((now - date) / 1000);
            
            const intervals = {
                year: 31536000,
                month: 2592000,
                week: 604800,
                day: 86400,
                hour: 3600,
                minute: 60
            };
            
            for (const [unit, secondsInUnit] of Object.entries(intervals)) {
                const interval = Math.floor(seconds / secondsInUnit);
                if (interval >= 1) {
                    return interval === 1 ? `1 ${unit} ago` : `${interval} ${unit}s ago`;
                }
            }
            
            return 'Just now';
        },
        
        formatTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        },
        
        showRoomInfo() {
            // Placeholder for room info modal
            this.showAlert('Room info feature coming soon', 'info');
        },
        
        leaveRoom() {
            if (confirm('Are you sure you want to leave this conversation?')) {
                this.currentRoomId = null;
                this.currentRoomName = '';
                this.messages = [];
                this.renderChat();
                this.renderChatList();
                
                // Hide send box
                const sendBox = document.getElementById('send-box');
                if (sendBox) sendBox.style.display = 'none';
            }
        }
    };

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', () => {
        ChatManager.init();
    });

    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
        if (ChatManager.autoRefreshInterval) {
            clearInterval(ChatManager.autoRefreshInterval);
        }
        if (ChatManager.messageRefreshInterval) {
            clearInterval(ChatManager.messageRefreshInterval);
        }
    });
    </script>

    <style>
    .list-group-item {
        transition: background-color 0.3s ease;
    }

    .list-group-item:hover {
        background-color: #f8f9fa !important;
    }

    .list-group-item.active {
        background-color: #007bff !important;
        border-color: #007bff;
    }

    #messageContainer {
        scroll-behavior: smooth;
    }

    #refresh-btn .fa-sync-alt {
        transition: transform 0.3s ease;
    }

    #refresh-btn:active .fa-sync-alt {
        transform: rotate(360deg);
    }

    #message-input {
        resize: none;
    }

    /* Skeleton Loading */
    .skeleton {
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
        border-radius: 4px;
    }

    .skeleton-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
    }

    .skeleton-text {
        height: 16px;
        margin-bottom: 8px;
    }

    .skeleton-button {
        border-radius: 4px;
    }

    @keyframes skeleton-loading {
        0% {
            background-position: 200% 0;
        }
        100% {
            background-position: -200% 0;
        }
    }

    /* Message Animation */
    .message-new {
        animation: message-slide-in 0.5s ease-out;
        opacity: 0;
        animation-fill-mode: forwards;
    }

    @keyframes message-slide-in {
        0% {
            opacity: 0;
            transform: translateY(20px);
        }
        100% {
            opacity: 1;
            transform: translateY(0);
        }
    }
    </style>
</main>