<?php
$userPhoto = '/assets/images/default-avatar.png'; // Replace with actual user photo logic
$userId = getCurrentUserId();
?>

<style>
/* Mobile Messenger Interface Styles */
.mobile-messenger-container {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 80px;
    background: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* Conversation List View */
.conversation-list-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.conversation-list-view.hidden {
    transform: translateX(-100%);
    position: absolute;
    width: 100%;
}

/* Conversation List */
.mobile-conversation-list {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

.conversation-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #f0f2f5;
    cursor: pointer;
    transition: background-color 0.2s;
    position: relative;
}

.conversation-item:active {
    background-color: #f0f2f5;
}

.conversation-item.unread {
    background-color: #f8f9fa;
}

.conversation-avatar {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    margin-right: 12px;
    flex-shrink: 0;
    object-fit: cover;
}

.conversation-avatar-placeholder {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    margin-right: 12px;
    flex-shrink: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
    font-size: 1.2rem;
}

.conversation-content {
    flex: 1;
    min-width: 0;
}

.conversation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.conversation-name {
    font-weight: 600;
    font-size: 0.95rem;
    color: #050505;
    margin: 0;
}

.conversation-time {
    font-size: 0.8rem;
    color: #65676b;
}

.conversation-preview {
    font-size: 0.9rem;
    color: #65676b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin: 0;
}

.conversation-item.unread .conversation-preview {
    font-weight: 600;
    color: #050505;
}

.unread-badge {
    position: absolute;
    right: 16px;
    bottom: 16px;
    background: #0d6efd;
    color: white;
    border-radius: 12px;
    padding: 2px 8px;
    font-size: 0.75rem;
    font-weight: 600;
}

/* Chat View */
.chat-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    transform: translateX(100%);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-view.active {
    transform: translateX(0);
}

/* Chat Header */
.chat-header {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #e9ecef;
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
}

.chat-back-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    border: none;
    color: #050505;
    margin-right: 8px;
    cursor: pointer;
}

.chat-back-btn:active {
    background: #f0f2f5;
}

.chat-user-info {
    flex: 1;
    display: flex;
    align-items: center;
}

.chat-user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    object-fit: cover;
}

.chat-user-avatar-placeholder {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
}

.chat-user-name {
    font-weight: 600;
    font-size: 1rem;
    color: #050505;
    margin: 0;
}

/* Messages Area */
.messages-container {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding: 16px;
    background: #fff;
}

.message-group {
    margin-bottom: 16px;
}

.message-item {
    display: flex;
    margin-bottom: 8px;
    animation: messageSlideIn 0.3s ease-out;
}

@keyframes messageSlideIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-item.sent {
    justify-content: flex-end;
}

.message-bubble {
    max-width: 75%;
    padding: 10px 14px;
    border-radius: 18px;
    word-wrap: break-word;
}

.message-item.received .message-bubble {
    background: #f0f2f5;
    color: #050505;
    border-bottom-left-radius: 4px;
}

.message-item.sent .message-bubble {
    background: #0d6efd;
    color: white;
    border-bottom-right-radius: 4px;
}

.message-time {
    font-size: 0.7rem;
    color: #65676b;
    margin-top: 4px;
    text-align: right;
}

.message-item.sent .message-time {
    color: rgba(255, 255, 255, 0.8);
}

/* Message Input */
.message-input-container {
    padding: 12px 16px;
    background: #fff;
    border-top: 1px solid #e9ecef;
    display: flex;
    align-items: flex-end;
    gap: 8px;
    transition: transform 0.3s ease;
}

.message-input-container.keyboard-open {
    transform: translateY(0);
}

.message-input-wrapper {
    flex: 1;
    position: relative;
}

.message-input {
    width: 100%;
    min-height: 40px;
    max-height: 120px;
    padding: 10px 16px;
    border: 1px solid #e9ecef;
    border-radius: 20px;
    background: #f0f2f5;
    resize: none;
    font-size: 0.95rem;
    line-height: 1.4;
    overflow-y: auto;
}

.message-input:focus {
    outline: none;
    background: #fff;
    border-color: #0d6efd;
}

.send-button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #0d6efd;
    border: none;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
    transition: transform 0.2s;
}

.send-button:active {
    transform: scale(0.95);
}

.send-button:disabled {
    background: #e9ecef;
    color: #adb5bd;
}

/* Empty States */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 32px;
    text-align: center;
}

.empty-state i {
    font-size: 4rem;
    color: #dee2e6;
    margin-bottom: 16px;
}

