{% extends "company_base.html" %}
{% block title %}Chat Assistent - {{ employee_name }}{% endblock %}

{% block head %}
<style>
body { background-color: #3d4848; }
#mainContent > div { padding: 0 !important; }
.chat-fixed-header, .chat-fixed-input { left: 256px; right: 0; transition: left 0.3s ease; }
aside.collapsed ~ main .chat-fixed-header,
aside.collapsed ~ main .chat-fixed-input { left: 64px; }
.dot { animation: bounce 1.4s infinite ease-in-out; display: inline-block; }
.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce { 0%, 80%, 100% { transform: translateY(0); } 40% { transform: translateY(-8px); } }
.post-type-chip { transition: all 0.2s; }
</style>
{% endblock %}

{% block content %}
<!-- Header -->
<div class="chat-fixed-header fixed bg-brand-bg z-20 top-0">
    <div class="px-8 py-4 flex items-center gap-4">
        <a href="/company/manage/posts?employee_id={{ employee_id }}" class="text-gray-400 hover:text-white transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
        </a>
        <div>
            <h1 class="text-xl font-bold text-white">💬 Chat Assistent</h1>
            <p class="text-xs text-gray-400">Für {{ employee_name }}</p>
        </div>
    </div>
</div>

<!-- Messages Area -->
<div id="chat-messages" class="px-8 space-y-4 pb-64 max-w-[80%] mx-auto" style="padding-top: 90px;">
    <div class="flex items-start gap-3">
        <div class="w-8 h-8 bg-brand-highlight/20 rounded-full flex items-center justify-center flex-shrink-0">
            <span class="text-lg">🤖</span>
        </div>
        <div class="max-w-[70%]">
            <div class="bg-brand-bg-dark rounded-2xl p-4 border border-gray-600">
                <p class="text-gray-300">
                    Hallo! Ich helfe dir, einen LinkedIn-Post für <strong>{{ employee_name }}</strong> zu erstellen.
                    Beschreibe, worüber der Post handeln soll.
                </p>
            </div>
        </div>
    </div>
</div>

<!-- Input Area -->
<div class="chat-fixed-input fixed bottom-0 bg-brand-bg z-10">
    <div class="pt-4 pb-6 px-8">
        <div class="space-y-3 mx-auto" style="max-width: 768px;">
            <!-- Post Type Chips -->
            {% if post_types %}
            <div class="flex flex-wrap gap-1.5" id="post-type-chips">
                {% for pt in post_types %}
                <button onclick="selectPostType('{{ pt.id }}', this)"
                    data-post-type-id="{{ pt.id }}"
                    class="post-type-chip px-3 py-1 rounded-full text-xs font-medium
                           {% if loop.first %}bg-brand-highlight text-black{% else %}bg-brand-bg-dark text-gray-400 hover:bg-brand-bg-light hover:text-gray-300{% endif %}"
                    {% if loop.first %}data-selected="true"{% endif %}>
                    {{ pt.name }}
                </button>
                {% endfor %}
            </div>
            {% else %}
            <p class="text-yellow-400 text-sm">Keine Post-Typen für diesen Mitarbeiter vorhanden. Bitte erst Post-Typen anlegen.</p>
            {% endif %}
            <!-- Input Bar -->
            <div class="flex gap-3 items-center">
                <div class="flex-1 relative">
                    <input type="text" id="chat-input"
                        placeholder="{% if limit_reached %}Token-Limit erreicht – morgen wieder verfügbar{% else %}Beschreibe den Post...{% endif %}"
                        class="w-full input-bg border border-gray-600 rounded-full px-6 py-3 text-white focus:outline-none focus:border-brand-highlight transition-colors {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}"
                        onkeydown="handleChatKeydown(event)"
                        {% if limit_reached %}disabled{% endif %}>
                </div>
                <button onclick="sendMessage()" id="send-btn"
                    class="w-12 h-12 bg-brand-highlight hover:bg-yellow-500 text-black rounded-full transition-all flex items-center justify-center flex-shrink-0 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}"
                    {% if limit_reached %}disabled{% endif %}>
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                </button>
                <button onclick="savePost()" id="save-btn"
                    class="hidden w-12 h-12 bg-green-600 hover:bg-green-500 text-white rounded-full transition-all items-center justify-center flex-shrink-0"
                    title="Post speichern">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let chatHistory = [];
let currentPost = null;
let selectedPostTypeId = null;
const EMPLOYEE_ID = "{{ employee_id }}";
let tokenLimitReached = {{ 'true' if limit_reached else 'false' }};

document.addEventListener('DOMContentLoaded', () => {
    const firstChip = document.querySelector('.post-type-chip[data-selected="true"]');
    if (firstChip) selectedPostTypeId = firstChip.dataset.postTypeId;
});

function selectPostType(postTypeId, element) {
    selectedPostTypeId = postTypeId;
    document.querySelectorAll('.post-type-chip').forEach(chip => {
        chip.classList.remove('bg-brand-highlight', 'text-black');
        chip.classList.add('bg-brand-bg-dark', 'text-gray-400');
        chip.removeAttribute('data-selected');
    });
    element.classList.remove('bg-brand-bg-dark', 'text-gray-400');
    element.classList.add('bg-brand-highlight', 'text-black');
    element.setAttribute('data-selected', 'true');
}

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

async function sendMessage() {
    if (tokenLimitReached) return;
    const input = document.getElementById('chat-input');
    const message = input.value.trim();
    if (!message) { showToast('Bitte gib eine Nachricht ein', 'error'); return; }
    if (!selectedPostTypeId) { showToast('Bitte wähle einen Post-Typ aus', 'error'); return; }

    addMessageToChat('user', message);
    input.value = '';

    const container = document.getElementById('chat-messages');
    const tempMsg = document.createElement('div');
    tempMsg.id = 'temp-msg';
    tempMsg.className = 'flex items-start gap-3';
    tempMsg.innerHTML = `<div class="w-8 h-8 bg-brand-highlight/20 rounded-full flex items-center justify-center flex-shrink-0"><span class="text-lg">🤖</span></div><div class="max-w-[70%]"><div class="bg-brand-bg-dark rounded-2xl p-4 border border-gray-600"><p class="text-gray-300">wird generiert<span class="dot">.</span><span class="dot">.</span><span class="dot">.</span></p></div></div>`;
    container.appendChild(tempMsg);
    container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });

    const sendBtn = document.getElementById('send-btn');
    const originalHTML = sendBtn.innerHTML;
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<svg class="w-5 h-5 animate-spin" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" opacity="0.3"/><path d="M12 2v4c3.31 0 6 2.69 6 6h4c0-5.52-4.48-10-10-10z"/></svg>';

    try {
        const endpoint = currentPost ? null : '/api/company/manage/chat/generate';
        // For refinement, use generate with current_post context
        const response = await fetch('/api/company/manage/chat/generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ employee_id: EMPLOYEE_ID, message: message, post_type_id: selectedPostTypeId, current_post: currentPost, chat_history: chatHistory })
        });
        const result = await response.json();
        document.getElementById('temp-msg')?.remove();

        if (result.success) {
            currentPost = result.post;
            addMessageToChat('ai', result.explanation || 'Hier ist der Entwurf:', result.post);
            chatHistory.push({ user: message, ai: result.post, explanation: result.explanation });
            const saveBtn = document.getElementById('save-btn');
            saveBtn.classList.remove('hidden');
            saveBtn.classList.add('flex');
        } else if (result.token_limit_exceeded) {
            tokenLimitReached = true;
            showToast(result.error || 'Token-Limit erreicht', 'error');
        } else {
            showToast('Fehler: ' + (result.error || 'Unbekannter Fehler'), 'error');
            addMessageToChat('ai', '❌ Fehler beim Generieren. Bitte versuche es erneut.');
        }
    } catch (error) {
        document.getElementById('temp-msg')?.remove();
        showToast('Netzwerkfehler', 'error');
    } finally {
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalHTML;
    }
}

