<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My AI App</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #0a0a0a;
            color: #e0e0e0;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        header {
            padding: 2rem;
            text-align: center;
        }
        h1 { font-size: 2rem; color: #ffd700; }
        .subtitle { color: #888; margin-top: 0.5rem; }
        .chat-container {
            width: 100%;
            max-width: 700px;
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 1rem;
        }
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 1rem 0;
        }
        .message {
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            max-width: 85%;
        }
        .message.user {
            background: #1a3a5c;
            margin-left: auto;
            white-space: pre-wrap;
        }
        .message.assistant {
            background: #1a1a2e;
        }
        .input-area {
            display: flex;
            gap: 0.5rem;
            padding: 1rem 0;
        }
        input {
            flex: 1;
            padding: 0.75rem 1rem;
            border: 1px solid #333;
            border-radius: 8px;
            background: #1a1a1a;
            color: #e0e0e0;
            font-size: 1rem;
        }
        input:focus { outline: none; border-color: #ffd700; }
        button {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            background: #ffd700;
            color: #0a0a0a;
            font-weight: bold;
            cursor: pointer;
        }
        button:hover { background: #ffed4a; }
        button:disabled { opacity: 0.5; cursor: not-allowed; }
        .tool-status {
            font-size: 0.8rem;
            color: #888;
            padding: 0.25rem 0;
            font-family: monospace;
        }
        .tool-status.completed { color: #6b8; }
        /* Markdown styles inside assistant messages */
        .message.assistant .md-content p { margin: 0.4em 0; }
        .message.assistant .md-content p:first-child { margin-top: 0; }
        .message.assistant .md-content p:last-child { margin-bottom: 0; }
        .message.assistant .md-content h1,
        .message.assistant .md-content h2,
        .message.assistant .md-content h3 {
            color: #ffd700; margin: 0.6em 0 0.3em; font-size: 1.1em;
        }
        .message.assistant .md-content h1 { font-size: 1.3em; }
        .message.assistant .md-content code {
            background: #2a2a3e; padding: 0.15em 0.35em; border-radius: 4px;
            font-size: 0.9em;
        }
        .message.assistant .md-content pre {
            background: #12121e; padding: 0.75rem; border-radius: 6px;
            overflow-x: auto; margin: 0.5em 0;
        }
        .message.assistant .md-content pre code {
            background: none; padding: 0;
        }
        .message.assistant .md-content ul,
        .message.assistant .md-content ol {
            padding-left: 1.5em; margin: 0.4em 0;
        }
        .message.assistant .md-content a { color: #7cacf8; }
        .message.assistant .md-content blockquote {
            border-left: 3px solid #444; padding-left: 0.75em;
            color: #999; margin: 0.4em 0;
        }
        .message.assistant .md-content table {
            border-collapse: collapse; margin: 0.5em 0; width: 100%;
        }
        .message.assistant .md-content th,
        .message.assistant .md-content td {
            border: 1px solid #333; padding: 0.3em 0.6em; text-align: left;
        }
        .message.assistant .md-content th { background: #1a1a2e; }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/marked@15/marked.min.js"></script>
</head>
<body>
    <header>
        <h1>My AI App</h1>
        <p class="subtitle">Powered by Amazon Bedrock AgentCore</p>
    </header>
    <div class="chat-container">
        <div class="messages" id="messages"></div>
        <div class="input-area">
            <input type="text" id="input" placeholder="Ask me anything..." autofocus>
            <button id="send" onclick="sendMessage()">Send</button>
        </div>
    </div>
    <script>
        const messagesEl = document.getElementById('messages');
        const inputEl = document.getElementById('input');
        const sendBtn = document.getElementById('send');
        const sessionId = crypto.randomUUID();

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

        function renderMarkdown(msgDiv) {
            const textEl = msgDiv.querySelector('.text-content');
            if (!textEl) return;
            const raw = textEl.textContent;
            if (!raw) return;
            const md = document.createElement('div');
            md.className = 'md-content';
            md.innerHTML = marked.parse(raw);
            textEl.replaceWith(md);
        }

        inputEl.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !sendBtn.disabled) sendMessage();
        });

        function shortToolName(name) {
            // Strip MCP prefixes like "mcp__strands__" for readability
            const parts = name.split('__');
            return parts[parts.length - 1] || name;
        }

        function processEvent(event, msgDiv) {
            if (!event || typeof event !== 'object') return;

            // Tool call started
            if (event.tool_use) {
                const name = shortToolName(event.tool_use.name);
                const el = document.createElement('div');
                el.className = 'tool-status';
                el.dataset.toolId = event.tool_use.id;
                el.textContent = '\uD83D\uDD27 Using ' + name + '...';
                msgDiv.appendChild(el);
                messagesEl.scrollTop = messagesEl.scrollHeight;
                return;
            }

            // Tool result
            if (event.tool_result) {
                const id = event.tool_result.id;
                const el = msgDiv.querySelector('.tool-status[data-tool-id="' + id + '"]');
                if (el) {
                    const name = el.textContent.replace('\uD83D\uDD27 Using ', '').replace('...', '');
                    el.textContent = '\u2713 ' + name + ' completed';
                    el.classList.add('completed');
                }
                return;
            }

            // Text delta
            const text = (typeof event.data === 'string' && event.data)
                || (typeof event.text === 'string' && event.text)
                || (event.delta && typeof event.delta.text === 'string' && event.delta.text)
                || (event.contentBlockDelta && event.contentBlockDelta.delta
                    && typeof event.contentBlockDelta.delta.text === 'string'
                    && event.contentBlockDelta.delta.text)
                || (typeof event.message === 'string' && event.message)
                || '';
            if (text) {
                // Append text to a text node (not tool-status divs)
                let textNode = msgDiv.querySelector('.text-content');
                if (!textNode) {
                    textNode = document.createElement('span');
                    textNode.className = 'text-content';
                    textNode.style.whiteSpace = 'pre-wrap';
                    msgDiv.appendChild(textNode);
                }
                textNode.textContent += text;
                messagesEl.scrollTop = messagesEl.scrollHeight;
            }
        }

        async function sendMessage() {
            const text = inputEl.value.trim();
            if (!text) return;

            addMessage(text, 'user');
            inputEl.value = '';
            sendBtn.disabled = true;

            const msgDiv = addMessage('', 'assistant');

            try {
                const resp = await fetch('/api/invoke', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: text, session_id: sessionId }),
                });

                const contentType = resp.headers.get('Content-Type') || '';

                if (contentType.includes('text/event-stream')) {
                    const reader = resp.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';

                    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;
                            const payload = line.slice(5).trim();
                            if (!payload || payload === '[DONE]') continue;
                            try {
                                const event = JSON.parse(payload);
                                processEvent(event, msgDiv);
                            } catch (_) { /* skip malformed SSE lines */ }
                        }
                    }
                } else {
                    const data = await resp.json();
                    msgDiv.textContent = data.message || data.response || JSON.stringify(data);
                }

                if (!msgDiv.textContent.trim()) {
                    msgDiv.textContent = '(empty response)';
                } else {
                    renderMarkdown(msgDiv);
                }
            } catch (err) {
                msgDiv.textContent = 'Error: Could not reach the agent. Is it deployed?';
            } finally {
                sendBtn.disabled = false;
                inputEl.focus();
            }
        }

        function addMessage(text, role) {
            const div = document.createElement('div');
            div.className = `message ${role}`;
            div.textContent = text;
            messagesEl.appendChild(div);
            messagesEl.scrollTop = messagesEl.scrollHeight;
            return div;
        }
    </script>
</body>
</html>
