{% extends "base.html" %}
{% block title %}{{ post.topic_title }} - Post Details{% endblock %}

{% block head %}
<style>
    .section-card {
        background: rgba(61, 72, 72, 0.3);
        border: 1px solid rgba(61, 72, 72, 0.6);
    }
    .title-truncate {
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .reference-post {
        background: linear-gradient(135deg, rgba(61, 72, 72, 0.4) 0%, rgba(45, 56, 56, 0.6) 100%);
        border: 1px solid rgba(255, 199, 0, 0.15);
        position: relative;
    }
    .reference-post::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 3px;
        background: linear-gradient(180deg, #ffc700 0%, rgba(255, 199, 0, 0.3) 100%);
        border-radius: 3px 0 0 3px;
    }
    .profile-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
    }
    .profile-item {
        background: rgba(45, 56, 56, 0.5);
        border-radius: 0.75rem;
        padding: 1rem;
        border: 1px solid rgba(61, 72, 72, 0.8);
    }
    .stat-bar {
        height: 6px;
        background: rgba(45, 56, 56, 0.8);
        border-radius: 3px;
        overflow: hidden;
    }
    .stat-bar-fill {
        height: 100%;
        background: linear-gradient(90deg, #ffc700 0%, #ffdb4d 100%);
        border-radius: 3px;
        transition: width 0.5s ease;
    }
    /* LinkedIn Preview styles */
    .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);
        line-height: 1.3;
    }
    .linkedin-headline {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.6);
        line-height: 1.3;
        margin-top: 2px;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .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;
        word-wrap: break-word;
    }
    .linkedin-content.collapsed {
        max-height: 120px;
        overflow: hidden;
        position: relative;
    }
    .linkedin-content.collapsed::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 40px;
        background: linear-gradient(transparent, white);
    }
    .linkedin-see-more {
        padding: 0 16px 12px;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        cursor: pointer;
        font-weight: 600;
    }
    .linkedin-see-more:hover {
        color: #0a66c2;
        text-decoration: underline;
    }
    .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-more-btn {
        padding: 4px;
        color: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        cursor: default;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .view-toggle {
        display: inline-flex;
        background: rgba(61, 72, 72, 0.5);
        border-radius: 8px;
        padding: 2px;
    }
    .view-toggle-btn {
        padding: 6px 12px;
        font-size: 12px;
        font-weight: 500;
        border-radius: 6px;
        color: #9ca3af;
        transition: all 0.2s;
    }
    .view-toggle-btn.active {
        background: rgba(255, 199, 0, 0.2);
        color: #ffc700;
    }
    /* 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 - full width */
    .linkedin-preview.desktop-view {
        max-width: 100%;
        margin: 0;
    }
    /* Desktop Background (LinkedIn beige) */
    .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; /* iPhone-Höhe */
        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; /* Scrollbar aktiviert */
        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 Circle - 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;
    }
    /* Custom scrollbar */
    .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; /* Space for notch (28px) + 5px margin */
    }
    .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-see-more {
        padding: 0 16px 16px;
        font-size: 13px;
    }
    .linkedin-preview.mobile-view .linkedin-engagement {
        padding: 12px 16px;
        font-size: 11px;
    }
    .linkedin-preview.mobile-view .linkedin-action-btn {
        font-size: 0; /* Hide text labels on mobile */
        padding: 14px 8px;
        gap: 0;
    }
    .linkedin-preview.mobile-view .linkedin-action-btn svg {
        width: 22px;
        height: 22px;
        margin: 0;
    }
    .view-toggle-btn:hover:not(.active) {
        color: #e5e7eb;
    }
    /* Tab styles */
    .tab-btn {
        position: relative;
        padding: 0.75rem 1.25rem;
        font-weight: 500;
        color: #9ca3af;
        transition: all 0.2s ease;
        border-bottom: 2px solid transparent;
    }
    .tab-btn:hover {
        color: #e5e7eb;
    }
    .tab-btn.active {
        color: #ffc700;
        border-bottom-color: #ffc700;
    }
    .tab-btn.active::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        right: 0;
        height: 2px;
        background: #ffc700;
    }
    .tab-content {
        display: none;
        animation: fadeIn 0.2s ease;
    }
    .tab-content.active {
        display: block;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(5px); }
        to { opacity: 1; transform: translateY(0); }
    }
    /* Edit mode styles */
    .edit-textarea {
        width: 100%;
        min-height: 300px;
        background: rgba(45, 56, 56, 0.5);
        border: 1px solid rgba(61, 72, 72, 0.8);
        border-radius: 0.75rem;
        padding: 1rem;
        color: #e5e7eb;
        font-family: inherit;
        font-size: 14px;
        line-height: 1.6;
        resize: vertical;
    }
    .edit-textarea:focus {
        outline: none;
        border-color: #ffc700;
    }
    .suggestion-card {
        background: rgba(45, 56, 56, 0.5);
        border: 1px solid rgba(61, 72, 72, 0.8);
        border-radius: 0.75rem;
        padding: 1rem;
        cursor: pointer;
        transition: all 0.2s;
    }
    .suggestion-card:hover {
        border-color: #ffc700;
        background: rgba(255, 199, 0, 0.05);
    }
    .suggestion-category {
        display: inline-block;
        padding: 2px 8px;
        background: rgba(255, 199, 0, 0.2);
        color: #ffc700;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }
    .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); }
    }
