{% extends "base.html" %}

{% block title %}Post-Typen{% endblock %}

{% block content %}
<div class="max-w-6xl mx-auto">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-white">Post-Typen</h1>
            <p class="text-gray-400 mt-1">Verwalte und kategorisiere deine LinkedIn-Posts</p>
        </div>
        <div class="flex gap-3">
            <a href="/post-types/manage" class="px-5 py-2.5 rounded-lg font-medium flex items-center gap-2 bg-brand-bg-dark border border-brand-bg-light text-white hover:bg-brand-bg-light 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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
                Post-Typen verwalten
            </a>
            <button onclick="runAnalysis()" id="analyze-btn" class="btn-primary px-5 py-2.5 rounded-lg font-medium flex items-center gap-2">
                <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="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>
                Analyse starten
            </button>
            <button onclick="openManualPostModal()" class="px-5 py-2.5 rounded-lg font-medium flex items-center gap-2 bg-brand-highlight text-brand-bg-dark hover:bg-brand-highlight-dark 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="M12 4v16m8-8H4"/>
                </svg>
                Post manuell hinzufügen
            </button>
        </div>
    </div>

    <!-- Filter & Search Bar -->
    <div class="card-bg border rounded-xl p-4 mb-6">
        <div class="flex flex-col md:flex-row gap-4">
            <!-- Search -->
            <div class="flex-1">
                <div class="relative">
                    <svg class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    <input type="text" id="search-input" placeholder="Posts durchsuchen..."
                           class="w-full input-bg border rounded-lg pl-10 pr-4 py-2.5 text-white"
                           oninput="filterPosts()">
                </div>
            </div>

            <!-- Post Type Filter -->
            <div class="md:w-64">
                <select id="type-filter" class="w-full input-bg border rounded-lg px-4 py-2.5 text-white" onchange="filterPosts()">
                    <option value="all">Alle Post-Typen</option>
                    <option value="uncategorized">Nicht kategorisiert</option>
                    {% for pt in post_types %}
                    <option value="{{ pt.id }}">{{ pt.name }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>

        <!-- Stats Row -->
        <div class="flex flex-wrap gap-4 mt-4 pt-4 border-t border-gray-600">
            <div class="text-sm">
                <span class="text-gray-400">Gesamt:</span>
                <span class="text-white font-medium ml-1">{{ (uncategorized_posts|length) + (categorized_posts|length) }} Posts</span>
            </div>
            <div class="text-sm">
                <span class="text-gray-400">Kategorisiert:</span>
                <span class="text-green-400 font-medium ml-1">{{ categorized_posts|length }}</span>
            </div>
            <div class="text-sm">
                <span class="text-gray-400">Nicht kategorisiert:</span>
                <span class="text-yellow-400 font-medium ml-1">{{ uncategorized_posts|length }}</span>
            </div>
        </div>
    </div>

    <!-- Posts List -->
    <div class="space-y-3" id="posts-list">
        {% for post in uncategorized_posts %}
        <div class="post-item card-bg border rounded-xl overflow-hidden"
             data-post-id="{{ post.id }}"
             data-type-id=""
             data-text="{{ post.post_text|lower }}">
            <div class="p-4">
                <div class="flex items-start justify-between gap-4">
                    <!-- Post Content -->
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="px-2 py-0.5 text-xs rounded-full bg-yellow-900/50 text-yellow-300">
                                Nicht kategorisiert
                            </span>
                            {% if post.post_date %}
                            <span class="text-xs text-gray-500">{{ post.post_date.strftime('%d.%m.%Y') if post.post_date else '' }}</span>
                            {% endif %}
                        </div>
                        <p class="text-gray-300 text-sm post-text line-clamp-3">{{ post.post_text[:300] }}{% if post.post_text|length > 300 %}...{% endif %}</p>
                    </div>

                    <!-- Post Type Selector -->
                    <div class="flex-shrink-0 w-48">
                        <select onchange="categorizePost('{{ post.id }}', this.value)"
                                class="w-full input-bg border rounded-lg px-3 py-2 text-sm text-white">
                            <option value="">Typ wählen...</option>
                            {% for pt in post_types %}
                            <option value="{{ pt.id }}">{{ pt.name }}</option>
                            {% endfor %}
                        </select>
                        <button onclick="deletePost('{{ post.id }}')"
                                class="mt-2 w-full px-3 py-2 text-sm text-red-400 hover:text-red-300 hover:bg-red-900/20 rounded-lg transition-colors">
                            Post löschen
                        </button>
                    </div>
                </div>

                <!-- Expand Button -->
                <button onclick="toggleExpand(this)" class="text-xs text-gray-500 hover:text-gray-300 mt-2 flex items-center gap-1">
                    <svg class="w-4 h-4 expand-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                    </svg>
                    <span class="expand-text">Mehr anzeigen</span>
                </button>
            </div>

            <!-- Full Content (hidden by default) -->
            <div class="full-content hidden border-t border-gray-600 p-4 bg-brand-bg/30">
                <p class="text-gray-300 text-sm whitespace-pre-wrap">{{ post.post_text }}</p>
                {% if post.likes or post.comments %}
                <div class="flex gap-4 mt-3 text-xs text-gray-500">
                    {% if post.likes %}<span>{{ post.likes }} Likes</span>{% endif %}
                    {% if post.comments %}<span>{{ post.comments }} Kommentare</span>{% endif %}
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}

        {% for post in categorized_posts %}
        <div class="post-item card-bg border rounded-xl overflow-hidden"
             data-post-id="{{ post.id }}"
             data-type-id="{{ post.post_type_id or '' }}"
             data-text="{{ post.post_text|lower }}">
            <div class="p-4">
                <div class="flex items-start justify-between gap-4">
                    <!-- Post Content -->
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-2">
                            {% set type_name = "Unbekannt" %}
                            {% for pt in post_types %}
                                {% if pt.id == post.post_type_id %}
                                    {% set type_name = pt.name %}
                                {% endif %}
                            {% endfor %}
                            <span class="px-2 py-0.5 text-xs rounded-full bg-brand-highlight/20 text-brand-highlight">
                                {{ type_name }}
                            </span>
                            {% if post.post_date %}
                            <span class="text-xs text-gray-500">{{ post.post_date.strftime('%d.%m.%Y') if post.post_date else '' }}</span>
                            {% endif %}
                        </div>
                        <p class="text-gray-300 text-sm post-text line-clamp-3">{{ post.post_text[:300] }}{% if post.post_text|length > 300 %}...{% endif %}</p>
                    </div>

                    <!-- Post Type Selector -->
                    <div class="flex-shrink-0 w-48">
                        <select onchange="categorizePost('{{ post.id }}', this.value)"
                                class="w-full input-bg border rounded-lg px-3 py-2 text-sm text-white">
                            <option value="">Typ ändern...</option>
                            {% for pt in post_types %}
                            <option value="{{ pt.id }}" {% if pt.id == post.post_type_id %}selected{% endif %}>{{ pt.name }}</option>
                            {% endfor %}
                        </select>
                        <button onclick="deletePost('{{ post.id }}')"
                                class="mt-2 w-full px-3 py-2 text-sm text-red-400 hover:text-red-300 hover:bg-red-900/20 rounded-lg transition-colors">
                            Post löschen
                        </button>
                    </div>
                </div>

                <!-- Expand Button -->
                <button onclick="toggleExpand(this)" class="text-xs text-gray-500 hover:text-gray-300 mt-2 flex items-center gap-1">
                    <svg class="w-4 h-4 expand-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                    </svg>
                    <span class="expand-text">Mehr anzeigen</span>
                </button>
            </div>

            <!-- Full Content (hidden by default) -->
            <div class="full-content hidden border-t border-gray-600 p-4 bg-brand-bg/30">
                <p class="text-gray-300 text-sm whitespace-pre-wrap">{{ post.post_text }}</p>
                {% if post.likes or post.comments %}
                <div class="flex gap-4 mt-3 text-xs text-gray-500">
                    {% if post.likes %}<span>{{ post.likes }} Likes</span>{% endif %}
                    {% if post.comments %}<span>{{ post.comments }} Kommentare</span>{% endif %}
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Empty State -->
    {% if not uncategorized_posts and not categorized_posts %}
    <div class="card-bg border rounded-xl p-12 text-center">
        <svg class="w-16 h-16 text-gray-600 mx-auto mb-4" 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>
        <h3 class="text-xl font-semibold text-white mb-2">Keine Posts gefunden</h3>
        <p class="text-gray-400">Es wurden noch keine LinkedIn-Posts geladen.</p>
    </div>
    {% endif %}

    <!-- No Results State (hidden by default) -->
    <div id="no-results" class="hidden card-bg border rounded-xl p-12 text-center">
        <svg class="w-16 h-16 text-gray-600 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
        </svg>
        <h3 class="text-xl font-semibold text-white mb-2">Keine Ergebnisse</h3>
        <p class="text-gray-400">Keine Posts gefunden, die deinen Filterkriterien entsprechen.</p>
    </div>
