<div class="main">
    <!-- Flash Messages -->
    <?php if($this->session->flashdata('success')): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                showSuccess('Success!', '<?php echo $this->session->flashdata('success'); ?>');
            });
        </script>
    <?php endif; ?>
    
    <?php if($this->session->flashdata('error')): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                showError('Error!', '<?php echo $this->session->flashdata('error'); ?>');
            });
        </script>
    <?php endif; ?>

    <div class="d-flex justify-content-between align-items-center">
        <p class="fd-3">Messages</p>
        <button class="btn btn-sm bg-black d-block d-lg-none" data-bs-toggle="offcanvas"
            data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
            <img src="<?php echo base_url(); ?>assets/images/icons/message1.png" alt="">
        </button>
    </div>

    <div class="d-block d-lg-none">
        <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasExample"
            aria-labelledby="offcanvasExampleLabel">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title" id="offcanvasExampleLabel">Chats</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">
                <form>
                    <div class="input-group mb-3 search-group">
                        <span class="input-group-text s-group-text" id="basic-addon1">
                            <img src="<?php echo base_url(); ?>assets/images/icons/searchicon.png" alt="">
                        </span>
                        <input type="text" class="form-control search-input" placeholder="search"
                            aria-label="search" aria-describedby="basic-addon1" id="search" name="search">
                    </div>
                </form>
                <div class="row g-3">
                    <?php if(!empty($conversations)): ?>
                        <?php foreach($conversations as $key => $conversation): ?>
                            <div class="col-md-12">
                                <a style="text-decoration: none; color: black;" href="<?php echo base_url(); ?>dashboard/message/<?php echo $key; ?>">
                                    <div class="card m-card <?php echo ($conversationId == $key) ? 'border-primary' : ''; ?>">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start flex-wrap">
                                                <div>
                                                    <div class="d-flex align-items-center gap-2">
                                                        <img class="s-chat-image"
                                                        <?php if(isset($conversation['otherUser']['image']) && $conversation['otherUser']['image']): ?> 
                                                        src="<?php echo $conversation['otherUser']['image']; ?>" 
                                                        <?php else: ?>
                                                        src="<?php echo base_url(); ?>assets/images/rimage2.png" 
                                                        <?php endif; ?>
                                                         alt="">
                                                        <div>
                                                            <p class="fd-7 mb-0">
                                                                <?php echo isset($conversation['otherUser']['userName']) ? $conversation['otherUser']['userName'] : 'User'; ?>
                                                            </p>
                                                            <p class="fd-5 mb-0">
                                                                <?php echo isset($conversation['lastMessage']['content']) ? $conversation['lastMessage']['content'] : 'No messages'; ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <p class="fs-6">
                                                    <?php 
                                                    if(isset($conversation['lastMessage']['timestamp'])) {
                                                        echo date('g:i A', $conversation['lastMessage']['timestamp'] / 1000);
                                                    } else {
                                                        echo 'Now';
                                                    }
                                                    ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-md-12">
                            <div class="text-center py-3">
                                <p class="text-muted">No conversations found</p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>


    <div class="row g-3">
        <div class="col-md-8">
            <?php if(!empty($conversationId)): ?>
                <!-- chat header -->
                <div class="d-flex justify-content-between flex-wrap align-items-center">
                    <div class="d-flex align-items-center gap-2">
                        <?php if(isset($selectedConversation['otherUser'])): ?>
                            <img class="main-chat-image" 
                                 src="<?php echo !empty($selectedConversation['otherUser']['image']) ? $selectedConversation['otherUser']['image'] : base_url().'assets/images/rimage2.png'; ?>" 
                                 alt="">
                            <p class="mb-0 fs-3"><?php echo $selectedConversation['otherUser']['firstName']." ".$selectedConversation['otherUser']['lastName']; ?></p>
                        <?php else: ?>
                            <img class="main-chat-image" src="<?php echo base_url(); ?>assets/images/main_chat.png" alt="">
                            <p class="mb-0 fs-3">Chat User</p>
                        <?php endif; ?>
                    </div>
                    <p class="mb-0 fs-4">
                        <?php if(isset($selectedConversation['otherUser']['isOnline']) && $selectedConversation['otherUser']['isOnline'] == 1){ ?>
                                                        <small class="text-success">● Online</small>
                                                     <?php } else { ?>
                                                        <small class="text-info">● Offline</small>
                                                     <?php } ?>
                    </p>
                </div>
                
                <!-- main chat area -->
                <div class="chat-area" style="height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; margin: 15px 0; border-radius: 8px;">
                    <?php if(!empty($chatlist)): ?>
                        <?php 
                        // Sort messages by timestamp
                        uasort($chatlist, function($a, $b) {
                            return $a['timestamp'] - $b['timestamp'];
                        });
                        ?>
                        
                        <!-- Debug Info (remove after testing) -->
                        <div style="background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 5px; font-size: 12px;">
                            <strong>Debug Info:</strong><br>
                            Current User ID: <?php echo $userId; ?><br>
                            Total Messages: <?php echo count($chatlist); ?>
                        </div>
                        
                    <?php foreach($chatlist as $messageId => $message): ?>
                        <div class="message mb-3 <?php echo ($message['fromID'] == $userId) ? 'text-end' : 'text-start'; ?>" 
                             data-timestamp="<?php echo $message['timestamp']; ?>" 
                             data-message-id="<?php echo $messageId; ?>">
                            <div class="message-bubble d-inline-block p-2 rounded <?php echo ($message['fromID'] == $userId) ? 'bg-primary text-white' : 'bg-light'; ?>" 
                                 style="max-width: 70%;">
                                <p class="mb-1"><?php echo htmlspecialchars($message['content']); ?></p>
                                <small class="<?php echo ($message['fromID'] == $userId) ? 'text-light' : 'text-muted'; ?>">
                                    <?php echo date('g:i A', $message['timestamp'] / 1000); ?>
                                    <?php if($message['fromID'] == $userId): ?>
                                        <span class="message-status ms-1">✓</span>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center text-muted">
                            <p>No messages yet. Start the conversation!</p>
                        </div>
                    <?php endif; ?>
                </div>
                
            <!-- write message -->
            <form id="messageForm" onsubmit="sendMessage(event)">
                <input type="hidden" name="conversationId" value="<?php echo $conversationId; ?>">
                <div class="input-group mb-3 message-group">
                    <input type="text" class="form-control message-input" placeholder="Write Message"
                        aria-label="Username" aria-describedby="basic-addon1" id="messageInput" name="message" required>
                    <span class="input-group-text m-group-text" id="basic-addon1">
                        <button type="submit" class="send-btn" id="sendBtn">
                            <img src="<?php echo base_url(); ?>assets/images/icons/sendIcon.png" alt="" id="sendIcon">
                            <div class="spinner-border spinner-border-sm d-none" role="status" id="sendSpinner">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </button>
                    </span>
                </div>
            </form>
            <?php else: ?>
                <!-- No conversation selected -->
                <div class="no-conversation-selected">
                    <div class="text-center py-5">
                        <div class="empty-state">
                            <img src="<?php echo base_url(); ?>assets/images/icons/message1.png" alt="Messages" class="empty-icon">
                            <h4 class="mt-3 mb-2">No Conversation Selected</h4>
                            <p class="text-muted mb-4">Please select a user from the conversation list to view and send messages.</p>
                            <div class="empty-actions">
                                <button class="btn btn-primary" onclick="showConversationList()">
                                    <i class="fas fa-comments"></i> View Conversations
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="col-md-4 d-none d-lg-block">
            <form>
                <div class="input-group mb-3 search-group">
                    <span class="input-group-text s-group-text" id="basic-addon1">
                        <img src="<?php echo base_url(); ?>assets/images/icons/searchicon.png" alt="">
                    </span>
                    <input type="text" class="form-control search-input" placeholder="search"
                        aria-label="search" aria-describedby="basic-addon1" id="search" name="search">
                </div>
            </form>
            
            <!-- chats -->
         
            <div class="my-chats">
                <div class="row g-3">
                    <?php if(!empty($conversations)): ?>
                        <?php foreach($conversations as $key => $conversation): ?>
                            <div class="col-md-12">
                                <a style="text-decoration: none; color: black;" href="<?php echo base_url(); ?>dashboard/message/<?php echo $key; ?>">
                                    <div class="card m-card <?php echo ($conversationId == $key) ? 'border-primary selected-conversation' : ''; ?>">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start flex-wrap">
                                                <div>
                                                    <div class="d-flex align-items-center gap-2">
                                                        <img class="s-chat-image"
                                                        <?php if(isset($conversation['otherUser']['image']) && $conversation['otherUser']['image']): ?> 
                                                        src="<?php echo $conversation['otherUser']['image']; ?>" 
                                                        <?php else: ?>
                                                        src="<?php echo base_url(); ?>assets/images/rimage2.png" 
                                                        <?php endif; ?>
                                                         alt="">
                                                        <div>
                                                            <p class="fd-7 mb-0">
                                                                <?php echo isset($conversation['otherUser']['firstName']) ? $conversation['otherUser']['firstName']." ".$conversation['otherUser']['lastName'] : 'User'; ?>
                                                            </p>
                                                            <p class="fd-5 mb-0 text-truncate" style="max-width: 150px;">
                                                                <?php echo isset($conversation['lastMessage']['content']) ? $conversation['lastMessage']['content'] : 'No messages'; ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="text-end">
                                                    <p class="fs-6 mb-0">
                                                        <?php 
                                                        if(isset($conversation['lastMessage']['timestamp'])) {
                                                            echo date('g:i A', $conversation['lastMessage']['timestamp'] / 1000);
                                                        } else {
                                                            echo 'Now';
                                                        }
                                                        ?>
                                                    </p>
                                                    <?php if(isset($conversation['otherUser']['isOnline']) && $conversation['otherUser']['isOnline'] == 1): ?>
                                                        <small class="text-success">● Online</small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-md-12">
                            <div class="text-center py-3">
                                <p class="text-muted">No conversations found</p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Empty state styling */
