<?php
/**
 * Admin live chat template for Ask Any plugin
 *
 * This template displays the live chat management interface with:
 * - Active chat sessions list
 * - Chat conversation view
 * - Agent assignment functionality
 * - Real-time messaging
 *
 * @package Askany
 * @since 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>
<div class="wrap">
	<h1><?php esc_html_e( 'Live Chat Management', 'askany' ); ?></h1>
	
	
	<div class="askany-chat-container">
		<!-- Chat Sessions Sidebar -->
		<div class="askany-chat-sidebar">
			<div class="askany-sidebar-header">
				<h3><?php esc_html_e( 'Active Chats', 'askany' ); ?></h3>
				<button type="button" class="button button-secondary" id="askany-refresh-sessions">
					<?php esc_html_e( 'Refresh', 'askany' ); ?>
				</button>
			</div>
			
			<div class="askany-sessions-list" id="askany-sessions-list">
				<?php if ( empty( $chat_sessions ) ) : ?>
					<div class="askany-no-sessions">
						<p><?php esc_html_e( 'No active chat sessions.', 'askany' ); ?></p>
					</div>
				<?php else : ?>
					<?php 
					$plugin = \Askany\Plugin::get_instance();
					$is_pro = $plugin->is_pro_active();
					$free_limit = 3;
					$session_index = 0;
					
					foreach ( $chat_sessions as $session ) { 
						$session_index++;
						$is_locked = !$is_pro && $session_index > $free_limit;
						$locked_class = $is_locked ? ' askany-locked' : '';
						
						// Get unread message count for this session (only user messages)
						$unread_count = $this->database->get_unread_message_count( $session->session_id, 'user' );
					?>
						<div class="askany-session-item<?php echo esc_attr($locked_class); ?>" data-session-id="<?php echo esc_attr( $session->session_id ); ?>">
							<?php if ( $is_locked ) : ?>
								<span class="askany-pro-badge">
									<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
										<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
									</svg>
									<?php esc_html_e('PRO', 'askany'); ?>
								</span>
							<?php endif; ?>
							
							<div class="askany-session-info">
								<div class="askany-session-user">
									<?php
									$user_name = $session->user_display_name ?: $session->user_name ?: __( 'Anonymous User', 'askany' );
									echo esc_html( $user_name );
									?>
									<?php if ( $unread_count > 0 ) : ?>
										<span class="askany-unread-count"><?php echo esc_html( $unread_count ); ?></span>
									<?php endif; ?>
								</div>
								<div class="askany-session-meta">
									<span class="askany-message-count"><?php echo esc_html( $session->message_count ); ?> <?php esc_html_e( 'messages', 'askany' ); ?></span>
									<span class="askany-session-time">
										<?php
										if ( $session->last_message_time ) {
											echo esc_html( human_time_diff( strtotime( $session->last_message_time ), current_time( 'timestamp' ) ) . ' ago' );
										} else {
											echo esc_html( human_time_diff( strtotime( $session->created_at ), current_time( 'timestamp' ) ) . ' ago' );
										}
										?>
									</span>
								</div>
								<div class="askany-session-status">
									<?php if ( $session->is_ai_handled ) : ?>
										<span class="askany-status-badge ai"><?php esc_html_e( 'AI Handled', 'askany' ); ?></span>
									<?php else : ?>
										<span class="askany-status-badge agent"><?php esc_html_e( 'Agent Assigned', 'askany' ); ?></span>
									<?php endif; ?>
								</div>
							</div>
							<div class="askany-session-actions">
								<button type="button" class="askany-action-btn askany-clear-history-btn" title="<?php esc_attr_e('Clear Chat History', 'askany'); ?>">
									<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
										<path d="M3 6h18"></path>
										<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
										<path d="M8 6V4c0-1 1-2 2-2h4c0 1 1 2 2 2v2"></path>
										<line x1="10" y1="11" x2="10" y2="17"></line>
										<line x1="14" y1="11" x2="14" y2="17"></line>
									</svg>
								</button>
								<button type="button" class="askany-action-btn askany-delete-session-btn" title="<?php esc_attr_e('Delete User Session', 'askany'); ?>">
									<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
										<circle cx="12" cy="12" r="10"></circle>
										<line x1="15" y1="9" x2="9" y2="15"></line>
										<line x1="9" y1="9" x2="15" y2="15"></line>
									</svg>
								</button>
							</div>
						</div>
					<?php } ?>
				<?php endif; ?>
			</div>
		</div>

		<!-- Chat Conversation Area -->
		<div class="askany-chat-main">
			<div class="askany-chat-header" id="askany-chat-header" style="display: none;">
				<div class="askany-chat-user-info">
					<h3 id="askany-current-user-name"></h3>
					<div class="askany-chat-controls">
						<select id="askany-agent-select">
							<option value=""><?php esc_html_e( 'AI Handling', 'askany' ); ?></option>
							<?php foreach ( $agents as $agent ) { ?>
								<option value="<?php echo esc_attr( $agent->user_id ); ?>">
									<?php echo esc_html( $agent->display_name ); ?>
								</option>
							<?php } ?>
						</select>
						<button type="button" class="button button-primary" id="askany-assign-agent">
							<?php esc_html_e( 'Assign Agent', 'askany' ); ?>
						</button>
						<button type="button" class="button button-secondary" id="askany-release-agent" style="display: none;">
							<?php esc_html_e( 'Release to AI', 'askany' ); ?>
						</button>
					</div>
				</div>
			</div>

			<div class="askany-chat-messages" id="askany-chat-messages">
				<div class="askany-no-chat-selected">
					<p><?php esc_html_e( 'Select a chat session to view the conversation.', 'askany' ); ?></p>
				</div>
			</div>

			<div class="askany-chat-input" id="askany-chat-input" style="display: none;">
				<div class="askany-input-container">
					<textarea id="askany-message-input" placeholder="<?php esc_attr_e( 'Type your message... (Markdown supported)', 'askany' ); ?>" rows="4"></textarea>
					<button type="button" class="askany-send-btn" id="askany-send-message" title="<?php esc_attr_e( 'Send message', 'askany' ); ?>">
						<svg width="20" height="20" viewBox="0 0 384 512" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path d="M214.6 41.4c-12.5-12.5-32.8-12.5-45.3 0l-160 160c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L160 141.2 160 448c0 17.7 14.3 32 32 32s32-14.3 32-32l0-306.7L329.4 246.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3l-160-160z" fill="currentColor"/>
						</svg>
					</button>
				</div>
			</div>
		</div>
	</div>

	<!-- Database Statistics -->
	<div class="askany-stats-container">
		<div class="askany-stats-grid">
			<div class="askany-stat-card">
				<div class="askany-stat-icon">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
						<circle cx="9" cy="7" r="4"></circle>
						<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
						<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
					</svg>
				</div>
				<div class="askany-stat-content">
					<div class="askany-stat-number" id="total-sessions"><?php echo esc_html( $stats['total_sessions'] ?? 0 ); ?></div>
					<div class="askany-stat-label"><?php esc_html_e( 'Total Sessions', 'askany' ); ?></div>
				</div>
			</div>
			
			<div class="askany-stat-card">
				<div class="askany-stat-icon active">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="10"></circle>
						<polyline points="12,6 12,12 16,14"></polyline>
					</svg>
				</div>
				<div class="askany-stat-content">
					<div class="askany-stat-number" id="active-sessions"><?php echo esc_html( $stats['active_sessions'] ?? 0 ); ?></div>
					<div class="askany-stat-label"><?php esc_html_e( 'Active (24h)', 'askany' ); ?></div>
				</div>
			</div>
			
			<div class="askany-stat-card">
				<div class="askany-stat-icon">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
						<line x1="9" y1="10" x2="15" y2="10"></line>
						<line x1="9" y1="14" x2="15" y2="14"></line>
					</svg>
				</div>
				<div class="askany-stat-content">
					<div class="askany-stat-number" id="total-messages"><?php echo esc_html( $stats['total_messages'] ?? 0 ); ?></div>
					<div class="askany-stat-label"><?php esc_html_e( 'Total Messages', 'askany' ); ?></div>
				</div>
			</div>
			
			<div class="askany-stat-card">
				<div class="askany-stat-icon ai">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="3"></circle>
						<path d="M12 1v6m0 6v6m11-7h-6m-6 0H1m15.5-6.5l-4.24 4.24M7.76 16.24l-4.24 4.24m12.73 0l-4.24-4.24M7.76 7.76L3.52 3.52"></path>
					</svg>
				</div>
				<div class="askany-stat-content">
					<div class="askany-stat-number" id="ai-sessions"><?php echo esc_html( $stats['ai_sessions'] ?? 0 ); ?></div>
					<div class="askany-stat-label"><?php esc_html_e( 'AI Handled', 'askany' ); ?></div>
				</div>
			</div>
			
			<div class="askany-stat-card">
				<div class="askany-stat-icon agent">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
						<circle cx="12" cy="7" r="4"></circle>
					</svg>
				</div>
				<div class="askany-stat-content">
					<div class="askany-stat-number" id="agent-sessions"><?php echo esc_html( $stats['agent_sessions'] ?? 0 ); ?></div>
					<div class="askany-stat-label"><?php esc_html_e( 'Agent Handled', 'askany' ); ?></div>
				</div>
			</div>
		</div>
	</div>
	

</div>

<script>
jQuery(document).ready(function($) {
	var currentSessionId = null;
	var messagePolling = null;
	var sessionPolling = null;
	var currentUserId = <?php echo esc_js( $current_user_id ); ?>;
	var lastMessageTime = null;
	var isTyping = false;
	var typingTimeout = null;
	var displayedMessageIds = new Set(); // Track displayed messages globally
	
	// Pro status and limits
	var isPro = <?php echo $is_pro ? 'true' : 'false'; ?>;
	var freeLimit = 3;

	// Initialize Markdown Editor for Live Chat Message Input
	var liveChatEditor = null;
	
	function initLiveChatMarkdownEditor() {
		if (liveChatEditor) {
			liveChatEditor.destroy();
		}
		liveChatEditor = new AskanyMarkdownEditor('askany-message-input', {
			showPreview: false,
			showTabs: false,
			compact: true,
			height: '80px',
			placeholder: 'Type your message... (Markdown supported)\n**Bold** *Italic* [Link](url)'
		});
	}
	
	// Initialize editor when chat input is shown
	function initEditorWhenReady() {
		if (typeof AskanyMarkdownEditor !== 'undefined') {
			setTimeout(function() {
				if ($('#askany-message-input').length) {
					initLiveChatMarkdownEditor();
				}
			}, 500);
		}
	}
	
	// Call init after page load
	initEditorWhenReady();
	
	// Session selection
	$(document).on('click', '.askany-session-item', function(e) {
		// Check if session is locked (Pro feature)
		if ($(this).hasClass('askany-locked')) {
			e.preventDefault();
			e.stopPropagation();
			// Open Pro upgrade modal
			if (typeof AskanyPro !== 'undefined') {
				AskanyPro.openModal();
			}
			return;
		}
		
		// Don't trigger session selection if clicking on action buttons
		if ($(e.target).closest('.askany-session-actions').length > 0) {
			return;
		}
		
		var sessionId = $(this).data('session-id');
		selectSession(sessionId);
	});
	
	// Clear chat history
	$(document).on('click', '.askany-clear-history-btn', function(e) {
		e.stopPropagation();
		var sessionId = $(this).closest('.askany-session-item').data('session-id');
		var userName = $(this).closest('.askany-session-item').find('.askany-session-user').text();
		
		Toast.ask('Clear Chat History', '<?php esc_html_e( 'Are you sure you want to clear the chat history for', 'askany' ); ?> "' + userName + '"? <?php esc_html_e( 'This will delete all messages but keep the session.', 'askany' ); ?>')
			.then(result => {
				if (result.ok) {
					clearChatHistory(sessionId);
				}
			});
	});
	
	// Delete user session
	$(document).on('click', '.askany-delete-session-btn', function(e) {
		e.stopPropagation();
		var sessionId = $(this).closest('.askany-session-item').data('session-id');
		var userName = $(this).closest('.askany-session-item').find('.askany-session-user').text();
		
		Toast.ask('Delete User Session', '<?php esc_html_e( 'Are you sure you want to delete the entire session for', 'askany' ); ?> "' + userName + '"? <?php esc_html_e( 'This will permanently delete the user and all their messages. This action cannot be undone.', 'askany' ); ?>')
			.then(result => {
				if (result.ok) {
					deleteUserSession(sessionId);
				}
			});
	});
	
	// Refresh sessions
	$('#askany-refresh-sessions').on('click', function() {
		refreshSessions();
	});
	
	// Assign agent
	$('#askany-assign-agent').on('click', function() {
		window.lastAgentInteraction = Date.now();
		var agentId = $('#askany-agent-select').val();
		if (!currentSessionId) return;
		
		assignAgent(currentSessionId, agentId);
	});
	
	// Release agent
	$('#askany-release-agent').on('click', function() {
		window.lastAgentInteraction = Date.now();
		if (!currentSessionId) return;
		releaseAgent(currentSessionId);
	});
	
	// Send message
	$('#askany-send-message').on('click', function() {
		sendMessage();
	});
	
	// Send message on Enter (Shift+Enter for new line)
	$('#askany-message-input').on('keydown', function(e) {
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			sendMessage();
		}
	});
	
	// Real-time typing indicators
	$('#askany-message-input').on('input', function() {
		handleTyping();
	});
	
	$('#askany-message-input').on('blur', function() {
		stopTyping();
	});
	
	// Track agent dropdown interactions
	$('#askany-agent-select').on('focus change', function() {
		window.lastAgentInteraction = Date.now();
	});
	
	// Start session polling for real-time updates
	startSessionPolling();
	
	// Update menu badge on page load
	updateMenuBadge();
	
	function selectSession(sessionId) {
		console.log('Selecting session:', sessionId);
		currentSessionId = sessionId;
		lastMessageTime = null;
		
		// Reset displayed messages tracking for new session
		displayedMessageIds.clear();
		
		// Clear existing messages in the container
		$('#askany-chat-messages').empty();
		
		// Mark messages as read when admin views the session
		console.log('Marking session as read...');
		markSessionAsRead(sessionId);
		
		// Update UI
		$('.askany-session-item').removeClass('active');
		$('.askany-session-item[data-session-id="' + sessionId + '"]').addClass('active');
		
		// Remove unread count badge from selected session immediately
		var $sessionItem = $('.askany-session-item[data-session-id="' + sessionId + '"]');
		var $unreadBadge = $sessionItem.find('.askany-unread-count');
		if ($unreadBadge.length > 0) {
			console.log('Removing unread badge from session');
			$unreadBadge.remove();
		}
		
		// Show chat interface
		$('#askany-chat-header').show();
		$('#askany-chat-input').show();
		
		// Load initial messages
		loadMessages(sessionId);
		
		// Start polling for new messages and typing indicators (clear any existing interval first)
		if (messagePolling) {
			clearInterval(messagePolling);
		}
		messagePolling = setInterval(function() {
			pollForUpdates();
		}, 2000);
		
		// Update menu badge count
		setTimeout(function() {
			console.log('Updating menu badge after session selection...');
			updateMenuBadge();
		}, 1000);
	}
	
	function loadMessages(sessionId) {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_get_chat_messages',
				session_id: sessionId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					displayMessages(response.data.messages);
					updateSessionInfo(response.data.session);
				}
			}
		});
	}
	
	function displayMessages(messages) {
		var messagesContainer = $('#askany-chat-messages');
		
		if (messages.length === 0) {
			if (messagesContainer.find('.askany-message').length === 0) {
				messagesContainer.html('<div class="askany-no-messages"><p><?php esc_html_e( 'No messages yet.', 'askany' ); ?></p></div>');
			}
			return;
		}
		
		// Remove "no messages" placeholder if it exists
		messagesContainer.find('.askany-no-messages').remove();
		
		// Check if user cleared chat from browser or admin cleared it
		var userClearedKey = 'askany_chat_cleared_' + currentSessionId;
		var adminClearedKey = 'askany_admin_cleared_' + currentSessionId;
		var userClearedData = localStorage.getItem(userClearedKey);
		var adminClearedTime = localStorage.getItem(adminClearedKey);
		var lastClearedMessageId = 0;
		
		if (userClearedData) {
			try {
				var clearedInfo = JSON.parse(userClearedData);
				lastClearedMessageId = clearedInfo.lastMessageId || 0;
			} catch (e) {
				console.log('Could not parse cleared data');
			}
		}
		
		var hasNewMessages = false;
		var shouldScroll = false;
		
		// Check if user is scrolled to bottom before adding messages
		var isScrolledToBottom = messagesContainer[0].scrollHeight - messagesContainer.scrollTop() <= messagesContainer.outerHeight() + 50;
		
		messages.forEach(function(message, index) {
			// Only add messages that haven't been displayed yet
			if (!displayedMessageIds.has(message.id)) {
				displayedMessageIds.add(message.id);
				hasNewMessages = true;
				
				var senderClass = message.sender_type;
				var senderName = message.sender_name || message.sender_type.toUpperCase();
				
				var avatarHtml = getMessageAvatar(message);
				var messageHtml = '<div class="askany-message ' + senderClass + '" data-message-id="' + message.id + '">';
				messageHtml += avatarHtml;
				messageHtml += '<div class="askany-message-bubble">';
				messageHtml += '<div class="askany-message-content">' + formatMessageContent(message) + '</div>';
				messageHtml += '<div class="askany-message-meta">' + senderName + ' • ' + formatTime(message.created_at) + '</div>';
				messageHtml += '</div>';
				messageHtml += '</div>';
				
				// Append new message
				messagesContainer.append(messageHtml);
				
				// Show clear notice AFTER the message where user cleared (if this is the cleared message)
				if (userClearedData && message.id === lastClearedMessageId) {
					var clearNoticeHtml = '<div class="askany-system-notice askany-clear-notice">' +
						'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
						'<circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line>' +
						'</svg>' +
						'<span><?php esc_html_e( 'User cleared chat history from their browser', 'askany' ); ?></span>' +
						'</div>';
					messagesContainer.append(clearNoticeHtml);
				}
				
				// Show notice if admin cleared chat
				if (adminClearedTime && index === messages.length - 1) {
					var adminClearNoticeHtml = '<div class="askany-system-notice askany-admin-clear-notice">' +
						'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
						'<circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line>' +
						'</svg>' +
						'<span><?php esc_html_e( 'Admin cleared chat history', 'askany' ); ?></span>' +
						'</div>';
					messagesContainer.append(adminClearNoticeHtml);
				}
				
				shouldScroll = true;
			}
		});
		
		// Only scroll if user was already at bottom or if there are new messages
		if (shouldScroll && (isScrolledToBottom || hasNewMessages)) {
			messagesContainer.scrollTop(messagesContainer[0].scrollHeight);
		}
	}
	
	function displayNewMessages(messages) {
		// This function adds new messages without updating session info
		// Used when we want to preserve agent dropdown state
		var messagesContainer = $('#askany-chat-messages');
		
		if (!messages || messages.length === 0) {
			return;
		}
		
		// Remove "no messages" placeholder if it exists
		messagesContainer.find('.askany-no-messages').remove();
		
		var hasNewMessages = false;
		var shouldScroll = false;
		
		// Check if user is scrolled to bottom before adding messages
		var isScrolledToBottom = messagesContainer[0].scrollHeight - messagesContainer.scrollTop() <= messagesContainer.outerHeight() + 50;
		
		messages.forEach(function(message) {
			// Only add messages that haven't been displayed yet
			if (!displayedMessageIds.has(message.id)) {
				displayedMessageIds.add(message.id);
				hasNewMessages = true;
				
				var senderClass = message.sender_type;
				var senderName = message.sender_name || message.sender_type.toUpperCase();
				
				var avatarHtml = getMessageAvatar(message);
				var messageHtml = '<div class="askany-message ' + senderClass + '" data-message-id="' + message.id + '">';
				messageHtml += avatarHtml;
				messageHtml += '<div class="askany-message-bubble">';
				messageHtml += '<div class="askany-message-content">' + formatMessageContent(message) + '</div>';
				messageHtml += '<div class="askany-message-meta">' + senderName + ' • ' + formatTime(message.created_at) + '</div>';
				messageHtml += '</div>';
				messageHtml += '</div>';
				
				// Append new message
				messagesContainer.append(messageHtml);
				shouldScroll = true;
			}
		});
		
		// Only scroll if user was already at bottom or if there are new messages
		if (shouldScroll && (isScrolledToBottom || hasNewMessages)) {
			messagesContainer.scrollTop(messagesContainer[0].scrollHeight);
		}
	}
	
	function updateSessionInfo(session) {
		if (!session) return;
		
		var userName = session.user_display_name || session.user_name || '<?php esc_html_e( 'Anonymous User', 'askany' ); ?>';
		$('#askany-current-user-name').text(userName);
		
		// Enhanced protection against dropdown resets
		var $agentSelect = $('#askany-agent-select');
		var $assignButton = $('#askany-assign-agent');
		var $releaseButton = $('#askany-release-agent');
		
		// Check if user is actively interacting with agent controls
		var isDropdownFocused = $agentSelect.is(':focus') || 
								$agentSelect.hasClass('select2-hidden-accessible') && $('.select2-dropdown').is(':visible');
		var isButtonClicked = $assignButton.is(':active') || $releaseButton.is(':active');
		var hasRecentInteraction = (Date.now() - (window.lastAgentInteraction || 0)) < 3000; // 3 seconds
		
		// Don't update if user is actively working with agent controls
		if (isDropdownFocused || isButtonClicked || hasRecentInteraction) {
			return;
		}
		
		// Only update if the actual session state has changed
		var currentAgentId = $agentSelect.val();
		var sessionAgentId = session.agent_id ? session.agent_id.toString() : '';
		var sessionIsAiHandled = session.is_ai_handled == '1';
		
		// Check if we need to update based on actual state changes
		var needsUpdate = false;
		
		if (sessionIsAiHandled && currentAgentId !== '') {
			// Session is AI handled but dropdown shows an agent
			needsUpdate = true;
		} else if (!sessionIsAiHandled && currentAgentId !== sessionAgentId) {
			// Session has agent but dropdown shows different agent
			needsUpdate = true;
		}
		
		if (needsUpdate) {
			// Update agent controls only when necessary
			if (sessionIsAiHandled) {
				$agentSelect.val('');
				$assignButton.show();
				$releaseButton.hide();
			} else {
				$agentSelect.val(sessionAgentId);
				$assignButton.show();
				$releaseButton.show();
			}
		}
	}
	
	function assignAgent(sessionId, agentId) {
		// Extend interaction protection during assignment
		window.lastAgentInteraction = Date.now();
		
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_assign_agent',
				session_id: sessionId,
				agent_id: agentId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					// Extend protection after successful assignment
					window.lastAgentInteraction = Date.now();
					Toast.success('<?php esc_html_e( 'Agent assigned successfully!', 'askany' ); ?>');
					loadMessages(sessionId);
				} else {
					Toast.error(response.data.message || '<?php esc_html_e( 'Error assigning agent', 'askany' ); ?>');
				}
			},
			error: function() {
				Toast.error('<?php esc_html_e( 'Error assigning agent', 'askany' ); ?>');
			}
		});
	}
	
	function releaseAgent(sessionId) {
		// Extend interaction protection during release
		window.lastAgentInteraction = Date.now();
		
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_release_agent',
				session_id: sessionId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					// Extend protection after successful release
					window.lastAgentInteraction = Date.now();
					Toast.success('<?php esc_html_e( 'Agent released successfully!', 'askany' ); ?>');
					loadMessages(sessionId);
				} else {
					Toast.error(response.data.message || '<?php esc_html_e( 'Error releasing agent', 'askany' ); ?>');
				}
			},
			error: function() {
				Toast.error('<?php esc_html_e( 'Error releasing agent', 'askany' ); ?>');
			}
		});
	}
	
	function sendMessage() {
		var message = $('#askany-message-input').val().trim();
		if (!message || !currentSessionId) return;
		
		$('#askany-send-message').prop('disabled', true);
		
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_send_agent_message',
				session_id: currentSessionId,
				message: message,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					$('#askany-message-input').val('');
					// Only reload messages, don't refresh sessions to prevent duplicates
					loadMessages(currentSessionId);
				} else {
					Toast.error(response.data.message || '<?php esc_html_e( 'Error sending message', 'askany' ); ?>');
				}
			},
			complete: function() {
				$('#askany-send-message').prop('disabled', false);
			}
		});
	}
	
	function refreshSessions() {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_get_chat_sessions',
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					updateSessionsWithUnreadCounts(response.data.sessions);
					// Also update menu badge when refreshing sessions
					updateMenuBadge();
				}
			}
		});
	}
	
	function updateSessionsList(sessions) {
		// Use the new function that handles unread counts
		updateSessionsWithUnreadCounts(sessions);
	}
	
	function escapeHtml(text) {
		var map = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		};
		return text.replace(/[&<>"']/g, function(m) { return map[m]; });
	}
	
	function formatMessageContent(message) {
		// Parse markdown for agent and AI messages, escape HTML for user messages
		if ((message.sender_type === 'agent' || message.sender_type === 'ai') && typeof AskanyMarkdown !== 'undefined' && AskanyMarkdown.parse) {
			return AskanyMarkdown.parse(message.message);
		}
		return escapeHtml(message.message);
	}
	
	function formatTime(timestamp) {
		var date = new Date(timestamp);
		return date.toLocaleTimeString();
	}
	
	/**
	 * Get avatar HTML for admin chat messages
	 */
	function getMessageAvatar(message) {
		var avatarHtml = '';
		
		if (message.sender_type === 'user') {
			// User avatar
			if (message.avatar_url) {
				// Logged-in user - use WordPress avatar URL from backend
				avatarHtml = '<div class="message-avatar"><img src="' + message.avatar_url + '" alt="User" class="avatar-image" /></div>';
			} else {
				// Guest user - default icon
				avatarHtml = '<div class="message-avatar"><div class="avatar-icon user-icon">';
				avatarHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
				avatarHtml += '<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>';
				avatarHtml += '<circle cx="12" cy="7" r="4"></circle>';
				avatarHtml += '</svg>';
				avatarHtml += '</div></div>';
			}
		} else if (message.sender_type === 'agent') {
			// Agent avatar
			if (message.avatar_url) {
				// Agent - use WordPress avatar URL from backend
				avatarHtml = '<div class="message-avatar"><img src="' + message.avatar_url + '" alt="Agent" class="avatar-image" /></div>';
			} else {
				// Default agent icon
				avatarHtml = '<div class="message-avatar"><div class="avatar-icon agent-icon">';
				avatarHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
				avatarHtml += '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>';
				avatarHtml += '<circle cx="9" cy="7" r="4"></circle>';
				avatarHtml += '<path d="M22 21v-2a4 4 0 0 0-3-3.87"></path>';
				avatarHtml += '<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>';
				avatarHtml += '</svg>';
				avatarHtml += '</div></div>';
			}
		} else {
			// AI assistant avatar
			if (message.avatar_url) {
				// Custom AI avatar from backend
				avatarHtml = '<div class="message-avatar"><img src="' + message.avatar_url + '" alt="AI" class="avatar-image" /></div>';
			} else {
				// Default AI icon
				avatarHtml = '<div class="message-avatar"><div class="avatar-icon assistant-icon">';
				avatarHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
				avatarHtml += '<path d="M12 8V4H8"></path>';
				avatarHtml += '<rect width="16" height="12" x="4" y="8" rx="2"></rect>';
				avatarHtml += '<path d="M2 14h2"></path>';
				avatarHtml += '<path d="M20 14h2"></path>';
				avatarHtml += '<path d="M15 13v2"></path>';
				avatarHtml += '<path d="M9 13v2"></path>';
				avatarHtml += '</svg>';
				avatarHtml += '</div></div>';
			}
		}
		
		return avatarHtml;
	}
	
	// ===== REAL-TIME FUNCTIONALITY =====
	
	/**
	 * Start session polling for real-time updates
	 */
	function startSessionPolling() {
		if (sessionPolling) {
			clearInterval(sessionPolling);
		}
		
		// Poll every 5 seconds for session updates
		sessionPolling = setInterval(function() {
			refreshSessions();
		}, 5000);
		
		// Poll every 2 seconds for typing indicators and new messages
		if (messagePolling) {
			clearInterval(messagePolling);
		}
		
		messagePolling = setInterval(function() {
			if (currentSessionId) {
				pollForUpdates();
			}
		}, 2000);
	}
	
	/**
	 * Poll for real-time updates (messages and typing indicators)
	 */
	function pollForUpdates() {
		if (!currentSessionId) return;
		
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_get_realtime_updates',
				session_id: currentSessionId,
				last_message_time: lastMessageTime,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success && response.data) {
					// Handle new messages
					if (response.data.messages && response.data.messages.length > 0) {
						var hasNewUserMessages = false;
						response.data.messages.forEach(function(message) {
							if (message.sender_type === 'user') {
								hasNewUserMessages = true;
							}
						});
						
						if (hasNewUserMessages) {
							// Only reload messages if we haven't done agent interaction recently
							var timeSinceInteraction = Date.now() - (window.lastAgentInteraction || 0);
							if (timeSinceInteraction > 5000) { // 5 seconds
								loadMessages(currentSessionId);
							} else {
								// Add messages directly without updating session info to preserve agent dropdown
								displayNewMessages(response.data.messages);
							}
						}
					}
					
					// Handle typing indicators
					if (response.data.typing_indicators) {
						handleTypingIndicators(response.data.typing_indicators);
					}
				}
			}
		});
	}
	
	/**
	 * Handle typing indicators from users
	 */
	function handleTypingIndicators(indicators) {
		// Remove existing typing indicators
		$('.admin-typing-indicator').remove();
		
		// Show typing indicators for users (not agents)
		if (indicators && indicators.length > 0) {
			indicators.forEach(function(indicator) {
				if (indicator.is_typing && indicator.user_type === 'user') {
					showUserTypingIndicator(indicator);
				}
			});
		}
	}
	
	/**
	 * Show user typing indicator in admin interface
	 */
	function showUserTypingIndicator(indicator) {
		var typingName = indicator.user_name || 'User';
		var $indicator = $(
			'<div class="askany-message admin-typing-indicator">' +
			'<div class="askany-message-bubble">' +
			'<div class="typing-indicator-content">' +
			'<span class="typing-text">💬 ' + typingName + ' is typing...</span>' +
			'<div class="typing-dots">' +
			'<span class="typing-dot"></span>' +
			'<span class="typing-dot"></span>' +
			'<span class="typing-dot"></span>' +
			'</div>' +
			'</div>' +
			'</div>' +
			'</div>'
		);
		
		$('#askany-chat-messages').append($indicator);
		$('#askany-chat-messages').scrollTop($('#askany-chat-messages')[0].scrollHeight);
	}
	
	/**
	 * Handle typing indicator
	 */
	function handleTyping() {
		if (!currentSessionId) return;
		
		if (!isTyping) {
			isTyping = true;
			sendTypingIndicator(true);
		}
		
		// Clear existing timeout
		if (typingTimeout) {
			clearTimeout(typingTimeout);
		}
		
		// Set new timeout to stop typing after 3 seconds of inactivity
		typingTimeout = setTimeout(function() {
			stopTyping();
		}, 3000);
	}
	
	/**
	 * Stop typing indicator
	 */
	function stopTyping() {
		if (!currentSessionId) return;
		
		if (isTyping) {
			isTyping = false;
			sendTypingIndicator(false);
		}
		
		if (typingTimeout) {
			clearTimeout(typingTimeout);
			typingTimeout = null;
		}
	}
	
	/**
	 * Send typing indicator to server
	 */
	function sendTypingIndicator(typing) {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_set_typing',
				session_id: currentSessionId,
				is_typing: typing ? '1' : '0',
				user_type: 'agent',
				nonce: askanyAdmin.nonce
			}
		});
	}
	
	// Clear chat history function
	function clearChatHistory(sessionId) {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_clear_chat_history',
				session_id: sessionId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					Toast.success('<?php esc_html_e( 'Chat history cleared successfully!', 'askany' ); ?>');
					
					// Set localStorage flag to clear user's browser chat on next visit
					localStorage.setItem('askany_admin_cleared_' + sessionId, new Date().toISOString());
					
					// Refresh the current session if it's the one we cleared
					if (currentSessionId === sessionId) {
						loadMessages(sessionId);
					}
					
					// Refresh sessions list to update message count
					refreshSessions();
				} else {
					Toast.error(response.data.message || '<?php esc_html_e( 'Error clearing chat history.', 'askany' ); ?>');
				}
			},
			error: function() {
				Toast.error('<?php esc_html_e( 'Error clearing chat history.', 'askany' ); ?>');
			}
		});
	}
	
	// Delete user session function
	function deleteUserSession(sessionId) {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_delete_user_session',
				session_id: sessionId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					Toast.success('<?php esc_html_e( 'User session deleted successfully!', 'askany' ); ?>');
					
					// If the deleted session was currently selected, clear the chat area
					if (currentSessionId === sessionId) {
						currentSessionId = null;
						$('#askany-chat-header').hide();
						$('#askany-chat-input').hide();
						$('#askany-chat-messages').html('<div class="askany-no-chat-selected"><p><?php esc_html_e( 'Select a chat session to view the conversation.', 'askany' ); ?></p></div>');
						
						// Clear polling
						if (messagePolling) {
							clearInterval(messagePolling);
							messagePolling = null;
						}
					}
					
					// Remove the session from the list
					$('.askany-session-item[data-session-id="' + sessionId + '"]').remove();
					
					// Refresh sessions list
					refreshSessions();
				} else {
					Toast.error(response.data.message || '<?php esc_html_e( 'Error deleting user session.', 'askany' ); ?>');
				}
			},
			error: function() {
				Toast.error('<?php esc_html_e( 'Error deleting user session.', 'askany' ); ?>');
			}
		});
	}
	
	/**
	 * Mark session messages as read
	 */
	function markSessionAsRead(sessionId) {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_mark_session_read',
				session_id: sessionId,
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					// Update was successful
					console.log('Session marked as read');
					
					// Remove unread badge from this session immediately
					$('.askany-session-item[data-session-id="' + sessionId + '"] .askany-unread-count').remove();
					
					// Update menu badge count after a short delay to ensure database is updated
					setTimeout(function() {
						updateMenuBadge();
					}, 500);
				} else {
					console.error('Failed to mark session as read:', response.data.message);
				}
			},
			error: function(xhr, status, error) {
				console.error('AJAX error marking session as read:', error);
			}
		});
	}
	
	/**
	 * Update menu badge with total unread count
	 */
	function updateMenuBadge() {
		$.ajax({
			url: askanyAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'askany_get_unread_count',
				nonce: askanyAdmin.nonce
			},
			success: function(response) {
				if (response.success) {
					var unreadCount = response.data.unread_count;
					
					// Find the menu item - try multiple selectors to ensure we find it
					var menuItem = $('a[href="admin.php?page=askany-live-chat"]');
					if (menuItem.length === 0) {
						menuItem = $('a[href*="askany-live-chat"]');
					}
					
					// Remove existing badge
					menuItem.find('.askany-unread-badge').remove();
					
					// Add new badge if there are unread messages
					if (unreadCount > 0) {
						menuItem.append(' <span class="askany-unread-badge">' + unreadCount + '</span>');
					}
					
					console.log('Menu badge updated. Unread count:', unreadCount);
				} else {
					console.error('Failed to get unread count:', response.data ? response.data.message : 'Unknown error');
				}
			},
			error: function(xhr, status, error) {
				console.error('AJAX error getting unread count:', error);
			}
		});
	}
	
	/**
	 * Update session list with unread counts
	 */
	function updateSessionsWithUnreadCounts(sessions) {
		var sessionsHtml = '';
		
		if (sessions.length === 0) {
			sessionsHtml = '<div class="askany-no-sessions"><p><?php esc_html_e( 'No active chat sessions.', 'askany' ); ?></p></div>';
		} else {
			var sessionIndex = 0;
			sessions.forEach(function(session) {
				sessionIndex++;
				var isLocked = !isPro && sessionIndex > freeLimit;
				
				var userName = session.user_display_name || session.user_name || '<?php esc_html_e( 'Anonymous User', 'askany' ); ?>';
				var statusClass = session.is_ai_handled == '1' ? 'ai' : 'agent';
				var statusText = session.is_ai_handled == '1' ? '<?php esc_html_e( 'AI Handled', 'askany' ); ?>' : '<?php esc_html_e( 'Agent Assigned', 'askany' ); ?>';
				var activeClass = session.session_id === currentSessionId ? 'active' : '';
				var lockedClass = isLocked ? ' askany-locked' : '';
				var unreadCount = session.unread_count || 0;
				
				sessionsHtml += '<div class="askany-session-item ' + activeClass + lockedClass + '" data-session-id="' + session.session_id + '">';
				
				// Add Pro badge if locked
				if (isLocked) {
					sessionsHtml += '<span class="askany-pro-badge">';
					sessionsHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="currentColor">';
					sessionsHtml += '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>';
					sessionsHtml += '</svg>';
					sessionsHtml += '<?php esc_html_e('PRO', 'askany'); ?>';
					sessionsHtml += '</span>';
				}
				
				sessionsHtml += '<div class="askany-session-info">';
				sessionsHtml += '<div class="askany-session-user">' + escapeHtml(userName);
				
				// Add unread count badge if there are unread messages
				if (unreadCount > 0) {
					sessionsHtml += ' <span class="askany-unread-count">' + unreadCount + '</span>';
				}
				
				sessionsHtml += '</div>';
				sessionsHtml += '<div class="askany-session-meta">';
				sessionsHtml += '<span class="askany-message-count">' + session.message_count + ' <?php esc_html_e( 'messages', 'askany' ); ?></span>';
				sessionsHtml += '</div>';
				sessionsHtml += '<div class="askany-session-status">';
				sessionsHtml += '<span class="askany-status-badge ' + statusClass + '">' + statusText + '</span>';
				sessionsHtml += '</div>';
				sessionsHtml += '</div>';
				sessionsHtml += '<div class="askany-session-actions">';
				sessionsHtml += '<button type="button" class="askany-action-btn askany-clear-history-btn" title="<?php esc_attr_e('Clear Chat History', 'askany'); ?>">';
				sessionsHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
				sessionsHtml += '<path d="M3 6h18"></path>';
				sessionsHtml += '<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>';
				sessionsHtml += '<path d="M8 6V4c0-1 1-2 2-2h4c0 1 1 2 2 2v2"></path>';
				sessionsHtml += '<line x1="10" y1="11" x2="10" y2="17"></line>';
				sessionsHtml += '<line x1="14" y1="11" x2="14" y2="17"></line>';
				sessionsHtml += '</svg>';
				sessionsHtml += '</button>';
				sessionsHtml += '<button type="button" class="askany-action-btn askany-delete-session-btn" title="<?php esc_attr_e('Delete User Session', 'askany'); ?>">';
				sessionsHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
				sessionsHtml += '<circle cx="12" cy="12" r="10"></circle>';
				sessionsHtml += '<line x1="15" y1="9" x2="9" y2="15"></line>';
				sessionsHtml += '<line x1="9" y1="9" x2="15" y2="15"></line>';
				sessionsHtml += '</svg>';
				sessionsHtml += '</button>';
				sessionsHtml += '</div>';
				sessionsHtml += '</div>';
			});
		}
		
		$('#askany-sessions-list').html(sessionsHtml);
	}
});
</script>

