{% extends "base.html" %}

{% block title %}Chat Assistent{% endblock %}

{% block content %}
<!-- Posts Sidebar -->
<div class="posts-sidebar" {% if limit_reached %}style="top: 1.5rem; height: calc(100vh - 1.5rem);"{% endif %}>
    <div class="posts-sidebar-header">
        <button id="new-post-btn" onclick="startNewPost()" {% if limit_reached %}disabled title="{{ limit_message }}"{% endif %}>
            + Neuer Post
        </button>
    </div>

    <div class="posts-sidebar-list">
        {% if saved_posts %}
            {% for post in saved_posts %}
                <div class="post-sidebar-item"
                     data-post-id="{{ post.id }}"
                     onclick="loadPostHistory('{{ post.id }}')">
                    <div class="post-sidebar-title">{{ post.topic_title }}</div>
                    <span class="post-sidebar-status status-{{ post.status }}">{{ post.status }}</span>
                </div>
            {% endfor %}
        {% else %}
            <div class="posts-sidebar-empty">
                Noch keine Posts vorhanden
            </div>
        {% endif %}
    </div>
</div>

<style>
/* Make chat page full height and remove padding */
#mainContent > div {
    padding: 0 !important;
}

/* Fixed elements adjust to sidebar with smooth transition */
.chat-fixed-header,
.chat-fixed-input {
    left: 256px;
    right: 0;
    transition: left 0.3s ease;
}

/* When sidebar is collapsed, adjust fixed elements */
aside.collapsed ~ main .chat-fixed-header,
aside.collapsed ~ main .chat-fixed-input {
    left: 64px;
}

/* Bouncing dots animation */
.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); }
}

/* Posts Sidebar */
.posts-sidebar {
    position: fixed;
    left: 256px;
    top: 0;
    width: 280px;
    height: 100vh;
    background-color: #2d3838;
    border-right: 1px solid #5a6868;
    z-index: 15;
    display: flex;
    flex-direction: column;
    transition: left 0.3s ease;
}

/* When main sidebar is collapsed */
aside.collapsed ~ main .posts-sidebar {
    left: 64px;
}

/* Hide on smaller screens */
@media (max-width: 1280px) {
    .posts-sidebar {
        display: none !important;
    }
    #chat-messages {
        margin-left: 0 !important;
    }
    .chat-fixed-header,
    .chat-fixed-input {
        left: 256px !important;
    }
    aside.collapsed ~ main .chat-fixed-header,
    aside.collapsed ~ main .chat-fixed-input {
        left: 64px !important;
    }
}

/* Sidebar Header */
.posts-sidebar-header {
    padding: 1rem;
    border-bottom: 1px solid #5a6868;
}

.posts-sidebar-header button {
    width: 100%;
    padding: 0.625rem 1rem;
    background-color: #ffc700;
    color: #2d3838;
    border-radius: 0.5rem;
    font-weight: 600;
    font-size: 0.875rem;
    transition: background-color 0.2s;
    border: none;
    cursor: pointer;
}

.posts-sidebar-header button:hover {
    background-color: #e6b300;
}

.posts-sidebar-header button:disabled {
    background-color: #4a5568;
    color: #a0aec0;
    cursor: not-allowed;
}

/* Posts List */
.posts-sidebar-list {
    flex: 1;
    overflow-y: auto;
    padding: 0.5rem;
}

/* Post Item */
.post-sidebar-item {
    padding: 0.75rem 1rem;
    margin-bottom: 0.25rem;
    background-color: #3d4848;
    border-left: 3px solid transparent;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.5rem;
}

.post-sidebar-item:hover {
    background-color: #4a5858;
    border-left-color: #ffc700;
}

.post-sidebar-item.active {
    background-color: #4a5858;
    border-left-color: #ffc700;
}

.post-sidebar-title {
    font-size: 0.875rem;
    color: #e5e5e5;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
}

.post-sidebar-status {
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.75rem;
    font-weight: 500;
    flex-shrink: 0;
}

.status-draft {
    background-color: rgba(107, 114, 128, 0.3);
    color: #d1d5db;
}

.status-approved {
    background-color: rgba(16, 185, 129, 0.2);
    color: #6ee7b7;
}