.no-conversation-selected {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 500px;
    background: #f8f9fa;
    border-radius: 15px;
    border: 2px dashed #dee2e6;
}

.empty-state {
    max-width: 400px;
    padding: 40px 20px;
}

.empty-icon {
    width: 80px;
    height: 80px;
    opacity: 0.3;
    filter: grayscale(100%);
}

.empty-state h4 {
    color: #495057;
    font-weight: 600;
}

.empty-state p {
    font-size: 1rem;
    line-height: 1.5;
}

.empty-actions .btn {
    border-radius: 25px;
    padding: 12px 25px;
    font-weight: 600;
    transition: all 0.3s ease;
}

.empty-actions .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,123,255,0.3);
}

/* Message bubble styling */
.message-bubble {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    border-radius: 18px !important;
    word-wrap: break-word;
}

.message-bubble.bg-primary {
    background: linear-gradient(135deg, #007bff, #0056b3) !important;
}

.chat-area {
    background: #f8f9fa;
    border-radius: 12px !important;
    scroll-behavior: smooth;
}

.main-chat-image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #e9ecef;
}

.s-chat-image {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #e9ecef;
}

.card.m-card {
    transition: all 0.3s ease;
    border: 1px solid #e9ecef;
}

.card.m-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.card.m-card.selected-conversation {
    border-color: #007bff !important;
    background-color: #f8f9ff;
    box-shadow: 0 2px 8px rgba(0,123,255,0.2);
}