<style>
:root {
	--primary-color: #0073aa;
	--primary-hover: #005177;
	--border-radius: 32px;
	--transition: opacity .15s ease, background-color .15s ease;
}

/* Unread message count badges */
.askany-unread-count {
	display: inline-block;
	background: #dc3232;
	color: white;
	font-size: 11px;
	font-weight: bold;
	padding: 2px 6px;
	border-radius: 10px;
	margin-left: 8px;
	min-width: 16px;
	text-align: center;
	line-height: 1.2;
}

.askany-unread-badge {
	background: #dc3232;
    border-radius: 8px;
    color: #fff;
    display: inline-block;
    font-size: 10px;
    font-weight: 700;
    line-height: 1;
    margin-left: 5px;
    min-width: 5px;
    padding: 2px 5px;
    text-align: center;
    vertical-align: top;
    margin-top: 3px;
}

/* Admin typing indicator styles */
.admin-typing-indicator {
	margin-bottom: 10px;
	padding: 8px 12px;
	background: rgba(0, 123, 255, 0.1);
	border: 1px solid rgba(0, 123, 255, 0.2);
	border-radius: 8px;
	font-style: italic;
}

.typing-indicator-content {
	display: flex;
	align-items: center;
	gap: 8px;
	color: #007cba;
}