</div>

<!-- Manual Post Modal -->
<div id="manual-post-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden items-center justify-center z-50">
    <div class="bg-brand-bg-dark border border-gray-600 rounded-xl p-8 w-full max-w-3xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold text-white">Post manuell hinzufügen</h2>
            <button onclick="closeManualPostModal()" class="text-gray-400 hover:text-white">
                <svg class="w-6 h-6" 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>
            </button>
        </div>
        <form onsubmit="submitManualPost(event)" class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Post-Typ</label>
                <select id="manual-post-type-id" class="w-full input-bg border rounded-lg px-4 py-3 text-white">
                    <option value="">Nicht kategorisiert</option>
                    {% for pt in post_types %}
                    <option value="{{ pt.id }}">{{ pt.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Post-Text</label>
                <textarea id="manual-post-text" rows="10"
                          class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                          placeholder="Füge hier einen bestehenden Beispielpost ein. Er wird gespeichert und bei der nächsten manuellen Re-Analyse berücksichtigt."></textarea>
            </div>
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeManualPostModal()" class="px-5 py-2.5 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-colors">Abbrechen</button>
                <button type="submit" class="btn-primary px-5 py-2.5 rounded-lg font-medium">Post speichern</button>
            </div>
        </form>
    </div>
</div>

<script>
function openManualPostModal() {
    document.getElementById('manual-post-text').value = '';
    document.getElementById('manual-post-type-id').value = '';
    document.getElementById('manual-post-modal').classList.remove('hidden');
    document.getElementById('manual-post-modal').classList.add('flex');
}

function closeManualPostModal() {
    document.getElementById('manual-post-modal').classList.add('hidden');
    document.getElementById('manual-post-modal').classList.remove('flex');
}

async function submitManualPost(event) {
    event.preventDefault();
    const postText = document.getElementById('manual-post-text').value.trim();
    const postTypeId = document.getElementById('manual-post-type-id').value;

    if (postText.length < 20) {
        if (window.showToast) showToast('Bitte einen Post mit mindestens 20 Zeichen eingeben.', 'error');
        return;
    }

    try {
        const response = await fetch('/api/post-types/manual-posts', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ post_text: postText, post_type_id: postTypeId || null })
        });
        const result = await response.json();
        if (!result.success) throw new Error(result.error || 'Post konnte nicht hinzugefügt werden');

        closeManualPostModal();
        if (window.showToast) {
            showToast('Post hinzugefügt. Er wird bei der nächsten manuellen Re-Analyse berücksichtigt.', 'success');
        }
        window.location.reload();
    } catch (error) {
        if (window.showToast) showToast(`Fehler: ${error.message}`, 'error');
    }
}

