    <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 => `
                <a href="#" class="list-group-item list-group-item-action ${this.currentRoomId == room.id ? 'active' : ''}"
                   onclick="ChatManager.selectRoom(${room.id}, '${this.escapeHtml(room.name || 'Chat')}')">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1 text-dark">
                            ${this.escapeHtml(room.name || 'Chat')}
                            ${room.unread_count > 0 ? `<span class="badge bg-danger ms-2">${room.unread_count}</span>` : ''}
                        </h6>
                        <small class="text-muted">${room.last_message_time ? this.timeAgo(room.last_message_time) : ''}</small>
                    </div>
                    <p class="mb-0 small text-truncate text-dark">
                        ${this.escapeHtml(room.last_message || 'No messages')}
                    </p>
                </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 chat header
        document.getElementById('chat-header').textContent = 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) {
            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 => {
            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>
                `;
            } 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-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;
            
            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) {
                    input.value = '';
                    
                    // Add the message locally
                    const newMsg = {
                        id: data.message_id || (this.lastMessageId + 1),
                        sender_id: <?php echo $userId; ?>,
                        sender_name: 'You',
                        sender_photo: '<?php echo $userPhoto; ?>',
                        message: message,
                        created_at: new Date().toISOString()
                    };
                    this.messages.push(newMsg);
                    this.appendMessages([newMsg]);
                    this.lastMessageId = newMsg.id;
                    
                    // No need to reload, as we appended locally
                } else {
                    this.showAlert('Failed to send message', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                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() {
            const modal = new bootstrap.Modal(document.getElementById('newChatModal'));
            modal.show();
            this.loadResearchers();
        },
        
        async loadResearchers() {
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/api/search.php?q=&type=researchers&limit=50');
                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}">${this.escapeHtml(user.first_name + ' ' + user.last_name)}</option>`
                        ).join('');
                } else {
                    select.innerHTML = '<option value="">No researchers found</option>';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('researcher-select').innerHTML = '<option value="">Error loading researchers</option>';
            }
        },
        
        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) {
                    bootstrap.Modal.getInstance(document.getElementById('newChatModal')).hide();
                    document.getElementById('initial-message').value = '';
                    this.showAlert('Message sent successfully!', 'success');
                    await this.loadChatRooms(); // Refresh chat list
                    // Select the newly created chat (most recent)
                    if (this.chatRooms.length > 0) {
                        this.selectRoom(this.chatRooms[0].id, this.chatRooms[0].name);
                    }
                } else {
                    this.showAlert(data.message || 'Failed to send message', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                this.showAlert('Failed to send message', 'danger');
            }
        },
        
        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);
    },        scrollToBottom() {
            const container = document.getElementById('messageContainer');
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        },
        
        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;
    }

    .skeleton {
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
    }

    .skeleton-text {
        height: 16px;
        border-radius: 4px;
    }

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

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

    .skeleton-message {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .skeleton-message .skeleton-avatar {
        flex-shrink: 0;
    }

    .skeleton-message .skeleton-text {
        flex: 1;
    }

    .skeleton-message .skeleton-text:nth-child(3) {
        width: 60%;
        margin-bottom: 8px;
    }

    .skeleton-message .skeleton-text:nth-child(4) {
        width: 30%;
    }

    @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>