<?php
/**
 * ============================================================================
 * ai-assistant/index.php - Ultimate AI Assistant (Premium + Full Features)
 * ============================================================================
 * Combines: ChatGPT-style UI + History/Behavior/Learning tabs + Streaming text
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

if (!isLoggedIn()) {
    redirect('/auth/login.php', 'Please login to access AIM AI', 'warning');
}

$userId = getUserId();
$userName = getUserName();
$userType = getUserType();
$pageTitle = 'AIM AI Assistant';

include __DIR__ . '/../includes/meta.php';
include __DIR__ . '/../includes/header.php';
?>

<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
:root {
    --chat-primary: #10a37f;
    --chat-primary-hover: #0d8968;
    --chat-bg: #ffffff;
    --chat-sidebar-bg: #f7f7f8;
    --chat-user-msg: #f4f4f4;
    --chat-ai-msg: #ffffff;
    --chat-border: #e5e5e5;
    --chat-text: #2d333a;
    --chat-text-light: #676b79;
    --chat-input-bg: #ffffff;
}

[data-theme="dark"] {
    --chat-bg: #212121;
    --chat-sidebar-bg: #171717;
    --chat-user-msg: #2f2f2f;
    --chat-ai-msg: #2f2f2f;
    --chat-border: #3d3d3d;
    --chat-text: #ececec;
    --chat-text-light: #b4b4b4;
    --chat-input-bg: #2f2f2f;
}

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    background: var(--chat-bg);
    color: var(--chat-text);
}

.chat-container {
    display: flex;
    height: calc(100vh - 70px);
    max-width: 100%;
}

/* Sidebar */
.chat-sidebar {
    width: 280px;
    background: var(--chat-sidebar-bg);
    border-right: 1px solid var(--chat-border);
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
}

.chat-sidebar-header {
    padding: 20px;
    border-bottom: 1px solid var(--chat-border);
}

.new-chat-btn {
    width: 100%;
    padding: 12px 16px;
    background: var(--chat-primary);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.new-chat-btn:hover {
    background: var(--chat-primary-hover);
    transform: translateY(-1px);
}

.sidebar-tabs {
    display: flex;
    padding: 8px;
    gap: 4px;
    border-bottom: 1px solid var(--chat-border);
}

.sidebar-tab {
    flex: 1;
    padding: 8px;
    background: transparent;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    color: var(--chat-text-light);
    transition: all 0.2s ease;
}

.sidebar-tab.active {
    background: var(--chat-user-msg);
    color: var(--chat-text);
    font-weight: 500;
}

.sidebar-content {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
}

.history-item, .settings-item {
    padding: 12px;
    margin-bottom: 4px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 14px;
    color: var(--chat-text);
}

.history-item:hover, .settings-item:hover {
    background: var(--chat-user-msg);
}

.history-item.active {
    background: var(--chat-user-msg);
    font-weight: 500;
}

/* Main Chat */
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: var(--chat-bg);
}

.chat-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--chat-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-title {
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 12px;
}

