<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Interface</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #ffffff;
        }

        .chat-container {
            display: flex;
            height: 100vh;
        }

        /* Sidebar Styles */
        .sidebar {
            width: 200px;
            background-color: #ffffff;
            border-right: 1px solid #ececf1;
            padding: 8px 12px;
            height: 100vh;
            overflow: auto;
        }

        .sidebar::-webkit-scrollbar {
            display: none;
        }

        .sidebar-header {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
        }

        .toggle-btn {
            padding: 4px;
            background: none;
            border: none;
            cursor: pointer;
        }

        .toggle-btn svg {
            width: 24px;
            height: 24px;
            color: #202123;
        }

        .search-box {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 10px;
            border: 1px solid #ececf1;
            border-radius: 6px;
            background-color: #f9f9f9;
        }

        .search-box input {
            border: none;
            outline: none;
            width: 100%;
            font-size: 13px;
            background: transparent;
        }

        .new-chat {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: none;
            border: 1px solid #ececf1;
            border-radius: 6px;
            cursor: pointer;
            width: 100%;
            margin: 8px 0;
            font-size: 13px;
            color: #2d2d2d;
        }

        /* Navigation Links */
        .nav-links {
            margin-top: 16px;
        }

        .nav-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 10px;
            color: #2d2d2d;
            text-decoration: none;
            border-radius: 6px;
            font-size: 13px;
        }

        .nav-item:hover {
            background-color: #f7f7f8;
        }

        .nav-item.active {
            background-color: #f0f0f0;
        }

        .nav-item svg {
            width: 20px;
            height: 20px;
        }

        /* Chat Content */
        .chat-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color:rgb(255, 255, 255);
            height: 100vh;
            overflow: auto;
            padding-top: 40px;
        }
        .chat-content::-webkit-scrollbar {
            display: none;
        }                                   

        .chat-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 16px;
            border-bottom: 1px solid #ffffff;
            position: fixed;
            width: 100%;
            background: white;
            top: 0;
            z-index: 99999999;
        }

        .model-selector {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
        }

        .memory-status {
            position: relative;
            width: 40px;
            height: 40px;
            cursor: pointer;
        }

        .memory-status img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
        }

        .profile-dropdown {
            position: absolute;
            top: 45px;
            right: 0;
            display: none;
            z-index: 1000;
        }

        .dropdown-menu {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
            width: 220px;
            padding: 6px 0;
            border: 1px solid #ececf1;
            margin-right: 13px;
            margin-top: 8px;
        }


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

        .profile-dropdown.active {
            display: block;
            animation: dropdownFade 0.2s ease;
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 8px 16px;
            color: #2d2d2d;
            text-decoration: none;
            font-size: 14px;
        }

        .dropdown-item:hover {
            background-color: #f7f7f8;
        }

        .dropdown-item svg {
            color: #666;
        }

        /* Add a divider line after Settings */
        .dropdown-item:nth-child(3) {
            border-bottom: 1px solid #ececf1;
            padding-bottom: 12px;
            margin-bottom: 4px;
        }

        /* Chat Area */
        .chat-area {
            flex: 1;
            padding: 20px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .chat-welcome {
            text-align: center;
            max-width: 600px;
        }

        .chat-welcome h1 {
            font-size: 30px;
            color: #2d2d2d;
            margin-bottom: 24px;
            font-weight: 500;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border: 1px solid #ececf1;
            border-radius: 6px;
            background: none;
            cursor: pointer;
            color: #666;
            font-size: 13px;
        }

        .action-btn:hover {
            background-color: #f7f7f8;
        }

        /* Chat Input */
        .chat-input {
            padding: 16px;
            border-top: 1px solid #ececf1;
            position: fixed;
            bottom: 0;
            width: 78%;        
        }

        .input-container {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border: 1px solid #ececf1;
            border-radius: 6px;
            background-color: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }

        .input-container input {
            flex: 1;
            border: none;
            outline: none;
            font-size: 14px;
            padding: 4px 0;
        }

        .input-actions {
            display: flex;
            gap: 6px;
        }

        .input-actions .action-btn {
            padding: 6px;
            border: none;
        }

        /* Yesterday Section */
        .yesterday-section {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #ececf1;
        }

        .yesterday-header {
            font-size: 11px;
            color: #666;
            margin-bottom: 8px;
            padding-left: 10px;
            text-transform: uppercase;
        }

        .chat-history {
            margin-top: 20px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            padding: 0 8px;
        }

        .chat-history-item {    
            padding: 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            border: 1px solid #ececf1;
        }

        .chat-history-item:hover {
            background-color: #f7f7f8;
        }

        .chat-history-item.active {
            background-color: #f0f0f1;
            border-color: #d9d9e3;
        }

        .chat-title {
            font-size: 14px;
            color: #2d2d2d;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-date {
            font-size: 12px;
            color: #666;
        }

        /* Sidebar Section Headers */
        .sidebar-section {
            padding: 10px;
            font-size: 13px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-top: 20px;
            
        }

        /* Message Formatting Styles */
        .message {
            display: flex;
            padding: 1.5rem;
            margin: 0.5rem 0;
            line-height: 1.6;
            font-size: 1rem;
            align-items: flex-start;
            gap: 1rem;
        }

        .user-message {
            background-color: #f7f7f8;
            flex-direction: row-reverse;
        }

        .assistant-message {
            background-color: #ffffff;
            border-bottom: 1px solid #ececf1;
        }

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

        .user-message .message-avatar {
            background-color: #5c5cff;
            color: white;
        }

        .assistant-message .message-avatar {
            background-color: #19c37d;
            color: white;
        }

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

        .user-message .message-content {
            text-align: right;
        }

        /* List Formatting */
        .message-content ul, 
        .message-content ol {
            margin: 1em 0;
            padding-left: 2em;
        }

        .message-content li {
            margin: 0.5em 0;
        }

        /* Code Block Formatting */
        .message-content pre {
            background-color: #f6f8fa;
            border-radius: 6px;
            padding: 1em;
            overflow-x: auto;
            margin: 1em 0;
            font-family: 'Consolas', 'Monaco', monospace;
        }

        .message-content code {
            background-color: #f6f8fa;
            padding: 0.2em 0.4em;
            border-radius: 3px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.9em;
        }

        /* Paragraph Spacing */
        .message-content p {
            margin: 1em 0;
        }

        /* Table Formatting */
        .message-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }

        .message-content th,
        .message-content td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .message-content th {
            background-color: #f6f8fa;
        }

        .delete-chat {
            opacity: 0;
            transition: opacity 0.2s ease;
            color: #ff4444;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
        }

        .chat-history-item:hover .delete-chat {
            opacity: 1;
        }

        .delete-chat:hover {
            background-color: #ffebeb;
        }

        /* Add these styles */
        .user-info {
            padding: 15px;
            border-bottom: 1px solid #e5e5e5;
            margin-bottom: 15px;
        }

        .user-name {
            font-weight: 500;
            color: #2d2d2d;
        }

        .logout-btn {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            margin-left: 10px;
        }

        .logout-btn:hover {
            color: #ff4444;
        }

        .chat-history-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            margin: 5px 0;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .chat-history-item:hover {
            background-color: #f0f0f0;
        }

        .chat-history-item.active {
            background-color: #e5e7eb;
        }

        .chat-info {
            flex: 1;
            overflow: hidden;
        }

        .chat-title {
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-date {
            font-size: 12px;
            color: #666;
        }

        .loading-messages {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .delete-chat {
            opacity: 0;
            transition: opacity 0.2s;
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            color: #666;
        }

        .chat-history-item:hover .delete-chat {
            opacity: 1;
        }

        .chat-header {
            position: sticky;
            top: 0;
            background: white;
            padding: 10px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            z-index: 100;
        }

        .switch-interface {
            padding: 8px 16px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .switch-interface:hover {
            background: #f5f5f5;
        }

        .switch-interface svg {
            width: 20px;
            height: 20px;
        }
    </style>
</head>
<body>
    <!-- Add this hidden input to store the chat ID -->
    <input type="hidden" id="active-chat-id" value="{{ active_chat_id or '' }}">
    
    <div class="chat-container">
        <!-- Sidebar -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="user-info">
                    <span class="user-name">{{ user_name }}</span>
                    <a href="/logout" class="logout-btn">Logout</a>
                </div>
            </div>

            <button class="new-chat" onclick="startNewChat()">
                <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="16" width="16" xmlns="http://www.w3.org/2000/svg"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                New Chat
            </button>

            <!-- Chat History Section -->
            <div class="sidebar-section">Chat History</div>
            <div class="chat-history">
                {% for chat in chats %}
                <div class="chat-history-item" 
                     data-chat-id="{{ chat.id }}"
                     onclick="switchChat('{{ chat.id }}')"
                     {% if chat.id == active_chat_id %}active{% endif %}>
                    <div class="chat-info">
                        <div class="chat-title">{{ chat.title }}</div>
                        <div class="chat-date">{{ chat.created_at.strftime('%Y-%m-%d %H:%M') if chat.created_at else '' }}</div>
                    </div>
                    <button class="delete-chat" onclick="event.stopPropagation(); deleteChat('{{ chat.id }}')">
                        <svg width="14" height="14" viewBox="0 0 24 24">
                            <path fill="currentColor" d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"/>
                        </svg>
                    </button>
                </div>
                {% endfor %}
            </div>

            <!-- Add this in the navbar section of chat.html -->
            <div class="nav-links">
                <!-- ... existing nav items ... -->
                
                <div class="nav-item">
                    <a href="/company/login" class="flex items-center gap-2 px-3 py-2 text-sm">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm3 1h6v4H7V5zm6 6H7v2h6v-2z" clip-rule="evenodd"/>
                        </svg>
                        Company Portal
                    </a>
                </div>

                <!-- For companies who want to register -->
                <div class="nav-item">
                    <a href="/company/register" class="flex items-center gap-2 px-3 py-2 text-sm">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd"/>
                        </svg>
                        Register Company
                    </a>
                </div>
            </div>
        </div>

        <!-- Chat Content -->
        <div class="chat-content">
            <div class="chat-header">
                <div class="model-selector">
                    RonnieGPT
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M6 9l6 6 6-6"/>
                    </svg>
                </div>
                <div class="memory-status dp-image">
                  <img src="download.jpg" alt="image">
                </div>
                <button class="switch-interface" onclick="window.location.href='/voice-chat'">
                    <svg width="20" height="20" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M12,2A3,3 0 0,1 15,5V11A3,3 0 0,1 12,14A3,3 0 0,1 9,11V5A3,3 0 0,1 12,2M19,11C19,14.53 16.39,17.44 13,17.93V21H11V17.93C7.61,17.44 5,14.53 5,11H7A5,5 0 0,0 12,16A5,5 0 0,0 17,11H19Z"/>
                    </svg>
                    Switch to Voice Chat
                </button>
            </div>

            <div class="chat-area">
                <div class="chat-welcome">
                    <h1>What can I help with?</h1>
                    <div class="action-buttons">
                        <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="3" y="3" width="18" height="18" rx="2"/>
                                <path d="M8 12h8M12 8v8"/>
                            </svg>
                            Create image
                        </button>
                        <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/>
                            </svg>
                            Summarize text
                        </button>
                        <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
                                <path d="M3.3 7l8.7 5 8.7-5M12 22V12"/>
                            </svg>
                            Surprise me
                        </button>
                        <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 12H3M3 6h18M3 18h18"/>
                            </svg>
                            Analyze data
                        </button>
                    </div>
                </div>
            </div>

            <div class="chat-input">
                <div class="input-container">
                    <input type="text" placeholder="Message ChatGPT">
                    <div class="input-actions">
                        <!-- <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/>
                                <path d="M12 16v-4M12 8h.01"/>
                            </svg>
                        </button>
                        -->
                        <button class="action-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add this right after the memory-status div -->
    <!-- <div class="profile-dropdown">
        <div class="dropdown-menu">
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <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>
                Explore GPTs
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="3"></circle>
                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                </svg>
                Customize ChatGPT
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="3"></circle>
                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                </svg>
                Settings
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
                    <line x1="8" y1="21" x2="16" y2="21"></line>
                    <line x1="12" y1="17" x2="12" y2="21"></line>
                </svg>
                Download the Windows app
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M20.24 12.24a6 6 0 0 0-8.49-8.49L5 10.5V19h8.5z"></path>
                    <line x1="16" y1="8" x2="2" y2="22"></line>
                    <line x1="17.5" y1="15" x2="9" y2="15"></line>
                </svg>
                Upgrade Plan
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"></circle>
                    <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
                Get ChatGPT search extension
            </a>
            <a href="#" class="dropdown-item">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                    <polyline points="16 17 21 12 16 7"></polyline>
                    <line x1="21" y1="12" x2="9" y2="12"></line>
                </svg>
                Log out
            </a>
        </div>
    </div> -->

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const profileImage = document.querySelector('.dp-image');
        const dropdown = document.querySelector('.profile-dropdown');

        // Toggle dropdown when clicking profile image
        profileImage.addEventListener('click', function(e) {
            e.stopPropagation();
            dropdown.classList.toggle('active');
        });

        // Close dropdown when clicking anywhere else on the page
        document.addEventListener('click', function(e) {
            if (!dropdown.contains(e.target) && !profileImage.contains(e.target)) {
                dropdown.classList.remove('active');
            }
        });

        // Close dropdown when pressing Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                dropdown.classList.remove('active');
            }
        });
    });

    let currentChatId = document.getElementById('active-chat-id').value;
    let isProcessing = false;

    // Load initial chat history when page loads
    document.addEventListener('DOMContentLoaded', async function() {
        if (!currentChatId) {
            // If no active chat, create a new one
            await startNewChat();
        } else {
            await loadChatHistory(currentChatId);
        }
    });

    function showTypingIndicator() {
        const chatArea = document.querySelector('.chat-area');
        const indicator = document.createElement('div');
        indicator.className = 'typing-indicator';
        indicator.innerHTML = `
            <span></span>
            <span></span>
            <span></span>
        `;
        chatArea.appendChild(indicator);
        chatArea.scrollTop = chatArea.scrollHeight;
        return indicator;
    }

    function setInputLoading(loading) {
        const inputContainer = document.querySelector('.input-container');
        const input = inputContainer.querySelector('input');
        const buttons = inputContainer.querySelectorAll('.action-btn');
        
        if (loading) {
            inputContainer.classList.add('loading');
            input.disabled = true;
            buttons.forEach(btn => btn.disabled = true);
        } else {
            inputContainer.classList.remove('loading');
            input.disabled = false;
            buttons.forEach(btn => btn.disabled = false);
        }
    }

    async function sendMessage() {
        if (isProcessing || !currentChatId) return;
        
        const inputElement = document.querySelector('.input-container input');
        const message = inputElement.value.trim();
        
        if (!message) return;
        
        isProcessing = true;
        setInputLoading(true);
        
        // Clear input
        inputElement.value = '';
        
        // Add user message to chat
        addMessageToChat('user', message);
        
        // Show typing indicator
        const typingIndicator = showTypingIndicator();
        
        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    chat_id: currentChatId
                })
            });
            
            const data = await response.json();
            
            // Remove typing indicator
            typingIndicator.remove();
            
            if (data.success) {
                addMessageToChat('assistant', data.message);
                // Refresh the sidebar to update chat titles
                await refreshSidebar();
            } else {
                addMessageToChat('assistant', `Error: ${data.error || 'Unknown error occurred'}`);
            }
        } catch (error) {
            console.error('Error:', error);
            typingIndicator.remove();
            addMessageToChat('assistant', 'Sorry, there was an error processing your request.');
        } finally {
            isProcessing = false;
            setInputLoading(false);
        }
    }

    function formatMessage(content) {
        // Convert markdown-style lists to HTML
        content = content.replace(/^\d+\.\s+(.+)/gm, '<li>$1</li>');
        content = content.replace(/^[\*\-]\s+(.+)/gm, '<li>$1</li>');
        
        // Wrap consecutive list items in ol/ul
        content = content.replace(/<li>(.+?)<\/li>\n<li>/g, '<li>$1</li><li>');
        content = content.replace(/(<li>.+?<\/li>)+/g, function(match) {
            return match.includes('1.') ? '<ol>' + match + '</ol>' : '<ul>' + match + '</ul>';
        });

        // Format code blocks
        content = content.replace(/```(\w+)?\n([\s\S]+?)\n```/g, function(match, lang, code) {
            return `<pre><code class="language-${lang || ''}">${code.trim()}</code></pre>`;
        });

        // Format inline code
        content = content.replace(/`([^`]+)`/g, '<code>$1</code>');

        // Convert line breaks to paragraphs
        content = content.split('\n\n').map(para => 
            para.trim() ? `<p>${para.trim()}</p>` : ''
        ).join('');

        // Bold text
        content = content.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');

        // Italic text
        content = content.replace(/\*(.+?)\*/g, '<em>$1</em>');

        return content;
    }

    function addMessageToChat(role, content, scroll = true) {
        const chatArea = document.querySelector('.chat-area');
        
        // Clear welcome message if it exists
        const welcomeMessage = chatArea.querySelector('.chat-welcome');
        if (welcomeMessage) {
            welcomeMessage.remove();
        }
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;
        
        // Create avatar with initial
        const avatarLetter = role === 'user' ? 'U' : 'A';
        
        messageDiv.innerHTML = `
            <div class="message-avatar">${avatarLetter}</div>
            <div class="message-content">
                ${formatMessage(content)}
            </div>
        `;
        chatArea.appendChild(messageDiv);
        
        if (scroll) {
            chatArea.scrollTo({
                top: chatArea.scrollHeight,
                behavior: 'smooth'
            });
        }
    }

    async function startNewChat() {
        
        try {
            const response = await fetch('/chat/new', {
                method: 'POST'
            });
            const data = await response.json();
            
            if (data.success) {
                currentChatId = data.chat_id;
                
                // Clear chat area
                const chatArea = document.querySelector('.chat-area');
                chatArea.innerHTML = `
                    <div class="chat-welcome">
                        <h1>What can I help with?</h1>
                        <div class="action-buttons">
                            <!-- Your action buttons here -->
                        </div>
                    </div>
                `;
                
                // Refresh sidebar to show new chat
                await refreshSidebar();
                
                // Update active state in sidebar
                document.querySelectorAll('.chat-history-item').forEach(item => {
                    item.classList.remove('active');
                    if (item.getAttribute('data-chat-id') === currentChatId) {
                        item.classList.add('active');
                    }
                });
                
                return data.chat_id;
            } else {
                console.error('Failed to create new chat:', data.error);
                return null;
            }
        } catch (error) {
            console.error('Error starting new chat:', error);
            return null;
        }
    }

    // Add event listeners
    document.querySelector('.input-container input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !isProcessing) {
            sendMessage();
        }
    });

    document.querySelector('.new-chat').addEventListener('click', startNewChat);

    // Add smooth transitions for the entire chat area
    const style = document.createElement('style');
    style.textContent = `
        .chat-area {
            transition: opacity 0.3s ease;
        }
        
        .chat-welcome {
            transition: opacity 0.3s ease;
        }
    `;
    document.head.appendChild(style);

    async function refreshSidebar() {
        try {
            const response = await fetch('/');
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            // Update chat history in sidebar
            const currentSidebar = document.querySelector('.chat-history');
            const newSidebar = doc.querySelector('.chat-history');
            if (currentSidebar && newSidebar) {
                currentSidebar.innerHTML = newSidebar.innerHTML;
                
                // Reattach event listeners and update active state
                document.querySelectorAll('.chat-history-item').forEach(item => {
                    const chatId = item.getAttribute('data-chat-id');
                    if (chatId === currentChatId) {
                        item.classList.add('active');
                    }
                    item.addEventListener('click', () => switchChat(chatId));
                });
            }
        } catch (error) {
            console.error('Error refreshing sidebar:', error);
        }
    }

    async function switchChat(chatId) {
        try {
            currentChatId = chatId;
            
            // Update active state in sidebar
            document.querySelectorAll('.chat-history-item').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-chat-id') === chatId) {
                    item.classList.add('active');
                }
            });
            
            // Clear current chat area
            const chatArea = document.querySelector('.chat-area');
            chatArea.innerHTML = '';
            
            // Show loading indicator
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'loading-messages';
            loadingDiv.textContent = 'Loading messages...';
            chatArea.appendChild(loadingDiv);
            
            // Load chat history
            const response = await fetch(`/chat/history?chat_id=${chatId}`);
            const data = await response.json();
            
            // Remove loading indicator
            loadingDiv.remove();
            
            if (data.success) {
                // Load all messages
                data.history.forEach(message => {
                    addMessageToChat(message.role, message.content);
                });
                
                // Scroll to bottom
                chatArea.scrollTop = chatArea.scrollHeight;
            } else {
                console.error('Error loading chat:', data.error);
            }
        } catch (error) {
            console.error('Error switching chat:', error);
        }
    }

    async function loadChatHistory(chatId) {
        try {
            const response = await fetch(`/chat/history?chat_id=${chatId}`);
            const data = await response.json();
            
            if (data.success) {
                // Clear current chat area
                const chatArea = document.querySelector('.chat-area');
                chatArea.innerHTML = '';
                
                // Load all messages
                data.history.forEach(message => {
                    addMessageToChat(message.role, message.content, false);
                });
                
                // Scroll to bottom
                chatArea.scrollTop = chatArea.scrollHeight;
            }
        } catch (error) {
            console.error('Error loading chat history:', error);
        }
    }

    // Add delete chat functionality
    async function deleteChat(chatId) {
        if (!confirm('Are you sure you want to delete this chat?')) {
            return;
        }

        try {
            const response = await fetch(`/chat/delete/${chatId}`, {
                method: 'DELETE'
            });
            const data = await response.json();
            
            if (data.success) {
                // Remove chat from sidebar
                const chatElement = document.querySelector(`[data-chat-id="${chatId}"]`);
                if (chatElement) {
                    chatElement.remove();
                }
                
                // If deleted chat was active, start a new chat
                if (currentChatId === chatId) {
                    startNewChat();
                }
            } else {
                alert('Failed to delete chat: ' + data.error);
            }
        } catch (error) {
            console.error('Error deleting chat:', error);
            alert('Failed to delete chat');
        }
    }
    </script>

    <!-- Add Prism.js for code syntax highlighting -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-javascript.min.js"></script>
</body>
</html>