.status-ready {
    background-color: rgba(59, 130, 246, 0.2);
    color: #93c5fd;
}

.status-scheduled {
    background-color: rgba(251, 146, 60, 0.2);
    color: #fdba74;
}

.status-published {
    background-color: rgba(16, 185, 129, 0.2);
    color: #6ee7b7;
}

.status-rejected {
    background-color: rgba(239, 68, 68, 0.2);
    color: #fca5a5;
}

/* Empty state */
.posts-sidebar-empty {
    padding: 2rem 1rem;
    text-align: center;
    color: #9ca3af;
    font-size: 0.875rem;
}

/* Adjust chat area for sidebar */
#chat-messages {
    margin-left: 280px;
}

.chat-fixed-header,
.chat-fixed-input {
    left: 536px; /* 256px (main sidebar) + 280px (posts sidebar) */
}

aside.collapsed ~ main .chat-fixed-header,
aside.collapsed ~ main .chat-fixed-input {
    left: 344px; /* 64px (collapsed main sidebar) + 280px (posts sidebar) */
}
</style>

<!-- Header (Fixed at top) -->
<div class="chat-fixed-header fixed bg-brand-bg z-20" style="top: {% if limit_reached %}1.5rem{% else %}0{% endif %}">
    <div class="px-8 py-4 flex items-center gap-4">
        <a href="/create" class="inline-flex items-center gap-2 text-sm text-gray-400 hover:text-brand-highlight transition-colors">
            <svg class="w-4 h-4" 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>
            Zurück
        </a>
        <h1 class="text-xl font-bold text-white">💬 Chat Assistent</h1>
    </div>
</div>

<!-- Messages Area (Full page scroll with padding for fixed header and input) -->
<div id="chat-messages" class="px-8 space-y-4 pb-64 max-w-[80%] mx-auto" style="padding-top: 80px;">
        <!-- Welcome Message -->
        <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 beim Erstellen deines LinkedIn-Posts.
                        Beschreibe mir einfach, worüber du schreiben möchtest, und ich erstelle einen ersten Entwurf für dich.
                    </p>
                    <p class="text-gray-400 text-sm mt-2">
                        Du kannst mich danach bitten, den Post anzupassen, umzuschreiben oder zu verbessern.
                    </p>
                </div>
            </div>
        </div>
    </div>