/* Send button styling */
.askany-send-btn {
	align-items: center;
	background-color: var(--primary-color);
	border: none;
	border-radius: var(--border-radius);
	cursor: pointer;
	display: flex;
	flex-shrink: 0;
	height: 32px;
	justify-content: center;
	margin-left: 8px;
	margin-right: 5px;
	min-width: 32px;
	transition: var(--transition);
	width: 32px;
	color: white;
}

.askany-send-btn:hover {
	background-color: var(--primary-hover);
	opacity: 0.9;
}

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

.askany-send-btn:disabled {
	background-color: #ccc;
	cursor: not-allowed;
	opacity: 0.6;
}

.askany-send-btn svg {
	width: 16px;
	height: 16px;
	transform: rotate(90deg);
	transition: transform 0.15s ease;
}

.askany-send-btn:hover svg {
	transform: rotate(90deg) scale(1.1);
}

.askany-input-container {
	display: flex;
	align-items: flex-end;
	gap: 8px;
}

.askany-input-container textarea {
	flex: 1;
	resize: vertical;
	min-height: 32px;
	border-radius: 16px;
	padding: 8px 12px;
}

.askany-markdown-textarea:focus{
	box-shadow: none; 
}

.typing-text {
	font-size: 13px;
	font-weight: 500;
}