.card.m-card.border-primary {
    border-width: 2px !important;
}

/* Online status indicator */
.text-success {
    font-weight: 600;
}

/* Message status indicators */
.message-status {
    opacity: 0.8;
    font-size: 0.8em;
}

.message-status.delivered {
    color: #28a745;
}

.message-status.sent {
    color: #6c757d;
}

.message-status.sending {
    color: #ffc107;
}

/* Message animations */
.message {
    transition: all 0.3s ease;
}

.message.sending {
    opacity: 0.7;
}

.message.sending .message-bubble {
    border: 1px dashed #007bff;
}

/* Typing indicator */
.typing-indicator {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    margin: 10px 0;
}

.typing-indicator .typing-dots {
    display: flex;
    align-items: center;
}

.typing-indicator .typing-dots span {
    height: 8px;
    width: 8px;
    background-color: #007bff;
    border-radius: 50%;
    display: inline-block;
    margin: 0 2px;
    animation: typing 1.4s infinite;
}

.typing-indicator .typing-dots span:nth-child(2) {
    animation-delay: 0.2s;
}

.typing-indicator .typing-dots span:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes typing {
    0%, 60%, 100% {
        transform: translateY(0);
        opacity: 0.4;
    }
    30% {
        transform: translateY(-10px);
        opacity: 1;
    }
}

