{% extends "base.html" %}
{% block title %}Агент — TG Agent{% endblock %}

{% block head_scripts %}
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
.agent-layout {
    display: flex;
    gap: 1rem;
    height: calc(100vh - 220px);
    min-height: 400px;
}
.agent-sidebar {
    width: 240px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    overflow-y: auto;
    padding: 0.85rem;
    border: 1px solid var(--bs-border-color);
    border-radius: 18px;
    background: var(--bs-body-bg);
    box-shadow: 0 14px 36px rgba(15, 23, 42, 0.04);
}
.thread-item {
    display: flex;
    align-items: center;
    gap: 0.3rem;
    padding: 0.4rem 0.6rem;
    border-radius: 6px;
    border: 1px solid var(--bs-border-color);
    cursor: pointer;
    text-decoration: none;
    color: inherit;
    font-size: 0.9rem;
    background: transparent;
    transition: background 0.15s;
}
.thread-item:hover { background: var(--bs-tertiary-bg); color: inherit; }
.thread-item.active {
    background: var(--bs-primary);
    border-color: var(--bs-primary);
    color: #fff;
    font-weight: 600;
}
.thread-item .thread-title {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.thread-delete-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0 2px;
    color: var(--bs-secondary-color);
    font-size: 0.8rem;
    line-height: 1;
    flex-shrink: 0;
    min-height: unset;
    width: auto;
}
.thread-delete-btn:hover { color: #dc3545; }

.agent-chat {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    min-height: 0;
    gap: 0.9rem;
}
.chat-status-panel {
    display: flex;
    flex-direction: column;
    gap: 0.7rem;
    padding: 1rem 1.1rem;
    border: 1px solid var(--bs-border-color);
    border-radius: 18px;
    background:
        linear-gradient(135deg, var(--bs-primary-bg-subtle), transparent 55%),
        var(--bs-body-bg);
    box-shadow: 0 16px 32px rgba(15, 23, 42, 0.05);
}
.chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 1rem;
    padding-bottom: 0.7rem;
    border-bottom: 1px solid var(--bs-border-color);
}
.chat-header-title {
    font-size: 1.45rem;
    font-weight: 600;
    line-height: 1.2;
    margin: 0;
}
.chat-header-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    justify-content: flex-end;
}
.chat-runtime {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    align-items: center;
    font-size: 0.82rem;
}
.runtime-chip {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.28rem 0.55rem;
    border-radius: 999px;
    border: 1px solid var(--bs-border-color);
    background: var(--bs-body-bg);
    color: var(--bs-secondary-color);
    line-height: 1.1;
}
.runtime-chip code {
    font-size: 0.78rem;
    color: inherit;
}
.runtime-chip-on {
    border-color: var(--bs-success-border-subtle);
    background: var(--bs-success-bg-subtle);
    color: var(--bs-success-text-emphasis);
}
.runtime-chip-off {
    border-color: var(--bs-secondary-border-subtle);
    background: var(--bs-secondary-bg);
}
.runtime-chip-accent {
    border-color: var(--bs-warning-border-subtle);
    background: var(--bs-warning-bg-subtle);
    color: var(--bs-warning-text-emphasis);
}
.chat-stage {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    border: 1px solid var(--bs-border-color);
    border-radius: 22px;
    background: var(--bs-body-bg);
    box-shadow: 0 20px 40px rgba(15, 23, 42, 0.05);
    overflow: hidden;
}
.chat-messages {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    padding: 1.1rem 1rem 0.9rem 1rem;
    background:
        radial-gradient(circle at top right, rgba(13, 110, 253, 0.05), transparent 28%),
        var(--bs-body-bg);
}
.message-bubble {
    max-width: 85%;
    padding: 0.6rem 0.9rem;
    border-radius: 10px;
    font-size: 0.9rem;
    line-height: 1.5;
    word-break: break-word;
}
.message-user {
    white-space: pre-wrap;
    align-self: flex-end;
    background: var(--bs-primary);
    color: #fff;
    border-bottom-right-radius: 3px;
}
.message-assistant {
    align-self: flex-start;
    background: var(--bs-body-bg);
    border: 1px solid var(--bs-border-color);
    border-bottom-left-radius: 3px;
}
.message-assistant p:first-child { margin-top: 0; }
.message-assistant p:last-child { margin-bottom: 0; }
.message-assistant table {
    font-size: 0.8rem;
    border-collapse: collapse;
    margin: 0.5rem 0;
    width: 100%;
}
.message-assistant th,
.message-assistant td {
    border: 1px solid var(--bs-border-color);
    padding: 0.3rem 0.5rem;
}
.message-assistant pre {
    background: var(--bs-tertiary-bg);
    padding: 0.5rem;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 0.8rem;
}
.message-assistant code { font-size: 0.8rem; }
.message-assistant h1 { font-size: 1.15rem; }
.message-assistant h2 { font-size: 1.05rem; }
.message-assistant h3 { font-size: 0.95rem; }
.message-assistant h4,
.message-assistant h5,
.message-assistant h6 { font-size: 0.9rem; }
.message-assistant h1,
.message-assistant h2,
.message-assistant h3,
.message-assistant h4,
.message-assistant h5,
.message-assistant h6 {
    margin: 0.5rem 0 0.25rem 0;
    line-height: 1.3;
}
.message-assistant hr {
    border: none;
    border-top: 1px solid var(--bs-border-color);
    margin: 0.75rem 0;
}
.message-error {
    align-self: flex-start;
    background: var(--bs-danger-bg-subtle);
    border: 1px solid var(--bs-danger-border-subtle);
    color: var(--bs-danger-text-emphasis);
    border-radius: 10px;
    padding: 0.6rem 0.9rem;
    font-size: 0.9rem;
    max-width: 85%;
}
.retry-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.2rem;
    margin-left: 10px;
    vertical-align: middle;
    padding: 0;
    line-height: 1;
    transition: transform 0.3s;
}
.retry-btn:hover {
    transform: rotate(180deg);
}
.typing-indicator {
    display: inline-block;
    color: var(--bs-secondary-color);
    font-style: italic;
}
.typing-indicator::after {
    content: "...";
    animation: dots 1.2s steps(3, end) infinite;
}
@keyframes dots {
    0%, 20% { content: "."; }
    40% { content: ".."; }
    60%, 100% { content: "..."; }
}

