{% extends group_config.template_base or "base_demo.html" %}

{% block title %}{{ role.name }} - Chat{% endblock %}

{% block content %}
<main class="container">
    <hgroup>
        <h1 style="color: {{ role.color }};">{{ role.icon }} {{ role.name }}</h1>
        <p>
            {{ role.description }}
            <a href="/crumbforest/roles/{{ role.id }}/export" role="button" class="outline secondary"
                style="font-size: 0.7em; padding: 0.2rem 0.5rem; margin-left: 1rem;" target="_blank">
                📥 Export Chat
            </a>
        </p>
    </hgroup>

    <style>
        :root {
            --role-color: {
                    {
                    role.color
                }
            }

            ;
        }
    </style>

    <!-- Prism.js for Syntax Highlighting -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-sql.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-json.min.js"></script>

    <article id="chat-container">
        <div id="messages"
            style="height: 500px; overflow-y: auto; padding: 1rem; border: 1px solid var(--pico-muted-border-color); border-radius: var(--pico-border-radius); margin-bottom: 1rem;">
            <!-- Messages will be added here via JS -->
            <div style="text-align: center; color: var(--pico-muted-color); margin-top: 2rem;">
                <small>Start a conversation with {{ role.name }}...</small>
            </div>
        </div>

        <footer>
            <form id="chat-form">
                <div class="grid">
                    <input type="text" name="question" id="question-input"
                        placeholder="Ask {{ role.name }} something..." required autofocus autocomplete="off">
                    <button type="submit" style="width: auto;">Send</button>
                </div>
            </form>
        </footer>
    </article>
</main>

<script>
    const roleId = "{{ role.id }}";
    const chatForm = document.getElementById('chat-form');
    const messagesDiv = document.getElementById('messages');
    const questionInput = document.getElementById('question-input');

    // Auto-scroll to bottom
    function scrollToBottom() {
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    chatForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const question = questionInput.value;
        if (!question.trim()) return;

        // Clear input
        questionInput.value = '';

        // Remove initial placeholder if present
        if (messagesDiv.querySelector('small')) {
            messagesDiv.innerHTML = '';
        }

        // Add user message
        addMessage('user', question);

        // Show loading
        const loadingId = addMessage('assistant', '{{ role.icon }} thinking...');

        try {
            const formData = new FormData();
            formData.append('question', question);

            const response = await fetch(`/crumbforest/roles/${roleId}/ask`, {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            // Remove loading
            const loadingEl = document.getElementById(loadingId);
            if (loadingEl) loadingEl.remove();

            if (response.ok) {
                addMessage('assistant', data.answer);
            } else {
                addMessage('error', data.answer || 'Error communicating with server.');
            }

        } catch (error) {
            const loadingEl = document.getElementById(loadingId);
            if (loadingEl) loadingEl.remove();
            addMessage('error', 'Oops! Network error.');
            console.error(error);
        }
    });

    function addMessage(role, content) {
        const msgId = 'msg-' + Date.now();
        const div = document.createElement('div');
        div.id = msgId;
        div.style.marginBottom = '1rem';
        div.style.padding = '1rem';
        div.style.borderRadius = 'var(--pico-border-radius)';
        div.style.maxWidth = '85%';

        // Simple Markdown Parsing for Code Blocks
        // Replaces ```language ... ``` with <pre><code class="language-...">...</code></pre>
        let formattedContent = content;

        // Escape HTML first to prevent injection (basic)
        formattedContent = formattedContent
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");

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

        // Inline code
        formattedContent = formattedContent.replace(/`([^`]+)`/g, '<code class="language-plaintext">$1</code>');

        // Line breaks (only outside of pre tags - simplified)
        // This is a bit hacky, a real markdown parser would be better, but sufficient for now
        formattedContent = formattedContent.replace(/\n/g, '<br>');
        // Fix double breaks in pre
        formattedContent = formattedContent.replace(/<pre>(.*?)<\/pre>/gs, (match) => {
            return match.replace(/<br>/g, '\n');
        });

        if (role === 'user') {
            div.style.background = 'var(--pico-primary-background)';
            div.style.color = 'var(--pico-primary-inverse)';
            div.style.marginLeft = 'auto'; // Align right
            div.style.textAlign = 'left';
            div.innerHTML = `<strong>You</strong><br>${formattedContent}`;
        } else if (role === 'assistant') {
            div.style.background = 'var(--role-color, var(--pico-secondary-background))';
            div.style.color = 'white'; // Always white text on colored background? Or depends on brightness?
            // Let's use a safe fallback or keep it simple. If role color is light, white text might be bad.
            // But most config colors seem dark enough? 
            // Dumbo is #6c757d (grey), SnakePy #3776ab (blue). White text is fine.
            // FunkFox #f7df1e (yellow) -> White text is BAD.
            // We might need a contrast color from config or calc().

            // For now, let's stick to the pico variable for text if we use role color for border?
            // Or use an opacity version?

            // Let's try attempting to use the role color as a border-left accent instead, to be safe with text contrast?
            div.style.background = 'var(--pico-card-background-color)';
            div.style.borderLeft = '5px solid var(--role-color, var(--pico-primary))';
            div.style.color = 'var(--pico-color)';

            div.style.marginRight = 'auto'; // Align left
            div.innerHTML = `<strong>{{ role.name }}</strong><br>${formattedContent}`;
        } else {
            div.style.background = 'var(--pico-del-color)';
            div.style.color = 'white';
            div.innerHTML = `<strong>Error</strong><br>${formattedContent}`;
        }

        messagesDiv.appendChild(div);

        // Trigger Prism Highlight
        if (window.Prism) {
            Prism.highlightAllUnder(div);
        }

        scrollToBottom();

        return msgId;
    }
</script>
{% endblock %}