/* Enhanced send button */
.send-btn {
    background: none;
    border: none;
    padding: 8px;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.send-btn:hover {
    background-color: #007bff;
    transform: scale(1.1);
}

.send-btn:hover img {
    filter: brightness(0) invert(1);
}

.send-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

/* Message input enhancements */
.message-input:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Conversation card enhancements */
.card.m-card {
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.card.m-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

.card.m-card:hover::before {
    left: 100%;
}

/* New message notification */
.new-message-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: #007bff;
    color: white;
    padding: 12px 20px;
    border-radius: 25px;
    box-shadow: 0 4px 12px rgba(0,123,255,0.3);
    z-index: 1050;
    transform: translateX(100%);
    transition: transform 0.3s ease;
}

.new-message-notification.show {
    transform: translateX(0);
}

/* Message bubble improvements */
.message-bubble {
    position: relative;
    word-wrap: break-word;
    max-width: 70% !important;
}

.message-bubble::after {
    content: '';
    position: absolute;
    width: 0;
    height: 0;
}

/* Sent message tail */
.text-end .message-bubble.bg-primary::after {
    right: -8px;
    top: 15px;
    border-left: 8px solid #007bff;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
}

/* Received message tail */
.text-start .message-bubble.bg-light::after {
    left: -8px;
    top: 15px;
    border-right: 8px solid #f8f9fa;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
}

/* Mobile responsive */
@media (max-width: 768px) {
    .no-conversation-selected {
        min-height: 300px;
        margin: 20px 0;
    }
    
    .empty-icon {
        width: 60px;
        height: 60px;
    }
    
    .empty-state {
        padding: 30px 15px;
    }
    
    .empty-state h4 {
        font-size: 1.3rem;
    }
    
    .empty-state p {
        font-size: 0.9rem;
    }
}
</style>

<script>
// Real-time chat functionality
let currentConversationId = '<?php echo $conversationId; ?>';
let currentUserId = '<?php echo $userId; ?>';
let lastTimestamp = 0;
let messagePollingInterval;
let isPageVisible = true;

// Initialize chat when page loads
document.addEventListener('DOMContentLoaded', function() {
    if (currentConversationId) {
        initializeChat();
        startMessagePolling();
        setupVisibilityChange();
        
        // Get initial last timestamp from existing messages
        const messages = document.querySelectorAll('.message');
        if (messages.length > 0) {
            const lastMessage = messages[messages.length - 1];
            const timestamp = lastMessage.getAttribute('data-timestamp');
            if (timestamp) {
                lastTimestamp = parseInt(timestamp);
            }
        }
    }
});

// Initialize chat functionality
function initializeChat() {
    const chatArea = document.querySelector('.chat-area');
    if (chatArea) {
        scrollToBottom();
    }
    
    // Add timestamp data attributes to existing messages
    const messages = document.querySelectorAll('.message');
    messages.forEach((message, index) => {
        const timeElement = message.querySelector('small');
        if (timeElement) {
            // Extract timestamp from PHP-generated messages
            const messageData = <?php echo json_encode($chatlist ?? []); ?>;
            const messageArray = Object.values(messageData);
            if (messageArray[index]) {
                message.setAttribute('data-timestamp', messageArray[index].timestamp);
                lastTimestamp = Math.max(lastTimestamp, messageArray[index].timestamp);
            }
        }
    });
}

// Send message via AJAX
function sendMessage(event) {
    event.preventDefault();
    
    const messageInput = document.getElementById('messageInput');
    const messageText = messageInput.value.trim();
    
    if (!messageText) {
        showWarning('Warning', 'Please enter a message');
        return;
    }
    
    // Show loading state
    setLoadingState(true);
    
    // Prepare form data
    const formData = new FormData();
    formData.append('conversationId', currentConversationId);
    formData.append('message', messageText);
    
    // Send AJAX request
    fetch('<?php echo base_url("dashboard/send_message"); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Clear input
            messageInput.value = '';
            
            // Add message to chat immediately with proper isSent flag
            addMessageToChat(data.messageData, true);
            
            // Update last timestamp to prevent re-fetching this message
            lastTimestamp = Math.max(lastTimestamp, data.messageData.timestamp);
            
            // Show success feedback
            showToast('Message sent!', 'success');
            
            // Scroll to bottom
            scrollToBottom();
            
            console.log('Message sent successfully:', data.messageData.id, 'timestamp:', data.messageData.timestamp);
        } else {
            showError('Error', data.message || 'Failed to send message');
        }
    })
    .catch(error => {
        console.error('Error sending message:', error);
        showError('Error', 'Network error. Please try again.');
    })
    .finally(() => {
        setLoadingState(false);
    });
}

