{% extends "company_base.html" %}
{% block title %}{{ post.topic_title }} - {{ employee_name }} - {{ session.company_name }}{% endblock %}

{% block head %}
<style>
    .section-card {
        background: rgba(61, 72, 72, 0.3);
        border: 1px solid rgba(61, 72, 72, 0.6);
    }
    .linkedin-preview {
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid rgba(0, 0, 0, 0.08);
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.04);
        font-family: -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Fira Sans', Ubuntu, Oxygen, 'Oxygen Sans', Cantarell, 'Droid Sans', 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Lucida Grande', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: rgba(0, 0, 0, 0.9);
        overflow: hidden;
    }
    .linkedin-header {
        padding: 12px 16px;
        display: flex;
        align-items: flex-start;
        gap: 8px;
    }
    .linkedin-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: linear-gradient(135deg, #0a66c2 0%, #004182 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 600;
        font-size: 18px;
        flex-shrink: 0;
        overflow: hidden;
    }
    .linkedin-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .linkedin-user-info { flex: 1; min-width: 0; }
    .linkedin-name { font-weight: 600; font-size: 14px; color: rgba(0, 0, 0, 0.9); }
    .linkedin-headline { font-size: 12px; color: rgba(0, 0, 0, 0.6); margin-top: 2px; }
    .linkedin-timestamp { font-size: 12px; color: rgba(0, 0, 0, 0.6); display: flex; align-items: center; gap: 4px; margin-top: 2px; }
    .linkedin-content { padding: 0 16px 8px; font-size: 14px; line-height: 1.4; color: rgba(0, 0, 0, 0.9); white-space: pre-wrap; }
    .linkedin-engagement { padding: 8px 16px; border-top: 1px solid rgba(0, 0, 0, 0.08); display: flex; align-items: center; gap: 4px; font-size: 12px; color: rgba(0, 0, 0, 0.6); }
    .linkedin-actions { display: flex; border-top: 1px solid rgba(0, 0, 0, 0.08); }
    .linkedin-action-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: 4px; padding: 0 16px; height: 40px; font-size: 14px; font-weight: 600; color: rgba(0, 0, 0, 0.6); background: transparent; border: none; cursor: default; transition: all 0.15s; }
    .linkedin-action-btn:hover { background: rgba(0, 0, 0, 0.04); color: rgba(0, 0, 0, 0.9); }
    .linkedin-action-btn svg { width: 16px; height: 16px; }
    .linkedin-post-image { width: 100%; max-height: 400px; object-fit: cover; }
    .image-upload-zone { border: 2px dashed rgba(61, 72, 72, 0.8); border-radius: 0.75rem; padding: 1.5rem; text-align: center; cursor: pointer; transition: all 0.2s; }
    .image-upload-zone:hover, .image-upload-zone.dragover { border-color: #ffc700; background: rgba(255, 199, 0, 0.05); }
    .image-upload-zone input[type="file"] { display: none; }
    .image-preview-container { position: relative; border-radius: 0.75rem; overflow: hidden; }
    .image-preview-container img { width: 100%; border-radius: 0.75rem; }
    .image-upload-progress { height: 4px; background: rgba(61, 72, 72, 0.8); border-radius: 2px; overflow: hidden; margin-top: 0.5rem; }
    .image-upload-progress-bar { height: 100%; background: #ffc700; border-radius: 2px; transition: width 0.3s; }
    .loading-spinner { border: 2px solid rgba(255, 199, 0, 0.2); border-top-color: #ffc700; border-radius: 50%; width: 20px; height: 20px; animation: spin 0.8s linear infinite; }
    @keyframes spin { to { transform: rotate(360deg); } }
    /* Preview Mode Toggle */
    .preview-mode-btn { padding: 6px 12px; font-size: 12px; font-weight: 500; border-radius: 6px; color: #9ca3af; background: transparent; border: none; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 6px; }
    .preview-mode-btn.active { background: rgba(255, 199, 0, 0.2); color: #ffc700; }
    .preview-mode-btn:hover:not(.active) { color: #d1d5db; }
    /* Desktop View */
    .linkedin-preview.desktop-view { max-width: 100%; margin: 0; }
    .desktop-view-container { background: #f3f2ef; padding: 16px; border-radius: 8px; }
    .mobile-view-container { background: transparent; padding: 0; }
    /* Mobile View - smartphone mockup */
    .linkedin-preview.mobile-view { max-width: 375px; height: 750px; margin: 0 auto; border: 14px solid #1f1f1f; border-radius: 42px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1); position: relative; overflow-y: auto; overflow-x: hidden; display: block; }
    /* iPhone Notch - bleibt fix beim Scrollen */
    .linkedin-preview.mobile-view::before { content: ''; position: sticky; top: 0; left: 50%; transform: translateX(-50%); width: 170px; height: 28px; background: #1f1f1f; border-radius: 0 0 20px 20px; z-index: 100; display: block; margin: 0 auto; pointer-events: none; }
    /* Notch Camera - bleibt fix beim Scrollen */
    .linkedin-preview.mobile-view::after { content: ''; position: sticky; top: 8px; left: 50%; transform: translateX(35px); width: 12px; height: 12px; background: #0a0a0a; border-radius: 50%; border: 1px solid #2a2a2a; z-index: 101; display: block; margin-top: -22px; pointer-events: none; }
    /* Verhindert, dass Content unter die Notch scrollt */
    .linkedin-preview.mobile-view .linkedin-actions { margin-bottom: 0; }
    .linkedin-preview.mobile-view::-webkit-scrollbar { width: 4px; }
    .linkedin-preview.mobile-view::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.05); }
    .linkedin-preview.mobile-view::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.2); border-radius: 2px; }
    .linkedin-preview.mobile-view .linkedin-header { padding: 8px 12px; padding-top: 33px; }
    .linkedin-preview.mobile-view .linkedin-avatar { width: 40px; height: 40px; font-size: 16px; }
    .linkedin-preview.mobile-view .linkedin-name { font-size: 13px; }
    .linkedin-preview.mobile-view .linkedin-headline { font-size: 11px; }
    .linkedin-preview.mobile-view .linkedin-timestamp { font-size: 11px; }
    .linkedin-preview.mobile-view .linkedin-content { padding: 0 12px 12px; font-size: 14px; line-height: 1.4; }
    .linkedin-preview.mobile-view .linkedin-engagement { padding: 12px 12px; font-size: 11px; }
    .linkedin-preview.mobile-view .linkedin-action-btn { font-size: 0; padding: 14px 8px; gap: 0; }
    .linkedin-preview.mobile-view .linkedin-action-btn svg { width: 22px; height: 22px; margin: 0; }
</style>
{% endblock %}

{% block content %}
<!-- Breadcrumb -->
<div class="mb-6">
    <nav class="flex items-center gap-2 text-sm">
        <a href="/company/manage" class="text-gray-400 hover:text-white transition-colors">Inhalte verwalten</a>
        <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        <a href="/company/manage?employee_id={{ employee_id }}" class="text-gray-400 hover:text-white transition-colors">{{ employee_name }}</a>
        <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        <a href="/company/manage/posts?employee_id={{ employee_id }}" class="text-gray-400 hover:text-white transition-colors">Posts</a>
        <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        <span class="text-white truncate max-w-xs">{{ post.topic_title or 'Post' }}</span>
    </nav>
</div>

<!-- Header -->
<div class="mb-6">
    <div class="flex items-start justify-between gap-4">
        <div class="flex-1 min-w-0">
            <h1 class="text-2xl font-bold text-white mb-2">{{ post.topic_title or 'Untitled Post' }}</h1>
            <div class="flex items-center gap-3 text-sm text-gray-400 flex-wrap">
                <span>{{ post.created_at.strftime('%d.%m.%Y um %H:%M Uhr') if post.created_at else 'N/A' }}</span>
                <span>{{ employee_name }}</span>
            </div>
        </div>
        <div class="flex items-center gap-3 flex-shrink-0">
            <span class="px-3 py-1.5 rounded-lg text-sm font-medium {{ 'bg-green-600/30 text-green-300 border border-green-600/50' if post.status == 'approved' else 'bg-yellow-600/30 text-yellow-300 border border-yellow-600/50' if post.status == 'draft' else 'bg-blue-600/30 text-blue-300 border border-blue-600/50' }}">
                {% if post.status == 'draft' %}Vorschlag{% elif post.status == 'approved' %}Bearbeitet{% elif post.status == 'published' %}Veröffentlicht{% else %}{{ post.status | capitalize }}{% endif %}
            </span>
        </div>
    </div>
</div>

<div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
    <!-- Post Content -->
    <div class="xl:col-span-2">
        <div class="section-card rounded-xl p-6">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold text-white flex items-center gap-2">
                    <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    LinkedIn Post
                </h2>
                <div class="flex items-center gap-2">
                    {% if not permissions or permissions.can_edit_posts %}
                    <button onclick="toggleEditView()" id="editToggleBtn" class="px-3 py-1.5 bg-brand-bg hover:bg-brand-bg-light rounded-lg text-sm text-gray-300 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                        Bearbeiten
                    </button>
                    {% endif %}
                    <button onclick="copyToClipboard()" class="px-3 py-1.5 bg-brand-bg hover:bg-brand-bg-light rounded-lg text-sm text-gray-300 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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                        Kopieren
                    </button>
                </div>
            </div>

            <!-- Edit View (hidden by default) -->
            {% if not permissions or permissions.can_edit_posts %}
            <div id="editView" class="hidden mb-4">
                <textarea id="editTextarea"
                    class="w-full bg-brand-bg border border-gray-600 rounded-xl p-4 text-gray-200 text-sm leading-relaxed resize-none focus:outline-none focus:border-brand-highlight transition-colors"
                    rows="12"
                    style="min-height: 200px; font-family: inherit;">{{ post.post_content }}</textarea>
                <div class="flex items-center justify-between mt-3">
                    <span class="text-sm text-gray-500" id="charCountLabel">
                        <span id="charCount">{{ post.post_content | length }}</span> / 3000 Zeichen
                    </span>
                    <div class="flex items-center gap-2">
                        <button onclick="cancelEdit()" class="px-4 py-2 bg-brand-bg hover:bg-brand-bg-light text-gray-300 rounded-lg text-sm transition-colors">
                            Abbrechen
                        </button>
                        <button onclick="saveEdit()" id="saveEditBtn" class="px-4 py-2 bg-brand-highlight hover:bg-yellow-500 text-brand-bg-dark font-medium rounded-lg text-sm 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="M5 13l4 4L19 7"/></svg>
                            Speichern
                        </button>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- LinkedIn Preview -->
            <div id="previewSection">
            <div class="mb-4 flex items-center justify-between">
                <div class="flex items-center gap-2 text-sm text-gray-400">
                    <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 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                    LinkedIn Vorschau
                </div>
                <div class="flex items-center gap-0.5 bg-brand-bg rounded-lg p-1">
                    <button onclick="setPreviewMode('desktop')" id="desktopPreviewBtn" class="preview-mode-btn active">
                        <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="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                        Desktop
                    </button>
                    <button onclick="setPreviewMode('mobile')" id="mobilePreviewBtn" class="preview-mode-btn">
                        <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="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
                        Smartphone
                    </button>
                </div>
            </div>
            <div id="linkedinPreviewContainer" class="desktop-view-container">
            <div id="linkedinPreview" class="linkedin-preview desktop-view">
                <div class="linkedin-header">
                    <div class="linkedin-avatar">
                        {% if profile_picture_url %}
                        <img src="{{ profile_picture_url }}" alt="{{ employee_name }}" loading="lazy" referrerpolicy="no-referrer">
                        {% else %}
                        {{ employee_name[:2] | upper if employee_name else 'UN' }}
                        {% endif %}
                    </div>
                    <div class="linkedin-user-info">
                        <div class="linkedin-name">{{ employee_name }}</div>
                        <div class="linkedin-headline">{{ session.company_name }}</div>
                        <div class="linkedin-timestamp">
                            <span>{{ post.created_at.strftime('%d.%m.%Y') if post.created_at else 'Jetzt' }}</span>
                            <span>•</span>
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                                <path d="M8 1a7 7 0 107 7 7 7 0 00-7-7zM3 8a5 5 0 011-3l.55.55A1.5 1.5 0 015 6.62v1.07a.75.75 0 00.22.53l.56.56a.75.75 0 00.53.22H7v.69a.75.75 0 00.22.53l.56.56a.75.75 0 01.22.53V13a5 5 0 01-5-5zm6.24 4.83l2-2.46a.75.75 0 00.09-.8l-.58-1.16A.76.76 0 0010 8H7v-.19a.51.51 0 01.28-.45l.38-.19a.74.74 0 00.3-1L7.4 5.19a.75.75 0 00-.67-.41H5.67a.75.75 0 01-.44-.14l-.34-.26a5 5 0 017.35 8.44z"/>
                            </svg>
                        </div>
                    </div>
                </div>
                <div class="linkedin-content">{{ post.post_content }}</div>

                <!-- LinkedIn Media Display -->
                <div id="linkedinMediaSection" class="{% if not post.media_items or post.media_items | length == 0 %}{% if not post.image_url %}hidden{% endif %}{% endif %}">
                    {% if post.media_items and post.media_items | length > 0 %}
                    {% if post.media_items | length == 3 %}
                    <!-- LinkedIn 3-Image Layout: 1 oben groß, 2+3 unten nebeneinander -->
                    <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 2px;">
                        {% if post.media_items[0].type == 'image' %}
                        <img src="{{ post.media_items[0].url }}" alt="Post media 1" class="w-full h-64 object-cover" style="grid-column: 1 / -1;">
                        {% elif post.media_items[0].type == 'video' %}
                        <video src="{{ post.media_items[0].url }}" class="w-full h-64 object-cover" controls style="grid-column: 1 / -1;"></video>
                        {% endif %}
                        {% if post.media_items[1].type == 'image' %}
                        <img src="{{ post.media_items[1].url }}" alt="Post media 2" class="w-full h-48 object-cover">
                        {% elif post.media_items[1].type == 'video' %}
                        <video src="{{ post.media_items[1].url }}" class="w-full h-48 object-cover" controls></video>
                        {% endif %}
                        {% if post.media_items[2].type == 'image' %}
                        <img src="{{ post.media_items[2].url }}" alt="Post media 3" class="w-full h-48 object-cover">
                        {% elif post.media_items[2].type == 'video' %}
                        <video src="{{ post.media_items[2].url }}" class="w-full h-48 object-cover" controls></video>
                        {% endif %}
                    </div>
                    {% else %}
                    <!-- Standard Grid für 1 oder 2 Bilder -->
                    <div class="grid" style="grid-template-columns: repeat({{ post.media_items | length }}, 1fr); gap: 2px;">
                        {% for item in post.media_items %}
                        {% if item.type == 'image' %}
                        <img src="{{ item.url }}" alt="Post media" class="w-full h-48 object-cover">
                        {% elif item.type == 'video' %}
                        <video src="{{ item.url }}" class="w-full h-48 object-cover" controls></video>
                        {% endif %}
                        {% endfor %}
                    </div>
                    {% endif %}
                    {% elif post.image_url %}
                    <!-- Backward compatibility: single image -->
                    <img src="{{ post.image_url }}" alt="Post image" class="linkedin-post-image">
                    {% endif %}
                </div>

                <div class="linkedin-engagement">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="#0a66c2">
                        <path d="M19.46 11l-3.91-3.91a7 7 0 01-1.69-2.74l-.49-1.47A2.76 2.76 0 0010.76 1 2.75 2.75 0 008 3.74v1.12a9.19 9.19 0 00.46 2.85L8.89 9H4.12A2.12 2.12 0 002 11.12a2.16 2.16 0 00.92 1.76A2.11 2.11 0 002 14.62a2.14 2.14 0 001.28 2 2 2 0 00-.28 1 2.12 2.12 0 002 2.12v.14A2.12 2.12 0 007.12 22h7.49a8.08 8.08 0 003.58-.84l.31-.16H21V11z"/>
                    </svg>
                    <span style="margin-left: 4px;">42</span>
                    <span style="margin-left: auto;">12 Kommentare • 3 Reposts</span>
                </div>
                <div class="linkedin-actions">
                    <button class="linkedin-action-btn">
                        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.46 11l-3.91-3.91a7 7 0 01-1.69-2.74l-.49-1.47A2.76 2.76 0 0010.76 1 2.75 2.75 0 008 3.74v1.12a9.19 9.19 0 00.46 2.85L8.89 9H4.12A2.12 2.12 0 002 11.12a2.16 2.16 0 00.92 1.76A2.11 2.11 0 002 14.62a2.14 2.14 0 001.28 2 2 2 0 00-.28 1 2.12 2.12 0 002 2.12v.14A2.12 2.12 0 007.12 22h7.49a8.08 8.08 0 003.58-.84l.31-.16H21V11z"/></svg>
                        Gefällt mir
                    </button>
                    <button class="linkedin-action-btn">
                        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 9h10v1H7zm0 4h7v-1H7zm16-2a6.78 6.78 0 01-2.84 5.61L12 22v-4H8A7 7 0 018 4h8a7 7 0 017 7z"/></svg>
                        Kommentieren
                    </button>
                    <button class="linkedin-action-btn">
                        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M23 12l-4.61 7H16l4-6H8a3.92 3.92 0 00-4 3.84V17a4 4 0 00.19 1.24L5.12 21H3l-.73-2.22A6.4 6.4 0 012 16.94 6 6 0 018 11h12l-4-6h2.39z"/></svg>
                        Reposten
                    </button>
                    <button class="linkedin-action-btn">
                        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M21 3L0 10l7.66 4.26L16 8l-6.26 8.34L14 24l7-21z"/></svg>
                        Senden
                    </button>
                </div>
            </div>
            </div>
            </div><!-- end previewSection -->
        </div>
    </div>

    <!-- Sidebar -->
    <div class="space-y-6">
        <!-- Actions -->
        <div class="section-card rounded-xl p-6">
            <h3 class="font-semibold text-white mb-4">Aktionen</h3>
            <div class="space-y-3">
                <button onclick="updateStatus('approved')" class="w-full px-4 py-3 bg-blue-600/20 hover:bg-blue-600/30 text-blue-300 rounded-lg transition-colors flex items-center justify-center gap-2 {% if post.status == 'approved' %}ring-2 ring-blue-500{% 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                    Als bearbeitet markieren
                </button>
                <button onclick="updateStatus('published')" class="w-full px-4 py-3 bg-green-600/20 hover:bg-green-600/30 text-green-300 rounded-lg transition-colors flex items-center justify-center gap-2 {% if post.status == 'published' %}ring-2 ring-green-500{% 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Als veröffentlicht markieren
                </button>
                <button onclick="updateStatus('draft')" class="w-full px-4 py-3 bg-yellow-600/20 hover:bg-yellow-600/30 text-yellow-300 rounded-lg transition-colors flex items-center justify-center gap-2 {% if post.status == 'draft' %}ring-2 ring-yellow-500{% 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="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
                    Zurück zu Vorschlag
                </button>
            </div>
        </div>

        <!-- AI Suggestions Panel -->
        {% if not permissions or permissions.can_edit_posts %}
        <div class="section-card rounded-xl p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="font-semibold text-white flex items-center gap-2">
                    <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
                    KI-Verbesserungen
                </h3>
                <button onclick="loadSuggestions()" id="refreshSuggestionsBtn" {% if limit_reached %}disabled{% endif %} class="p-1.5 rounded-lg bg-brand-bg hover:bg-brand-bg-light text-gray-400 hover:text-white transition-colors {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}" title="{% if limit_reached %}{{ limit_message }}{% else %}KI-Vorschläge generieren{% endif %}">
                    <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>
                </button>
            </div>

            <!-- Quick Suggestions -->
            <div id="quickSuggestions" class="space-y-2 mb-4">
                <p class="text-xs text-gray-500 mb-3">Schnelle Anpassungen:</p>
                <button {% if not limit_reached %}onclick="applyQuickSuggestion('Mache den Hook emotionaler und aufmerksamkeitsstärker')"{% endif %} {% if limit_reached %}disabled{% endif %} class="w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}">
                    <span class="text-brand-highlight">⚡</span> Hook verstärken
                </button>
                <button {% if not limit_reached %}onclick="applyQuickSuggestion('Füge einen starken Call-to-Action am Ende hinzu')"{% endif %} {% if limit_reached %}disabled{% endif %} class="w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}">
                    <span class="text-brand-highlight">🎯</span> Call-to-Action hinzufügen
                </button>
                <button {% if not limit_reached %}onclick="applyQuickSuggestion('Füge eine kurze persönliche Anekdote oder Erfahrung hinzu')"{% endif %} {% if limit_reached %}disabled{% endif %} class="w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}">
                    <span class="text-brand-highlight">📖</span> Storytelling einbauen
                </button>
                <button {% if not limit_reached %}onclick="applyQuickSuggestion('Verbessere die Struktur: Kürzere Absätze, mehr Weißraum, bessere Lesbarkeit')"{% endif %} {% if limit_reached %}disabled{% endif %} class="w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}">
                    <span class="text-brand-highlight">📝</span> Struktur optimieren
                </button>
                <button {% if not limit_reached %}onclick="applyQuickSuggestion('Kürze den Post auf das Wesentliche, entferne überflüssige Worte')"{% endif %} {% if limit_reached %}disabled{% endif %} class="w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2 {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}">
                    <span class="text-brand-highlight">✂️</span> Kürzer & prägnanter
                </button>
            </div>

            <!-- Loading State -->
            <div id="suggestionsLoading" class="hidden flex items-center justify-center py-4">
                <div class="loading-spinner"></div>
                <span class="ml-2 text-sm text-gray-400">Generiere Vorschläge...</span>
            </div>

            <!-- AI Generated Suggestions List -->
            <div id="suggestionsList" class="space-y-3 hidden"></div>

            <!-- Custom Instruction -->
            <div class="mt-4 pt-4 border-t border-brand-bg-light">
                <label class="text-xs text-gray-400 block mb-2">Eigene Anweisung</label>
                <div class="flex gap-2">
                    <input type="text" id="customSuggestion" placeholder="z.B. Mache es humorvoller" class="flex-1 px-3 py-2 bg-brand-bg border border-brand-bg-light rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-highlight {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}" {% if limit_reached %}disabled{% endif %}>
                    <button {% if not limit_reached %}onclick="applyCustomSuggestion()"{% endif %} id="applyCustomBtn" class="px-3 py-2 bg-brand-highlight hover:bg-brand-highlight/90 text-brand-bg-dark rounded-lg transition-colors {% if limit_reached %}opacity-50 cursor-not-allowed{% endif %}" {% if limit_reached %}disabled{% endif %}>
                        <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="M13 5l7 7-7 7M5 5l7 7-7 7"/></svg>
                    </button>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Schedule Section -->
        {% if not permissions or permissions.can_schedule_posts %}
        <div class="section-card rounded-xl p-6">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                Planen
            </h3>
            {% if post.status == 'scheduled' and post.scheduled_at %}
            <div class="mb-3 p-3 bg-brand-highlight/10 border border-brand-highlight/30 rounded-lg">
                <p class="text-xs text-gray-400 mb-1">Geplant für</p>
                <p class="text-white font-medium text-sm">{{ post.scheduled_at.strftime('%d.%m.%Y %H:%M') }} Uhr</p>
            </div>
            <button onclick="unschedulePost()" class="w-full px-4 py-2.5 bg-red-600/20 hover:bg-red-600/30 text-red-300 rounded-lg text-sm transition-colors flex items-center justify-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="M6 18L18 6M6 6l12 12"/></svg>
                Planung aufheben
            </button>
            {% else %}
            {% if post.status != 'ready' %}
            <p class="text-xs text-gray-500 mb-3">Nur freigegebene Posts (Status "Freigegeben") können geplant werden.</p>
            {% endif %}
            <input type="datetime-local" id="scheduleInput"
                class="w-full bg-brand-bg border border-gray-600 rounded-lg px-3 py-2 text-white text-sm mb-3 focus:outline-none focus:border-brand-highlight transition-colors {% if post.status != 'ready' %}opacity-50 cursor-not-allowed{% endif %}"
                {% if post.status != 'ready' %}disabled{% endif %}>
            <button onclick="schedulePost()" id="scheduleBtn"
                class="w-full px-4 py-2.5 bg-brand-highlight hover:bg-yellow-500 text-brand-bg-dark font-medium rounded-lg text-sm transition-colors flex items-center justify-center gap-2 {% if post.status != 'ready' %}opacity-50 cursor-not-allowed{% endif %}"
                {% if post.status != 'ready' %}disabled{% endif %}>
                <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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                Post planen
            </button>
            {% endif %}
        </div>
        {% endif %}

        <!-- Media Upload Section (Multi-Media Support) -->
        <div class="section-card rounded-xl p-6">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                Medien (<span id="mediaCount">{{ post.media_items | length if post.media_items else 0 }}</span>/3)
            </h3>

            <!-- Media Grid (shown when media exists) -->
            <div id="mediaGrid" class="grid gap-3 mb-3 {% if not post.media_items or post.media_items | length == 0 %}hidden{% endif %}" style="grid-template-columns: repeat({{ post.media_items | length if post.media_items and post.media_items | length <= 3 else 1 }}, 1fr);">
                {% if post.media_items %}
                {% for item in post.media_items %}
                <div class="media-item relative group rounded-lg overflow-hidden" data-index="{{ item.order if item.order is defined else loop.index0 }}"
                     {% if not permissions or permissions.can_edit_posts %}draggable="true" style="cursor: grab;"{% else %}style="cursor: default;"{% endif %}>
                    {% if item.type == 'image' %}
                    <img src="{{ item.url }}" alt="Media {{ loop.index }}" class="w-full h-48 object-cover">
                    {% elif item.type == 'video' %}
                    <video src="{{ item.url }}" class="w-full h-48 object-cover" controls></video>
                    {% endif %}

                    <!-- Delete button (only if can edit) -->
                    {% if not permissions or permissions.can_edit_posts %}
                    <button onclick="deleteMedia({{ item.order if item.order is defined else loop.index0 }})" class="absolute top-2 right-2 p-2 bg-red-600 rounded-full opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-700">
                        <svg class="w-4 h-4 text-white" 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>
                    {% endif %}

                    <!-- Order badge -->
                    <div class="absolute bottom-2 left-2 px-2 py-1 bg-black/50 rounded text-xs text-white">
                        {{ loop.index }}
                    </div>
                </div>
                {% endfor %}
                {% endif %}
            </div>

            <!-- Upload Zone (only if can edit, shown when < 3 media items) -->
            {% if not permissions or permissions.can_edit_posts %}
            <div id="mediaUploadZone" class="{% if post.media_items and post.media_items | length >= 3 %}hidden{% endif %} border-2 border-dashed border-brand-bg-light rounded-xl p-6 text-center cursor-pointer hover:border-brand-highlight transition-colors">
                <input type="file" id="mediaFileInput" accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime" class="hidden">
                <svg class="w-8 h-8 mx-auto mb-2 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
                <p class="text-sm text-gray-400">Bild oder Video hierher ziehen oder <span class="text-brand-highlight">durchsuchen</span></p>
                <p class="text-xs text-gray-500 mt-1">Bilder: max. 5 MB | Videos: max. 50 MB</p>
                <p id="mediaTypeWarning" class="text-xs text-yellow-400 mt-2 hidden">⚠️ Kann nicht Bilder und Videos mischen</p>
            </div>

            <!-- Upload Progress -->
            <div id="mediaUploadProgress" class="hidden">
                <div class="image-upload-progress">
                    <div id="mediaProgressBar" class="image-upload-progress-bar" style="width: 0%"></div>
                </div>
                <p class="text-xs text-gray-400 mt-1 text-center">Wird hochgeladen...</p>
            </div>
            {% else %}
            {% if not post.media_items or post.media_items | length == 0 %}
            <p class="text-xs text-gray-500 text-center py-4">Keine Medien vorhanden.</p>
            {% endif %}
            {% endif %}
        </div>

        <!-- Post Info -->
        <div class="section-card rounded-xl p-6">
            <h3 class="font-semibold text-white mb-4">Details</h3>
            <div class="space-y-3 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-400">Erstellt</span>
                    <span class="text-white">{{ post.created_at.strftime('%d.%m.%Y') if post.created_at else 'N/A' }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-400">Zeichen</span>
                    <span class="text-white" id="charCountDisplay">{{ post.post_content | length }}</span>
                </div>
                {% if post.scheduled_at %}
                <div class="flex justify-between">
                    <span class="text-gray-400">Geplant</span>
                    <span class="text-brand-highlight text-xs">{{ post.scheduled_at.strftime('%d.%m.%Y %H:%M') }}</span>
                </div>
                {% endif %}
                {% if post.topic_title %}
                <div class="pt-3 border-t border-brand-bg-light">
                    <span class="text-gray-400 block mb-1">Topic</span>
                    <span class="text-white">{{ post.topic_title }}</span>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
const POST_ID = '{{ post.id }}';
const EMPLOYEE_ID = '{{ employee_id }}';
const CAN_EDIT = {{ 'true' if (not permissions or permissions.can_edit_posts) else 'false' }};

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 text-sm ${
        type === 'success' ? 'bg-green-600 text-white' :
        type === 'error' ? 'bg-red-600 text-white' :
        'bg-gray-700 text-white'
    }`;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

function copyToClipboard() {
    const content = document.querySelector('.linkedin-content').textContent;
    navigator.clipboard.writeText(content).then(() => {
        const btn = document.querySelector('[onclick="copyToClipboard()"]');
        const original = btn.innerHTML;
        btn.innerHTML = '<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="M5 13l4 4L19 7"/></svg> Kopiert!';
        setTimeout(() => { btn.innerHTML = original; }, 2000);
    });
}

// ==================== EDIT FUNCTIONS ====================

function toggleEditView() {
    const editView = document.getElementById('editView');
    const previewSection = document.getElementById('previewSection');
    const editBtn = document.getElementById('editToggleBtn');

    if (editView.classList.contains('hidden')) {
        editView.classList.remove('hidden');
        previewSection.classList.add('hidden');
        editBtn.innerHTML = '<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 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg> Vorschau';
        updateCharCount();
    } else {
        cancelEdit();
    }
}

function cancelEdit() {
    const editView = document.getElementById('editView');
    const previewSection = document.getElementById('previewSection');
    const editBtn = document.getElementById('editToggleBtn');
    if (editView) editView.classList.add('hidden');
    if (previewSection) previewSection.classList.remove('hidden');
    if (editBtn) editBtn.innerHTML = '<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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg> Bearbeiten';
}

function updateCharCount() {
    const textarea = document.getElementById('editTextarea');
    const charCount = document.getElementById('charCount');
    const label = document.getElementById('charCountLabel');
    if (!textarea || !charCount) return;
    const len = textarea.value.length;
    charCount.textContent = len;
    if (label) {
        label.style.color = len > 3000 ? '#ef4444' : len > 2700 ? '#f59e0b' : '#9ca3af';
    }
}

async function saveEdit() {
    const textarea = document.getElementById('editTextarea');
    const newContent = textarea.value.trim();
    const saveBtn = document.getElementById('saveEditBtn');

    if (!newContent) { showToast('Der Post darf nicht leer sein.', 'error'); return; }
    if (newContent.length > 3000) { showToast('Post überschreitet das LinkedIn-Limit von 3000 Zeichen.', 'error'); return; }

    const originalHTML = saveBtn.innerHTML;
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<div class="w-4 h-4 border-2 border-brand-bg-dark border-t-transparent rounded-full animate-spin"></div>';

    try {
        const formData = new FormData();
        formData.append('content', newContent);
        const response = await fetch(`/api/posts/${POST_ID}`, { method: 'PUT', body: formData });
        const result = await response.json();
        if (result.success) {
            // Update LinkedIn preview content
            const linkedinContent = document.querySelector('.linkedin-content');
            if (linkedinContent) linkedinContent.textContent = newContent;
            const charDisplay = document.getElementById('charCountDisplay');
            if (charDisplay) charDisplay.textContent = newContent.length;
            cancelEdit();
            showToast('Post gespeichert!', 'success');
        } else {
            showToast('Fehler: ' + (result.detail || 'Speichern fehlgeschlagen'), 'error');
        }
    } catch (e) {
        showToast('Netzwerkfehler', 'error');
    } finally {
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalHTML;
    }
}

// ==================== SCHEDULE FUNCTIONS ====================

async function schedulePost() {
    const input = document.getElementById('scheduleInput');
    if (!input || !input.value) { showToast('Bitte Datum und Uhrzeit auswählen', 'error'); return; }

    const scheduleBtn = document.getElementById('scheduleBtn');
    const originalHTML = scheduleBtn.innerHTML;
    scheduleBtn.disabled = true;
    scheduleBtn.innerHTML = '<div class="w-4 h-4 border-2 border-brand-bg-dark border-t-transparent rounded-full animate-spin"></div>';

    try {
        const localDate = new Date(input.value);
        const isoString = localDate.toISOString();
        const formData = new FormData();
        formData.append('scheduled_at', isoString);
        const response = await fetch(`/api/posts/${POST_ID}/schedule`, { method: 'POST', body: formData });
        const result = await response.json();
        if (result.success) {
            showToast('Post geplant!', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Fehler: ' + (result.detail || 'Planen fehlgeschlagen'), 'error');
        }
    } catch (e) {
        showToast('Netzwerkfehler', 'error');
    } finally {
        scheduleBtn.disabled = false;
        scheduleBtn.innerHTML = originalHTML;
    }
}

async function unschedulePost() {
    if (!confirm('Planung aufheben?')) return;
    try {
        const response = await fetch(`/api/posts/${POST_ID}/unschedule`, { method: 'POST' });
        const result = await response.json();
        if (result.success) {
            showToast('Planung aufgehoben', 'success');
            setTimeout(() => location.reload(), 800);
        } else {
            showToast('Fehler: ' + (result.detail || 'Aufheben fehlgeschlagen'), 'error');
        }
    } catch (e) {
        showToast('Netzwerkfehler', 'error');
    }
}

// Preview Mode Toggle (Desktop/Mobile)
function setPreviewMode(mode) {
    const preview = document.getElementById('linkedinPreview');
    const container = document.getElementById('linkedinPreviewContainer');
    const desktopBtn = document.getElementById('desktopPreviewBtn');
    const mobileBtn = document.getElementById('mobilePreviewBtn');

    if (mode === 'desktop') {
        preview.classList.remove('mobile-view');
        preview.classList.add('desktop-view');
        container.classList.add('desktop-view-container');
        container.classList.remove('mobile-view-container');
        desktopBtn.classList.add('active');
        mobileBtn.classList.remove('active');
    } else if (mode === 'mobile') {
        preview.classList.remove('desktop-view');
        preview.classList.add('mobile-view');
        container.classList.remove('desktop-view-container');
        container.classList.add('mobile-view-container');
        mobileBtn.classList.add('active');
        desktopBtn.classList.remove('active');
    }
}

async function updateStatus(newStatus) {
    try {
        const formData = new FormData();
        formData.append('status', newStatus);

        const response = await fetch(`/api/posts/${POST_ID}/status`, {
            method: 'PATCH',
            body: formData
        });

        if (response.ok) {
            location.reload();
        } else {
            alert('Fehler beim Aktualisieren des Status');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Fehler beim Aktualisieren des Status');
    }
}

// ==================== AI SUGGESTIONS ====================

async function loadSuggestions() {
    const loadingEl = document.getElementById('suggestionsLoading');
    const listEl = document.getElementById('suggestionsList');
    const quickSuggestions = document.getElementById('quickSuggestions');
    const refreshBtn = document.getElementById('refreshSuggestionsBtn');
    if (!loadingEl) return;

    loadingEl.classList.remove('hidden');
    quickSuggestions.classList.add('hidden');
    listEl.classList.add('hidden');
    listEl.innerHTML = '';
    refreshBtn.disabled = true;

    try {
        const response = await fetch(`/api/posts/${POST_ID}/suggestions`);
        if (!response.ok) throw new Error('Fehler beim Laden der Vorschläge');

        const result = await response.json();
        const suggestions = result.suggestions || [];

        loadingEl.classList.add('hidden');

        if (suggestions.length === 0) {
            listEl.innerHTML = '<p class="text-sm text-gray-400 text-center py-2">Keine Vorschläge verfügbar.</p>';
            quickSuggestions.classList.remove('hidden');
        } else {
            listEl.innerHTML = '';
            const header = document.createElement('p');
            header.className = 'text-xs text-gray-500 mb-3';
            header.textContent = 'Vorschläge:';
            listEl.appendChild(header);

            suggestions.forEach(s => {
                const btn = document.createElement('button');
                btn.className = 'w-full text-left px-3 py-2 bg-brand-bg/50 hover:bg-brand-bg rounded-lg text-sm text-gray-300 hover:text-white transition-colors flex items-center gap-2';
                btn.innerHTML = `<span class="text-brand-highlight">✨</span> ${escapeHtml(s.label)}`;
                btn.addEventListener('click', () => applySuggestion(s.action));
                listEl.appendChild(btn);
            });

            const backBtn = document.createElement('button');
            backBtn.className = 'w-full mt-3 px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors';
            backBtn.innerHTML = '← Zurück zu Schnelloptionen';
            backBtn.addEventListener('click', () => {
                listEl.classList.add('hidden');
                quickSuggestions.classList.remove('hidden');
            });
            listEl.appendChild(backBtn);
            listEl.classList.remove('hidden');
        }
    } catch (error) {
        console.error('Error loading suggestions:', error);
        loadingEl.classList.add('hidden');
        quickSuggestions.classList.remove('hidden');
        showToast('Fehler beim Laden der Vorschläge', 'error');
    } finally {
        refreshBtn.disabled = false;
    }
}

async function applySuggestion(suggestion) {
    const listEl = document.getElementById('suggestionsList');
    const quickSuggestions = document.getElementById('quickSuggestions');
    const loadingEl = document.getElementById('suggestionsLoading');

    listEl.classList.add('hidden');
    loadingEl.classList.remove('hidden');

    try {
        const formData = new FormData();
        formData.append('suggestion', suggestion);
        const response = await fetch(`/api/posts/${POST_ID}/revise`, { method: 'POST', body: formData });
        if (!response.ok) throw new Error('Fehler beim Anwenden des Vorschlags');

        const result = await response.json();
        const newContent = result.new_content;

        // Update the LinkedIn preview
        const linkedinContent = document.querySelector('.linkedin-content');
        if (linkedinContent) linkedinContent.textContent = newContent;
        const editTextarea = document.getElementById('editTextarea');
        if (editTextarea) editTextarea.value = newContent;
        const charDisplay = document.getElementById('charCountDisplay');
        if (charDisplay) charDisplay.textContent = newContent.length;

        showToast('Vorschlag erfolgreich angewendet!', 'success');
        loadingEl.classList.add('hidden');
        quickSuggestions.classList.remove('hidden');
    } catch (error) {
        console.error('Error applying suggestion:', error);
        showToast('Fehler: ' + error.message, 'error');
        loadingEl.classList.add('hidden');
        quickSuggestions.classList.remove('hidden');
    }
}

async function applyQuickSuggestion(suggestion) {
    const quickSuggestions = document.getElementById('quickSuggestions');
    const loadingEl = document.getElementById('suggestionsLoading');

    quickSuggestions.classList.add('hidden');
    loadingEl.classList.remove('hidden');

    try {
        const formData = new FormData();
        formData.append('suggestion', suggestion);
        const response = await fetch(`/api/posts/${POST_ID}/revise`, { method: 'POST', body: formData });
        if (!response.ok) throw new Error('Fehler beim Anwenden');

        const result = await response.json();
        const newContent = result.new_content;

        const linkedinContent = document.querySelector('.linkedin-content');
        if (linkedinContent) linkedinContent.textContent = newContent;
        const editTextarea = document.getElementById('editTextarea');
        if (editTextarea) editTextarea.value = newContent;
        const charDisplay = document.getElementById('charCountDisplay');
        if (charDisplay) charDisplay.textContent = newContent.length;

        showToast('Verbesserung angewendet!', 'success');
    } catch (error) {
        console.error('Error applying quick suggestion:', error);
        showToast('Fehler: ' + error.message, 'error');
    } finally {
        loadingEl.classList.add('hidden');
        quickSuggestions.classList.remove('hidden');
    }
}

async function applyCustomSuggestion() {
    const input = document.getElementById('customSuggestion');
    const suggestion = input.value.trim();
    if (!suggestion) { showToast('Bitte gib eine Anweisung ein.', 'error'); return; }

    const btn = document.getElementById('applyCustomBtn');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<div class="loading-spinner" style="width:16px;height:16px;"></div>';
    btn.disabled = true;

    try {
        const formData = new FormData();
        formData.append('suggestion', suggestion);
        const response = await fetch(`/api/posts/${POST_ID}/revise`, { method: 'POST', body: formData });
        if (!response.ok) throw new Error('Fehler beim Anwenden der Anweisung');

        const result = await response.json();
        const newContent = result.new_content;

        const linkedinContent = document.querySelector('.linkedin-content');
        if (linkedinContent) linkedinContent.textContent = newContent;
        const editTextarea = document.getElementById('editTextarea');
        if (editTextarea) editTextarea.value = newContent;
        const charDisplay = document.getElementById('charCountDisplay');
        if (charDisplay) charDisplay.textContent = newContent.length;

        input.value = '';
        showToast('Anweisung erfolgreich angewendet!', 'success');
    } catch (error) {
        console.error('Error applying custom suggestion:', error);
        showToast('Fehler: ' + error.message, 'error');
    } finally {
        btn.innerHTML = originalHTML;
        btn.disabled = false;
    }
}

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

// ==================== MULTI-MEDIA UPLOAD ====================

let currentMediaItems = {{ media_items_dict | tojson | safe }};

async function handleMediaUpload(file) {
    if (!file) return;

    const uploadZone = document.getElementById('mediaUploadZone');
    const progressEl = document.getElementById('mediaUploadProgress');
    const progressBar = document.getElementById('mediaProgressBar');
    const warningEl = document.getElementById('mediaTypeWarning');

    if (currentMediaItems.length >= 3) {
        showToast('Maximal 3 Medien erlaubt', 'error');
        return;
    }

    const isVideo = file.type.startsWith('video/');
    const hasImages = currentMediaItems.some(item => item.type === 'image');
    const hasVideos = currentMediaItems.some(item => item.type === 'video');

    if ((isVideo && hasImages) || (!isVideo && hasVideos)) {
        warningEl.classList.remove('hidden');
        showToast('Kann nicht Bilder und Videos mischen', 'error');
        setTimeout(() => warningEl.classList.add('hidden'), 3000);
        return;
    }

    if (isVideo && currentMediaItems.length > 0) {
        showToast('Nur 1 Video pro Post erlaubt', 'error');
        return;
    }

    uploadZone.classList.add('hidden');
    progressEl.classList.remove('hidden');
    progressBar.style.width = '30%';

    try {
        const formData = new FormData();
        formData.append('file', file);
        progressBar.style.width = '60%';

        const response = await fetch(`/api/posts/${POST_ID}/media`, {
            method: 'POST',
            body: formData
        });

        progressBar.style.width = '90%';

        if (!response.ok) {
            const err = await response.json();
            throw new Error(err.detail || 'Upload fehlgeschlagen');
        }

        const result = await response.json();
        progressBar.style.width = '100%';
        currentMediaItems = result.media_items || [];

        setTimeout(() => {
            progressEl.classList.add('hidden');
            refreshMediaGrid();
            refreshLinkedInPreview();
        }, 300);

        const mediaType = isVideo ? 'Video' : 'Bild';
        showToast(`${mediaType} erfolgreich hochgeladen!`, 'success');

    } catch (error) {
        console.error('Media upload error:', error);
        showToast('Fehler: ' + error.message, 'error');
        progressEl.classList.add('hidden');
        uploadZone.classList.remove('hidden');
    }
}

async function deleteMedia(index) {
    if (!confirm('Media wirklich löschen?')) return;

    try {
        const response = await fetch(`/api/posts/${POST_ID}/media/${index}`, { method: 'DELETE' });

        if (!response.ok) {
            const err = await response.json();
            throw new Error(err.detail || 'Löschen fehlgeschlagen');
        }

        const result = await response.json();
        currentMediaItems = result.media_items || [];

        refreshMediaGrid();
        refreshLinkedInPreview();
        showToast('Media entfernt', 'success');

    } catch (error) {
        console.error('Media delete error:', error);
        showToast('Fehler: ' + error.message, 'error');
    }
}

function refreshMediaGrid() {
    const grid = document.getElementById('mediaGrid');
    const count = document.getElementById('mediaCount');
    const uploadZone = document.getElementById('mediaUploadZone');

    count.textContent = currentMediaItems.length;

    if (currentMediaItems.length === 0) {
        grid.classList.add('hidden');
        uploadZone.classList.remove('hidden');
        return;
    }

    grid.classList.remove('hidden');
    grid.style.gridTemplateColumns = `repeat(${currentMediaItems.length}, 1fr)`;

    grid.innerHTML = currentMediaItems.map((item, i) => {
        const isDragged = draggedItemData && item.url === draggedItemData.url;
        const ghostClass = isDragged ? 'is-ghost' : '';
        const ghostStyle = isDragged ? 'opacity: 0.3;' : '';
        const deleteBtn = CAN_EDIT ? `
            <button onclick="deleteMedia(${item.order})"
                class="absolute top-2 right-2 p-2 bg-red-600 rounded-full opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-700 z-10">
                <svg class="w-4 h-4 text-white" 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>` : '';

        return `
        <div class="media-item relative group rounded-lg overflow-hidden border-2 border-transparent hover:border-brand-highlight ${ghostClass}"
             data-array-index="${i}"
             ${CAN_EDIT ? 'draggable="true"' : ''}
             style="${CAN_EDIT ? 'cursor: grab;' : 'cursor: default;'} transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); ${ghostStyle}">
            <div class="media-content">
                ${item.type === 'image'
                    ? `<img src="${item.url}" alt="Media ${i+1}" class="w-full h-48 object-cover pointer-events-none">`
                    : `<video src="${item.url}" class="w-full h-48 object-cover pointer-events-none" controls></video>`
                }
            </div>
            ${deleteBtn}
            <div class="absolute bottom-2 left-2 px-2 py-1 bg-black/50 rounded text-xs text-white pointer-events-none">${i+1}</div>
        </div>
        `;
    }).join('');

    initDragAndDrop();

    if (currentMediaItems.length >= 3) {
        uploadZone.classList.add('hidden');
    } else {
        uploadZone.classList.remove('hidden');
    }
}

function refreshLinkedInPreview() {
    const linkedinMediaSection = document.getElementById('linkedinMediaSection');
    if (!linkedinMediaSection) return;

    if (currentMediaItems.length === 0) {
        linkedinMediaSection.classList.add('hidden');
        return;
    }

    linkedinMediaSection.classList.remove('hidden');

    // LinkedIn 3-Image Layout: 1 oben groß, 2+3 unten nebeneinander
    if (currentMediaItems.length === 3) {
        linkedinMediaSection.innerHTML = `
            <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 2px;">
                ${currentMediaItems[0].type === 'image'
                    ? `<img src="${currentMediaItems[0].url}" class="w-full h-64 object-cover" style="grid-column: 1 / -1;">`
                    : `<video src="${currentMediaItems[0].url}" class="w-full h-64 object-cover" controls style="grid-column: 1 / -1;"></video>`
                }
                ${currentMediaItems[1].type === 'image'
                    ? `<img src="${currentMediaItems[1].url}" class="w-full h-48 object-cover">`
                    : `<video src="${currentMediaItems[1].url}" class="w-full h-48 object-cover" controls></video>`
                }
                ${currentMediaItems[2].type === 'image'
                    ? `<img src="${currentMediaItems[2].url}" class="w-full h-48 object-cover">`
                    : `<video src="${currentMediaItems[2].url}" class="w-full h-48 object-cover" controls></video>`
                }
            </div>
        `;
    } else {
        // Standard Grid für 1 oder 2 Bilder
        const gridClass = currentMediaItems.length === 1 ? 'grid-cols-1' : 'grid-cols-2';
        linkedinMediaSection.innerHTML = `
            <div class="grid ${gridClass}" style="gap: 2px;">
                ${currentMediaItems.map(item =>
                    item.type === 'image'
                        ? `<img src="${item.url}" class="w-full h-48 object-cover">`
                        : `<video src="${item.url}" class="w-full h-48 object-cover" controls></video>`
                ).join('')}
            </div>
        `;
    }
}

// Drag-and-Drop Reorder (Ultra Smooth with Ghost)
let draggedArrayIndex = null;
let originalDraggedIndex = null; // Track the original starting position
let draggedElement = null;
let lastTargetIndex = null;
let isSaving = false;
let draggedItemData = null;

function initDragAndDrop() {
    const mediaGrid = document.getElementById('mediaGrid');
    if (!mediaGrid) return;

    const mediaItems = mediaGrid.querySelectorAll('.media-item');

    mediaItems.forEach((item, idx) => {
        item.addEventListener('dragstart', (e) => {
            draggedArrayIndex = parseInt(e.currentTarget.dataset.arrayIndex);
            originalDraggedIndex = draggedArrayIndex; // Save the original position
            draggedElement = e.currentTarget;
            lastTargetIndex = draggedArrayIndex;
            draggedItemData = currentMediaItems[draggedArrayIndex];

            setTimeout(() => {
                e.currentTarget.style.opacity = '0.3';
            }, 0);

            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setDragImage(e.currentTarget, e.currentTarget.offsetWidth / 2, e.currentTarget.offsetHeight / 2);
        });

        item.addEventListener('dragend', (e) => {
            const allItems = mediaGrid.querySelectorAll('.media-item');
            allItems.forEach(i => {
                i.style.opacity = '1';
                i.classList.remove('is-ghost');
            });

            console.log('🎯 Dragend:', {originalDraggedIndex, lastTargetIndex});

            if (lastTargetIndex !== null && lastTargetIndex !== originalDraggedIndex && !isSaving) {
                console.log('💾 Triggering save...');
                saveReorderInBackground();
            } else {
                console.log('⏭️ Skip save');
            }

            draggedArrayIndex = null;
            originalDraggedIndex = null;
            draggedElement = null;
            lastTargetIndex = null;
            draggedItemData = null;
        });

        item.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';

            if (draggedArrayIndex === null) return;

            const targetArrayIndex = parseInt(e.currentTarget.dataset.arrayIndex);

            if (targetArrayIndex !== lastTargetIndex && draggedArrayIndex !== targetArrayIndex) {
                lastTargetIndex = targetArrayIndex;

                const newMediaItems = [...currentMediaItems];
                const [movedItem] = newMediaItems.splice(draggedArrayIndex, 1);
                newMediaItems.splice(targetArrayIndex, 0, movedItem);

                currentMediaItems = newMediaItems;
                draggedArrayIndex = targetArrayIndex;

                refreshMediaGrid();
                refreshLinkedInPreview();
            }
        });

        item.addEventListener('drop', (e) => {
            e.preventDefault();
        });
    });
}

async function saveReorderInBackground() {
    if (isSaving) return;
    isSaving = true;

    const orderArray = currentMediaItems.map((item, i) => item.order);

    try {
        const response = await fetch(`/api/posts/${POST_ID}/media/reorder`, {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({order: orderArray})
        });

        if (!response.ok) throw new Error('Speichern fehlgeschlagen');

        const result = await response.json();
        currentMediaItems = result.media_items || [];

        console.log('✓ Reihenfolge im Hintergrund gespeichert');

    } catch (error) {
        console.error('Background save error:', error);
        showToast('Fehler beim Speichern - bitte Seite neu laden', 'error');
    } finally {
        isSaving = false;
    }
}

function initMediaUpload() {
    if (!CAN_EDIT) return;
    const uploadZone = document.getElementById('mediaUploadZone');
    const fileInput = document.getElementById('mediaFileInput');

    if (!uploadZone) return;

    uploadZone.addEventListener('click', () => fileInput.click());
    fileInput.addEventListener('change', (e) => {
        if (e.target.files[0]) handleMediaUpload(e.target.files[0]);
        e.target.value = '';
    });

    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('dragover');
    });
    uploadZone.addEventListener('dragleave', () => {
        uploadZone.classList.remove('dragover');
    });
    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
        if (e.dataTransfer.files[0]) handleMediaUpload(e.dataTransfer.files[0]);
    });

    initDragAndDrop();
}

document.addEventListener('DOMContentLoaded', () => {
    initMediaUpload();

    const editTextarea = document.getElementById('editTextarea');
    if (editTextarea) {
        editTextarea.addEventListener('input', updateCharCount);
    }

    // Pre-fill schedule input with current scheduled_at if exists
    const scheduleInput = document.getElementById('scheduleInput');
    {% if post.scheduled_at %}
    if (scheduleInput) {
        const dt = new Date('{{ post.scheduled_at.isoformat() }}');
        const pad = n => String(n).padStart(2, '0');
        scheduleInput.value = `${dt.getFullYear()}-${pad(dt.getMonth()+1)}-${pad(dt.getDate())}T${pad(dt.getHours())}:${pad(dt.getMinutes())}`;
    }
    {% endif %}
});
</script>
{% endblock %}