function addMessageToChat(type, text, post = null) {
    const container = document.getElementById('chat-messages');
    const div = document.createElement('div');
    const postHtml = post ? `<div class="mt-3 p-4 bg-brand-bg rounded-2xl border border-brand-highlight/30"><span class="text-brand-highlight font-medium text-sm">Post-Entwurf</span><div class="text-gray-200 whitespace-pre-wrap text-sm leading-relaxed mt-2">${escapeHtml(post)}</div></div>` : '';

    if (type === 'user') {
        div.className = 'flex items-start gap-3 justify-end';
        div.innerHTML = `<div class="max-w-[70%]"><div class="bg-blue-900/30 rounded-2xl p-4 border border-blue-700/50"><p class="text-white">${escapeHtml(text)}</p></div></div><div class="w-8 h-8 bg-brand-highlight rounded-full flex items-center justify-center flex-shrink-0"><span class="text-brand-bg-dark font-bold text-sm">K</span></div>`;
    } else {
        div.className = 'flex items-start gap-3';
        div.innerHTML = `<div class="w-8 h-8 bg-brand-highlight/20 rounded-full flex items-center justify-center flex-shrink-0"><span class="text-lg">🤖</span></div><div class="max-w-[70%]"><div class="bg-brand-bg-dark rounded-2xl p-4 border border-gray-600"><p class="text-gray-300">${escapeHtml(text)}</p>${postHtml}</div></div>`;
    }
    container.appendChild(div);
    container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
}

async function savePost() {
    if (!currentPost) { showToast('Kein Post zum Speichern', 'error'); return; }
    const saveBtn = document.getElementById('save-btn');
    const originalHTML = saveBtn.innerHTML;
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>';

    try {
        const topicTitle = (chatHistory[0]?.user || currentPost).slice(0, 80);
        const response = await fetch('/api/company/manage/chat/save', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ employee_id: EMPLOYEE_ID, post_content: currentPost, post_type_id: selectedPostTypeId, chat_history: chatHistory, topic_title: topicTitle })
        });
        const result = await response.json();
        if (result.success) {
            showToast('Post gespeichert!', 'success');
            setTimeout(() => { window.location.href = `/company/manage/post/${result.post_id}?employee_id=${EMPLOYEE_ID}`; }, 1000);
        } else {
            showToast('Fehler: ' + (result.error || 'Speichern fehlgeschlagen'), 'error');
        }
    } catch (e) {
        showToast('Netzwerkfehler beim Speichern', 'error');
    } finally {
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalHTML;
    }
}

function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
}
</script>
{% endblock %}