<!-- Input Area (Fixed at bottom, floating over messages) -->
<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 Selector (Chips) - Above Input -->
            <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 transition-all
                           {% 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>

            <!-- 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 deinen 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 hover:scale-110 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}"
                    {% if limit_reached %}disabled title="{{ limit_message }}"{% else %}title="Senden (Enter)"{% 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 hover:scale-110"
                    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 conversationId = null;
let selectedPostTypeId = null;
let currentLoadedPostId = null; // Track active post
let tokenLimitReached = {{ 'true' if limit_reached else 'false' }};

function disableChat(message) {
    tokenLimitReached = true;
    const input = document.getElementById('chat-input');
    const sendBtn = document.getElementById('send-btn');
    const newPostBtn = document.getElementById('new-post-btn');
    if (input) {
        input.disabled = true;
        input.placeholder = message || 'Token-Limit erreicht – morgen wieder verfügbar';
        input.classList.add('opacity-50', 'cursor-not-allowed');
    }
    if (sendBtn) {
        sendBtn.disabled = true;
        sendBtn.classList.add('opacity-50', 'cursor-not-allowed');
        sendBtn.title = message || 'Token-Limit erreicht';
    }
    if (newPostBtn) {
        newPostBtn.disabled = true;
        newPostBtn.title = message || 'Token-Limit erreicht';
    }
}

// User profile data
const userProfilePicture = "{{ profile_picture or '' }}";
const userInitial = "{{ (session.display_name or session.linkedin_name or 'U')[0] | upper }}";

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

function selectPostType(postTypeId, element) {
    // Update selected state
    selectedPostTypeId = postTypeId;

    // Update chip styles
    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) {
    // Send on Enter (not Shift+Enter)
    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;
    }

    // Add user message to chat
    addMessageToChat('user', message);
    input.value = '';

    // Add temporary "generating" message
    const tempMessageId = 'temp-generating-msg';
    const container = document.getElementById('chat-messages');
    const tempMsg = document.createElement('div');
    tempMsg.id = tempMessageId;
    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' });

    // Disable input while processing - show black spinner in button
    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 ? '/api/employee/chat/refine' : '/api/employee/chat/generate';

        const response = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                message: message,
                post_type_id: selectedPostTypeId,
                conversation_id: conversationId,
                current_post: currentPost,
                chat_history: chatHistory
            })
        });

        const result = await response.json();

        // Remove temporary "generating" message
        const tempMsg = document.getElementById(tempMessageId);
        if (tempMsg) tempMsg.remove();

        if (result.success) {
            currentPost = result.post;
            conversationId = result.conversation_id;

            // Add AI response to chat
            addMessageToChat('ai', result.explanation || 'Hier ist dein Post:', result.post);

            // Store in history
            chatHistory.push({
                user: message,
                ai: result.post,
                explanation: result.explanation
            });

            // Auto-save if this is a loaded post, otherwise show save button
            if (currentLoadedPostId) {
                await autoSaveLoadedPost();
            } else {
                // Show save button only for new posts
                const saveBtn = document.getElementById('save-btn');
                saveBtn.classList.remove('hidden');
                saveBtn.classList.add('flex');
            }
        } else if (result.token_limit_exceeded) {
            disableChat(result.error);
            // Remove temp message, show save option if there's an unsaved new post
            if (!currentLoadedPostId && currentPost) {
                showTokenLimitModal();
            }
        } else {
            showToast('Fehler: ' + (result.error || 'Unbekannter Fehler'), 'error');
            addMessageToChat('ai', '❌ Entschuldigung, es gab einen Fehler. Bitte versuche es erneut.');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Netzwerkfehler beim Generieren', 'error');

        // Remove temporary message on error
        const tempMsg = document.getElementById(tempMessageId);
        if (tempMsg) tempMsg.remove();

        addMessageToChat('ai', '❌ Netzwerkfehler. Bitte überprüfe deine Verbindung.');
    } finally {
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalHTML;
    }
}

function addMessageToChat(type, text, post = null) {
    const container = document.getElementById('chat-messages');
    const messageDiv = document.createElement('div');

    if (type === 'user') {
        // User messages: right-aligned, avatar on right, max-width 70%
        messageDiv.className = 'flex items-start gap-3 justify-end';

        const userAvatarHtml = userProfilePicture
            ? `<img src="${userProfilePicture}" alt="User" class="w-full h-full object-cover" referrerpolicy="no-referrer">`
            : `<span class="text-brand-bg-dark font-bold text-sm">${userInitial}</span>`;

        messageDiv.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 overflow-hidden flex items-center justify-center flex-shrink-0">
                ${userAvatarHtml}
            </div>
        `;
    } else {
        // Bot messages: left-aligned, avatar on left, max-width 70%
        messageDiv.className = 'flex items-start gap-3';
        const postHtml = post ? `
            <div class="mt-3 p-4 bg-brand-bg rounded-2xl border border-brand-highlight/30">
                <div class="flex items-center gap-2 mb-2">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                    </svg>
                    <span class="text-brand-highlight font-medium text-sm">Post-Entwurf</span>
                </div>
                <div class="text-gray-200 whitespace-pre-wrap text-sm leading-relaxed">${escapeHtml(post)}</div>
            </div>
        ` : '';

        messageDiv.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(messageDiv);

    // Scroll to bottom smoothly
    setTimeout(() => {
        container.scrollTo({
            top: container.scrollHeight,
            behavior: 'smooth'
        });
    }, 100);
}

async function savePost() {
    if (!currentPost) {
        showToast('Kein Post zum Speichern vorhanden', 'error');
        return;
    }

    if (!selectedPostTypeId) {
        showToast('Bitte wähle einen Post-Typ aus', 'error');
        return;
    }

    const saveBtn = document.getElementById('save-btn');

    saveBtn.disabled = true;
    const originalHTML = saveBtn.innerHTML;
    saveBtn.innerHTML = '<svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>';

    try {
        // If this is a loaded post, update it instead of creating a new one
        if (currentLoadedPostId) {
            const response = await fetch(`/api/employee/chat/update/${currentLoadedPostId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    post_content: currentPost,
                    chat_history: chatHistory
                })
            });

            const result = await response.json();

            if (result.success) {
                showToast('Post erfolgreich aktualisiert!', 'success');
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalHTML;
            } else {
                showToast('Fehler beim Aktualisieren: ' + (result.error || 'Unbekannter Fehler'), 'error');
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalHTML;
            }
        } else {
            // Create new post
            const response = await fetch('/api/employee/chat/save', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    post_content: currentPost,
                    post_type_id: selectedPostTypeId,
                    conversation_id: conversationId,
                    chat_history: chatHistory
                })
            });

            const result = await response.json();

            if (result.success) {
                showToast('Post erfolgreich gespeichert!', 'success');

                // Redirect to post details after short delay
                setTimeout(() => {
                    window.location.href = `/posts/${result.post_id}`;
                }, 1000);
            } else {
                showToast('Fehler beim Speichern: ' + (result.error || 'Unbekannter Fehler'), 'error');
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalHTML;
            }
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Netzwerkfehler beim Speichern', 'error');
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalHTML;
    }
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function startNewPost() {
    if (tokenLimitReached) return;

    // Reset state
    chatHistory = [];
    currentPost = null;
    conversationId = null;
    currentLoadedPostId = null;

    // Remove active class from all sidebar items
    document.querySelectorAll('.post-sidebar-item').forEach(item => {
        item.classList.remove('active');
    });

    // Clear chat area (keep only welcome message)
    const container = document.getElementById('chat-messages');
    container.innerHTML = `
        <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 beim Erstellen deines LinkedIn-Posts.
                        Beschreibe mir einfach, worüber du schreiben möchtest, und ich erstelle einen ersten Entwurf für dich.
                    </p>
                    <p class="text-gray-400 text-sm mt-2">
                        Du kannst mich danach bitten, den Post anzupassen, umzuschreiben oder zu verbessern.
                    </p>
                </div>
            </div>
        </div>
    `;

    // Hide save button
    const saveBtn = document.getElementById('save-btn');
    saveBtn.classList.add('hidden');
    saveBtn.classList.remove('flex');
}