// Add message to chat area
function addMessageToChat(messageData, isSent = false) {
    const chatArea = document.querySelector('.chat-area');
    if (!chatArea) return;
    
    // Check if message already exists to prevent duplicates
    const existingMessage = document.querySelector(`[data-message-id="${messageData.id}"]`);
    if (existingMessage) {
        console.log('Message already exists, skipping:', messageData.id);
        return;
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message mb-3 ${isSent ? 'text-end' : 'text-start'}`;
    messageDiv.setAttribute('data-timestamp', messageData.timestamp);
    messageDiv.setAttribute('data-message-id', messageData.id);
    
    const bubbleClass = isSent ? 'bg-primary text-white' : 'bg-light';
    const timeClass = isSent ? 'text-light' : 'text-muted';
    
    messageDiv.innerHTML = `
        <div class="message-bubble d-inline-block p-2 rounded ${bubbleClass}" style="max-width: 70%;">
            <p class="mb-1">${escapeHtml(messageData.content)}</p>
            <small class="${timeClass}">
                ${messageData.formattedTime}
                ${isSent ? '<span class="message-status ms-1">✓</span>' : ''}
            </small>
        </div>
    `;
    
    // Add fade-in animation
    messageDiv.style.opacity = '0';
    messageDiv.style.transform = 'translateY(10px)';
    
    chatArea.appendChild(messageDiv);
    
    // Animate in
    setTimeout(() => {
        messageDiv.style.transition = 'all 0.3s ease';
        messageDiv.style.opacity = '1';
        messageDiv.style.transform = 'translateY(0)';
    }, 10);
    
    console.log('Added message:', messageData.id, 'isSent:', isSent);
}

// Start polling for new messages
function startMessagePolling() {
    if (messagePollingInterval) {
        clearInterval(messagePollingInterval);
    }
    
    messagePollingInterval = setInterval(() => {
        if (isPageVisible && currentConversationId) {
            checkForNewMessages();
        }
    }, 2000); // Poll every 2 seconds
}

// Check for new messages
function checkForNewMessages() {
    const url = `<?php echo base_url("dashboard/get_messages"); ?>?conversationId=${currentConversationId}&lastTimestamp=${lastTimestamp}`;
    
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (data.success && data.messages && data.messages.length > 0) {
            data.messages.forEach(message => {
                // Check if message already exists in the chat
                const existingMessage = document.querySelector(`[data-message-id="${message.id}"]`);
                
                if (!existingMessage) {
                    // Determine if this is a sent or received message
                    const isSent = message.fromID === currentUserId;
                    addMessageToChat(message, isSent);
                    
                    // Show notification only for received messages when page is not visible
                    if (!isSent && !isPageVisible) {
                        showNotification('New message', message.content);
                    }
                }
            });
            
            // Update last timestamp
            if (data.lastTimestamp) {
                lastTimestamp = data.lastTimestamp;
            }
            
            // Scroll to bottom
            scrollToBottom();
        }
    })
    .catch(error => {
        console.error('Error checking for new messages:', error);
    });
}

// Set loading state for send button
function setLoadingState(loading) {
    const sendBtn = document.getElementById('sendBtn');
    const sendIcon = document.getElementById('sendIcon');
    const sendSpinner = document.getElementById('sendSpinner');
    const messageInput = document.getElementById('messageInput');
    
    if (loading) {
        sendBtn.disabled = true;
        messageInput.disabled = true;
        sendIcon.classList.add('d-none');
        sendSpinner.classList.remove('d-none');
    } else {
        sendBtn.disabled = false;
        messageInput.disabled = false;
        sendIcon.classList.remove('d-none');
        sendSpinner.classList.add('d-none');
    }
}

// Scroll to bottom of chat
function scrollToBottom() {
    const chatArea = document.querySelector('.chat-area');
    if (chatArea) {
        setTimeout(() => {
            chatArea.scrollTop = chatArea.scrollHeight;
        }, 100);
    }
}

// Handle page visibility changes
function setupVisibilityChange() {
    document.addEventListener('visibilitychange', function() {
        isPageVisible = !document.hidden;
        
        if (isPageVisible) {
            // Page became visible, check for new messages immediately
            checkForNewMessages();
        }
    });
}

// Show browser notification
function showNotification(title, body) {
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification(title, {
            body: body,
            icon: '<?php echo base_url("assets/images/icons/message1.png"); ?>',
            badge: '<?php echo base_url("assets/images/icons/message1.png"); ?>'
        });
    }
}

// Request notification permission
function requestNotificationPermission() {
    if ('Notification' in window && Notification.permission === 'default') {
        Notification.requestPermission();
    }
}

// Escape HTML to prevent XSS
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Show conversation list for mobile
function showConversationList() {
    const offcanvas = new bootstrap.Offcanvas(document.getElementById('offcanvasExample'));
    offcanvas.show();
}

// Handle Enter key in message input
document.addEventListener('DOMContentLoaded', function() {
    const messageInput = document.getElementById('messageInput');
    if (messageInput) {
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage(e);
            }
        });
    }
    
    // Request notification permission on first interaction
    document.addEventListener('click', requestNotificationPermission, { once: true });
});

// Clean up on page unload
window.addEventListener('beforeunload', function() {
    if (messagePollingInterval) {
        clearInterval(messagePollingInterval);
    }
});
</script>