async function deletePost(postId) {
    if (!confirm('Diesen Post wirklich löschen?')) return;

    try {
        const response = await fetch(`/api/post-types/posts/${postId}`, { method: 'DELETE' });
        const result = await response.json();
        if (!result.success) throw new Error(result.error || 'Post konnte nicht gelöscht werden');

        const postEl = document.querySelector(`[data-post-id="${postId}"]`);
        if (postEl) postEl.remove();
        if (window.showToast) showToast('Post gelöscht.', 'success');
    } catch (error) {
        if (window.showToast) showToast(`Fehler: ${error.message}`, 'error');
    }
}

function toggleExpand(btn) {
    const card = btn.closest('.post-item');
    const fullContent = card.querySelector('.full-content');
    const icon = btn.querySelector('.expand-icon');
    const text = btn.querySelector('.expand-text');

    if (fullContent.classList.contains('hidden')) {
        fullContent.classList.remove('hidden');
        icon.style.transform = 'rotate(180deg)';
        text.textContent = 'Weniger anzeigen';
        card.querySelector('.post-text').classList.remove('line-clamp-3');
    } else {
        fullContent.classList.add('hidden');
        icon.style.transform = '';
        text.textContent = 'Mehr anzeigen';
        card.querySelector('.post-text').classList.add('line-clamp-3');
    }
}