.empty-state h3 {
    font-size: 1.2rem;
    color: #495057;
    margin-bottom: 8px;
}

.empty-state p {
    color: #6c757d;
    margin-bottom: 24px;
}

/* Skeleton Loading */
.skeleton-conversation {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #f0f2f5;
}

.skeleton-avatar {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    margin-right: 12px;
}

.skeleton-content {
    flex: 1;
}

.skeleton-line {
    height: 12px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
    margin-bottom: 8px;
}

.skeleton-line.short {
    width: 60%;
}

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

/* Loading indicator */
.loading-indicator {
    text-align: center;
    padding: 20px;
    color: #6c757d;
}

.spinner {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #0d6efd;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto 12px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>

<div class="mobile-messenger-container">
    <!-- Conversation List View -->
    <div class="conversation-list-view" id="conversationListView">
        <div class="mobile-conversation-list" id="mobileConversationList">
            <!-- Loading skeleton -->
            <div id="conversationListSkeleton">
                <?php for ($i = 0; $i < 5; $i++): ?>
                <div class="skeleton-conversation">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-content">
                        <div class="skeleton-line"></div>
                        <div class="skeleton-line short"></div>
                    </div>
                </div>
                <?php endfor; ?>
            </div>
        </div>
    </div>

    <!-- Chat View -->
    <div class="chat-view" id="chatView">
        <!-- Chat Header -->
        <div class="chat-header" id="chatHeader">
            <button class="chat-back-btn" onclick="MobileChatManager.closeChat()">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="chat-user-info" id="chatUserInfo">
                <!-- Will be populated dynamically -->
            </div>
        </div>

        <!-- Messages Container -->
        <div class="messages-container" id="messagesContainer">
            <div class="empty-state">
                <i class="fas fa-comments"></i>
                <h3>No messages yet</h3>
                <p>Start the conversation!</p>
            </div>
        </div>

        <!-- Message Input -->
        <div class="message-input-container" id="messageInputContainer">
            <div class="message-input-wrapper">
                <textarea 
                    id="messageInput" 
                    class="message-input" 
                    placeholder="Type a message..."
                    rows="1"
                ></textarea>
            </div>
            <button class="send-button" id="sendButton" onclick="MobileChatManager.sendMessage()">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>
</div>

<script>
// Mobile Chat Manager
const MobileChatManager = {
    currentRoomId: null,
    currentRoomName: '',
    currentRoomAvatar: null,
    chatRooms: [],
    messages: [],
    lastMessageId: null,
    autoRefreshInterval: null,
    messageRefreshInterval: null,
    userId: <?php echo $userId; ?>,
    
    init() {
        this.loadConversations();
        this.setupEventListeners();
        this.startAutoRefresh();
    },
    
    setupEventListeners() {
        // Message input auto-resize
        const messageInput = document.getElementById('messageInput');
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });
        
        // Send on Enter (without Shift)
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        // Handle keyboard visibility
        this.setupKeyboardHandling();
        
        // Search functionality
        const searchInput = document.getElementById('mobile-search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchConversations(e.target.value);
            });
        }
    },
    
    setupKeyboardHandling() {
        const messageInput = document.getElementById('messageInput');
        const messageInputContainer = document.getElementById('messageInputContainer');
        const messagesContainer = document.getElementById('messagesContainer');
        
        // Detect keyboard open/close
        let initialHeight = window.innerHeight;
        
        window.addEventListener('resize', () => {
            const currentHeight = window.innerHeight;
            const heightDiff = initialHeight - currentHeight;
            
            if (heightDiff > 150) {
                // Keyboard is open
                messageInputContainer.classList.add('keyboard-open');
                // Scroll to bottom
                setTimeout(() => this.scrollToBottom(), 100);
            } else {
                // Keyboard is closed
                messageInputContainer.classList.remove('keyboard-open');
            }
        });
        
        // Focus handling
        messageInput.addEventListener('focus', () => {
            setTimeout(() => this.scrollToBottom(), 300);
        });
    },
    
    async loadConversations() {
        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.renderConversationList();
            } else {
                this.showError('Failed to load conversations');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showError('Failed to load conversations');
        }
    },
    
    renderConversationList() {
        const container = document.getElementById('mobileConversationList');
        const skeleton = document.getElementById('conversationListSkeleton');
        
        if (skeleton) {
            skeleton.remove();
        }
        
        if (this.chatRooms.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>No conversations</h3>
                    <p>Start a new conversation to get started</p>
                    <button class="btn btn-primary" onclick="showNewChatModal()">
                        <i class="fas fa-plus"></i> New Message
                    </button>
                </div>
            `;
            return;
        }
        
        const html = this.chatRooms.map(room => {
            const initials = this.getInitials(room.name || 'Chat');
            const unreadBadge = room.unread_count > 0 ? 
                `<span class="unread-badge">${room.unread_count}</span>` : '';
            
            return `
                <div class="conversation-item ${room.unread_count > 0 ? 'unread' : ''}" 
                     onclick="MobileChatManager.openChat(${room.id}, '${this.escapeHtml(room.name || 'Chat')}', '${room.avatar || ''}')">
                    ${room.avatar ? 
                        `<img src="${room.avatar}" class="conversation-avatar" alt="${this.escapeHtml(room.name)}">` :
                        `<div class="conversation-avatar-placeholder">${initials}</div>`
                    }
                    <div class="conversation-content">
                        <div class="conversation-header">
                            <h3 class="conversation-name">${this.escapeHtml(room.name || 'Chat')}</h3>
                            <span class="conversation-time">${this.timeAgo(room.last_message_time)}</span>
                        </div>
                        <p class="conversation-preview">${this.escapeHtml(room.last_message || 'No messages')}</p>
                    </div>
                    ${unreadBadge}
                </div>
            `;
        }).join('');
        
        container.innerHTML = html;
    },
    
    async openChat(roomId, roomName, roomAvatar) {
        this.currentRoomId = roomId;
        this.currentRoomName = roomName;
        this.currentRoomAvatar = roomAvatar;
        
        // Update chat header
        const initials = this.getInitials(roomName);
        document.getElementById('chatUserInfo').innerHTML = `
            ${roomAvatar ? 
                `<img src="${roomAvatar}" class="chat-user-avatar" alt="${this.escapeHtml(roomName)}">` :
                `<div class="chat-user-avatar-placeholder">${initials}</div>`
            }
            <h2 class="chat-user-name">${this.escapeHtml(roomName)}</h2>
        `;
        
        // Show chat view with animation
        document.getElementById('conversationListView').classList.add('hidden');
        document.getElementById('chatView').classList.add('active');
        
        // Load messages
        await this.loadMessages();
        
        // Start message refresh
        this.startMessageRefresh();
        
        // Mark as read
        await this.markRoomAsRead();
    },
    
    closeChat() {
        // Hide chat view
        document.getElementById('chatView').classList.remove('active');
        document.getElementById('conversationListView').classList.remove('hidden');
        
        // Clear current room
        this.currentRoomId = null;
        this.currentRoomName = '';
        this.currentRoomAvatar = null;
        
        // Stop message refresh
        if (this.messageRefreshInterval) {
            clearInterval(this.messageRefreshInterval);
        }
        
        // Reload conversations to update unread counts
        this.loadConversations();
    },
    
    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) {
                    this.messages.push(...newMessages);
                    this.messages.sort((a, b) => a.id - b.id);
                    this.appendMessages(newMessages.sort((a, b) => a.id - b.id));
                } else {
                    this.messages = newMessages;
                    this.renderMessages();
                }
                
                if (this.messages.length > 0) {
                    this.lastMessageId = Math.max(...this.messages.map(m => m.id));
                }
            }
        } catch (error) {
            console.error('Error:', error);
        }
    },
    
    renderMessages() {
        const container = document.getElementById('messagesContainer');
        
        if (this.messages.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-comments"></i>
                    <h3>No messages yet</h3>
                    <p>Start the conversation!</p>
                </div>
            `;
            return;
        }
        
        const html = this.messages.map(msg => {
            const isSent = msg.sender_id == this.userId;
            const time = this.formatTime(msg.created_at);
            
            return `
                <div class="message-item ${isSent ? 'sent' : 'received'}">
                    <div class="message-bubble">
                        ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                        <div class="message-time">${time}</div>
                    </div>
                </div>
            `;
        }).join('');
        
        container.innerHTML = html;
        this.scrollToBottom();
    },
    
    appendMessages(newMessages) {
        if (newMessages.length === 0) return;
        
        const container = document.getElementById('messagesContainer');
        const emptyState = container.querySelector('.empty-state');
        if (emptyState) {
            emptyState.remove();
        }
        
        newMessages.forEach(msg => {
            const isSent = msg.sender_id == this.userId;
            const time = this.formatTime(msg.created_at);
            
            const messageEl = document.createElement('div');
            messageEl.className = `message-item ${isSent ? 'sent' : 'received'}`;
            messageEl.innerHTML = `
                <div class="message-bubble">
                    ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                    <div class="message-time">${time}</div>
                </div>
            `;
            
            container.appendChild(messageEl);
        });
        
        this.scrollToBottom();
    },
    
    async sendMessage() {
        const input = document.getElementById('messageInput');
        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 = '';
                input.style.height = 'auto';
                
                // Add message locally
                const newMsg = {
                    id: data.message_id || (this.lastMessageId + 1),
                    sender_id: this.userId,
                    message: message,
                    created_at: new Date().toISOString()
                };
                this.messages.push(newMsg);
                this.appendMessages([newMsg]);
                this.lastMessageId = newMsg.id;
                
                // Close any open mobile menus after sending
                this.closeMobileMenus();
            }
        } catch (error) {
            console.error('Error:', error);
        }
    },
    
    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
                })
            });
        } catch (error) {
            console.error('Error:', error);
        }
    },
    
    searchConversations(searchTerm) {
        const term = searchTerm.toLowerCase();
        const items = document.querySelectorAll('.conversation-item');
        
        items.forEach(item => {
            const name = item.querySelector('.conversation-name').textContent.toLowerCase();
            const preview = item.querySelector('.conversation-preview').textContent.toLowerCase();
            
            if (name.includes(term) || preview.includes(term)) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    },
    
    startAutoRefresh() {
        this.autoRefreshInterval = setInterval(() => {
            if (!this.currentRoomId) {
                this.loadConversations();
            }
        }, 30000);
    },
    
    startMessageRefresh() {
        if (this.messageRefreshInterval) {
            clearInterval(this.messageRefreshInterval);
        }
        
        this.messageRefreshInterval = setInterval(() => {
            if (this.currentRoomId) {
                this.loadMessages(true);
            }
        }, 10000);
    },
    
    scrollToBottom() {
        const container = document.getElementById('messagesContainer');
        if (container) {
            container.scrollTop = container.scrollHeight;
        }
    },
    
    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();
        }
        return parts[0][0].toUpperCase();
    },
    
    timeAgo(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        if (seconds < 60) return 'Just now';
        if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
        if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
        if (seconds < 604800) return `${Math.floor(seconds / 86400)}d`;
        return date.toLocaleDateString();
    },
    
    formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    
    showError(message) {
        console.error(message);
    },
    
    closeMobileMenus() {
        // Close search container if open
        const searchContainer = document.getElementById('mobile-search-container');
        if (searchContainer && searchContainer.classList.contains('active')) {
            searchContainer.classList.remove('active');
        }
        
        // Close any open offcanvas menus
        const offcanvases = document.querySelectorAll('.offcanvas.show');
        offcanvases.forEach(offcanvas => {
            const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvas);
            if (bsOffcanvas) {
                bsOffcanvas.hide();
            }
        });
        
        // Close any open modals
        const modals = document.querySelectorAll('.modal.show');
        modals.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());
        
        // Ensure mobile conversation list is in correct state
        const conversationList = document.getElementById('conversationList');
        const chatView = document.getElementById('chatView');
        if (conversationList && chatView) {
            // If we're in chat view, keep it open; otherwise ensure conversation list is visible
            if (!chatView.classList.contains('active')) {
                conversationList.classList.add('active');
            }
        }
    }
};

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

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

// New Chat Modal Functions
function showNewChatModal(targetUserId = null) {
    const modal = new bootstrap.Modal(document.getElementById('newChatModal'));
    modal.show();
    loadResearchers(targetUserId);
}

async function loadResearchers(targetUserId = null) {
    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}" ${targetUserId == user.id ? 'selected' : ''}>${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 function sendNewMessage() {
    const researcherId = document.getElementById('researcher-select').value;
    const message = document.getElementById('initial-message').value.trim();
    
    if (!researcherId || !message) {
        alert('Please select a researcher and enter a message');
        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();
            // Remove any remaining modal backdrops
            document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
            document.getElementById('initial-message').value = '';
            MobileChatManager.loadConversations();
            MobileChatManager.closeMobileMenus();
        } else {
            alert(data.message || 'Failed to send message');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to send message');
    }
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Setup send button for new chat modal
document.addEventListener('DOMContentLoaded', () => {
    const sendBtn = document.getElementById('send-new-message-btn');
    if (sendBtn) {
        sendBtn.addEventListener('click', sendNewMessage);
    }
});
</script>