</style>
{% endblock %}

{% block content %}
<!-- Breadcrumb & Header -->
<div class="mb-6">
    <a href="/posts" class="inline-flex items-center gap-2 text-gray-400 hover:text-brand-highlight transition-colors mb-4">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
        Zurück zu meinen Posts
    </a>
    <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 title-truncate" title="{{ post.topic_title or 'Untitled Post' }}">
                {{ 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 class="text-gray-600">|</span>
                <span>{{ post.iterations }} Iteration{{ 's' if post.iterations != 1 else '' }}</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' }}">
                {{ post.status | capitalize }}
            </span>
            {% if final_feedback and final_feedback.get('overall_score') is not none %}
            <span class="px-3 py-1.5 rounded-lg text-sm font-bold {{ 'bg-green-600/30 text-green-300' if final_feedback.get('overall_score', 0) >= 85 else 'bg-yellow-600/30 text-yellow-300' if final_feedback.get('overall_score', 0) >= 70 else 'bg-red-600/30 text-red-300' }}">
                Score: {{ final_feedback.get('overall_score', 0) }}/100
            </span>
            {% endif %}
        </div>
    </div>
</div>

<!-- Tab Navigation -->
<div class="mb-6 border-b border-brand-bg-light">
    <nav class="flex gap-1" role="tablist">
        <button class="tab-btn active" onclick="switchTab('ergebnis')" role="tab" aria-selected="true" data-tab="ergebnis">
            <svg class="w-4 h-4 inline-block mr-2" 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>
            Ergebnis
        </button>
        <button class="tab-btn" onclick="switchTab('iterationen')" role="tab" aria-selected="false" data-tab="iterationen">
            <svg class="w-4 h-4 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            Iterationen
            <span id="versionCount" class="ml-1 px-1.5 py-0.5 text-xs bg-brand-bg rounded">{{ post.writer_versions | length if post.writer_versions else 0 }}</span>
        </button>
    </nav>
</div>

<!-- Tab: Ergebnis -->
<div id="tab-ergebnis" class="tab-content active">
    <!-- Top Section: Post + AI Suggestions -->
    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6 mb-6">
        <!-- Post Content -->
        <div class="xl:col-span-2">
            <div class="section-card rounded-xl p-6 h-full">
                <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>
                        Finaler Post
                    </h2>
                    <div class="flex items-center gap-3">
                        <!-- View Toggle -->
                        <div class="view-toggle">
                            <button onclick="setView('preview')" id="previewToggle" class="view-toggle-btn active">
                                <svg class="w-4 h-4 inline-block mr-1" 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>
                                Preview
                            </button>
                            <button onclick="setView('raw')" id="rawToggle" class="view-toggle-btn">
                                <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/></svg>
                                Raw
                            </button>
                            <button onclick="setView('edit')" id="editToggle" class="view-toggle-btn">
                                <svg class="w-4 h-4 inline-block mr-1" 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>
                        </div>
                        <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>

                <!-- LinkedIn Preview View -->
                <div id="previewModeContainer" 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 id="previewModeButtons" class="flex items-center gap-1 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="{{ session.linkedin_name }}" loading="lazy" referrerpolicy="no-referrer">
                            {% else %}
                            {{ session.linkedin_name[:2] | upper if session.linkedin_name else 'UN' }}
                            {% endif %}
                        </div>
                        <div class="linkedin-user-info">
                            <div class="linkedin-name">{{ session.linkedin_name or 'LinkedIn User' }}</div>
                            <div class="linkedin-headline">{{ session.customer_name or 'LinkedIn Member' }}</div>
                            <div class="linkedin-timestamp">
                                <span>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 class="linkedin-more-btn">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                <circle cx="6" cy="12" r="2"/>
                                <circle cx="12" cy="12" r="2"/>
                                <circle cx="18" cy="12" r="2"/>
                            </svg>
                        </div>
                    </div>
                    <div id="linkedinContent" class="linkedin-content collapsed">{{ post.post_content }}</div>
                    <div id="seeMoreBtn" class="linkedin-see-more" onclick="toggleContent()">...mehr anzeigen</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>
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="#df704d" style="margin-left: -6px;">
                            <path d="M22.51 11.35a5.84 5.84 0 00-2.53-4.83 5.71 5.71 0 00-5.36-.58 5.64 5.64 0 00-2.62 2.09 5.64 5.64 0 00-2.62-2.09 5.71 5.71 0 00-5.36.58 5.84 5.84 0 00-2.53 4.83 6.6 6.6 0 00.49 2.56c1 2.33 9.91 8.09 9.91 8.09s8.92-5.76 9.91-8.09a6.6 6.6 0 00.71-2.56z"/>
                        </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>

                <!-- Raw View -->
                <div id="rawView" class="bg-brand-bg/50 rounded-lg p-5 hidden">
                    <pre id="finalPostContent" class="whitespace-pre-wrap text-gray-200 font-sans text-sm leading-relaxed">{{ post.post_content }}</pre>
                </div>

                <!-- Edit View -->
                <div id="editView" class="hidden">
                    <textarea id="editTextarea" class="edit-textarea">{{ post.post_content }}</textarea>
                    <div class="flex items-center justify-between mt-4">
                        <span class="text-sm" id="charCountLabel">
                            <span id="charCount">{{ post.post_content | length }}</span> / 3000 Zeichen
                        </span>
                        <div class="flex items-center gap-3">
                            <button onclick="cancelEdit()" class="px-4 py-2 bg-brand-bg hover:bg-brand-bg-light text-gray-300 rounded-lg transition-colors">
                                Abbrechen
                            </button>
                            <button onclick="saveEdit()" id="saveEditBtn" class="px-4 py-2 bg-brand-highlight hover:bg-brand-highlight/90 text-brand-bg-dark font-medium 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="M5 13l4 4L19 7"/></svg>
                                Speichern
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- AI Suggestions - Rechte Seite oben -->
        <div>
            <div class="section-card rounded-xl p-6 h-full">
                <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 (Default) -->
                <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>

                <!-- Suggestions 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 Suggestion Input -->
                <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>
        </div>
    </div>

    <!-- Media Upload Section (Multi-Media Support) -->
    <div class="section-card rounded-xl p-6 mb-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 }}" draggable="true" style="cursor: grab;">
                {% 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 -->
                <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>

                <!-- 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 (shown when < 3 media items) -->
        <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>
    </div>

    <!-- Bottom Section: Score, Feedback, Actions -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        <!-- Score Breakdown -->
        {% if final_feedback and final_feedback.get('scores') and final_feedback.get('overall_score') is not none %}
        <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="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                Score: {{ final_feedback.get('overall_score', 0) }}/100
            </h3>
            <div class="space-y-3">
                <div>
                    <div class="flex justify-between text-sm mb-1">
                        <span class="text-gray-400">Authentizität</span>
                        <span class="text-white font-medium">{{ final_feedback.scores.authenticity_and_style }}/40</span>
                    </div>
                    <div class="stat-bar">
                        <div class="stat-bar-fill" style="width: {{ (final_feedback.scores.authenticity_and_style / 40 * 100) | int }}%"></div>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between text-sm mb-1">
                        <span class="text-gray-400">Content</span>
                        <span class="text-white font-medium">{{ final_feedback.scores.content_quality }}/35</span>
                    </div>
                    <div class="stat-bar">
                        <div class="stat-bar-fill" style="width: {{ (final_feedback.scores.content_quality / 35 * 100) | int }}%"></div>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between text-sm mb-1">
                        <span class="text-gray-400">Technik</span>
                        <span class="text-white font-medium">{{ final_feedback.scores.technical_execution }}/25</span>
                    </div>
                    <div class="stat-bar">
                        <div class="stat-bar-fill" style="width: {{ (final_feedback.scores.technical_execution / 25 * 100) | int }}%"></div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Final Feedback Summary -->
        {% if final_feedback %}
        <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 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/></svg>
                Feedback
            </h3>
            <p class="text-sm text-gray-300 mb-3">{{ final_feedback.feedback }}</p>
            {% if final_feedback.strengths %}
            <div class="bg-green-900/10 rounded-lg p-3 border border-green-600/20">
                <span class="text-xs font-medium text-green-400 block mb-2">Stärken</span>
                <ul class="space-y-1">
                    {% for s in final_feedback.strengths %}
                    <li class="text-sm text-gray-400 flex items-start gap-2"><span class="text-green-400">+</span> {{ s }}</li>
                    {% endfor %}
                </ul>
            </div>
            {% endif %}
        </div>
        {% endif %}

        <!-- Quick Actions -->
        <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="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                Aktionen
            </h3>
            <div class="space-y-2">
                <button onclick="copyToClipboard()" class="w-full px-4 py-2.5 bg-brand-highlight hover:bg-brand-highlight/90 text-brand-bg-dark font-medium rounded-lg 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="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>
                    Post kopieren
                </button>
                <a href="/create" class="w-full px-4 py-2.5 bg-brand-bg hover:bg-brand-bg-light text-white rounded-lg 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="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
                    Neuen Post erstellen
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Tab: Iterationen -->
<div id="tab-iterationen" class="tab-content">
    <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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                Iterationen
            </h2>
            <!-- Pagination Controls -->
            <div id="paginationControls" class="flex items-center gap-2 {% if not post.writer_versions or post.writer_versions | length == 0 %}hidden{% endif %}">
                <button id="prevVersion" onclick="changeVersion(-1)" class="p-2 rounded-lg bg-brand-bg hover:bg-brand-bg-light text-gray-400 hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                </button>
                <span class="text-sm text-gray-400">
                    <span id="currentVersionNum">1</span> / <span id="totalVersionNum">{{ post.writer_versions | length if post.writer_versions else 0 }}</span>
                </span>
                <button id="nextVersion" onclick="changeVersion(1)" class="p-2 rounded-lg bg-brand-bg hover:bg-brand-bg-light text-gray-400 hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed">
                    <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 5l7 7-7 7"/></svg>
                </button>
            </div>
        </div>

        <!-- Version Content Container -->
        <div id="versionsContainer">
            {% if post.writer_versions and post.writer_versions | length > 0 %}
            {% for i in range(post.writer_versions | length) %}
            <div class="version-panel {% if i == 0 %}block{% else %}hidden{% endif %}" data-version="{{ i }}">
                <div class="flex items-center justify-between mb-3">
                    <span class="px-3 py-1 bg-brand-highlight/20 text-brand-highlight rounded-lg text-sm font-medium">Version {{ i + 1 }}</span>
                    {% if post.critic_feedback and i < post.critic_feedback | length %}
                    <div class="flex items-center gap-2">
                        {% if post.critic_feedback[i].get('overall_score') is not none %}
                        <span class="px-2 py-1 rounded text-xs font-medium {{ 'bg-green-600/30 text-green-300' if post.critic_feedback[i].get('overall_score', 0) >= 85 else 'bg-yellow-600/30 text-yellow-300' }}">
                            Score: {{ post.critic_feedback[i].get('overall_score', 0) }}/100
                        </span>
                        {% endif %}
                        {% if post.critic_feedback[i].get('approved') %}
                        <span class="px-2 py-1 bg-green-600/30 text-green-300 rounded text-xs">Approved</span>
                        {% endif %}
                    </div>
                    {% endif %}
                </div>

                <div class="bg-brand-bg/30 rounded-lg p-4 mb-4">
                    <pre class="whitespace-pre-wrap text-gray-300 font-sans text-sm">{{ post.writer_versions[i] }}</pre>
                </div>

                {% if post.critic_feedback and i < post.critic_feedback | length %}
                {% set fb = post.critic_feedback[i] %}
                <div class="bg-brand-bg/20 rounded-lg p-4 border border-brand-bg-light">
                    <h4 class="text-sm font-medium text-white mb-2 flex items-center gap-2">
                        <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/></svg>
                        Critic Feedback
                    </h4>
                    <p class="text-sm text-gray-400 mb-3">{{ fb.feedback }}</p>
                    <div class="grid md:grid-cols-2 gap-4">
                        {% if fb.strengths %}
                        <div class="bg-green-900/10 rounded-lg p-3 border border-green-600/20">
                            <span class="text-xs font-medium text-green-400 block mb-2">Stärken</span>
                            <ul class="space-y-1 text-sm text-gray-400">
                                {% for s in fb.strengths %}
                                <li class="flex items-start gap-2"><span class="text-green-400 mt-0.5">+</span> {{ s }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        {% endif %}
                        {% if fb.improvements %}
                        <div class="bg-yellow-900/10 rounded-lg p-3 border border-yellow-600/20">
                            <span class="text-xs font-medium text-yellow-400 block mb-2">Verbesserungen</span>
                            <ul class="space-y-1 text-sm text-gray-400">
                                {% for imp in fb.improvements %}
                                <li class="flex items-start gap-2"><span class="text-yellow-400 mt-0.5">-</span> {{ imp }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        {% endif %}
                    </div>
                </div>
                {% endif %}
            </div>
            {% endfor %}
            {% else %}
            <p id="noVersionsMsg" class="text-sm text-gray-400 text-center py-4">Noch keine Versionen vorhanden.</p>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentVersion = 0;
let totalVersions = {{ post.writer_versions | length if post.writer_versions else 0 }};
let currentView = 'preview';
let contentExpanded = false;
let originalContent = '';
const postId = '{{ post.id }}';

// Function to add a new version to the UI
function addNewVersion(content) {
    totalVersions++;

    // Update version counts in UI
    document.getElementById('versionCount').textContent = totalVersions;
    document.getElementById('totalVersionNum').textContent = totalVersions;

    // Show pagination controls if this is the first version
    const paginationControls = document.getElementById('paginationControls');
    if (paginationControls) {
        paginationControls.classList.remove('hidden');
    }

    // Remove "no versions" message if present
    const noVersionsMsg = document.getElementById('noVersionsMsg');
    if (noVersionsMsg) {
        noVersionsMsg.remove();
    }

    // Hide all existing version panels
    document.querySelectorAll('.version-panel').forEach(panel => {
        panel.classList.add('hidden');
        panel.classList.remove('block');
    });

    // Create new version panel
    const container = document.getElementById('versionsContainer');
    const newPanel = document.createElement('div');
    newPanel.className = 'version-panel block';
    newPanel.dataset.version = totalVersions - 1;
    newPanel.innerHTML = `
        <div class="flex items-center justify-between mb-3">
            <span class="px-3 py-1 bg-brand-highlight/20 text-brand-highlight rounded-lg text-sm font-medium">Version ${totalVersions}</span>
            <span class="px-2 py-1 bg-blue-600/30 text-blue-300 rounded text-xs">Manuell bearbeitet</span>
        </div>
        <div class="bg-brand-bg/30 rounded-lg p-4 mb-4">
            <pre class="whitespace-pre-wrap text-gray-300 font-sans text-sm">${escapeHtml(content)}</pre>
        </div>
    `;
    container.appendChild(newPanel);

    // Update current version to the new one
    currentVersion = totalVersions - 1;
    document.getElementById('currentVersionNum').textContent = totalVersions;

    // Update button states
    const prevBtn = document.getElementById('prevVersion');
    const nextBtn = document.getElementById('nextVersion');
    if (prevBtn) prevBtn.disabled = currentVersion === 0;
    if (nextBtn) nextBtn.disabled = true;
}

// View Toggle functions
function setView(view) {
    currentView = view;
    const previewContainer = document.getElementById('linkedinPreviewContainer');
    const rawEl = document.getElementById('rawView');
    const editEl = document.getElementById('editView');
    const seeMoreBtn = document.getElementById('seeMoreBtn');
    const previewToggle = document.getElementById('previewToggle');
    const rawToggle = document.getElementById('rawToggle');
    const editToggle = document.getElementById('editToggle');
    const previewModeContainer = document.getElementById('previewModeContainer');

    // Hide all views
    previewContainer.classList.add('hidden');
    rawEl.classList.add('hidden');
    editEl.classList.add('hidden');
    if (seeMoreBtn) seeMoreBtn.classList.add('hidden');

    // Remove active from all toggles
    previewToggle.classList.remove('active');
    rawToggle.classList.remove('active');
    editToggle.classList.remove('active');

    if (view === 'preview') {
        previewContainer.classList.remove('hidden');
        if (seeMoreBtn) seeMoreBtn.classList.remove('hidden');
        previewToggle.classList.add('active');
        // Show preview mode container only in preview view
        if (previewModeContainer) previewModeContainer.classList.remove('hidden');
    } else if (view === 'raw') {
        rawEl.classList.remove('hidden');
        rawToggle.classList.add('active');
        // Hide preview mode container
        if (previewModeContainer) previewModeContainer.classList.add('hidden');
    } else if (view === 'edit') {
        editEl.classList.remove('hidden');
        editToggle.classList.add('active');
        // Hide preview mode container
        if (previewModeContainer) previewModeContainer.classList.add('hidden');
        // Reset textarea to current content
        const currentContent = document.getElementById('finalPostContent').textContent;
        document.getElementById('editTextarea').value = currentContent;
        updateCharCount();
    }
}

// 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');
    }
}

// Edit functions
function updateCharCount() {
    const textarea = document.getElementById('editTextarea');
    const charCount = document.getElementById('charCount');
    const label = document.getElementById('charCountLabel');
    const len = textarea.value.length;
    charCount.textContent = len;
    if (len > 3000) {
        label.style.color = '#ef4444';
    } else if (len > 2700) {
        label.style.color = '#f59e0b';
    } else {
        label.style.color = '#9ca3af';
    }
}

function cancelEdit() {
    setView('preview');
}

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

    if (!newContent) {
        alert('Der Post darf nicht leer sein.');
        return;
    }

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

    // Show loading state
    const originalBtnHTML = saveBtn.innerHTML;
    saveBtn.innerHTML = '<div class="loading-spinner"></div>';
    saveBtn.disabled = true;

    try {
        const formData = new FormData();
        formData.append('content', newContent);

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

        if (!response.ok) {
            throw new Error('Fehler beim Speichern');
        }

        const result = await response.json();

        // Update the content in all views
        document.getElementById('finalPostContent').textContent = newContent;
        document.getElementById('linkedinContent').textContent = newContent;
        originalContent = newContent;

        // Add new version to iterations
        addNewVersion(newContent);

        // Switch to preview view
        setView('preview');
        initLinkedInPreview();

        // Show success message
        showToast('Post erfolgreich gespeichert!', 'success');

    } catch (error) {
        console.error('Error saving post:', error);
        showToast('Fehler beim Speichern: ' + error.message, 'error');
    } finally {
        saveBtn.innerHTML = originalBtnHTML;
        saveBtn.disabled = false;
    }
}

// Suggestions functions
async function loadSuggestions() {
    const loadingEl = document.getElementById('suggestionsLoading');
    const listEl = document.getElementById('suggestionsList');
    const quickSuggestions = document.getElementById('quickSuggestions');
    const refreshBtn = document.getElementById('refreshSuggestionsBtn');

    // Show loading, hide quick suggestions
    loadingEl.classList.remove('hidden');
    quickSuggestions.classList.add('hidden');
    listEl.classList.add('hidden');
    listEl.innerHTML = '';
    refreshBtn.disabled = true;

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

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

        // Hide loading
        loadingEl.classList.add('hidden');

        // Render suggestions
        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 = '';

            // Add header
            const header = document.createElement('p');
            header.className = 'text-xs text-gray-500 mb-3';
            header.textContent = 'Basierend auf Kritiker-Feedback:';
            listEl.appendChild(header);

            suggestions.forEach((s, i) => {
                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);
            });

            // Add button to go back to quick suggestions
            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');

    // Show loading
    listEl.classList.add('hidden');
    loadingEl.classList.remove('hidden');

    try {
        const formData = new FormData();
        formData.append('suggestion', suggestion);

        const response = await fetch(`/api/posts/${postId}/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 content in all views
        document.getElementById('finalPostContent').textContent = newContent;
        document.getElementById('linkedinContent').textContent = newContent;
        document.getElementById('editTextarea').value = newContent;
        originalContent = newContent;

        // Add new version to iterations
        addNewVersion(newContent);

        // Reinitialize LinkedIn preview
        initLinkedInPreview();

        // Show success and go back to quick suggestions
        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 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/${postId}/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;

        // Update the content in all views
        document.getElementById('finalPostContent').textContent = newContent;
        document.getElementById('linkedinContent').textContent = newContent;
        document.getElementById('editTextarea').value = newContent;
        originalContent = newContent;

        // Add new version to iterations
        addNewVersion(newContent);

        // Clear input and reinitialize preview
        input.value = '';
        initLinkedInPreview();

        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;
    }
}

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

    // Show loading, hide quick suggestions
    quickSuggestions.classList.add('hidden');
    loadingEl.classList.remove('hidden');

    try {
        const formData = new FormData();
        formData.append('suggestion', suggestion);

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

        if (!response.ok) {
            throw new Error('Fehler beim Anwenden');
        }

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

        // Update the content in all views
        document.getElementById('finalPostContent').textContent = newContent;
        document.getElementById('linkedinContent').textContent = newContent;
        document.getElementById('editTextarea').value = newContent;
        originalContent = newContent;

        // Add new version to iterations
        addNewVersion(newContent);

        // Reinitialize LinkedIn preview
        initLinkedInPreview();

        showToast('Verbesserung angewendet!', 'success');

    } catch (error) {
        console.error('Error applying quick suggestion:', error);
        showToast('Fehler: ' + error.message, 'error');
    } finally {
        // Hide loading, show quick suggestions again
        loadingEl.classList.add('hidden');
        quickSuggestions.classList.remove('hidden');
    }
}

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

function showToast(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 transition-all transform translate-y-0 opacity-100 ${
        type === 'success' ? 'bg-green-600 text-white' :
        type === 'error' ? 'bg-red-600 text-white' :
        'bg-brand-bg-light text-white'
    }`;
    toast.textContent = message;
    document.body.appendChild(toast);

    // Animate out and remove
    setTimeout(() => {
        toast.classList.add('opacity-0', 'translate-y-2');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

function toggleContent() {
    const contentEl = document.getElementById('linkedinContent');
    const seeMoreBtn = document.getElementById('seeMoreBtn');

    if (contentExpanded) {
        contentEl.classList.add('collapsed');
        seeMoreBtn.textContent = '...mehr anzeigen';
        seeMoreBtn.style.display = 'block';
    } else {
        contentEl.classList.remove('collapsed');
        seeMoreBtn.textContent = '...weniger anzeigen';
    }
    contentExpanded = !contentExpanded;
}

function initLinkedInPreview() {
    const contentEl = document.getElementById('linkedinContent');
    const seeMoreBtn = document.getElementById('seeMoreBtn');

    if (contentEl && seeMoreBtn) {
        // Check if content is short enough to not need "see more"
        const maxCollapsedHeight = 120;
        contentEl.classList.remove('collapsed');
        const fullHeight = contentEl.scrollHeight;
        contentEl.classList.add('collapsed');

        if (fullHeight <= maxCollapsedHeight) {
            // Content is short, hide "see more" button and remove collapsed class
            seeMoreBtn.style.display = 'none';
            contentEl.classList.remove('collapsed');
        }
    }
}

// Tab switching function
function switchTab(tabName) {
    // Hide all tab contents
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });

    // Deactivate all tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.setAttribute('aria-selected', 'false');
    });

    // Show selected tab content
    const tabContent = document.getElementById('tab-' + tabName);
    if (tabContent) {
        tabContent.classList.add('active');
    }

    // Activate selected tab button
    const tabBtn = document.querySelector(`.tab-btn[data-tab="${tabName}"]`);
    if (tabBtn) {
        tabBtn.classList.add('active');
        tabBtn.setAttribute('aria-selected', 'true');
    }
}

function copyToClipboard() {
    const content = document.getElementById('finalPostContent').textContent;
    navigator.clipboard.writeText(content).then(() => {
        const btn = event.target.closest('button');
        const originalHTML = 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 = originalHTML, 2000);
    });
}

function changeVersion(delta) {
    const newVersion = currentVersion + delta;
    if (newVersion < 0 || newVersion >= totalVersions) return;

    // Hide current
    document.querySelector(`.version-panel[data-version="${currentVersion}"]`).classList.add('hidden');
    document.querySelector(`.version-panel[data-version="${currentVersion}"]`).classList.remove('block');

    // Show new
    currentVersion = newVersion;
    document.querySelector(`.version-panel[data-version="${currentVersion}"]`).classList.remove('hidden');
    document.querySelector(`.version-panel[data-version="${currentVersion}"]`).classList.add('block');

    // Update counter
    document.getElementById('currentVersionNum').textContent = currentVersion + 1;

    // Update button states
    document.getElementById('prevVersion').disabled = currentVersion === 0;
    document.getElementById('nextVersion').disabled = currentVersion === totalVersions - 1;
}

// ==================== 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');

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

    // Validate no mixing
    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;
    }

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

    // Show progress
    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/${postId}/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%';

        // Update current media items
        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/${postId}/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) => `
        <div class="media-item relative group rounded-lg overflow-hidden border-2 border-transparent hover:border-brand-highlight"
             data-array-index="${i}"
             draggable="true"
             style="cursor: grab; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);">
            <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>
            <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>
            <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('');

    // Re-attach drag handlers after refresh
    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) => {
        // Dragstart - Element wird gegriffen
        item.addEventListener('dragstart', (e) => {
            draggedArrayIndex = parseInt(e.currentTarget.dataset.arrayIndex);
            originalDraggedIndex = draggedArrayIndex; // Save the original position
            draggedElement = e.currentTarget;
            lastTargetIndex = draggedArrayIndex;
            draggedItemData = currentMediaItems[draggedArrayIndex];

            // Smooth fade out des gezogenen Elements
            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);
        });

        // Dragend - Element wird losgelassen
        item.addEventListener('dragend', (e) => {
            // Entferne alle Ghost-Klassen
            const allItems = mediaGrid.querySelectorAll('.media-item');
            allItems.forEach(i => {
                i.style.opacity = '1';
                i.classList.remove('is-ghost');
            });

            // Wenn sich die Position geändert hat, speichere im Hintergrund
            console.log('🎯 Dragend:', {originalDraggedIndex, lastTargetIndex, changed: lastTargetIndex !== null && lastTargetIndex !== originalDraggedIndex});

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

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

        // Dragover - Element schwebt über anderem Element (LIVE REORDER)
        item.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';

            if (draggedArrayIndex === null) return;

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

            // Nur neu ordnen wenn sich die Position geändert hat
            if (targetArrayIndex !== lastTargetIndex && draggedArrayIndex !== targetArrayIndex) {
                lastTargetIndex = targetArrayIndex;

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

                currentMediaItems = newMediaItems;
                draggedArrayIndex = targetArrayIndex;

                // Smooth Re-Render
                refreshMediaGridSmooth();
                refreshLinkedInPreview();
            }
        });

        // Drop - Element wird losgelassen
        item.addEventListener('drop', (e) => {
            e.preventDefault();
        });
    });
}

// Smooth version of refreshMediaGrid that maintains the dragging state
function refreshMediaGridSmooth() {
    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;' : '';

        return `
        <div class="media-item relative group rounded-lg overflow-hidden border-2 border-transparent hover:border-brand-highlight ${ghostClass}"
             data-array-index="${i}"
             draggable="true"
             style="cursor: grab; 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>
            <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>
            <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('');

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

    // Re-attach drag handlers
    initDragAndDrop();
}