.chat-model-badge {
    padding: 4px 12px;
    background: var(--chat-primary);
    color: white;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.api-status {
    font-size: 11px;
    padding: 4px 10px;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.api-status.active {
    background: #dcfce7;
    color: #166534;
}

.api-status.inactive {
    background: #fee2e2;
    color: #991b1b;
}

.chat-actions {
    display: flex;
    gap: 8px;
}

.chat-action-btn {
    padding: 8px 12px;
    background: transparent;
    border: 1px solid var(--chat-border);
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    color: var(--chat-text);
}

.chat-action-btn:hover {
    background: var(--chat-user-msg);
}

/* Messages */
.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    scroll-behavior: smooth;
}

.message-group {
    display: flex;
    gap: 12px;
    animation: messageSlideIn 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

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

.message-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    font-size: 16px;
}

.message-avatar.user {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.message-avatar.ai {
    background: linear-gradient(135deg, #10a37f 0%, #0d8968 100%);
    color: white;
}

.message-content {
    flex: 1;
    max-width: 780px;
}

.message-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.message-author {
    font-weight: 600;
    font-size: 13px;
}

.message-time {
    font-size: 11px;
    color: var(--chat-text-light);
}

.message-text {
    line-height: 1.6;
    font-size: 15px;
}

.message-text p {
    margin: 0 0 10px 0;
}

.message-text strong {
    font-weight: 600;
}

.message-text ul, .message-text ol {
    margin: 8px 0;
    padding-left: 20px;
}

.message-text li {
    margin: 4px 0;
}

/* Typing Indicator */
.typing-indicator {
    display: flex;
    gap: 4px;
    padding: 10px 0;
}

.typing-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--chat-text-light);
    animation: typingBounce 1.4s infinite ease-in-out;
}

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

@keyframes typingBounce {
    0%, 60%, 100% { transform: translateY(0); }
    30% { transform: translateY(-8px); }
}

/* Streaming Cursor */
.streaming-cursor {
    display: inline-block;
    width: 2px;
    height: 1em;
    background: var(--chat-text);
    margin-left: 2px;
    animation: cursorBlink 1s infinite;
    vertical-align: text-bottom;
}

@keyframes cursorBlink {
    0%, 49% { opacity: 1; }
    50%, 100% { opacity: 0; }
}

/* Input */
.chat-input-container {
    padding: 16px 24px 24px;
    background: var(--chat-bg);
    border-top: 1px solid var(--chat-border);
}

.quick-prompts {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-bottom: 12px;
    max-width: 780px;
    margin-left: auto;
    margin-right: auto;
}

.quick-prompt {
    padding: 6px 14px;
    background: var(--chat-user-msg);
    border: 1px solid var(--chat-border);
    border-radius: 16px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.quick-prompt:hover {
    background: var(--chat-border);
    transform: translateY(-2px);
}

.chat-input-wrapper {
    max-width: 780px;
    margin: 0 auto;
    position: relative;
}

.chat-input {
    width: 100%;
    min-height: 52px;
    max-height: 200px;
    padding: 14px 52px 14px 16px;
    background: var(--chat-input-bg);
    border: 1px solid var(--chat-border);
    border-radius: 12px;
    font-size: 15px;
    font-family: 'Inter', sans-serif;
    color: var(--chat-text);
    resize: none;
    transition: all 0.2s ease;
}

.chat-input:focus {
    outline: none;
    border-color: var(--chat-primary);
    box-shadow: 0 0 0 3px rgba(16, 163, 127, 0.1);
}

.send-button {
    position: absolute;
    right: 8px;
    bottom: 8px;
    width: 36px;
    height: 36px;
    background: var(--chat-primary);
    border: none;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    color: white;
}

.send-button:hover:not(:disabled) {
    background: var(--chat-primary-hover);
    transform: scale(1.05);
}

.send-button:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

/* Welcome Screen */
.welcome-screen {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    text-align: center;
    padding: 40px;
}

.welcome-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #10a37f 0%, #0d8968 100%);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
    margin-bottom: 24px;
}

.welcome-title {
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 12px;
    background: linear-gradient(135deg, #10a37f 0%, #667eea 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.welcome-subtitle {
    font-size: 16px;
    color: var(--chat-text-light);
    margin-bottom: 32px;
    max-width: 500px;
}

/* Badges */
.language-badge {
    padding: 2px 8px;
    background: #667eea;
    color: white;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 500;
}

.source-badge {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 500;
}

.source-badge.openai {
    background: #10a37f;
    color: white;
}

.source-badge.rule-based {
    background: #94a3b8;
    color: white;
}

/* Scrollbar */
.chat-messages::-webkit-scrollbar,
.sidebar-content::-webkit-scrollbar {
    width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb,
.sidebar-content::-webkit-scrollbar-thumb {
    background: var(--chat-border);
    border-radius: 3px;
}

/* Mobile */
@media (max-width: 768px) {
    .chat-sidebar {
        position: fixed;
        left: -280px;
        height: 100vh;
        z-index: 1000;
    }
    
    .chat-sidebar.open {
        left: 0;
    }
}
</style>

<div class="chat-container">
    <!-- Sidebar -->
    <aside class="chat-sidebar" id="chatSidebar">
        <div class="chat-sidebar-header">
            <button class="new-chat-btn" onclick="startNewChat()">
                <i class="bi bi-plus-lg"></i>
                New Chat
            </button>
        </div>
        
        <div class="sidebar-tabs">
            <button class="sidebar-tab active" onclick="switchSidebarTab('history')" data-tab="history">
                <i class="bi bi-clock-history"></i> History
            </button>
            <button class="sidebar-tab" onclick="switchSidebarTab('settings')" data-tab="settings">
                <i class="bi bi-sliders"></i> Settings
            </button>
        </div>
        
        <div class="sidebar-content" id="sidebarContent">
            <!-- Content loaded dynamically -->
        </div>
        
        <div style="padding: 16px; border-top: 1px solid var(--chat-border);">
            <button class="chat-action-btn" style="width: 100%;" onclick="toggleTheme()">
                <i class="bi bi-moon-stars me-2"></i> Theme
            </button>
        </div>
    </aside>

    <!-- Main Chat -->
    <main class="chat-main">
        <div class="chat-header">
            <div class="chat-title">
                <button class="chat-action-btn d-md-none" onclick="toggleSidebar()">
                    <i class="bi bi-list"></i>
                </button>
                <i class="bi bi-robot"></i>
                AIM AI Assistant
                <span class="chat-model-badge">GPT-3.5</span>
                <span class="api-status" id="apiStatus">
                    <i class="bi bi-circle-fill" style="font-size: 6px;"></i>
                    <span id="apiStatusText">Checking...</span>
                </span>
            </div>
            <div class="chat-actions">
                <button class="chat-action-btn" onclick="exportChat()" title="Export chat">
                    <i class="bi bi-download"></i>
                </button>
                <button class="chat-action-btn" onclick="viewStats()" title="Statistics">
                    <i class="bi bi-graph-up"></i>
                </button>
            </div>
        </div>

        <div class="chat-messages" id="chatMessages">
            <!-- Welcome Screen -->
            <div class="welcome-screen" id="welcomeScreen">
                <div class="welcome-icon">🌾</div>
                <h1 class="welcome-title">Welcome, <?php echo htmlspecialchars($userName); ?>!</h1>
                <p class="welcome-subtitle">
                    Your intelligent agricultural assistant. Ask me anything about farming, 
                    crop management, market prices, or agricultural best practices in English or Lusoga.
                </p>
                <div class="quick-prompts">
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">
                        🌱 Best time to plant maize
                    </div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">
                        🐛 Maize rust disease treatment
                    </div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">
                        💰 Current market prices
                    </div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">
                        Obulwadhe bwa muwogo
                    </div>
                </div>
            </div>
        </div>

        <div class="chat-input-container">
            <div class="quick-prompts" id="quickPromptsBottom" style="display: none;">
                <div class="quick-prompt" onclick="sendQuickPrompt(this)">Okusimba kasooli</div>
                <div class="quick-prompt" onclick="sendQuickPrompt(this)">Fertilizer tips</div>
                <div class="quick-prompt" onclick="sendQuickPrompt(this)">Weather advice</div>
            </div>
            
            <div class="chat-input-wrapper">
                <textarea 
                    class="chat-input" 
                    id="messageInput" 
                    placeholder="Ask me anything about farming..."
                    rows="1"
                ></textarea>
                <button class="send-button" id="sendButton" onclick="sendMessage()" disabled>
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>
        </div>
    </main>
</div>

<script>
const APP_URL = '<?php echo APP_URL; ?>';
const USER_ID = <?php echo $userId; ?>;
const USER_TYPE = '<?php echo $userType; ?>';

let isStreaming = false;
let currentConversations = [];
let currentSidebarTab = 'history';

$(document).ready(function() {
    // Auto-resize textarea
    const textarea = document.getElementById('messageInput');
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
        updateSendButton();
    });

    textarea.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    // Load initial content
    loadSidebarContent('history');
    checkAPIStatus();
    
    // Check API status every 30 seconds
    setInterval(checkAPIStatus, 30000);
});

function updateSendButton() {
    const input = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendButton');
    sendBtn.disabled = !input.value.trim() || isStreaming;
}

function checkAPIStatus() {
    const statusEl = document.getElementById('apiStatus');
    const statusTextEl = document.getElementById('apiStatusText');
    
    // Check if OpenAI is configured
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/check-api.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.configured) {
                statusEl.className = 'api-status active';
                statusTextEl.textContent = 'OpenAI Active';
            } else {
                statusEl.className = 'api-status inactive';
                statusTextEl.textContent = 'Rule-based';
            }
        },
        error: function() {
            statusEl.className = 'api-status inactive';
            statusTextEl.textContent = 'Rule-based';
        }
    });
}

