{% extends "onboarding/base.html" %}

{% block title %}Posts analysieren{% endblock %}

{% block content %}
<div class="text-center mb-8">
    <h1 class="text-2xl font-bold text-white mb-2">Posts analysieren</h1>
    <p class="text-gray-400">Wir analysieren die bisherigen LinkedIn-Posts deines Kunden, um den Schreibstil zu lernen.</p>
</div>

{% if error %}
<div class="bg-red-900/50 border border-red-500 text-red-200 px-4 py-3 rounded-lg mb-6">
    {{ error }}
</div>
{% endif %}

<!-- Scraping Status -->
<div id="scraping-section" class="mb-8">
    <div class="card-bg border border-gray-600 rounded-lg p-6">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h3 class="text-lg font-medium text-white">LinkedIn Posts von {{ profile.display_name }}</h3>
                <p class="text-sm text-gray-400">Profil: {{ profile.linkedin_url }}</p>
            </div>
            <div id="post-count" class="text-2xl font-bold text-brand-highlight">
                <span id="post-count-number">{{ scraped_posts_count }}</span> Posts
            </div>
        </div>

        <!-- Scraping in Progress Notice -->
        <div id="scraping-progress" class="{% if not scraping_in_progress %}hidden{% endif %} bg-brand-highlight/10 border border-brand-highlight/30 rounded-lg p-4 mb-4">
            <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-brand-highlight 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>
                <div>
                    <p class="text-brand-highlight font-medium">Posts werden im Hintergrund geladen...</p>
                    <p class="text-sm text-gray-400">Du kannst fortfahren sobald genug Posts vorhanden sind.</p>
                </div>
            </div>
        </div>

        {% if scraped_posts_count < 10 %}
        <div id="low-posts-warning" class="bg-yellow-900/30 border border-yellow-600 rounded-lg p-4 mb-4">
            <div class="flex items-start gap-3">
                <svg class="w-5 h-5 text-yellow-500 mt-0.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>
                <div>
                    <p class="text-yellow-200 font-medium">Zu wenige Posts gefunden</p>
                    <p class="text-yellow-300/70 text-sm">Für eine gute Stilanalyse brauchen wir mindestens 10 Posts. Du kannst entweder manuell Beispiel-Posts hinzufügen oder warten bis das Scraping fertig ist.</p>
                </div>
            </div>
        </div>
        {% endif %}

        <button id="rescrape-btn" class="btn-secondary py-2 px-4 rounded-lg transition-colors flex items-center gap-2">
            <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="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>
            <span>Posts neu laden</span>
        </button>
    </div>
</div>

<!-- Manual Posts Section -->
<div id="manual-posts-section" class="{% if scraped_posts_count >= 10 %}hidden{% endif %} mb-8">
    <h3 class="text-lg font-medium text-white mb-4">Beispiel-Posts manuell hinzufügen</h3>

    <form id="manual-post-form" class="space-y-4">
        <div>
            <textarea id="manual-post-text" rows="6"
                      class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                      placeholder="Füge hier einen LinkedIn-Post deines Kunden ein..."></textarea>
        </div>
        <button type="submit" class="btn-secondary py-2 px-4 rounded-lg transition-colors">
            Post hinzufügen
        </button>
    </form>

    <!-- Added Manual Posts -->
    <div id="manual-posts-list" class="mt-4 space-y-2">
        {% for post in example_posts %}
        <div class="bg-brand-bg border border-gray-600 rounded-lg p-3 flex justify-between items-start">
            <p class="text-sm text-gray-300 line-clamp-2">{{ post.post_text[:200] }}{% if post.post_text|length > 200 %}...{% endif %}</p>
            <button class="text-gray-500 hover:text-red-400 ml-2" onclick="removeManualPost('{{ post.id }}', this.parentElement)">
                <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="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        {% endfor %}
    </div>
</div>

<!-- Navigation -->
<div class="flex justify-between pt-8 border-t border-gray-600">
    <a href="/onboarding/profile" class="text-gray-400 hover:text-white transition-colors 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="M11 17l-5-5m0 0l5-5m-5 5h12"/>
        </svg>
        Zurück
    </a>
    <form method="POST" action="/onboarding/posts">
        <button type="submit" id="continue-btn" class="btn-primary font-medium py-3 px-8 rounded-lg transition-colors flex items-center gap-2"
                {% if scraped_posts_count < 5 %}disabled{% endif %}>
            Weiter
            <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 7l5 5m0 0l-5 5m5-5H6"/>
            </svg>
        </button>
    </form>
</div>

<script>
async function removeManualPost(postId, element) {
    try {
        const response = await fetch(`/api/onboarding/remove-manual-post/${postId}`, {method: 'DELETE'});
        if (response.ok) {
            if (element) {
                element.remove();
            } else {
                // Find and remove the element by post ID
                const btn = document.querySelector(`[onclick*="${postId}"]`);
                if (btn) btn.closest('.bg-brand-bg').remove();
            }
        }
    } catch (e) {
        console.error('Error removing manual post:', e);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const postCountEl = document.getElementById('post-count-number');
    const progressEl = document.getElementById('scraping-progress');
    const warningEl = document.getElementById('low-posts-warning');
    const manualSection = document.getElementById('manual-posts-section');
    const continueBtn = document.getElementById('continue-btn');
    const rescrapeBtn = document.getElementById('rescrape-btn');

    // Poll for post count updates
    let pollInterval = setInterval(async () => {
        try {
            const response = await fetch('/api/posts-count');
            const data = await response.json();

            postCountEl.textContent = data.count;

            // Update UI based on count
            if (data.count >= 10) {
                if (warningEl) warningEl.classList.add('hidden');
                if (manualSection) manualSection.classList.add('hidden');
            }

            if (data.count >= 5) {
                continueBtn.disabled = false;
            }

            // Check if scraping is still in progress
            if (!data.scraping_active) {
                progressEl.classList.add('hidden');
            }
        } catch (e) {
            console.error('Error polling post count:', e);
        }
    }, 3000);

    // Manual post form
    const form = document.getElementById('manual-post-form');
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const textarea = document.getElementById('manual-post-text');
        const text = textarea.value.trim();

        if (!text) return;

        try {
            const response = await fetch('/api/onboarding/add-manual-post', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_text: text})
            });

            if (response.ok) {
                const data = await response.json();
                textarea.value = '';

                // Add to list
                const list = document.getElementById('manual-posts-list');
                const div = document.createElement('div');
                div.className = 'bg-brand-bg border border-gray-600 rounded-lg p-3 flex justify-between items-start';
                div.innerHTML = `
                    <p class="text-sm text-gray-300 line-clamp-2">${text.substring(0, 200)}${text.length > 200 ? '...' : ''}</p>
                    <button class="text-gray-500 hover:text-red-400 ml-2" onclick="removeManualPost('${data.id}', this.parentElement)">
                        <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="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                `;
                list.appendChild(div);
            }
        } catch (e) {
            console.error('Error adding manual post:', e);
        }
    });

    // Rescrape button
    rescrapeBtn.addEventListener('click', async () => {
        try {
            const response = await fetch('/api/onboarding/rescrape', {method: 'POST'});
            if (response.ok) {
                progressEl.classList.remove('hidden');
                showToast('Scraping gestartet...');
            }
        } catch (e) {
            console.error('Error starting rescrape:', e);
        }
    });

    // Cleanup on leave
    window.addEventListener('beforeunload', () => {
        clearInterval(pollInterval);
    });
});
</script>
{% endblock %}