.chat-composer {
    padding: 0.95rem 1rem 1rem 1rem;
    border-top: 1px solid var(--bs-border-color);
    display: flex;
    flex-direction: column;
    gap: 0.7rem;
    background: var(--bs-body-bg);
}
.chat-composer-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.75rem;
    flex-wrap: wrap;
    min-height: 1.4rem;
}
.composer-caption {
    font-size: 0.78rem;
    color: var(--bs-secondary-color);
}
.composer-subtle {
    font-size: 0.78rem;
    color: var(--bs-secondary-color);
    text-align: right;
}
.chat-input-area {
    display: flex;
    gap: 0.75rem;
    align-items: stretch;
}
.chat-input-area textarea {
    flex: 1;
    resize: none;
    min-height: 110px;
    max-height: 180px;
    font-size: 0.9rem;
    padding: 0.9rem 1rem;
    border-radius: 16px;
}
.composer-actions {
    width: 230px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 0.55rem;
    justify-content: flex-end;
}
.chat-send-btn,
.model-select {
    width: 100%;
    min-width: 0;
    font-size: 0.9rem;
}
.chat-send-btn {
    min-height: 46px;
    border-radius: 14px;
    font-weight: 600;
}
.composer-hint {
    padding: 0.5rem 0.65rem;
    border-radius: 14px;
    border: 1px solid var(--bs-border-color);
    background: var(--bs-tertiary-bg);
    color: var(--bs-secondary-color);
    font-size: 0.8rem;
    line-height: 1.35;
}
.composer-hint strong {
    display: block;
    margin-bottom: 0.2rem;
    color: var(--bs-body-color);
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--bs-secondary-color);
    gap: 1rem;
    text-align: center;
}