function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (!message || isStreaming) return;
    
    // Hide welcome screen
    $('#welcomeScreen').fadeOut(300, function() {
        $(this).remove();
    });
    $('#quickPromptsBottom').show();
    
    // Add user message
    addUserMessage(message);
    
    // Clear input
    input.value = '';
    input.style.height = 'auto';
    updateSendButton();
    
    // Show typing indicator
    showTypingIndicator();
    
    // Small delay for better UX
    setTimeout(() => {
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/chat.php',
            type: 'POST',
            data: {
                message: message,
                user_id: USER_ID,
                user_type: USER_TYPE
            },
            dataType: 'json',
            success: function(response) {
                removeTypingIndicator();
                
                if (response.success) {
                    streamAIMessage(response.response, response.language, response.source);
                } else {
                    addAIMessage('Sorry, I encountered an error. Please try again.', 'en', null);
                }
            },
            error: function(xhr, status, error) {
                removeTypingIndicator();
                addAIMessage('Connection error. Please check your internet and try again.', 'en', null);
                console.error('AJAX Error:', status, error);
            }
        });
    }, 300);
}

function addUserMessage(message) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const html = `
        <div class="message-group">
            <div class="message-avatar user">
                <i class="bi bi-person-fill"></i>
            </div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">You</span>
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text">${escapeHtml(message).replace(/\n/g, '<br>')}</div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

function streamAIMessage(message, language = 'en', source = null) {
    isStreaming = true;
    updateSendButton();
    
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const langBadge = language === 'lusoga' ? '<span class="language-badge">Lusoga</span>' : '';
    
    let sourceBadge = '';
    if (source) {
        const badgeClass = source === 'openai' ? 'openai' : 'rule-based';
        const badgeText = source === 'openai' ? 'OpenAI' : 'Knowledge Base';
        sourceBadge = `<span class="source-badge ${badgeClass}">${badgeText}</span>`;
    }
    
    const messageId = 'msg-' + Date.now();
    const html = `
        <div class="message-group" id="${messageId}">
            <div class="message-avatar ai">
                <i class="bi bi-robot"></i>
            </div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    ${langBadge}
                    ${sourceBadge}
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text" id="${messageId}-text"></div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    const element = document.getElementById(`${messageId}-text`);
    
    // Format and stream
    const formattedMessage = formatAIResponse(message);
    streamText(element, formattedMessage, () => {
        isStreaming = false;
        updateSendButton();
        // Reload history after new message
        if (currentSidebarTab === 'history') {
            loadSidebarContent('history');
        }
    });
    
    scrollToBottom();
}