.typing-dots {
	display: flex;
	gap: 3px;
}

.typing-dots .typing-dot {
	width: 6px;
	height: 6px;
	background-color: #007cba;
	border-radius: 50%;
	animation: admin-typing-dot-animation 1.2s infinite;
}

.typing-dots .typing-dot:nth-child(1) {
	animation-delay: 0s;
}

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

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

@keyframes admin-typing-dot-animation {
	0%, 60%, 100% {
		transform: translateY(0);
		opacity: 0.4;
	}
	30% {
		transform: translateY(-6px);
		opacity: 1;
	}
}
</style>


<style>
/* Markdown content styling in live chat messages */
.askany-message-content h1,
.askany-message-content h2,
.askany-message-content h3,
.askany-message-content h4,
.askany-message-content h5,
.askany-message-content h6 {
	margin-top: 8px;
	margin-bottom: 6px;
	font-weight: 600;
	line-height: 1.3;
}

.askany-message-content h1 { font-size: 20px; }
.askany-message-content h2 { font-size: 18px; }
.askany-message-content h3 { font-size: 16px; }
.askany-message-content h4 { font-size: 15px; }
.askany-message-content h5 { font-size: 14px; }
.askany-message-content h6 { font-size: 13px; }

.askany-message-content p {
	margin: 6px 0;
	line-height: 1.5;
}