function filterPosts() {
    const searchTerm = document.getElementById('search-input').value.toLowerCase();
    const typeFilter = document.getElementById('type-filter').value;
    const posts = document.querySelectorAll('.post-item');
    let visibleCount = 0;

    posts.forEach(post => {
        const text = post.dataset.text;
        const typeId = post.dataset.typeId;

        const matchesSearch = !searchTerm || text.includes(searchTerm);
        let matchesType = true;

        if (typeFilter === 'uncategorized') {
            matchesType = !typeId;
        } else if (typeFilter !== 'all') {
            matchesType = typeId === typeFilter;
        }

        if (matchesSearch && matchesType) {
            post.classList.remove('hidden');
            visibleCount++;
        } else {
            post.classList.add('hidden');
        }
    });

    // Show/hide no results message
    const noResults = document.getElementById('no-results');
    if (visibleCount === 0 && posts.length > 0) {
        noResults.classList.remove('hidden');
    } else {
        noResults.classList.add('hidden');
    }
}

async function categorizePost(postId, postTypeId) {
    if (!postTypeId) return;

    const postEl = document.querySelector(`[data-post-id="${postId}"]`);

    try {
        const response = await fetch('/api/categorize-post', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({post_id: postId, post_type_id: postTypeId})
        });

        if (response.ok) {
            // Update the badge
            const badge = postEl.querySelector('.px-2.py-0\\.5');
            const select = postEl.querySelector('select');
            const selectedOption = select.options[select.selectedIndex];

            badge.textContent = selectedOption.text;
            badge.className = 'px-2 py-0.5 text-xs rounded-full bg-brand-highlight/20 text-brand-highlight';

            // Update data attribute
            postEl.dataset.typeId = postTypeId;

            // Show success toast
            if (window.showToast) {
                showToast('Post kategorisiert!', 'success');
            }
        }
    } catch (error) {
        console.error('Error categorizing post:', error);
        if (window.showToast) {
            showToast('Fehler beim Kategorisieren', 'error');
        }
    }
}

async function runAnalysis() {
    const btn = document.getElementById('analyze-btn');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.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> Analysiere...';

    try {
        const response = await fetch('/api/run-post-type-analysis', {
            method: 'POST'
        });

        if (response.ok) {
            const data = await response.json();
            if (window.showToast) {
                showToast('Post-Typ-Analyse gestartet!');
            }
            // Listen for job completion via SSE, then reload
            if (data.job_id) {
                const evtSource = new EventSource('/api/job-updates');
                evtSource.onmessage = function(event) {
                    try {
                        const jobData = JSON.parse(event.data);
                        if (jobData.id === data.job_id) {
                            if (jobData.status === 'completed' || jobData.status === 'failed') {
                                evtSource.close();
                                btn.disabled = false;
                                btn.innerHTML = originalHTML;
                                if (jobData.status === 'completed') {
                                    window.location.reload();
                                } else {
                                    if (window.showToast) showToast('Analyse fehlgeschlagen', 'error');
                                }
                            }
                        }
                    } catch (e) {
                        console.error('Error parsing SSE data:', e);
                    }
                };
                evtSource.onerror = function() {
                    evtSource.close();
                    btn.disabled = false;
                    btn.innerHTML = originalHTML;
                };
            } else {
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            }
        } else {
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        }
    } catch (error) {
        console.error('Error starting analysis:', error);
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    }
}
</script>
{% endblock %}