function streamText(element, html, callback) {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    const text = tempDiv.textContent || tempDiv.innerText;
    
    let index = 0;
    const speed = 25; // Slightly slower for more natural feel
    
    const cursor = document.createElement('span');
    cursor.className = 'streaming-cursor';
    element.appendChild(cursor);
    
    function typeChar() {
        if (index < text.length) {
            cursor.remove();
            
            const char = text[index];
            const span = document.createElement('span');
            span.textContent = char;
            element.appendChild(span);
            element.appendChild(cursor);
            
            index++;
            
            // Variable speed
            let delay = speed;
            if (char === '.' || char === '!' || char === '?') delay = speed * 4;
            else if (char === ',' || char === ';') delay = speed * 2;
            
            setTimeout(typeChar, delay);
            
            if (index % 3 === 0) scrollToBottom();
        } else {
            cursor.remove();
            element.innerHTML = html;
            scrollToBottom();
            callback();
        }
    }
    
    typeChar();
}

function addAIMessage(message, language = 'en', source = null) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const langBadge = language === 'lusoga' ? '<span class="language-badge">Lusoga</span>' : '';
    
    let sourceBadge = '';
    if (source) {
        const badgeClass = source === 'openai' ? 'openai' : 'rule-based';
        const badgeText = source === 'openai' ? 'OpenAI' : 'Knowledge Base';
        sourceBadge = `<span class="source-badge ${badgeClass}">${badgeText}</span>`;
    }
    
    const html = `
        <div class="message-group">
            <div class="message-avatar ai">
                <i class="bi bi-robot"></i>
            </div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    ${langBadge}
                    ${sourceBadge}
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text">${formatAIResponse(message)}</div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

function showTypingIndicator() {
    const html = `
        <div class="message-group" id="typingIndicator">
            <div class="message-avatar ai">
                <i class="bi bi-robot"></i>
            </div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    <span class="message-time">typing...</span>
                </div>
                <div class="typing-indicator">
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

function removeTypingIndicator() {
    $('#typingIndicator').remove();
}

function formatAIResponse(text) {
    let formatted = escapeHtml(text);
    formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    formatted = formatted.replace(/^- (.+)$/gm, '<li>$1</li>');
    formatted = formatted.replace(/(<li>.*?<\/li>)/s, '<ul>$1</ul>');
    formatted = formatted.replace(/\n\n/g, '</p><p>');
    formatted = '<p>' + formatted + '</p>';
    return formatted;
}