.askany-message-content strong {
	font-weight: 600;
}

.askany-message-content em {
	font-style: italic;
}

.askany-message-content del {
	text-decoration: line-through;
	opacity: 0.7;
}

.askany-message-content code {
	padding: 2px 4px;
	background: rgba(0, 0, 0, 0.08);
	border-radius: 3px;
	font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
	font-size: 13px;
}

.askany-message-content pre {
	background: rgba(0, 0, 0, 0.05);
	padding: 8px;
	border-radius: 4px;
	overflow-x: auto;
	margin: 6px 0;
}

.askany-message-content pre code {
	padding: 0;
	background: transparent;
	font-size: 12px;
}

.askany-message-content ul,
.askany-message-content ol {
	margin: 6px 0;
	padding-left: 20px;
}

.askany-message-content li {
	margin: 3px 0;
	line-height: 1.4;
}

.askany-message-content blockquote {
	margin: 6px 0;
	padding: 6px 10px;
	border-left: 3px solid rgba(0, 0, 0, 0.2);
	background: rgba(0, 0, 0, 0.03);
	font-style: italic;
}

.askany-message-content a {
	color: #0073aa;
	text-decoration: none;
	border-bottom: 1px solid transparent;
	transition: border-color 0.2s;
}

.askany-message-content a:hover {
	border-bottom-color: #0073aa;
}

.askany-message-content br {
	display: block;
	content: "";
	margin: 2px 0;
}
</style>
