{% extends "base.html" %}
{% block title %}Chat with {{ individual_name }} — Personaut{% endblock %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/chat.css') }}">
{% endblock %}

{% block content %}
<div class="chat-header">
    <div style="display:flex;align-items:center;gap:1rem">
        {% if portrait_url %}
        <img src="{{ portrait_url }}" alt="{{ individual_name }}"
            style="width:48px;height:48px;border-radius:50%;object-fit:cover;border:2px solid var(--accent);box-shadow:0 1px 6px rgba(108,93,211,0.2)">
        {% endif %}
        <div>
            <h1>Chat with {{ individual_name }}
                <span class="llm-badge {{ badge_class }}">{{ badge_text }}</span>
                <span class="token-total-badge" id="token-total">
                    <span class="label">tokens</span>
                    <span class="val" id="token-total-val">{{ total_tokens }}</span>
                    <span class="sep">│</span>
                    <span class="token-item prompt" title="Prompt tokens">↑{{ total_prompt }}</span>
                    <span class="token-item completion" title="Completion tokens">↓{{ total_completion }}</span>
                </span>
            </h1>
            <p class="chat-subtitle">Session: {{ session_id }}</p>
        </div>
    </div>
    <div style="display:flex;gap:0.5rem;align-items:center">
        <button type="button" class="btn btn-secondary btn-sm" id="btn-gen-video"
            onclick="generateVideo('{{ session_id }}')" style="font-size:0.8rem;padding:0.35rem 0.75rem">
            🎬 Generate POV Video
        </button>
        <a href="/chat" class="btn btn-secondary btn-sm">← Sessions</a>
    </div>
</div>

<div id="video-container" style="display:none;margin-bottom:1.5rem">
    <div class="panel">
        <div class="panel-header" style="cursor:pointer"
            onclick="document.getElementById('video-inner').style.display=document.getElementById('video-inner').style.display==='none'?'block':'none'">
            <h3>🎬 POV Video</h3>
            <span class="panel-toggle">▼</span>
        </div>
        <div id="video-inner" style="text-align:center;padding:1rem">
            <video id="video-player" controls
                style="max-width:100%;border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,0.2)">
                <source id="video-source" src="" type="video/mp4">
            </video>
        </div>
    </div>
</div>

{% if radar_data %}
<div class="panel" id="radar-panel">
    <div class="panel-header" onclick="toggleRadar()">
        <h3>🧠 Emotional State — {{ radar_data[0].name }}</h3>
        <span class="panel-toggle" id="radar-toggle">▼</span>
    </div>
    <div class="panel-body" id="radar-body">
        <div class="radar-canvas-wrap">
            <canvas id="radar-chart" width="240" height="240"></canvas>
        </div>
        <div class="radar-legend" id="radar-legend"></div>
    </div>
</div>
{% endif %}

<!-- Physical Features Panel -->
{% if physical_features %}
<div class="panel" id="physical-panel">
    <div class="panel-header"
        onclick="document.getElementById('physical-body').classList.toggle('collapsed');document.getElementById('physical-toggle').textContent=document.getElementById('physical-body').classList.contains('collapsed')?'▶':'▼'">
        <h3>🧍 Physical Features — {{ individual_name }}</h3>
        <span class="panel-toggle" id="physical-toggle">▶</span>
    </div>
    <div class="panel-body collapsed" id="physical-body">
        <div
            style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:0.5rem 1.5rem;padding:0.25rem 0">
            {% for key, value in physical_features.items() %}
            <div style="font-size:0.85rem">
                <span style="color:var(--txt3);text-transform:capitalize">{{ key.replace('_', ' ') }}:</span>
                <span style="color:var(--txt1);font-weight:500">{% if value is iterable and value is not string %}{{
                    value|join(', ') }}{% else %}{{ value }}{% endif %}</span>
            </div>
            {% endfor %}
        </div>
    </div>
</div>
{% endif %}

<!-- Memories Panel -->
{% if individual_id %}
<div class="panel" id="memories-panel">
    <div class="panel-header" onclick="toggleMemories()">
        <h3>💭 Memories — {{ individual_name }} <span id="memory-count-badge" class="count-badge">({{
                memories|length
                }})</span></h3>
        <span class="panel-toggle" id="memories-toggle">▶</span>
    </div>
    <div class="panel-body collapsed" id="memories-body">
        <!-- Search -->
        <div style="width:100%">
            <div class="panel-form-row" style="margin-bottom:.6rem">
                <input type="text" id="memory-search-input" placeholder="Search memories..." class="panel-input"
                    onkeypress="if(event.key==='Enter')searchMemories()">
                <button class="panel-btn panel-btn--accent" onclick="searchMemories()">🔍</button>
            </div>

            <!-- Memory list -->
            <div id="memory-list" class="item-list" style="max-height:180px">
                {% for mem in memories %}
                <div class="memory-item" id="mem-{{ mem.id }}">
                    <div class="item-content">
                        <div class="item-text">{{ mem.description }}</div>
                        <div class="item-meta">
                            salience: <span
                                class="{% if mem.salience >= 0.8 %}salience-high{% elif mem.salience >= 0.5 %}salience-mid{% else %}salience-low{% endif %}">{{
                                '%.0f'|format(mem.salience * 100) }}%</span>
                            {% if mem.emotional_state %}
                            · <span class="emo-tags">{{ mem.emotional_state.keys()|list|join(', ') }}</span>
                            {% endif %}
                        </div>
                    </div>
                    <button onclick="deleteMemory('{{ mem.id }}')" class="btn-delete" title="Delete memory">✕</button>
                </div>
                {% endfor %}
                {% if not memories %}
                <div id="no-memories-msg" class="empty-panel">
                    No memories yet. Add one below.
                </div>
                {% endif %}
            </div>

            <!-- Add memory form -->
            <div class="panel-form">
                <div class="section-label">Add Memory</div>
                <textarea id="new-memory-desc" placeholder="Describe a memory..." class="panel-textarea"></textarea>
                <div class="salience-row">
                    <label>Salience:</label>
                    <input type="range" id="new-memory-salience" min="0" max="100" value="50">
                    <span id="salience-display" class="salience-display">50%</span>
                </div>
                <div class="panel-form-row" style="margin-top:.35rem">
                    <input type="text" id="new-memory-emotions" placeholder="Optional emotions: happy=0.8, sad=0.3"
                        class="panel-input">
                    <button class="panel-btn panel-btn--accent" onclick="addMemory()">+ Add</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

<!-- Masks Panel -->
{% if individual_id %}
<div class="panel" id="masks-panel">
    <div class="panel-header" onclick="toggleMasks()">
        <h3>🎭 Masks — {{ individual_name }} <span id="mask-count-badge" class="count-badge">({{ masks|length
                }})</span>
        </h3>
        <span class="panel-toggle" id="masks-toggle">▶</span>
    </div>
    <div class="panel-body collapsed" id="masks-body">
        <div style="width:100%">
            <!-- Mask list -->
            <div id="mask-list" class="item-list">
                {% for mask in masks %}
                <div class="mask-item" id="mask-{{ mask.id }}">
                    <div class="item-content">
                        <div style="display:flex;align-items:center;gap:.4rem">
                            <span class="mask-name">{{ mask.name }}</span>
                            {% if mask.active_by_default %}
                            <span class="badge-always-on">ALWAYS ON</span>
                            {% endif %}
                        </div>
                        {% if mask.description %}
                        <div class="mask-desc">{{ mask.description }}</div>
                        {% endif %}
                        {% if mask.emotional_modifications %}
                        <div class="mod-chips">
                            {% for emo, val in mask.emotional_modifications.items() %}
                            <span
                                class="mod-chip {% if val > 0 %}mod-chip--positive{% else %}mod-chip--negative{% endif %}">{{
                                emo }} {% if val > 0 %}+{% endif %}{{ '%.1f'|format(val) }}</span>
                            {% endfor %}
                        </div>
                        {% endif %}
                        {% if mask.trigger_situations %}
                        <div class="mask-triggers-text">triggers: {{ mask.trigger_situations|join(', ') }}</div>
                        {% endif %}
                    </div>
                    <button onclick="deleteMask(JSON.stringify('{{ mask.id }}').slice(1,-1))" class="btn-delete"
                        title="Delete mask">✕</button>
                </div>
                {% endfor %}
                {% if not masks %}
                <div id="no-masks-msg" class="empty-panel">No masks yet. Add one below.</div>
                {% endif %}
            </div>

            <!-- Add mask form -->
            <div class="panel-form">
                <div class="section-label">Add Mask</div>
                <div class="panel-form-row">
                    <select id="mask-preset" class="panel-select" style="flex:1">
                        <option value="">Custom mask...</option>
                        <option value="professional">🏢 Professional</option>
                        <option value="casual">😊 Casual</option>
                        <option value="stoic">🧊 Stoic</option>
                        <option value="enthusiastic">⚡ Enthusiastic</option>
                        <option value="nurturing">💗 Nurturing</option>
                        <option value="guarded">🛡️ Guarded</option>
                    </select>
                    <button class="panel-btn panel-btn--blue" onclick="addMaskFromPreset()">+ Preset</button>
                </div>
                <input type="text" id="new-mask-name" placeholder="Mask name"
                    class="panel-input panel-input--mask panel-input--full">
                <input type="text" id="new-mask-desc" placeholder="Description (optional)"
                    class="panel-input panel-input--mask panel-input--full">
                <input type="text" id="new-mask-mods" placeholder="Emotional mods: angry=-0.5, content=0.2"
                    class="panel-input panel-input--mask panel-input--full">
                <div class="panel-form-row">
                    <input type="text" id="new-mask-triggers" placeholder="Trigger keywords: office, meeting, work"
                        class="panel-input panel-input--mask">
                    <button class="panel-btn panel-btn--blue" onclick="addCustomMask()">+ Add</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

<!-- Triggers Panel -->
{% if individual_id %}
<div class="panel" id="triggers-panel">
    <div class="panel-header" onclick="toggleTriggers()">
        <h3>⚡ Triggers — {{ individual_name }} <span id="trigger-count-badge" class="count-badge">({{
                triggers|length
                }})</span></h3>
        <span class="panel-toggle" id="triggers-toggle">▶</span>
    </div>
    <div class="panel-body collapsed" id="triggers-body">
        <div style="width:100%">
            <!-- Trigger list -->
            <div id="trigger-list" class="item-list">
                {% for trig in triggers %}
                <div class="trigger-item" id="trig-{{ trig.id }}">
                    <div class="item-content">
                        <div style="display:flex;align-items:center;gap:.4rem;flex-wrap:wrap">
                            <span
                                class="badge-type {% if trig.trigger_type == 'emotional' %}badge-type--emotional{% else %}badge-type--situational{% endif %}">{{
                                trig.trigger_type|upper }}</span>
                            <span class="trigger-desc">{{ trig.description }}</span>
                            <span onclick="toggleTriggerActive('{{ trig.id }}')"
                                class="badge-toggle {% if trig.active %}badge-toggle--on{% else %}badge-toggle--off{% endif %}">{%
                                if trig.active %}ON{% else %}OFF{% endif %}</span>
                        </div>
                        {% if trig.rules %}
                        <div class="mod-chips" style="margin-top:.25rem">
                            {% for rule in trig.rules %}
                            <span class="rule-chip">{{ rule.field }} {{ rule.operator }} {{ rule.threshold }}</span>
                            {% endfor %}
                            <span class="rule-match-mode">{% if trig.match_all %}ALL{% else %}ANY{% endif %}</span>
                        </div>
                        {% endif %}
                        {% if trig.keyword_triggers %}
                        <div class="trigger-keywords">keywords: {{ trig.keyword_triggers|join(', ') }}</div>
                        {% endif %}
                        {% if trig.response_data %}
                        <div class="trigger-response">response: {{ trig.response_type }} → {{ trig.response_data }}
                        </div>
                        {% endif %}
                    </div>
                    <button onclick="deleteTrigger(JSON.stringify('{{ trig.id }}').slice(1,-1))" class="btn-delete"
                        title="Delete trigger">✕</button>
                </div>
                {% endfor %}
                {% if not triggers %}
                <div id="no-triggers-msg" class="empty-panel">No triggers yet. Add one below.</div>
                {% endif %}
            </div>

            <!-- Add trigger form -->
            <div class="panel-form">
                <div class="section-label">Add Trigger</div>
                <div class="panel-form-row">
                    <select id="new-trigger-type" class="panel-select panel-input--trigger">
                        <option value="emotional">Emotional</option>
                        <option value="situational">Situational</option>
                    </select>
                    <input type="text" id="new-trigger-desc" placeholder="Trigger description"
                        class="panel-input panel-input--trigger">
                </div>
                <input type="text" id="new-trigger-rules" placeholder="Rules: anxious > 0.8, helpless > 0.6"
                    class="panel-input panel-input--trigger panel-input--full">
                <input type="text" id="new-trigger-keywords"
                    placeholder="Keywords (situational): dark, enclosed, basement"
                    class="panel-input panel-input--trigger panel-input--full">
                <div class="panel-form-row">
                    <input type="text" id="new-trigger-response" placeholder="Response mods: anxious=-0.3, content=0.2"
                        class="panel-input panel-input--trigger">
                    <select id="new-trigger-matchall" class="panel-select panel-input--trigger" style="width:auto">
                        <option value="true">ALL rules</option>
                        <option value="false">ANY rule</option>
                    </select>
                    <button class="panel-btn panel-btn--amber" onclick="addTrigger()">+ Add</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

<div class="chat-container">
    <div class="messages" id="messages">
        <div class="message received">
            <div class="message-sender">System</div>Chat session started. Say hello to {{ individual_name }}!
        </div>
        {% for msg in messages %}
        <div class="message {{ 'sent' if not msg.sender_id else 'received' }}">
            {% if msg.sender_name %}<div class="message-sender">{{ msg.sender_name }}</div>{% endif %}
            {{ msg.content }}
        </div>
        {% endfor %}
    </div>
    <div class="input-area">
        <input type="text" id="message-input" placeholder="Type a message to {{ individual_name }}..."
            onkeypress="if(event.key==='Enter')sendMessage('{{ session_id }}')">
        <button class="btn btn-primary" id="send-btn" onclick="sendMessage('{{ session_id }}')">Send</button>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/chat.js') }}"></script>
<script>
    // Page-specific data (used by chat.js)
    const RADAR_DATA = {{ radar_json| safe }};
    const CAT_COLORS = {{ cat_colors_json| safe }};
    const INDIVIDUAL_ID = '{{ individual_id }}';
    const SESSION_ID = '{{ session_id }}';

    drawRadar();
    initSalienceSlider();

    // ── Video generation ──────────────────────────────────────
    async function generateVideo(sessionId) {
        const btn = document.getElementById('btn-gen-video');
        const origText = btn.innerHTML;
        btn.disabled = true;
        btn.style.opacity = '0.6';
        btn.innerHTML = '⏳ Generating video...';

        // Progress messages to show while waiting
        const msgs = [
            '🎥 Crafting cinematic prompt...',
            '🎬 Veo is rendering your scene...',
            '🎞️ Still generating... (this can take a few minutes)',
            '✨ Almost there...',
        ];
        let msgIdx = 0;
        const interval = setInterval(() => {
            msgIdx = Math.min(msgIdx + 1, msgs.length - 1);
            btn.innerHTML = msgs[msgIdx];
        }, 30000);

        try {
            const resp = await fetch('/chat/' + sessionId + '/generate-video', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            clearInterval(interval);

            if (!resp.ok) {
                const err = await resp.json();
                throw new Error(err.detail || 'Video generation failed');
            }

            const data = await resp.json();
            if (data.video_url) {
                const container = document.getElementById('video-container');
                const source = document.getElementById('video-source');
                const player = document.getElementById('video-player');
                source.src = data.video_url + '?t=' + Date.now();
                player.load();
                container.style.display = 'block';
                btn.innerHTML = '🎬 Regenerate POV Video';
            }
        } catch (e) {
            clearInterval(interval);
            alert('Video generation failed: ' + e.message);
            btn.innerHTML = origText;
        } finally {
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    }
</script>
{% endblock %}