<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NeonChat — {{ character.name }}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        :root {
            --bg: #0a0a0f; --surface: #15151f; --surface2: #1e1e2e;
            --border: #252535; --text: #e0e0e8; --muted: #6b6b80;
            --accent: #8338ec; --accent2: #ff006e; --user: #3a86ff;
        }
        body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); height: 100vh; display: flex; flex-direction: column; }
        
        header { display: flex; align-items: center; gap: 14px; padding: 14px 20px; background: var(--surface); border-bottom: 1px solid var(--border); }
        .avatar { font-size: 2rem; width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; background: var(--surface2); border-radius: 50%; }
        .char-name { font-size: 1.2rem; font-weight: 600; }
        .char-desc { font-size: 0.8rem; color: var(--muted); }
        .header-actions { margin-left: auto; display: flex; gap: 8px; }
        .btn { padding: 8px 16px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface2); color: var(--text); cursor: pointer; font-size: 0.85rem; transition: all 0.15s; }
        .btn:hover { border-color: var(--accent); }
        .btn-danger:hover { border-color: var(--accent2); color: var(--accent2); }
        
        .chat-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 12px; scroll-behavior: smooth; }
        .msg { max-width: 75%; padding: 12px 16px; border-radius: 16px; line-height: 1.6; font-size: 0.95rem; white-space: pre-wrap; word-break: break-word; }
        .msg-user { align-self: flex-end; background: var(--user); color: white; border-bottom-right-radius: 4px; }
        .msg-bot { align-self: flex-start; background: var(--surface); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
        .msg-system { align-self: center; background: transparent; color: var(--muted); font-size: 0.85rem; font-style: italic; }
        .msg-greeting { align-self: flex-start; background: var(--surface); border: 1px solid var(--accent); border-bottom-left-radius: 4px; }
        .typing { align-self: flex-start; color: var(--muted); font-size: 0.9rem; padding: 8px 16px; display: flex; gap: 4px; }
        .typing span { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); animation: blink 1.2s infinite; }
        .typing span:nth-child(2) { animation-delay: 0.2s; }
        .typing span:nth-child(3) { animation-delay: 0.4s; }
        @keyframes blink { 0%,100% { opacity: 0.2; } 50% { opacity: 1; } }
        
        .input-area { padding: 16px 20px; background: var(--surface); border-top: 1px solid var(--border); }
        .input-row { display: flex; gap: 10px; max-width: 1200px; margin: 0 auto; }
        textarea { flex: 1; background: var(--surface2); border: 1px solid var(--border); border-radius: 12px; padding: 12px 16px; color: var(--text); font-size: 0.95rem; font-family: inherit; resize: none; outline: none; transition: border 0.15s; max-height: 120px; }
        textarea:focus { border-color: var(--accent); }
        textarea::placeholder { color: var(--muted); }
        .send-btn { background: linear-gradient(135deg, var(--accent), var(--accent2)); border: none; border-radius: 12px; padding: 0 24px; color: white; font-size: 1rem; cursor: pointer; transition: opacity 0.15s; font-weight: 600; }
        .send-btn:hover { opacity: 0.9; }
        .send-btn:disabled { opacity: 0.4; cursor: not-allowed; }
        
        .memory-panel { position: fixed; top: 0; right: -400px; width: 380px; height: 100vh; background: var(--surface); border-left: 1px solid var(--border); padding: 20px; overflow-y: auto; transition: right 0.3s; z-index: 100; }
        .memory-panel.open { right: 0; }
        .memory-panel h3 { margin-bottom: 12px; font-size: 1rem; color: var(--accent); }
        .memory-panel h4 { margin: 16px 0 8px; font-size: 0.85rem; color: var(--muted); }
        .memory-entry { padding: 8px 12px; background: var(--surface2); border-radius: 8px; margin-bottom: 6px; font-size: 0.85rem; line-height: 1.5; }
        .summary-text { color: var(--text); line-height: 1.6; font-size: 0.85rem; }
        .memory-overlay { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 99; display: none; }
        .memory-overlay.show { display: block; }
        
        .session-info { font-size: 0.75rem; color: var(--muted); padding: 4px 8px; background: var(--surface2); border-radius: 6px; }
        
        @media (max-width: 768px) {
            .msg { max-width: 90%; }
        }
    </style>