.agent-context {
    width: 220px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 0.6rem;
    padding: 0.85rem;
    font-size: 0.8rem;
    border: 1px solid var(--bs-border-color);
    border-radius: 18px;
    background: var(--bs-body-bg);
    box-shadow: 0 14px 36px rgba(15, 23, 42, 0.04);
}
.agent-context h3 {
    margin: 0 0 0.25rem 0;
    font-size: 0.8rem;
    color: var(--bs-secondary-color);
    text-transform: uppercase;
}
.agent-context label { margin-bottom: 0.1rem; }
.agent-context select,
.agent-context input[type=number] { margin-bottom: 0; font-size: 0.85rem; }
.message-context {
    max-width: 95%;
    align-self: stretch;
    background: var(--bs-tertiary-bg);
    border: 1px dashed var(--bs-border-color);
    border-radius: 6px;
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
    color: var(--bs-secondary-color);
    white-space: pre-wrap;
    word-break: break-word;
}

@media (max-width: 991.98px) {
    .agent-sidebar {
        display: none;
    }
    .agent-context {
        display: none;
    }
    .agent-layout {
        height: calc(100vh - 180px);
    }
    .agent-chat {
        flex: 1;
    }
    .message-bubble {
        max-width: 95%;
    }
    .mobile-agent-toolbar {
        display: flex !important;
    }
}
@media (min-width: 992px) {
    .mobile-agent-toolbar {
        display: none !important;
    }
}
@media (max-width: 767.98px) {
    .agent-layout {
        height: calc(100vh - 160px);
    }
    .chat-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .chat-header-badges {
        justify-content: flex-start;
    }
    .chat-status-panel {
        padding: 0.9rem;
        border-radius: 16px;
    }
    .chat-stage {
        border-radius: 18px;
    }
    .chat-input-area {
        flex-wrap: wrap;
        align-items: stretch;
    }
    .chat-input-area textarea {
        width: 100%;
        flex: 1 1 100%;
        min-height: 72px;
    }
    .composer-actions {
        width: 100%;
    }
    .chat-composer-meta {
        align-items: flex-start;
    }
    .composer-subtle {
        width: 100%;
        text-align: left;
    }
}
</style>
{% endblock %}

{% block content %}
<h1>Агент</h1>

<!-- Mobile toolbar -->
<div class="mobile-agent-toolbar gap-2 mb-2" style="display:none">
    <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebar-offcanvas">Треды</button>
    <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="offcanvas" data-bs-target="#context-offcanvas">Контекст</button>
</div>

<!-- Offcanvas: sidebar -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="sidebar-offcanvas">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title">Треды</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body d-flex flex-column gap-2">
        {% for thread in threads %}
        <a class="thread-item {% if active_thread and active_thread.id == thread.id %}active{% endif %}"
           href="/agent?thread_id={{ thread.id }}">
            <span class="thread-title" title="{{ thread.title }}">{{ thread.title }}</span>
            <button class="thread-delete-btn"
                    onclick="deleteThread(event, {{ thread.id }})"
                    title="Удалить тред">&#10005;</button>
        </a>
        {% else %}
        <p class="small text-muted">Тредов пока нет</p>
        {% endfor %}
        <form method="post" action="/agent/threads" style="margin-top:auto" data-busy>
            <button type="submit" class="btn btn-outline-primary btn-sm w-100">+ Новый тред</button>
        </form>
    </div>
</div>

<!-- Offcanvas: context -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="context-offcanvas">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title">Контекст</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body d-flex flex-column gap-2">
        <label for="ctx-channel-m">Канал</label>
        <select id="ctx-channel-m" class="form-select form-select-sm">
            <option value="">— выберите —</option>
        </select>
        <label for="ctx-limit-m">Сообщений</label>
        <input type="number" id="ctx-limit-m" class="form-control form-control-sm" placeholder="все" min="1" max="10000">
        <button id="ctx-load-btn-m" class="btn btn-outline-primary btn-sm" {% if not active_thread %}disabled{% endif %}>
            Загрузить
        </button>
        <small id="ctx-status-m" class="text-muted"></small>
    </div>
</div>

