{% extends "base.html" %}
{% block title %}{{ agent.name }} - Sigma Portal{% endblock %}

{% block extra_css %}
<style>
    body {
        overflow: hidden;
    }

    .main-content {
        margin-top: 60px;
        height: calc(100vh - 60px);
        display: flex;
        flex-direction: column;
        padding: 0;
        max-width: none;
    }

    /* ===== HEADER ===== */
    .chat-header {
        background: white;
        border-bottom: 1px solid #e5e7eb;
        padding: 0.875rem 1.5rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-shrink: 0;
    }

    .header-left {
        display: flex;
        align-items: center;
        gap: 0.875rem;
    }

    .back-button {
        background: #f3f4f6;
        border: none;
        padding: 0.5rem 0.875rem;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 600;
        font-size: 1rem;
        transition: all 0.15s ease;
        color: #374151;
        font-family: 'SF Pro Display', sans-serif;
        width: auto !important;
        margin: 0 !important;
    }

    .back-button:hover {
        background: #e5e7eb;
    }

    .agent-info {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .agent-avatar {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.125rem;
        flex-shrink: 0;
    }

    .agent-details {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .agent-details h1 {
        font-size: 1rem;
        font-weight: 600;
        color: #111827;
        margin: 0 0 2px 0;
        line-height: 1;
        font-family: 'SF Pro Display', sans-serif;
        white-space: nowrap;
    }

    .agent-details p {
        font-size: 1rem;
        color: #6b7280;
        margin: 0;
        line-height: 1;
        font-family: 'SF Pro Display', sans-serif;
        white-space: nowrap;
    }

    .header-actions {
        display: flex;
        gap: 0.625rem;
    }

    .header-btn {
        padding: 0.5rem 0.875rem;
        border: none;
        border-radius: 6px;
        font-weight: 600;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.15s ease;
        font-family: 'SF Pro Display', sans-serif;
        white-space: nowrap;
        line-height: 1;
        width: auto !important;
        margin: 0 !important;
    }

    .btn-settings {
        background: #f3f4f6;
        color: #374151;
    }

    .btn-settings:hover {
        background: #e5e7eb;
    }

    .btn-new {
        background: #3b82f6;
        color: white;
    }

    .btn-new:hover {
        background: #2563eb;
    }

    /* ===== LAYOUT ===== */
    .chat-layout {
        display: flex;
        flex: 1;
        overflow: hidden;
    }

    /* ===== SIDEBAR ===== */
    .chat-sidebar {
        width: 260px;
        background: white;
        border-right: 1px solid #e5e7eb;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .sidebar-header {
        padding: 0.875rem 1rem;
        border-bottom: 1px solid #e5e7eb;
        font-weight: 600;
        font-size: 1rem;
        color: #111827;
        background: #f9fafb;
        font-family: 'SF Pro Display', sans-serif;
    }

    .conversations-list {
        flex: 1;
        overflow-y: auto;
    }

    .conversation-item {
        padding: 0.875rem 1rem;
        border-bottom: 1px solid #f3f4f6;
        cursor: pointer;
        transition: background 0.15s ease;
    }

    .conversation-item:hover {
        background: #f9fafb;
    }

    .conversation-item.active {
        background: #eff6ff;
        border-left: 3px solid #3b82f6;
        padding-left: calc(1rem - 3px);
    }

    .conversation-title {
        font-weight: 500;
        color: #111827;
        font-size: 1rem;
        margin-bottom: 0.25rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-family: 'SF Pro Display', sans-serif;
    }

    .conversation-date {
        font-size: 1rem;
        color: #9ca3af;
        font-family: 'SF Pro Display', sans-serif;
    }

    .empty-conversations {
        padding: 2rem 1rem;
        text-align: center;
        color: #9ca3af;
        font-size: 1rem;
        line-height: 1.5;
        font-family: 'SF Pro Display', sans-serif;
    }

    /* ===== CHAT MAIN ===== */
    .chat-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        background: #f9fafb;
    }

    .messages-container {
        flex: 1;
        overflow-y: auto;
        padding: 1.5rem;
    }

    /* ===== WELCOME ===== */
    .welcome-screen {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        text-align: center;
    }

    .welcome-icon {
        font-size: 3.5rem;
        margin-bottom: 1rem;
    }

    .welcome-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #111827;
        margin: 0 0 0.5rem 0;
        font-family: 'SF Pro Display', sans-serif;
    }

    .welcome-text {
        font-size: 1rem;
        color: #6b7280;
        max-width: 480px;
        margin: 0;
        line-height: 1.5;
        font-family: 'SF Pro Display', sans-serif;
    }

    /* ===== MESSAGES ===== */
    .message {
        display: flex;
        gap: 0.75rem;
        margin-bottom: 1.25rem;
        animation: slideUp 0.2s ease;
    }

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

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

    .user-avatar {
        background: linear-gradient(135deg, #e5e7eb, #d1d5db);
    }

    .assistant-avatar {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
    }

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

    .message-bubble {
        background: white;
        padding: 0.75rem 1rem;
        border-radius: 12px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }

    .message.user .message-bubble {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: white;
    }

    .message-text {
        font-size: 1rem;
        line-height: 1.5;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-family: 'SF Pro Display', sans-serif;
    }

    .message-time {
        font-size: 1rem;
        color: #9ca3af;
        margin-top: 0.375rem;
        padding-left: 0.125rem;
        font-family: 'SF Pro Display', sans-serif;
    }

    .message.user .message-time {
        color: rgba(255, 255, 255, 0.7);
    }

    /* ===== TYPING INDICATOR ===== */
    .typing-indicator {
        display: none;
        padding: 0.75rem 1rem;
        background: white;
        border-radius: 12px;
        width: fit-content;
        margin-bottom: 1.25rem;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }

    .typing-indicator.active {
        display: flex;
        gap: 0.375rem;
        align-items: center;
    }

    .typing-dot {
        width: 6px;
        height: 6px;
        background: #9ca3af;
        border-radius: 50%;
        animation: bounce 1.4s infinite ease-in-out;
    }

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

    @keyframes bounce {
        0%,
        60%,
        100% {
            transform: translateY(0);
            opacity: 0.6;
        }
        30% {
            transform: translateY(-6px);
            opacity: 1;
        }
    }

    /* ===== INPUT AREA ===== */
    .input-area {
        background: white;
        border-top: 1px solid #e5e7eb;
        padding: 1rem 1.5rem;
        flex-shrink: 0;
    }

    .input-container {
        display: flex;
        gap: 0.75rem;
        align-items: flex-end;
        max-width: 1400px;
        margin: 0 auto;
    }

    .input-wrapper {
        flex: 1;
        display: flex;
    }

    .message-input {
        width: 100% !important;
        min-height: 44px;
        max-height: 160px;
        padding: 0.75rem 1rem;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        font-size: 1rem;
        font-family: 'SF Pro Display', sans-serif;
        resize: none;
        transition: all 0.15s ease;
        background: #f9fafb;
        line-height: 1.5;
        margin: 0 !important;
        box-sizing: border-box;
    }

    .message-input:focus {
        outline: none;
        border-color: #3b82f6;
        background: white;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .message-input::placeholder {
        color: #9ca3af;
        font-family: 'SF Pro Display', sans-serif;
    }

    .send-button {
        padding: 0.625rem 1.25rem;
        background: #3b82f6;
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.15s ease;
        flex-shrink: 0;
        white-space: nowrap;
        font-family: 'SF Pro Display', sans-serif;
        height: 44px;
        width: auto !important;
        margin: 0 !important;
    }

    .send-button:hover:not(:disabled) {
        background: #2563eb;
        transform: translateY(-1px);
    }

    .send-button:active:not(:disabled) {
        transform: translateY(0);
    }

    .send-button:disabled {
        background: #d1d5db;
        cursor: not-allowed;
    }

    /* ===== SCROLLBAR ===== */
    .messages-container::-webkit-scrollbar,
    .conversations-list::-webkit-scrollbar {
        width: 6px;
    }

    .messages-container::-webkit-scrollbar-track,
    .conversations-list::-webkit-scrollbar-track {
        background: transparent;
    }

    .messages-container::-webkit-scrollbar-thumb,
    .conversations-list::-webkit-scrollbar-thumb {
        background: #d1d5db;
        border-radius: 10px;
    }

    .messages-container::-webkit-scrollbar-thumb:hover,
    .conversations-list::-webkit-scrollbar-thumb:hover {
        background: #9ca3af;
    }

    /* ===== RESPONSIVE ===== */
    @media (max-width: 768px) {
        .chat-sidebar {
            display: none;
        }

        .chat-header {
            padding: 0.75rem 1rem;
        }

        .messages-container {
            padding: 1rem;
        }

        .input-area {
            padding: 0.875rem 1rem;
        }

        .message-content {
            max-width: 85%;
        }

        .header-btn span {
            display: none;
        }

        .btn-settings::after {
            content: '⚙️';
        }

        .btn-new::after {
            content: '+';
        }

        .send-button {
            padding: 0.625rem 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="main-content">
    <!-- Header -->
    <div class="chat-header">
        <div class="header-left">
            <button class="back-button" onclick="location.href='{{ url_for('ai.ai_landing') }}'">
                ← Back
            </button>
            <div class="agent-info">
                <div class="agent-avatar">
                    {% if agent.type == 'generative' %}💬{% else %}⚡{% endif %}
                </div>
                <div class="agent-details">
                    <h1>{{ agent.name }}</h1>
                    <p>{{ agent.type|capitalize }} Agent</p>
                </div>
            </div>
        </div>
        <div class="header-actions">
            <button class="header-btn btn-settings">
                <span>⚙️ Settings</span>
            </button>
            <button class="header-btn btn-new" onclick="startNewConversation()">
                <span>+ New Chat</span>
            </button>
        </div>
    </div>

    <!-- Main Layout -->
    <div class="chat-layout">
        <!-- Sidebar -->
        <div class="chat-sidebar">
            <div class="sidebar-header">Conversations</div>
            <div class="conversations-list" id="conversationsList">
                {% if conversations %}
                    {% for conv in conversations %}
                    <div class="conversation-item" onclick="loadConversation('{{ conv.id }}')">
                        <div class="conversation-title">{{ conv.title }}</div>
                        <div class="conversation-date">{{ conv.created_at[:10] }}</div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="empty-conversations">
                        No conversations yet.<br>Start chatting below!
                    </div>
                {% endif %}
            </div>
        </div>

        <!-- Chat Area -->
        <div class="chat-main">
            <div class="messages-container" id="messagesContainer">
                <div class="welcome-screen" id="welcomeScreen">
                    <div class="welcome-icon">{% if agent.type == 'generative' %}💬{% else %}⚡{% endif %}</div>
                    <h2 class="welcome-title">{{ agent.name }}</h2>
                    <p class="welcome-text">{{ agent.description }}</p>
                </div>

                <div class="typing-indicator" id="typingIndicator">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                </div>
            </div>

            <!-- Input Area -->
            <div class="input-area">
                <div class="input-container">
                    <div class="input-wrapper">
                        <textarea
                            id="messageInput"
                            class="message-input"
                            placeholder="Type your message..."
                            rows="1"
                            onkeydown="handleKeyPress(event)"
                        ></textarea>
                    </div>
                    <button id="sendButton" class="send-button" onclick="sendMessage()">
                        Send
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentConversationId = null;
const agentId = "{{ agent.id }}";

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

function handleKeyPress(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

function startNewConversation() {
    currentConversationId = null;
    document.getElementById('messagesContainer').innerHTML = `
        <div class="welcome-screen" id="welcomeScreen">
            <div class="welcome-icon">{% if agent.type == 'generative' %}💬{% else %}⚡{% endif %}</div>
            <h2 class="welcome-title">{{ agent.name }}</h2>
            <p class="welcome-text">{{ agent.description }}</p>
        </div>
        <div class="typing-indicator" id="typingIndicator">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
        </div>
    `;
    document.querySelectorAll('.conversation-item').forEach(item => {
        item.classList.remove('active');
    });
}

function loadConversation(conversationId) {
    currentConversationId = conversationId;
    document.querySelectorAll('.conversation-item').forEach(item => {
        item.classList.remove('active');
    });
    event.target.closest('.conversation-item').classList.add('active');
}

async function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();

    if (!message) return;

    input.value = '';
    input.style.height = 'auto';
    input.disabled = true;
    document.getElementById('sendButton').disabled = true;

    const welcomeScreen = document.getElementById('welcomeScreen');
    if (welcomeScreen) {
        welcomeScreen.style.display = 'none';
    }

    addMessage('user', message);

    const typingIndicator = document.getElementById('typingIndicator');
    typingIndicator.classList.add('active');

    try {
        const response = await fetch(`/ai/agent/${agentId}/chat`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                conversation_id: currentConversationId,
            }),
        });

        const data = await response.json();

        if (data.success) {
            currentConversationId = data.conversation_id;
            typingIndicator.classList.remove('active');
            addMessage('assistant', data.message.content, data.message.tool_use);

            if (!currentConversationId) {
                location.reload();
            }
        } else {
            typingIndicator.classList.remove('active');
            addMessage('assistant', 'Error: ' + (data.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error:', error);
        typingIndicator.classList.remove('active');
        addMessage('assistant', 'Failed to send message. Please try again.');
    }

    input.disabled = false;
    document.getElementById('sendButton').disabled = false;
    input.focus();
}

function addMessage(role, content, toolUse = null) {
    const container = document.getElementById('messagesContainer');
    const typingIndicator = document.getElementById('typingIndicator');

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;

    const avatarDiv = document.createElement('div');
    avatarDiv.className = `message-avatar ${role}-avatar`;
    avatarDiv.textContent = role === 'user' ? '👤' : '{% if agent.type == "generative" %}💬{% else %}⚡{% endif %}';

    const contentWrapper = document.createElement('div');
    contentWrapper.className = 'message-content';

    const bubbleDiv = document.createElement('div');
    bubbleDiv.className = 'message-bubble';

    const textDiv = document.createElement('div');
    textDiv.className = 'message-text';
    textDiv.textContent = content;

    bubbleDiv.appendChild(textDiv);

    if (toolUse) {
        const toolDiv = document.createElement('div');
        toolDiv.style.cssText = 'margin-top: 0.5rem; padding: 0.375rem 0.75rem; background: #fef3c7; color: #92400e; border-radius: 6px; font-size: 1rem; font-weight: 500;';
        toolDiv.innerHTML = `🔧 Used tool: ${toolUse.name}`;
        bubbleDiv.appendChild(toolDiv);
    }

    contentWrapper.appendChild(bubbleDiv);

    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';
    timeDiv.textContent = new Date().toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
    });
    contentWrapper.appendChild(timeDiv);

    messageDiv.appendChild(avatarDiv);
    messageDiv.appendChild(contentWrapper);

    container.insertBefore(messageDiv, typingIndicator);

    container.scrollTo({
        top: container.scrollHeight,
        behavior: 'smooth',
    });
}

window.addEventListener('load', function () {
    document.getElementById('messageInput').focus();
});
</script>
{% endblock %}