async function loadPostHistory(postId) {
    // Mark sidebar item as active
    document.querySelectorAll('.post-sidebar-item').forEach(item => {
        item.classList.remove('active');
        if (item.dataset.postId === postId) {
            item.classList.add('active');
        }
    });

    // Show loading in chat area
    const container = document.getElementById('chat-messages');
    container.innerHTML = `
        <div class="flex items-center justify-center h-64">
            <div class="text-gray-400">
                <svg class="w-8 h-8 animate-spin mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                </svg>
                <p>Lade Chat-Verlauf...</p>
            </div>
        </div>
    `;

    try {
        const response = await fetch(`/api/employee/chat/history/${postId}`);
        const result = await response.json();

        if (!result.success) {
            showToast('Fehler: ' + (result.error || 'Konnte Post nicht laden'), 'error');
            return;
        }

        // Update state
        currentLoadedPostId = postId;
        chatHistory = result.chat_history;
        currentPost = result.post;
        selectedPostTypeId = result.post_type_id;

        // Clear chat area
        container.innerHTML = '';

        // Add welcome message
        const welcomeDiv = document.createElement('div');
        welcomeDiv.className = 'flex items-start gap-3';
        welcomeDiv.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">
                        Hallo! Ich helfe dir beim Erstellen deines LinkedIn-Posts.
                        Beschreibe mir einfach, worüber du schreiben möchtest, und ich erstelle einen ersten Entwurf für dich.
                    </p>
                    <p class="text-gray-400 text-sm mt-2">
                        Du kannst mich danach bitten, den Post anzupassen, umzuschreiben oder zu verbessern.
                    </p>
                </div>
            </div>
        `;
        container.appendChild(welcomeDiv);

        // Rebuild chat from history
        chatHistory.forEach(item => {
            // Add user message if exists
            if (item.user && item.user.trim()) {
                addMessageToChat('user', item.user);
            }

            // Add AI message if exists
            if (item.ai) {
                addMessageToChat('ai', item.explanation || 'Hier ist dein Post:', item.ai);
            }
        });

        // Update post type selection
        if (selectedPostTypeId) {
            updatePostTypeSelection(selectedPostTypeId);
        }

        // Scroll to bottom
        setTimeout(() => {
            container.scrollTo({
                top: container.scrollHeight,
                behavior: 'smooth'
            });
        }, 100);

    } catch (error) {
        console.error('Error loading post history:', error);
        showToast('Netzwerkfehler beim Laden', 'error');

        // Restore welcome message on error
        container.innerHTML = `
            <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 beim Erstellen deines LinkedIn-Posts.
                            Beschreibe mir einfach, worüber du schreiben möchtest, und ich erstelle einen ersten Entwurf für dich.
                        </p>
                        <p class="text-gray-400 text-sm mt-2">
                            Du kannst mich danach bitten, den Post anzupassen, umzuschreiben oder zu verbessern.
                        </p>
                    </div>
                </div>
            </div>
        `;
    }
}

function updatePostTypeSelection(postTypeId) {
    // Remove active state from all chips
    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');
    });

    // Add active state to matching chip
    const targetChip = document.querySelector(`.post-type-chip[data-post-type-id="${postTypeId}"]`);
    if (targetChip) {
        targetChip.classList.remove('bg-brand-bg-dark', 'text-gray-400');
        targetChip.classList.add('bg-brand-highlight', 'text-black');
        targetChip.setAttribute('data-selected', 'true');
    }
}

async function autoSaveLoadedPost() {
    if (!currentLoadedPostId || !currentPost) {
        return;
    }

    try {
        const response = await fetch(`/api/employee/chat/update/${currentLoadedPostId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                post_content: currentPost,
                chat_history: chatHistory
            })
        });

        const result = await response.json();

        if (!result.success) {
            showToast('Fehler beim Auto-Speichern: ' + (result.error || 'Unbekannter Fehler'), 'error');
        }
        // Silent success - no toast for successful auto-save
    } catch (error) {
        console.error('Error auto-saving post:', error);
        showToast('Netzwerkfehler beim Auto-Speichern', 'error');
    }
}

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    const colors = {
        success: 'bg-green-600 border-green-500',
        error: 'bg-red-600 border-red-500',
        info: 'bg-blue-600 border-blue-500',
        warning: 'bg-yellow-600 border-yellow-500'
    };

    const icons = {
        success: '<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>',
        error: '<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="M6 18L18 6M6 6l12 12"/></svg>',
        info: '<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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>',
        warning: '<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 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>'
    };

    toast.className = `fixed bottom-8 right-8 ${colors[type]} text-white px-6 py-4 rounded-xl shadow-2xl border-2 z-50 flex items-center gap-3 transform transition-all duration-300`;
    toast.innerHTML = `
        ${icons[type]}
        <span class="font-medium">${message}</span>
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(1rem)';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Token limit modal (for new posts when limit is reached mid-session)
function showTokenLimitModal() {
    document.getElementById('tokenLimitModal').classList.remove('hidden');
}

function closeLimitModal() {
    document.getElementById('tokenLimitModal').classList.add('hidden');
}

async function saveAndCloseLimitModal() {
    closeLimitModal();
    if (currentPost) {
        // Trigger save
        const saveBtn = document.getElementById('save-btn');
        if (saveBtn && !saveBtn.classList.contains('hidden')) {
            saveBtn.click();
        } else {
            showToast('Bitte speichere deinen Post manuell.', 'error');
        }
    }
}
</script>

<!-- Token Limit Modal -->
<div id="tokenLimitModal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50">
    <div class="card-bg rounded-xl border p-6 max-w-md w-full mx-4">
        <h3 class="text-lg font-semibold text-white mb-3">Token-Limit erreicht</h3>
        <p class="text-gray-400 text-sm mb-4">Das tägliche Token-Limit wurde erreicht. Möchtest du deinen bisherigen Post speichern?</p>
        <div class="flex gap-3">
            <button onclick="saveAndCloseLimitModal()" class="flex-1 btn-primary px-4 py-2 rounded-lg">Post speichern</button>
            <button onclick="closeLimitModal()" class="px-4 py-2 bg-gray-600 rounded-lg text-white">Verwerfen</button>
        </div>
    </div>
</div>

{% endblock %}