<div class="agent-layout">
    <!-- Sidebar: thread list -->
    <div class="agent-sidebar">
        <h3 class="text-muted text-uppercase small">Треды</h3>

        {% for thread in threads %}
        <a class="thread-item {% if active_thread and active_thread.id == thread.id %}active{% endif %}"
           href="/agent?thread_id={{ thread.id }}"
           data-thread-id="{{ thread.id }}">
            <span class="thread-title" title="{{ thread.title }}">{{ thread.title }}</span>
            <button class="thread-delete-btn"
                    onclick="deleteThread(event, {{ thread.id }})"
                    title="Удалить тред">&#10005;</button>
        </a>
        {% else %}
        <p class="small text-muted">Тредов пока нет</p>
        {% endfor %}

        <form method="post" action="/agent/threads" style="margin-top:auto" data-busy>
            <button type="submit" class="btn btn-outline-primary btn-sm w-100 mt-2">+ Новый тред</button>
        </form>
    </div>

    <!-- Main chat area -->
    <div class="agent-chat">
        {% if active_thread %}
        <div class="chat-status-panel">
            <div class="chat-header">
                <div class="chat-header-title">{{ active_thread.title }}</div>
                <div class="chat-header-badges">
                    {% if agent_status and agent_status.selected_backend %}
                    <span class="badge text-bg-secondary">{{ agent_status.selected_backend }}</span>
                    {% endif %}
                    {% if agent_status and agent_status.using_override %}
                    <span class="badge text-bg-warning">dev override</span>
                    {% endif %}
                </div>
            </div>

            {% if agent_status %}
            <div class="chat-runtime">
                <span class="runtime-chip {{ 'runtime-chip-on' if agent_status.selected_backend == 'claude' else 'runtime-chip-off' }}">
                    Claude
                    <strong>{{ "on" if agent_status.selected_backend == "claude" else "off" }}</strong>
                </span>
                <span class="runtime-chip {{ 'runtime-chip-on' if agent_status.selected_backend == 'deepagents' else 'runtime-chip-off' }}">
                    deepagents
                    <strong>{{ "on" if agent_status.selected_backend == "deepagents" else "off" }}</strong>
                </span>
                {% if agent_status.selected_backend == "deepagents" and agent_status.fallback_model %}
                <span class="runtime-chip runtime-chip-accent">
                    provider
                    <code>{{ agent_status.fallback_provider or "unknown" }}</code>
                </span>
                <span class="runtime-chip runtime-chip-accent">
                    model
                    <code>{{ agent_status.fallback_model }}</code>
                </span>
                {% endif %}
            </div>
            {% if agent_status.error %}
            <div class="alert alert-warning py-2 mb-0">{{ agent_status.error }}</div>
            {% endif %}
            {% endif %}
        </div>

        <div class="chat-stage">
            <div class="chat-messages" id="chat-messages">
                {% for msg in messages %}
                {% if msg.role == 'assistant' %}
                <div class="message-bubble message-{{ msg.role }}" data-md>{{ msg.content }}</div>
                {% else %}
                <div class="message-bubble message-{{ msg.role }}">{{ msg.content }}</div>
                {% endif %}
                {% else %}
                <div class="empty-state">
                    <span style="font-size:2rem">&#129302;</span>
                    <p>Напишите первое сообщение</p>
                </div>
                {% endfor %}
            </div>

            <div class="chat-composer">
                <div class="chat-composer-meta">
                    <span class="composer-caption">Сообщение отправится в текущий тред.</span>
                    {% if agent_status and agent_status.selected_backend == "deepagents" %}
                    <span class="composer-subtle">Runtime управляется настройками deepagents.</span>
                    {% else %}
                    <span class="composer-subtle">Модель Claude можно переключить прямо здесь.</span>
                    {% endif %}
                </div>
                <div class="chat-input-area">
                    <textarea id="chat-input" class="form-control"
                              placeholder="Введите сообщение… (Enter — отправить, Shift+Enter — перенос строки)"
                              ></textarea>
                    <div class="composer-actions">
                        {% if not agent_status or agent_status.selected_backend != "deepagents" %}
                        <div class="composer-caption">Модель Claude</div>
                        <select id="model-select" class="form-select model-select">
                            <option value="">Авто</option>
                            {% for value, label in model_options %}
                            <option value="{{ value }}">{{ label }}</option>
                            {% endfor %}
                        </select>
                        {% else %}
                        <div class="composer-hint">
                            <strong>Deepagents runtime</strong>
                            Модель и provider берутся из сохраненных настроек и показываются в статусе выше.
                        </div>
                        {% endif %}
                        <button class="btn btn-primary chat-send-btn" id="send-btn"
                                onclick="sendMessage()">Отправить</button>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <!-- Right context panel -->
    <div class="agent-context" id="context-panel">
        <h3>Контекст</h3>
        <label for="ctx-channel">Канал</label>
        <select id="ctx-channel" class="form-select form-select-sm">
            <option value="">— выберите —</option>
        </select>
        <div id="ctx-topic-wrap" style="display:none">
            <label for="ctx-topic">Тема форума</label>
            <select id="ctx-topic" class="form-select form-select-sm">
                <option value="">Все темы</option>
            </select>
        </div>
        <label for="ctx-limit">Сообщений</label>
        <input type="number" id="ctx-limit" class="form-control form-control-sm" placeholder="все" min="1" max="10000">
        <button id="ctx-load-btn" class="btn btn-outline-primary btn-sm" {% if not active_thread %}disabled{% endif %}>
            Загрузить
        </button>
        <small id="ctx-status" class="text-muted"></small>
    </div>