// Speichert die neue Reihenfolge im Hintergrund
async function saveReorderInBackground() {
    if (isSaving) return;
    isSaving = true;

    // Erstelle Order-Array für Backend
    const orderArray = currentMediaItems.map((item, i) => item.order);

    console.log('🔍 Sending reorder:', {
        currentMediaItems: currentMediaItems.map(item => ({url: item.url.substring(item.url.length-20), order: item.order})),
        orderArray: orderArray
    });

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

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            console.error('❌ Reorder failed:', response.status, errorData);
            throw new Error('Speichern fehlgeschlagen: ' + (errorData.detail || response.statusText));
        }

        const result = await response.json();
        console.log('✅ Reorder response:', {
            received: result.media_items.map(item => ({url: item.url.substring(item.url.length-20), order: item.order}))
        });

        // Update mit Server-Response (für korrekte order-Werte)
        currentMediaItems = result.media_items || [];

        // Stilles Update ohne Re-Render (UI ist schon aktuell)
        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() {
    const uploadZone = document.getElementById('mediaUploadZone');
    const fileInput = document.getElementById('mediaFileInput');

    if (!uploadZone) return;

    // Click to upload
    uploadZone.addEventListener('click', () => fileInput.click());

    // File selected
    fileInput.addEventListener('change', (e) => {
        if (e.target.files[0]) handleMediaUpload(e.target.files[0]);
        e.target.value = ''; // Reset input
    });

    // Drag & drop for upload zone
    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]);
    });

    // Initialize drag-and-drop for reordering
    initDragAndDrop();
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    // Initialize original content from DOM
    originalContent = document.getElementById('finalPostContent').textContent;

    if (totalVersions > 0) {
        const prevBtn = document.getElementById('prevVersion');
        const nextBtn = document.getElementById('nextVersion');
        if (prevBtn) prevBtn.disabled = true;
        if (nextBtn) nextBtn.disabled = totalVersions <= 1;
    }
    // Initialize LinkedIn preview
    initLinkedInPreview();

    // Initialize media upload (multi-media support)
    initMediaUpload();

    // Add event listener for textarea character count + initialize color
    const textarea = document.getElementById('editTextarea');
    if (textarea) {
        textarea.addEventListener('input', updateCharCount);
        updateCharCount();
    }

    // Allow Enter key to apply custom suggestion
    const customInput = document.getElementById('customSuggestion');
    if (customInput) {
        customInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                applyCustomSuggestion();
            }
        });
    }
});
</script>
{% endblock %}