function sendQuickPrompt(element) {
    const prompt = element.textContent.trim().replace(/^[🌱🐛💰🌾]+\s*/, '');
    document.getElementById('messageInput').value = prompt;
    sendMessage();
}

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

function scrollToBottom() {
    const messages = document.getElementById('chatMessages');
    messages.scrollTop = messages.scrollHeight;
}

// Sidebar functions
function switchSidebarTab(tab) {
    currentSidebarTab = tab;
    $('.sidebar-tab').removeClass('active');
    $(`.sidebar-tab[data-tab="${tab}"]`).addClass('active');
    loadSidebarContent(tab);
}

function loadSidebarContent(tab) {
    const container = $('#sidebarContent');
    
    if (tab === 'history') {
        container.html('<div class="text-center py-4"><div class="spinner-border spinner-border-sm"></div></div>');
        
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/history.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.conversations.length > 0) {
                    currentConversations = response.conversations;
                    displayHistory(response.conversations);
                } else {
                    container.html('<div class="text-center py-4 text-muted" style="font-size: 13px;">No conversations yet</div>');
                }
            }
        });
    } else if (tab === 'settings') {
        displaySettings();
    }
}

function displayHistory(conversations) {
    let html = '';
    conversations.forEach((conv, index) => {
        const preview = conv.message.substring(0, 35) + (conv.message.length > 35 ? '...' : '');
        const date = new Date(conv.created_at).toLocaleDateString();
        html += `
            <div class="history-item" onclick="loadConversation(${conv.id})" data-id="${conv.id}">
                <div style="display: flex; align-items: start; gap: 8px;">
                    <i class="bi bi-chat-left-text" style="margin-top: 2px;"></i>
                    <div style="flex: 1; min-width: 0;">
                        <div style="font-size: 13px; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                            ${escapeHtml(preview)}
                        </div>
                        <div style="font-size: 11px; color: var(--chat-text-light);">${date}</div>
                    </div>
                </div>
            </div>
        `;
    });
    $('#sidebarContent').html(html);
}

function displaySettings() {
    const html = `
        <div style="padding: 8px;">
            <div class="settings-item" onclick="showBehaviorSettings()">
                <i class="bi bi-sliders me-2"></i>
                Behavior Settings
            </div>
            <div class="settings-item" onclick="viewStats()">
                <i class="bi bi-graph-up me-2"></i>
                View Statistics
            </div>
            <div class="settings-item" onclick="clearAllHistory()">
                <i class="bi bi-trash me-2"></i>
                Clear All History
            </div>
            <div class="settings-item" onclick="exportChat()">
                <i class="bi bi-download me-2"></i>
                Export Chat
            </div>
        </div>
    `;
    $('#sidebarContent').html(html);
}

function loadConversation(id) {
    // Find the conversation
    const conv = currentConversations.find(c => c.id === id);
    if (!conv) return;
    
    // Clear chat and add this conversation
    $('#chatMessages').empty();
    $('#quickPromptsBottom').show();
    
    // Add user message
    addUserMessage(conv.message);
    
    // Add AI response (no streaming for historical messages)
    addAIMessage(conv.response, conv.language, conv.source);
    
    // Highlight in sidebar
    $('.history-item').removeClass('active');
    $(`.history-item[data-id="${id}"]`).addClass('active');
}

function startNewChat() {
    if (confirm('Start a new conversation?')) {
        location.reload();
    }
}

function toggleSidebar() {
    $('#chatSidebar').toggleClass('open');
}

function toggleTheme() {
    const html = document.documentElement;
    const currentTheme = html.getAttribute('data-theme');
    html.setAttribute('data-theme', currentTheme === 'dark' ? 'light' : 'dark');
    localStorage.setItem('theme', currentTheme === 'dark' ? 'light' : 'dark');
}

function showBehaviorSettings() {
    alert('Behavior settings panel - Coming soon!');
}

function viewStats() {
    alert('Statistics panel - Coming soon!');
}

function clearAllHistory() {
    if (confirm('Delete all conversation history? This cannot be undone.')) {
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/clear-history.php',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('History cleared', 'success');
                    loadSidebarContent('history');
                }
            }
        });
    }
}

function exportChat() {
    alert('Export feature - Coming soon!');
}

// Load theme
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>