</div>

<script>
(function() {
    var threadId = {{ active_thread.id if active_thread else 'null' }};
    var sending = false;
    var abortController = null;

    // Model selector: persist in localStorage
    var modelSelect = document.getElementById('model-select');
    if (modelSelect) {
        var savedModel = localStorage.getItem('agent_model') || '';
        modelSelect.value = savedModel;
        modelSelect.addEventListener('change', function() {
            localStorage.setItem('agent_model', this.value);
        });
    }

    // Configure marked
    marked.setOptions({breaks: true, gfm: true});

    function renderMd(text) {
        return marked.parse(text || '');
    }

    // Render existing assistant messages loaded from DB
    document.querySelectorAll('[data-md]').forEach(function(el) {
        el.innerHTML = renderMd(el.textContent);
    });

    // Scroll to bottom on load
    var chatMessages = document.getElementById('chat-messages');
    if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // Enter to send
    var input = document.getElementById('chat-input');
    if (input) {
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    }

    function setStopMode(active) {
        var sendBtn = document.getElementById('send-btn');
        var inputEl = document.getElementById('chat-input');
        if (active) {
            sendBtn.textContent = 'Стоп';
            sendBtn.classList.remove('btn-primary');
            sendBtn.classList.add('btn-secondary');
            sendBtn.onclick = function() { stopGeneration(); };
            sendBtn.disabled = false;
            inputEl.disabled = true;
        } else {
            sendBtn.textContent = 'Отправить';
            sendBtn.classList.remove('btn-secondary');
            sendBtn.classList.add('btn-primary');
            sendBtn.onclick = function() { sendMessage(); };
            sendBtn.disabled = false;
            inputEl.disabled = false;
        }
    }

    window.stopGeneration = async function() {
        if (!sending || !threadId) return;
        var sendBtn = document.getElementById('send-btn');
        sendBtn.disabled = true;

        if (abortController) {
            abortController.abort();
            abortController = null;
        }

        try {
            await fetch('/agent/threads/' + threadId + '/stop', {method: 'POST'});
        } catch(e) { /* ignore */ }

        var container = document.getElementById('chat-messages');
        container.querySelectorAll('.message-bubble[data-pending]').forEach(function(el) {
            el.remove();
        });

        if (!container.querySelector('.message-bubble') && !container.querySelector('.message-context')) {
            var empty = document.createElement('div');
            empty.className = 'empty-state';
            empty.innerHTML = '<span style="font-size:2rem">&#129302;</span><p>Напишите первое сообщение</p>';
            container.appendChild(empty);
        }

        sending = false;
        setStopMode(false);
        document.getElementById('chat-input').focus();
    };

    function addRegenerateButton(bubble, text, removeUserBubble) {
        var btn = document.createElement('button');
        btn.className = 'retry-btn';
        btn.innerHTML = '&#128260;'; // 🔄
        btn.title = 'Повторить';
        btn.onclick = function() {
            if (removeUserBubble) {
                var prev = bubble.previousElementSibling;
                if (prev && prev.classList.contains('message-user') && prev.textContent === text) {
                    prev.remove();
                }
            }
            bubble.remove();
            sendMessage(text);
        };
        bubble.appendChild(btn);
    }

    window.sendMessage = async function(textToRetry) {
        if (sending || !threadId) return;
        var inputEl = document.getElementById('chat-input');
        var text = textToRetry || (inputEl.value || '').trim();
        if (!text) return;

        sending = true;
        if (!textToRetry) {
            inputEl.value = '';
        }
        setStopMode(true);

        abortController = new AbortController();

        var container = document.getElementById('chat-messages');

        var emptyState = container.querySelector('.empty-state');
        if (emptyState) emptyState.remove();

        var userBubble = document.createElement('div');
        userBubble.className = 'message-bubble message-user';
        userBubble.setAttribute('data-pending', 'true');
        userBubble.textContent = text;
        container.appendChild(userBubble);
        container.scrollTop = container.scrollHeight;

        var aiBubble = document.createElement('div');
        aiBubble.className = 'message-bubble message-assistant';
        aiBubble.setAttribute('data-pending', 'true');
        aiBubble.innerHTML = '<span class="typing-indicator">Думаю</span>';
        container.appendChild(aiBubble);
        container.scrollTop = container.scrollHeight;

        try {
            var resp = await fetch('/agent/threads/' + threadId + '/chat', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({message: text, model: (document.getElementById('model-select') || {}).value || ''}),
                signal: abortController.signal
            });

            if (!resp.ok) {
                var errBody = await resp.json().catch(function() { return {}; });
                throw new Error(errBody.detail || 'HTTP ' + resp.status);
            }

            var reader = resp.body.getReader();
            var decoder = new TextDecoder();
            var buffer = '';
            var fullText = '';

            while (true) {
                var result = await reader.read();
                if (result.done) break;

                buffer += decoder.decode(result.value, {stream: true});
                var lines = buffer.split('\n');
                buffer = lines.pop();

                for (var line of lines) {
                    line = line.trim();
                    if (!line.startsWith('data:')) continue;
                    var jsonStr = line.slice(5).trim();
                    try {
                        var data = JSON.parse(jsonStr);
                        if (data.error) {
                            aiBubble.className = 'message-error';
                            aiBubble.textContent = data.error;
                            fullText = data.error;
                            addRegenerateButton(aiBubble, text, true);
                        } else if (data.text !== undefined) {
                            fullText += data.text;
                            aiBubble.innerHTML = renderMd(fullText);
                            container.scrollTop = container.scrollHeight;
                        } else if (data.done) {
                            fullText = data.full_text || fullText;
                            aiBubble.innerHTML = renderMd(fullText);
                            container.scrollTop = container.scrollHeight;
                        }
                    } catch(e) { /* skip bad JSON */ }
                }
            }

            if (aiBubble.querySelector('.typing-indicator')) {
                aiBubble.textContent = 'Нет ответа от агента.';
            }

            userBubble.removeAttribute('data-pending');
            aiBubble.removeAttribute('data-pending');

        } catch(err) {
            if (err.name === 'AbortError') return;
            aiBubble.className = 'message-error';
            aiBubble.textContent = 'Ошибка соединения: ' + err.message;
        }

        sending = false;
        abortController = null;
        setStopMode(false);
        inputEl.focus();
        container.scrollTop = container.scrollHeight;
    };

    window.deleteThread = async function(e, tid) {
        e.preventDefault();
        e.stopPropagation();
        if (!confirm('Удалить тред?')) return;
        var btn = e.target.closest('button') || e.target;
        setAsyncButtonBusy(btn, true, '');
        try {
            await fetch('/agent/threads/' + tid, {method: 'DELETE'});
            window.location.href = '/agent';
        } catch(err) {
            setAsyncButtonBusy(btn, false);
            alert('Ошибка удаления: ' + err.message);
        }
    };

    // Context panel
    async function loadChannels() {
        try {
            var resp = await fetch('/agent/channels-json');
            var channels = await resp.json();
            var sel = document.getElementById('ctx-channel');
            channels.forEach(function(ch) {
                var opt = document.createElement('option');
                opt.value = ch.id;
                opt.dataset.type = ch.channel_type;
                opt.textContent = ch.title;
                sel.appendChild(opt);
            });
        } catch(e) {
            console.error('Failed to load channels:', e);
            document.getElementById('ctx-status').textContent = 'Ошибка загрузки каналов';
        }
    }

    var ctxChannel = document.getElementById('ctx-channel');
    if (ctxChannel) {
        ctxChannel.addEventListener('change', async function() {
            var opt = this.options[this.selectedIndex];
            var topicWrap = document.getElementById('ctx-topic-wrap');
            var topicSel = document.getElementById('ctx-topic');
            topicSel.innerHTML = '<option value="">Все темы</option>';
            if (opt && opt.value) {
                var knownType = opt.dataset.type;
                var shouldFetch = !knownType || knownType === 'null' || knownType === 'undefined'
                                  || knownType === 'forum';
                if (shouldFetch) {
                    try {
                        var resp = await fetch('/agent/forum-topics?channel_id=' + opt.value);
                        var topics = await resp.json();
                        if (topics.length > 0) {
                            topicWrap.style.display = '';
                            opt.dataset.type = 'forum';
                            topics.forEach(function(t) {
                                var o = document.createElement('option');
                                o.value = t.id;
                                o.textContent = t.title;
                                topicSel.appendChild(o);
                            });
                        } else if (knownType === 'forum') {
                            topicWrap.style.display = '';
                            var o = document.createElement('option');
                            o.value = '';
                            o.textContent = '(темы не загружены)';
                            o.disabled = true;
                            topicSel.appendChild(o);
                        } else {
                            topicWrap.style.display = 'none';
                        }
                    } catch(e) {
                        console.error('Failed to load topics:', e);
                        topicWrap.style.display = knownType === 'forum' ? '' : 'none';
                    }
                } else {
                    topicWrap.style.display = 'none';
                }
            } else {
                topicWrap.style.display = 'none';
            }
        });
    }

    var ctxLoadBtn = document.getElementById('ctx-load-btn');
    if (ctxLoadBtn) {
        ctxLoadBtn.addEventListener('click', async function() {
            if (!threadId) return;
            var channelId = document.getElementById('ctx-channel').value;
            if (!channelId) return;
            var limitVal = document.getElementById('ctx-limit').value.trim();
            var limit = limitVal ? parseInt(limitVal) : 0;
            var topicId = document.getElementById('ctx-topic').value || null;
            var status = document.getElementById('ctx-status');
            setAsyncButtonBusy(this, true, 'Загрузить');
            status.textContent = 'Загрузка…';
            var self = this;
            try {
                var resp = await fetch('/agent/threads/' + threadId + '/context', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({channel_id: channelId, limit: limit, topic_id: topicId})
                });
                var data = await resp.json();
                var bubble = document.createElement('div');
                bubble.className = 'message-bubble message-context';
                bubble.textContent = data.content;
                var msgContainer = document.getElementById('chat-messages');
                if (msgContainer) {
                    var emptyState = msgContainer.querySelector('.empty-state');
                    if (emptyState) emptyState.remove();
                    msgContainer.appendChild(bubble);
                    msgContainer.scrollTop = msgContainer.scrollHeight;
                }
                status.textContent = 'Загружено ✓';
            } catch(e) {
                status.textContent = 'Ошибка: ' + e.message;
            } finally {
                setAsyncButtonBusy(self, false);
            }
        });
    }

    loadChannels();
})();
</script>
{% endblock %}