</head>
<body>
    <header>
        <a href="/" style="color: var(--muted); text-decoration: none; font-size: 1.3rem;">←</a>
        <div class="avatar">{{ character.avatar }}</div>
        <div>
            <div class="char-name">{{ character.name }}</div>
            <div class="char-desc">{{ character.description[:60] }}{% if character.description|length > 60 %}...{% endif %}</div>
        </div>
        <div class="header-actions">
            <span class="session-info" id="sessionInfo" title="Session-ID">Session: ...</span>
            <span class="session-info" id="passcodeInfo" title="Passcode für andere Geräte" style="border-color: var(--accent); color: var(--accent);">Code: ...</span>
            <a href="/edit/{{ character_name }}" style="text-decoration: none;" title="Charakter bearbeiten"><button class="btn" type="button">✏️ Bearbeiten</button></a>
            <button class="btn" id="portraitBtn" onclick="generatePortrait()">🖼️ Portrait</button>
            <button class="btn" onclick="toggleMemory()">🧠 Gedächtnis</button>
            <button class="btn btn-danger" onclick="clearMemory()">🗑️ Vergessen</button>
        </div>
    </header>

    <div class="chat-container" id="chat">
        {% if character.greeting and not history %}
        <div class="msg msg-greeting">{{ character.greeting }}</div>
        {% endif %}
        {% for h in history %}
        <div class="msg {{ 'msg-user' if h.role == 'user' else 'msg-bot' }}">{{ h.content }}</div>
        {% endfor %}
    </div>

    <div class="input-area">
        <div class="input-row">
            <textarea id="input" placeholder="Nachricht an {{ character.name }}..." rows="1" onkeydown="handleKey(event)"></textarea>
            <button class="send-btn" id="send" onclick="sendMessage()">→</button>
        </div>
    </div>

    <div class="memory-overlay" id="overlay" onclick="toggleMemory()"></div>
    <div class="memory-panel" id="memoryPanel">
        <h3>🧠 Gedächtnis — {{ character.name }}</h3>
        <h4>Langzeit (Zusammenfassungen)</h4>
        <div id="longTerm">{{ long_term or '<i style="color:var(--muted)">Noch keine Erinnerungen</i>' }}</div>
        <h4>Kurzzeit (letzte Nachrichten)</h4>
        <div id="shortTerm">Lädt...</div>
    </div>

    <script>
        const charName = "{{ character.name }}";
        const charFilename = "{{ character.filename if character.filename else character_name }}";
        const chat = document.getElementById('chat');
        const input = document.getElementById('input');
        const sendBtn = document.getElementById('send');
        let isSending = false;

        // Show session ID (short) and passcode
        const sessionId = "{{ session_id }}";
        const passcode = "{{ passcode }}";
        document.getElementById('sessionInfo').textContent = 'Session: ' + sessionId.substring(0, 8) + '...';
        document.getElementById('passcodeInfo').textContent = 'Code: ' + passcode;

        // Auto-scroll
        chat.scrollTop = chat.scrollHeight;

        // Auto-resize textarea
        input.addEventListener('input', () => {
            input.style.height = 'auto';
            input.style.height = Math.min(input.scrollHeight, 120) + 'px';
        });

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

        async function sendMessage() {
            const msg = input.value.trim();
            if (!msg || isSending) return;
            isSending = true;
            sendBtn.disabled = true;

            // User message
            const userDiv = document.createElement('div');
            userDiv.className = 'msg msg-user';
            userDiv.textContent = msg;
            chat.appendChild(userDiv);
            input.value = '';
            input.style.height = 'auto';
            chat.scrollTop = chat.scrollHeight;

            // Typing indicator
            const typing = document.createElement('div');
            typing.className = 'typing';
            typing.innerHTML = '<span></span><span></span><span></span>';
            chat.appendChild(typing);
            chat.scrollTop = chat.scrollHeight;

            // Streaming via EventSource (fetch with streaming)
            const botDiv = document.createElement('div');
            botDiv.className = 'msg msg-bot';
            chat.appendChild(botDiv);

            try {
                const resp = await fetch(`/api/chat/${encodeURIComponent(charFilename)}`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({message: msg, stream: true})
                });

                const reader = resp.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let fullResponse = '';

                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;
                    buffer += decoder.decode(value, {stream: true});
                    
                    const lines = buffer.split('\n');
                    buffer = lines.pop();
                    
                    for (const line of lines) {
                        if (!line.startsWith('data: ')) continue;
                        try {
                            const data = JSON.parse(line.slice(6));
                            if (data.token) {
                                fullResponse += data.token;
                                botDiv.textContent = fullResponse;
                                chat.scrollTop = chat.scrollHeight;
                            }
                            if (data.done) {
                                // Streaming complete
                            }
                        } catch(e) {}
                    }
                }
                typing.remove();
                if (!fullResponse.trim()) {
                    botDiv.textContent = '*(Keine Antwort)*';
                }
            } catch(e) {
                typing.remove();
                botDiv.remove();
                const errDiv = document.createElement('div');
                errDiv.className = 'msg msg-system';
                errDiv.textContent = '⚠️ Verbindungsfehler: ' + e.message;
                chat.appendChild(errDiv);
            }

            isSending = false;
            sendBtn.disabled = false;
            input.focus();
        }

        function toggleMemory() {
            const panel = document.getElementById('memoryPanel');
            const overlay = document.getElementById('overlay');
            if (panel.classList.contains('open')) {
                panel.classList.remove('open');
                overlay.classList.remove('show');
            } else {
                panel.classList.add('open');
                overlay.classList.add('show');
                loadMemory();
            }
        }

        async function loadMemory() {
            try {
                const resp = await fetch(`/api/memory/${encodeURIComponent(charFilename)}`);
                const data = await resp.json();
                const shortDiv = document.getElementById('shortTerm');
                shortDiv.innerHTML = '';
                if (data.short_term && data.short_term.length > 0) {
                    data.short_term.forEach(m => {
                        const div = document.createElement('div');
                        div.className = 'memory-entry';
                        div.textContent = `${m.role === 'user' ? 'Du' : charName}: ${m.content}`;
                        shortDiv.appendChild(div);
                    });
                } else {
                    shortDiv.innerHTML = '<i style="color:var(--muted)">Keine aktuellen Nachrichten</i>';
                }
            } catch(e) {
                document.getElementById('shortTerm').textContent = 'Fehler beim Laden';
            }
        }

        async function clearMemory() {
            if (!confirm(`Gedächtnis von ${charName} wirklich löschen?`)) return;
            await fetch(`/api/memory/clear/${encodeURIComponent(charFilename)}`, {method: 'POST'});
            chat.innerHTML = '';
            if ("{{ character.greeting }}") {
                const g = document.createElement('div');
                g.className = 'msg msg-greeting';
                g.textContent = "{{ character.greeting }}";
                chat.appendChild(g);
            }
        }

        // Load history on reconnect (fixes the "conversation is somewhere else" bug)
        async function loadHistory() {
            try {
                const resp = await fetch(`/api/history/${encodeURIComponent(charFilename)}`);
                const data = await resp.json();
                if (data.history && data.history.length > 0) {
                    // Only reload if we have more messages than currently shown
                    const currentMsgs = chat.querySelectorAll('.msg').length;
                    if (data.history.length > currentMsgs || currentMsgs === 0) {
                        chat.innerHTML = '';
                        if ("{{ character.greeting }}") {
                            const g = document.createElement('div');
                            g.className = 'msg msg-greeting';
                            g.textContent = "{{ character.greeting }}";
                            chat.appendChild(g);
                        }
                        data.history.forEach(h => {
                            const div = document.createElement('div');
                            div.className = `msg ${h.role === 'user' ? 'msg-user' : 'msg-bot'}`;
                            div.textContent = h.content;
                            chat.appendChild(div);
                        });
                        chat.scrollTop = chat.scrollHeight;
                    }
                }
            } catch(e) {
                console.error('History load failed:', e);
            }
        }

        // Load history on page load (fixes reconnect issue)
        // Only if we don't already have history from server-side rendering
        {% if not history %}
        loadHistory();
        {% endif %}

        // Check ComfyUI status on load
        fetch('/api/comfyui/status').then(r => r.json()).then(data => {
            if (!data.running) {
                const btn = document.getElementById('portraitBtn');
                btn.title = 'ComfyUI läuft nicht — starte ComfyUI zuerst';
                btn.style.opacity = '0.5';
            }
        });

        async function generatePortrait() {
            const btn = document.getElementById('portraitBtn');
            const oldText = btn.textContent;
            btn.textContent = '⏳ Generiert...';
            btn.disabled = true;

            try {
                const resp = await fetch(`/api/character/${encodeURIComponent(charFilename)}/portrait`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({})
                });
                const data = await resp.json();
                
                if (!resp.ok) {
                    alert(data.error || 'Generierung fehlgeschlagen');
                    btn.textContent = oldText;
                    btn.disabled = false;
                    return;
                }
                
                if (data.job_id) {
                    const jobId = data.job_id;
                    const pollInterval = setInterval(async () => {
                        try {
                            const statusResp = await fetch(`/api/portrait/status/${jobId}`);
                            const statusData = await statusResp.json();
                            
                            if (statusData.status === 'done' && statusData.image) {
                                clearInterval(pollInterval);
                                const imgUrl = `${statusData.image}?t=${Date.now()}`;
                                
                                // Update avatar in header
                                const avatarEl = document.querySelector('.avatar');
                                avatarEl.innerHTML = `<img src="${imgUrl}" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">`;
                                
                                // Also show the portrait in the chat as a message
                                const portraitMsg = document.createElement('div');
                                portraitMsg.className = 'msg msg-bot';
                                portraitMsg.style.padding = '0';
                                portraitMsg.style.overflow = 'hidden';
                                portraitMsg.innerHTML = `
                                    <img src="${imgUrl}" style="width: 100%; max-width: 300px; border-radius: 16px 16px 16px 4px; display: block;">
                                    <div style="padding: 8px 12px; font-size: 0.8rem; color: var(--muted);">🖼️ Neues Portrait generiert</div>
                                `;
                                chat.appendChild(portraitMsg);
                                chat.scrollTop = chat.scrollHeight;
                                
                                btn.textContent = '✅ Fertig!';
                                setTimeout(() => { btn.textContent = oldText; btn.disabled = false; }, 2000);
                            } else if (statusData.status === 'error') {
                                clearInterval(pollInterval);
                                alert(statusData.error || 'Generierung fehlgeschlagen');
                                btn.textContent = oldText;
                                btn.disabled = false;
                            }
                        } catch(e) {
                            // ignore poll errors, keep trying
                        }
                    }, 3000);
                    
                    // Timeout after 5 minutes
                    setTimeout(() => {
                        clearInterval(pollInterval);
                        btn.textContent = oldText;
                        btn.disabled = false;
                    }, 300000);
                } else if (data.error) {
                    alert(data.error);
                    btn.textContent = oldText;
                    btn.disabled = false;
                }
            } catch(e) {
                alert('Verbindungsfehler: ' + e.message);
                btn.textContent = oldText;
                btn.disabled = false;
            }
        }
    </script>
</body>
</html>