{% extends "base.html" %}
{% block title %}Post aus Datei erstellen - LinkedIn Posts{% endblock %}

{% block content %}
<!-- Wizard Container (hidden during generation) -->
<div id="wizardContainer" {% if limit_reached %}style="pointer-events: none; opacity: 0.5;"{% endif %}>
    <div class="max-w-2xl mx-auto">
        <div class="mb-4">
            <a href="/create" class="inline-flex items-center gap-2 text-gray-400 hover:text-brand-highlight transition-colors">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
                Zurück
            </a>
        </div>
        <div class="mb-8 text-center">
            <h1 class="text-3xl font-bold text-white mb-2">Post aus Datei erstellen</h1>
            <p class="text-gray-400">Lade eine Datei hoch und generiere daraus einen LinkedIn Post</p>
        </div>

        {% if limit_reached %}
        <div class="mb-6 card-bg border rounded-xl p-4 text-center text-sm text-gray-300">
            {{ limit_message or 'Token-Limit erreicht – keine KI-Aktionen mehr heute möglich. Morgen wird das Limit zurückgesetzt.' }}
        </div>
        {% endif %}

        <!-- Wizard Steps Indicator -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <div id="stepIndicator1" class="w-10 h-10 rounded-full bg-brand-highlight text-brand-bg-dark flex items-center justify-center font-bold">1</div>
                    <span class="ml-2 text-white font-medium hidden sm:inline">Datei</span>
                </div>
                <div class="flex-1 h-1 mx-4 bg-brand-bg-light rounded">
                    <div id="progressLine1" class="h-full bg-brand-highlight rounded transition-all duration-300" style="width: 0%"></div>
                </div>
                <div class="flex items-center">
                    <div id="stepIndicator2" class="w-10 h-10 rounded-full bg-brand-bg-light text-gray-400 flex items-center justify-center font-bold">2</div>
                    <span class="ml-2 text-gray-400 font-medium hidden sm:inline">Post-Typ</span>
                </div>
                <div class="flex-1 h-1 mx-4 bg-brand-bg-light rounded">
                    <div id="progressLine2" class="h-full bg-brand-highlight rounded transition-all duration-300" style="width: 0%"></div>
                </div>
                <div class="flex items-center">
                    <div id="stepIndicator3" class="w-10 h-10 rounded-full bg-brand-bg-light text-gray-400 flex items-center justify-center font-bold">3</div>
                    <span class="ml-2 text-gray-400 font-medium hidden sm:inline">Gedanken</span>
                </div>
                <div class="flex-1 h-1 mx-4 bg-brand-bg-light rounded">
                    <div id="progressLine3" class="h-full bg-brand-highlight rounded transition-all duration-300" style="width: 0%"></div>
                </div>
                <div class="flex items-center">
                    <div id="stepIndicator4" class="w-10 h-10 rounded-full bg-brand-bg-light text-gray-400 flex items-center justify-center font-bold">4</div>
                    <span class="ml-2 text-gray-400 font-medium hidden sm:inline">Hook</span>
                </div>
            </div>
        </div>

        <!-- Step 1: Datei -->
        <div id="step1" class="wizard-step card-bg rounded-xl border p-8">
            <h2 class="text-xl font-semibold text-white mb-2">Datei hochladen</h2>
            <p class="text-gray-400 mb-6">Lade eine Datei hoch (PDF, DOCX, PPTX, XLSX, TXT, MD, RTF). Max. 10 MB.</p>

            <div class="space-y-3">
                <input type="file" id="fileInput" class="w-full input-bg border rounded-lg px-4 py-3 text-white" accept=".pdf,.docx,.pptx,.xlsx,.txt,.md,.rtf">
                <button onclick="extractFile()" id="extractFileBtn" class="btn-primary px-6 py-3 rounded-lg font-medium">
                    Datei analysieren
                </button>
                <p id="fileError" class="text-sm text-red-400 hidden"></p>
            </div>

            <div id="fileProgress" class="mt-4 hidden">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm text-gray-400" id="fileProgressLabel">Upload läuft...</span>
                    <span class="text-sm text-gray-400" id="fileProgressPercent">0%</span>
                </div>
                <div class="w-full bg-brand-bg-dark rounded-full h-2">
                    <div id="fileProgressBar" class="bg-brand-highlight h-2 rounded-full transition-all duration-200" style="width: 0%"></div>
                </div>
            </div>

            <div id="linkPreview" class="mt-6 hidden">
                <div class="border-t border-brand-bg-light pt-6">
                    <p class="text-sm text-gray-400 mb-2">Vorschau</p>
                    <h3 id="linkTitle" class="text-lg font-semibold text-white mb-2"></h3>
                    <p id="linkSummary" class="text-gray-300 text-sm"></p>
                    <ul id="linkKeyPoints" class="mt-3 text-sm text-gray-400 space-y-1"></ul>
                </div>
            </div>

            <div class="flex justify-end mt-8">
                <button onclick="goToStep(2)" id="fileNextBtn" class="btn-primary px-8 py-3 rounded-lg font-medium disabled:opacity-50" disabled>
                    Weiter
                </button>
            </div>
        </div>

        <!-- Step 2: Post-Typ -->
        <div id="step2" class="wizard-step card-bg rounded-xl border p-8 hidden">
            <h2 class="text-xl font-semibold text-white mb-2">Post-Typ auswählen</h2>
            <p class="text-gray-400 mb-6">Wähle einen Post-Typ, um den Schreibstil anzupassen. <span class="text-gray-500">(optional)</span></p>

            <div id="postTypeCards" class="flex flex-wrap gap-3 mb-8">
                <p class="text-gray-500">Lade Post-Typen...</p>
            </div>
            <input type="hidden" id="selectedPostTypeId" value="">

            <div class="flex justify-between gap-3 mt-8">
                <button onclick="goToStep(1)" class="px-6 py-3 rounded-lg font-medium bg-brand-bg hover:bg-brand-bg-light text-white transition-colors">
                    Zurück
                </button>
                <button onclick="goToStep(3)" class="btn-primary px-8 py-3 rounded-lg font-medium">
                    Weiter
                </button>
            </div>
        </div>

        <!-- Step 3: Gedanken -->
        <div id="step3" class="wizard-step card-bg rounded-xl border p-8 hidden">
            <h2 class="text-xl font-semibold text-white mb-2">Deine Gedanken zum Thema</h2>
            <p class="text-gray-400 mb-6">Was möchtest du zu diesem Thema sagen? Deine persönliche Meinung, Erfahrungen oder Einsichten werden in den Post eingebaut.</p>

            <div class="relative">
                <textarea id="userThoughts" rows="8" placeholder="Schreibe oder sprich deine Gedanken ein...

z.B. 'Ich habe letzte Woche selbst erfahren, dass...'
oder 'Meine Meinung dazu ist...'"
                    class="w-full input-bg border rounded-lg px-4 py-4 text-white pr-16 text-lg"></textarea>

                <!-- Speech-to-Text Button -->
                <button id="speechBtn" type="button"
                    class="absolute right-4 top-4 p-3 rounded-lg bg-brand-bg hover:bg-brand-highlight hover:text-brand-bg-dark transition-colors group"
                    title="Spracheingabe starten">
                    <svg id="micIcon" class="w-6 h-6 text-gray-400 group-hover:text-brand-bg-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"/>
                    </svg>
                    <svg id="micIconRecording" class="w-6 h-6 text-red-500 hidden animate-pulse" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.91-3c-.49 0-.9.36-.98.85C16.52 14.2 14.47 16 12 16s-4.52-1.8-4.93-4.15c-.08-.49-.49-.85-.98-.85-.61 0-1.09.54-1 1.14.49 3 2.89 5.35 5.91 5.78V20c0 .55.45 1 1 1s1-.45 1-1v-2.08c3.02-.43 5.42-2.78 5.91-5.78.1-.6-.39-1.14-1-1.14z"/>
                    </svg>
                </button>
            </div>

            <div class="flex items-center justify-between mt-2">
                <p id="speechSupport" class="text-xs text-gray-500"></p>
                <p id="speechStatus" class="text-sm text-brand-highlight hidden"></p>
            </div>

            <div class="flex justify-between gap-3 mt-8">
                <button onclick="goToStep(2)" class="px-6 py-3 rounded-lg font-medium bg-brand-bg hover:bg-brand-bg-light text-white transition-colors">
                    Zurück
                </button>
                <button onclick="goToStep(4)" class="btn-primary px-8 py-3 rounded-lg font-medium">
                    Weiter
                </button>
            </div>
        </div>

        <!-- Step 4: Hook-Auswahl -->
        <div id="step4" class="wizard-step card-bg rounded-xl border p-8 hidden">
            <h2 class="text-xl font-semibold text-white mb-2">Hook auswählen</h2>
            <p class="text-gray-400 mb-6">Der Hook ist der erste Satz deines Posts. Wähle einen KI-generierten oder schreibe deinen eigenen.</p>

            <div id="hookLoading" class="text-center py-12">
                <svg class="w-10 h-10 animate-spin mx-auto text-brand-highlight" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <p class="text-gray-400 mt-4">Generiere Hooks...</p>
            </div>

            <div id="hookOptions" class="space-y-3 hidden">
                <!-- Hook options will be inserted here -->
            </div>

            <div id="hookError" class="text-red-400 text-center py-6 hidden"></div>

            <div class="border-t border-brand-bg-light pt-6 mt-6">
                <label class="block text-sm font-medium text-gray-300 mb-3">Oder eigenen Hook eingeben</label>
                <textarea id="customHook" rows="2" placeholder="Dein eigener Hook-Text..."
                    class="w-full input-bg border rounded-lg px-4 py-3 text-white"></textarea>
            </div>

            <div class="flex justify-between gap-3 mt-8">
                <button onclick="goToStep(3)" class="px-6 py-3 rounded-lg font-medium bg-brand-bg hover:bg-brand-bg-light text-white transition-colors">
                    Zurück
                </button>
                <button onclick="startPostCreation()" id="createPostBtn" class="btn-primary px-8 py-3 rounded-lg font-medium flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
                    Post erstellen
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Generation & Result Container (shown after clicking "Post erstellen") -->
<div id="generationContainer" class="hidden">
    <div class="max-w-4xl mx-auto">
        <div class="mb-8 text-center">
            <h1 class="text-3xl font-bold text-white mb-2">Post wird generiert</h1>
            <p class="text-gray-400" id="topicTitle"></p>
        </div>

        <!-- Progress Section -->
        <div id="generationProgress" class="card-bg rounded-xl border p-8 mb-8">
            <div class="max-w-xl mx-auto">
                <div class="flex items-center justify-between mb-3">
                    <span id="progressMessage" class="text-gray-300">Starte Post-Erstellung...</span>
                    <span id="progressPercent" class="text-gray-400 font-medium">0%</span>
                </div>
                <div class="w-full bg-brand-bg-dark rounded-full h-3">
                    <div id="progressBar" class="bg-brand-highlight h-3 rounded-full transition-all duration-300" style="width: 0%"></div>
                </div>
                <div id="iterationInfo" class="mt-3 text-sm text-gray-400 text-center"></div>
            </div>
        </div>

        <!-- Live Versions Display -->
        <div id="liveVersions" class="hidden mb-8">
            <div class="card-bg rounded-xl border p-8">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-lg font-semibold text-white">Live-Vorschau</h3>
                    <div id="versionTabs" class="flex gap-2">
                        <!-- Version tabs will be inserted here -->
                    </div>
                </div>
                <div id="versionsContainer"></div>
            </div>
        </div>

        <!-- Final Result -->
        <div id="finalResult" class="hidden">
            <div class="card-bg rounded-xl border p-8">
                <div id="resultHeader" class="flex items-center justify-between mb-6">
                    <!-- Result header will be inserted here -->
                </div>
                <div id="postResult" class="bg-brand-bg/50 rounded-lg p-6 mb-6">
                    <!-- Final post will be inserted here -->
                </div>
                <!-- Media Upload Area (Multi-Media Support) -->
                <div id="resultMediaArea" class="mb-6 hidden">
                    <h4 class="text-white font-semibold mb-3">Medien (<span id="resultMediaCount">0</span>/3)</h4>

                    <!-- Media Grid -->
                    <div id="resultMediaGrid" class="grid gap-3 mb-3 hidden"></div>

                    <!-- Upload Zone -->
                    <div id="resultMediaUploadZone" class="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="resultMediaInput" 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="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>
                        <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="resultMediaTypeWarning" class="text-xs text-yellow-400 mt-2 hidden">⚠️ Kann nicht Bilder und Videos mischen</p>
                    </div>

                    <!-- Upload Progress -->
                    <div id="resultMediaProgress" class="hidden mt-2">
                        <div style="height:4px;background:rgba(61,72,72,0.8);border-radius:2px;overflow:hidden;">
                            <div id="resultMediaProgressBar" style="height:100%;background:#ffc700;border-radius:2px;transition:width 0.3s;width:0%"></div>
                        </div>
                        <p class="text-xs text-gray-400 mt-1 text-center">Wird hochgeladen...</p>
                    </div>
                </div>
                <div id="resultActions" class="flex gap-3 flex-wrap justify-center">
                    <!-- Action buttons will be inserted here -->
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// ==================== STATE ====================
let currentStep = 1;
let selectedTopic = null;
let currentPostTypes = [];
let selectedHook = null;
let generatedHooks = [];
let isRecording = false;
let currentVersionIndex = 0;

// ==================== ELEMENTS ====================
const steps = [1, 2, 3, 4];
const wizardContainer = document.getElementById('wizardContainer');
const generationContainer = document.getElementById('generationContainer');
const selectedPostTypeIdInput = document.getElementById('selectedPostTypeId');
const postTypeCards = document.getElementById('postTypeCards');
const fileInput = document.getElementById('fileInput');
const extractFileBtn = document.getElementById('extractFileBtn');
const fileError = document.getElementById('fileError');
const linkPreview = document.getElementById('linkPreview');
const linkTitle = document.getElementById('linkTitle');
const linkSummary = document.getElementById('linkSummary');
const linkKeyPoints = document.getElementById('linkKeyPoints');
const fileNextBtn = document.getElementById('fileNextBtn');
const fileProgress = document.getElementById('fileProgress');
const fileProgressBar = document.getElementById('fileProgressBar');
const fileProgressPercent = document.getElementById('fileProgressPercent');
const fileProgressLabel = document.getElementById('fileProgressLabel');
const userThoughtsInput = document.getElementById('userThoughts');
const speechBtn = document.getElementById('speechBtn');
const micIcon = document.getElementById('micIcon');
const micIconRecording = document.getElementById('micIconRecording');
const speechStatus = document.getElementById('speechStatus');
const speechSupport = document.getElementById('speechSupport');
const hookLoading = document.getElementById('hookLoading');
const hookOptions = document.getElementById('hookOptions');
const hookError = document.getElementById('hookError');
const customHook = document.getElementById('customHook');
const generationProgress = document.getElementById('generationProgress');
const progressBar = document.getElementById('progressBar');
const progressMessage = document.getElementById('progressMessage');
const progressPercent = document.getElementById('progressPercent');
const iterationInfo = document.getElementById('iterationInfo');
const liveVersions = document.getElementById('liveVersions');
const versionTabs = document.getElementById('versionTabs');
const versionsContainer = document.getElementById('versionsContainer');
const finalResult = document.getElementById('finalResult');
const resultHeader = document.getElementById('resultHeader');
const postResult = document.getElementById('postResult');
const resultActions = document.getElementById('resultActions');
const topicTitleEl = document.getElementById('topicTitle');

// ==================== WIZARD NAVIGATION ====================
function goToStep(step) {
    // Hide all steps
    document.querySelectorAll('.wizard-step').forEach(el => el.classList.add('hidden'));

    // Show target step
    document.getElementById(`step${step}`).classList.remove('hidden');

    // Update step indicators
    steps.forEach(s => {
        const indicator = document.getElementById(`stepIndicator${s}`);
        const progressLine = document.getElementById(`progressLine${s}`);

        if (s < step) {
            indicator.className = 'w-10 h-10 rounded-full bg-brand-highlight text-brand-bg-dark flex items-center justify-center font-bold';
            if (progressLine) progressLine.style.width = '100%';
        } else if (s === step) {
            indicator.className = 'w-10 h-10 rounded-full bg-brand-highlight text-brand-bg-dark flex items-center justify-center font-bold';
            if (progressLine) progressLine.style.width = '0%';
        } else {
            indicator.className = 'w-10 h-10 rounded-full bg-brand-bg-light text-gray-400 flex items-center justify-center font-bold';
            if (progressLine) progressLine.style.width = '0%';
        }
    });

    currentStep = step;

    // Load hooks when entering step 4
    if (step === 4) {
        loadHooks();
    }
}

// ==================== LOAD DATA ====================
async function loadData() {
    // Load post types
    try {
        const ptResponse = await fetch('/api/post-types');
        const ptData = await ptResponse.json();

        if (ptData.post_types && ptData.post_types.length > 0) {
            currentPostTypes = ptData.post_types;
            postTypeCards.innerHTML = `
                <button type="button" onclick="selectPostType('')" id="ptc_all"
                    class="px-5 py-3 rounded-lg border text-sm transition-colors bg-brand-highlight/20 border-brand-highlight text-white font-medium">
                    Alle Typen
                </button>
            ` + ptData.post_types.map(pt => `
                <button type="button" onclick="selectPostType('${pt.id}')" id="ptc_${pt.id}"
                    class="px-5 py-3 rounded-lg border text-sm transition-colors bg-brand-bg border-brand-bg-light hover:border-brand-highlight/50 text-white">
                    ${pt.name}
                    ${pt.has_analysis ? '<span class="ml-1 text-green-400 text-xs">*</span>' : ''}
                </button>
            `).join('');
        } else {
            postTypeCards.innerHTML = '<p class="text-gray-500">Keine Post-Typen verfügbar. Du kannst diesen Schritt überspringen.</p>';
        }
    } catch (error) {
        console.error('Failed to load post types:', error);
        postTypeCards.innerHTML = '<p class="text-gray-500">Keine Post-Typen verfügbar. Du kannst diesen Schritt überspringen.</p>';
    }

}

function selectPostType(typeId) {
    selectedPostTypeIdInput.value = typeId;

    // Update card styles
    document.querySelectorAll('[id^="ptc_"]').forEach(card => {
        if (card.id === `ptc_${typeId}` || (typeId === '' && card.id === 'ptc_all')) {
            card.className = 'px-5 py-3 rounded-lg border text-sm transition-colors bg-brand-highlight/20 border-brand-highlight text-white font-medium';
        } else {
            card.className = 'px-5 py-3 rounded-lg border text-sm transition-colors bg-brand-bg border-brand-bg-light hover:border-brand-highlight/50 text-white';
        }
    });

    // Go to next step
    goToStep(3);
}

// ==================== LINK EXTRACTION ====================
async function extractFile() {
    fileError.classList.add('hidden');
    linkPreview.classList.add('hidden');
    fileNextBtn.disabled = true;
    fileProgress.classList.add('hidden');

    if (!fileInput.files || !fileInput.files[0]) {
        fileError.textContent = 'Bitte eine Datei auswählen.';
        fileError.classList.remove('hidden');
        return;
    }

    extractFileBtn.disabled = true;
    extractFileBtn.textContent = 'Analysiere...';

    try {
        const file = fileInput.files[0];
        const formData = new FormData();
        formData.append('file', file);

        fileProgress.classList.remove('hidden');
        fileProgressBar.style.width = '0%';
        fileProgressPercent.textContent = '0%';
        fileProgressLabel.textContent = 'Upload läuft...';

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/file-extract', true);
        xhr.upload.onprogress = (event) => {
            if (event.lengthComputable) {
                const percent = Math.round((event.loaded / event.total) * 100);
                fileProgressBar.style.width = `${percent}%`;
                fileProgressPercent.textContent = `${percent}%`;
            }
        };
        xhr.upload.onload = () => {
            fileProgressBar.style.width = '100%';
            fileProgressPercent.textContent = '100%';
            fileProgressLabel.textContent = 'Upload abgeschlossen – konvertiere und fasse zusammen...';
            fileProgressBar.classList.add('animate-pulse');
        };
        xhr.onload = () => {
            try {
                const data = JSON.parse(xhr.responseText || '{}');
                if (xhr.status < 200 || xhr.status >= 300) {
                    throw new Error(data.detail || 'Datei-Analyse fehlgeschlagen');
                }
                selectedTopic = data.topic;
                renderLinkPreview(data.topic);
                fileNextBtn.disabled = false;
                fileProgressLabel.textContent = 'Analyse abgeschlossen';
                fileProgressBar.classList.remove('animate-pulse');
            } catch (err) {
                fileError.textContent = `Fehler: ${err.message || err}`;
                fileError.classList.remove('hidden');
                fileProgressBar.classList.remove('animate-pulse');
            }
        };
        xhr.onerror = () => {
            fileError.textContent = 'Upload fehlgeschlagen.';
            fileError.classList.remove('hidden');
            fileProgressBar.classList.remove('animate-pulse');
        };
        xhr.send(formData);
    } catch (error) {
        fileError.textContent = `Fehler: ${error.message}`;
        fileError.classList.remove('hidden');
    } finally {
        extractFileBtn.disabled = false;
        extractFileBtn.textContent = 'Datei analysieren';
    }
}

function renderLinkPreview(topic) {
    linkTitle.textContent = topic.title || 'Link';
    linkSummary.textContent = topic.summary || topic.fact || '';
    linkKeyPoints.innerHTML = '';

    if (topic.key_points && topic.key_points.length > 0) {
        linkKeyPoints.innerHTML = topic.key_points.slice(0, 5).map(p => `
            <li>• ${escapeHtml(p)}</li>
        `).join('');
    }

    linkPreview.classList.remove('hidden');
}

fileInput.addEventListener('change', () => {
    fileNextBtn.disabled = true;
    linkPreview.classList.add('hidden');
    fileError.classList.add('hidden');
    fileProgress.classList.add('hidden');
});

// ==================== SPEECH TO TEXT (OpenAI Whisper) ====================
let mediaRecorder = null;
let audioChunks = [];

function getMicErrorMessage(error) {
    if (!error || !error.name) return 'Mikrofon-Zugriff fehlgeschlagen.';
    if (error.name === 'NotAllowedError') return 'Mikrofon-Zugriff verweigert. Bitte im Browser erlauben.';
    if (error.name === 'NotFoundError') return 'Kein Mikrofon gefunden.';
    if (error.name === 'NotReadableError') return 'Mikrofon wird bereits verwendet.';
    if (error.name === 'SecurityError') return 'Mikrofon funktioniert nur über HTTPS.';
    if (error.name === 'NotSupportedError') return 'Mikrofon wird in diesem Browser nicht unterstützt.';
    return `Mikrofon-Fehler: ${error.name}`;
}

async function updateMicPermissionStatus() {
    if (!navigator.permissions || !navigator.permissions.query) return;
    try {
        const status = await navigator.permissions.query({ name: 'microphone' });
        if (status.state === 'denied') {
            speechSupport.textContent = 'Mikrofon blockiert. Bitte im Browser freigeben.';
        } else if (status.state === 'granted') {
            speechSupport.textContent = 'Klicke zum Aufnehmen, nochmal klicken zum Stoppen.';
        }
        status.onchange = () => updateMicPermissionStatus();
    } catch (err) {
        // Ignore permission query errors and keep default text
    }
}

function initSpeechRecognition() {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        speechSupport.textContent = 'Mikrofon-Zugriff wird von diesem Browser nicht unterstützt.';
        speechBtn.classList.add('opacity-50', 'cursor-not-allowed');
        speechBtn.disabled = true;
        return;
    }
    if (!window.isSecureContext) {
        speechSupport.textContent = 'Mikrofon funktioniert nur über HTTPS.';
    }

    speechSupport.textContent = 'Klicke zum Aufnehmen, nochmal klicken zum Stoppen.';
    updateMicPermissionStatus();

    speechBtn.onclick = async () => {
        if (isRecording) {
            stopRecording();
        } else {
            startRecording();
        }
    };
}

async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        audioChunks = [];

        const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
            ? 'audio/webm;codecs=opus'
            : 'audio/webm';

        mediaRecorder = new MediaRecorder(stream, { mimeType });

        mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
                audioChunks.push(event.data);
            }
        };

        mediaRecorder.onstop = async () => {
            stream.getTracks().forEach(track => track.stop());

            const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });

            speechStatus.textContent = 'Transkribiere...';

            try {
                const text = await transcribeAudio(audioBlob);
                if (text && text.trim()) {
                    if (userThoughtsInput.value && !userThoughtsInput.value.endsWith(' ')) {
                        userThoughtsInput.value += ' ';
                    }
                    userThoughtsInput.value += text.trim();
                }
                speechStatus.classList.add('hidden');
            } catch (error) {
                speechStatus.textContent = `Fehler: ${error.message}`;
                setTimeout(() => speechStatus.classList.add('hidden'), 3000);
            }
        };

        mediaRecorder.start();
        isRecording = true;

        micIcon.classList.add('hidden');
        micIconRecording.classList.remove('hidden');
        speechStatus.innerHTML = '<span class="inline-block w-2 h-2 bg-red-500 rounded-full animate-pulse mr-2"></span>Aufnahme läuft...';
        speechStatus.classList.remove('hidden');
        speechBtn.classList.add('bg-red-500/20');

    } catch (error) {
        console.error('Failed to start recording:', error);
        speechStatus.textContent = getMicErrorMessage(error);
        speechStatus.classList.remove('hidden');
        setTimeout(() => speechStatus.classList.add('hidden'), 3000);
    }
}

function stopRecording() {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
    }

    isRecording = false;
    micIcon.classList.remove('hidden');
    micIconRecording.classList.add('hidden');
    speechBtn.classList.remove('bg-red-500/20');
}

async function transcribeAudio(audioBlob) {
    const formData = new FormData();
    formData.append('audio', audioBlob, 'recording.webm');

    const response = await fetch('/api/transcribe', {
        method: 'POST',
        body: formData
    });

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

    const data = await response.json();
    return data.text;
}

// ==================== HOOK GENERATION ====================
async function loadHooks() {
    hookLoading.classList.remove('hidden');
    hookOptions.classList.add('hidden');
    hookError.classList.add('hidden');
    generatedHooks = [];
    selectedHook = null;

    if (!selectedTopic) {
        hookLoading.classList.add('hidden');
        hookError.textContent = 'Kein Link-Topic gefunden. Bitte zuerst einen Link analysieren.';
        hookError.classList.remove('hidden');
        return;
    }

    const formData = new FormData();
    formData.append('topic_json', JSON.stringify(selectedTopic));
    formData.append('user_thoughts', userThoughtsInput.value.trim());
    if (selectedPostTypeIdInput.value) {
        formData.append('post_type_id', selectedPostTypeIdInput.value);
    }

    try {
        const response = await fetch('/api/hooks', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error('Hook-Generierung fehlgeschlagen');
        }

        const data = await response.json();
        generatedHooks = data.hooks || [];

        if (generatedHooks.length === 0) {
            throw new Error('Keine Hooks generiert');
        }

        renderHookOptions();
        hookLoading.classList.add('hidden');
        hookOptions.classList.remove('hidden');

    } catch (error) {
        console.error('Hook generation failed:', error);
        hookLoading.classList.add('hidden');
        hookError.textContent = `Fehler: ${error.message}. Du kannst trotzdem einen eigenen Hook eingeben.`;
        hookError.classList.remove('hidden');
    }
}

function renderHookOptions() {
    hookOptions.innerHTML = generatedHooks.map((hook, i) => `
        <label class="flex items-start gap-3 p-4 bg-brand-bg/50 rounded-lg cursor-pointer hover:bg-brand-bg transition-colors border-2 ${selectedHook === hook.hook ? 'border-brand-highlight bg-brand-highlight/10' : 'border-transparent hover:border-brand-highlight/30'}">
            <input type="radio" name="hook" value="${i}" class="mt-1 text-brand-highlight" ${selectedHook === hook.hook ? 'checked' : ''}>
            <div class="flex-1">
                <span class="inline-block px-2 py-0.5 text-xs font-medium bg-brand-bg-light text-gray-300 rounded mb-2">${escapeHtml(hook.style)}</span>
                <p class="text-white">${escapeHtml(hook.hook)}</p>
            </div>
        </label>
    `).join('');

    // Add event listeners
    document.querySelectorAll('input[name="hook"]').forEach(radio => {
        radio.addEventListener('change', () => {
            const index = parseInt(radio.value, 10);
            selectedHook = generatedHooks[index].hook;
            customHook.value = '';
            renderHookOptions();
        });
    });
}

// Clear selected hook when custom hook is entered
customHook.addEventListener('input', () => {
    if (customHook.value.trim()) {
        selectedHook = null;
        document.querySelectorAll('input[name="hook"]').forEach(radio => radio.checked = false);
    }
});

// ==================== POST CREATION ====================
async function startPostCreation() {
    if (!selectedTopic) {
        showError('Kein Link-Topic gefunden. Bitte zuerst einen Link analysieren.');
        return;
    }

    // Get final hook
    const finalHook = customHook.value.trim() || selectedHook || '';

    // Switch to generation view
    wizardContainer.classList.add('hidden');
    generationContainer.classList.remove('hidden');
    topicTitleEl.textContent = selectedTopic?.title || 'Datei-Topic';

    // Reset generation UI
    generationProgress.classList.remove('hidden');
    liveVersions.classList.add('hidden');
    finalResult.classList.add('hidden');
    currentVersionIndex = 0;

    const formData = new FormData();
    formData.append('topic_json', JSON.stringify(selectedTopic));
    formData.append('user_thoughts', userThoughtsInput.value.trim());
    formData.append('selected_hook', finalHook);
    if (selectedPostTypeIdInput.value) {
        formData.append('post_type_id', selectedPostTypeIdInput.value);
    }

    try {
        const response = await fetch('/api/posts', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();

        const taskId = data.task_id;
        window.lastProgressData = null;

        const pollInterval = setInterval(async () => {
            const statusResponse = await fetch(`/api/tasks/${taskId}`);
            const status = await statusResponse.json();

            progressBar.style.width = `${status.progress}%`;
            progressPercent.textContent = `${status.progress}%`;
            progressMessage.textContent = status.message;

            if (status.iteration !== undefined) {
                iterationInfo.textContent = `Iteration ${status.iteration} von ${status.max_iterations}`;
            }

            // Update live versions display
            if (status.versions && status.versions.length > 0) {
                window.lastProgressData = status;
                if (status.versions.length > currentVersionIndex + 1) {
                    currentVersionIndex = status.versions.length - 1;
                }
                renderVersions(status.versions, status.feedback_list || []);
            }

            if (status.status === 'completed') {
                clearInterval(pollInterval);
                showFinalResult(status.result);
            } else if (status.status === 'error') {
                clearInterval(pollInterval);
                showError(status.message);
            }
        }, 1000);
    } catch (error) {
        showError(error.message);
    }
}

function showFinalResult(result) {
    generationProgress.classList.add('hidden');
    liveVersions.classList.add('hidden');
    finalResult.classList.remove('hidden');

    resultHeader.innerHTML = `
        <div class="flex items-center gap-3 flex-wrap">
            <span class="px-3 py-1.5 rounded-lg text-sm font-medium bg-green-600/30 text-green-300">
                Post erstellt
            </span>
            <span class="text-gray-400">Iterationen: <span class="text-white">${result.iterations}</span></span>
        </div>
    `;

    postResult.innerHTML = `<pre class="whitespace-pre-wrap text-gray-200 font-sans text-lg leading-relaxed">${result.final_post}</pre>`;

    // Store post ID for media upload and show media area
    window.currentResultPostId = result.post_id;
    const mediaArea = document.getElementById('resultMediaArea');
    mediaArea.classList.remove('hidden');
    // Reset media UI
    resultMediaItems = [];
    refreshResultMediaGrid();
    initResultMediaUpload();

    resultActions.innerHTML = `
        <button onclick="copyPost()" class="px-6 py-3 bg-brand-bg hover:bg-brand-bg-light rounded-lg text-white transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
        <a href="/posts/${result.post_id}" class="px-6 py-3 bg-brand-highlight hover:bg-brand-highlight/90 rounded-lg text-brand-bg-dark font-medium transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
            Post öffnen
        </a>
        <button onclick="resetWizard()" class="px-6 py-3 bg-brand-bg hover:bg-brand-bg-light rounded-lg text-white transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
            Neuen Post erstellen
        </button>
    `;
}

function showError(message) {
    generationProgress.classList.add('hidden');
    finalResult.classList.remove('hidden');

    resultHeader.innerHTML = `<span class="text-red-400 font-medium">Fehler bei der Generierung</span>`;
    postResult.innerHTML = `<p class="text-red-400">${message}</p>`;
    resultActions.innerHTML = `
        <button onclick="resetWizard()" class="px-6 py-3 bg-brand-bg hover:bg-brand-bg-light rounded-lg text-white transition-colors">
            Zurück zum Wizard
        </button>
    `;
}

function resetWizard() {
    // Reset state
    currentStep = 1;
    selectedTopic = null;
    selectedHook = null;
    generatedHooks = [];
    currentVersionIndex = 0;

    // Clear inputs
    fileInput.value = '';
    linkPreview.classList.add('hidden');
    fileNextBtn.disabled = true;
    fileError.classList.add('hidden');
    fileProgress.classList.add('hidden');
    userThoughtsInput.value = '';
    customHook.value = '';
    document.querySelectorAll('input[name="hook"]').forEach(radio => radio.checked = false);

    // Switch back to wizard
    generationContainer.classList.add('hidden');
    wizardContainer.classList.remove('hidden');

    // Go to step 1
    goToStep(1);
}

// ==================== VERSION DISPLAY ====================
function renderVersions(versions, feedbackList) {
    if (!versions || versions.length === 0) {
        liveVersions.classList.add('hidden');
        return;
    }

    liveVersions.classList.remove('hidden');

    // Render version tabs
    versionTabs.innerHTML = versions.map((_, i) => `
        <button onclick="showVersion(${i})" id="versionTab${i}"
            class="px-4 py-2 rounded-lg text-sm font-medium transition-colors
            ${i === currentVersionIndex ? 'bg-brand-highlight text-brand-bg-dark' : 'bg-brand-bg text-gray-300 hover:bg-brand-bg-light'}">
            V${i + 1}
        </button>
    `).join('');

    const currentVersion = versions[currentVersionIndex];

    versionsContainer.innerHTML = `
        <div class="grid grid-cols-1 gap-6">
            <div class="bg-brand-bg/50 rounded-lg p-5">
                <div class="flex items-center justify-between mb-3">
                    <span class="text-sm font-medium text-gray-300">Version ${currentVersionIndex + 1}</span>
                    <span class="text-xs text-gray-500">Wird erstellt...</span>
                </div>
                <pre class="whitespace-pre-wrap text-gray-200 font-sans text-sm max-h-80 overflow-y-auto">${currentVersion}</pre>
            </div>
        </div>
    `;
}

function showVersion(index) {
    currentVersionIndex = index;
    const cachedData = window.lastProgressData;
    if (cachedData) {
        renderVersions(cachedData.versions, cachedData.feedback_list);
    }
}

function copyPost() {
    const postText = document.querySelector('#postResult pre').textContent;
    navigator.clipboard.writeText(postText).then(() => {
        const btn = document.querySelector('[onclick="copyPost()"]');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg> Kopiert!';
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    });
}

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

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 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);
    setTimeout(() => {
        toast.classList.add('opacity-0', 'translate-y-2');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// ==================== RESULT IMAGE UPLOAD ====================
// ==================== RESULT MEDIA UPLOAD (Multi-Media) ====================

let resultMediaInitialized = false;
let resultMediaItems = [];

async function handleResultMediaUpload(file) {
    if (!file || !window.currentResultPostId) return;

    const uploadZone = document.getElementById('resultMediaUploadZone');
    const progressEl = document.getElementById('resultMediaProgress');
    const progressBar = document.getElementById('resultMediaProgressBar');
    const warningEl = document.getElementById('resultMediaTypeWarning');

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

    const isVideo = file.type.startsWith('video/');
    const hasImages = resultMediaItems.some(item => item.type === 'image');
    const hasVideos = resultMediaItems.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 && resultMediaItems.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/${window.currentResultPostId}/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%';
        resultMediaItems = result.media_items || [];

        setTimeout(() => {
            progressEl.classList.add('hidden');
            refreshResultMediaGrid();
        }, 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 deleteResultMedia(index) {
    if (!window.currentResultPostId) return;
    if (!confirm('Media wirklich löschen?')) return;

    try {
        const response = await fetch(`/api/posts/${window.currentResultPostId}/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();
        resultMediaItems = result.media_items || [];

        refreshResultMediaGrid();
        showToast('Media entfernt', 'success');

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

// Drag-and-drop state for result media
let resultDraggedItemData = null;
let resultDraggedArrayIndex = null;
let resultOriginalDraggedIndex = null;

function refreshResultMediaGrid() {
    const grid = document.getElementById('resultMediaGrid');
    const count = document.getElementById('resultMediaCount');
    const uploadZone = document.getElementById('resultMediaUploadZone');

    count.textContent = resultMediaItems.length;

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

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

    grid.innerHTML = resultMediaItems.map((item, i) => {
        const isDragged = resultDraggedItemData && item.url === resultDraggedItemData.url;
        const ghostStyle = isDragged ? 'opacity: 0.3;' : '';

        return `
        <div class="media-item relative group rounded-lg overflow-hidden"
             data-array-index="${i}"
             draggable="true"
             style="transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); ${ghostStyle} cursor: move;">
            ${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>`
            }
            <button onclick="deleteResultMedia(${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 pointer-events-none" 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 (resultMediaItems.length >= 3) {
        uploadZone.classList.add('hidden');
    } else {
        uploadZone.classList.remove('hidden');
    }

    // Initialize drag-and-drop for result media
    initResultMediaDragAndDrop();
}

function initResultMediaDragAndDrop() {
    const grid = document.getElementById('resultMediaGrid');
    if (!grid) return;

    const items = grid.querySelectorAll('.media-item');

    items.forEach(item => {
        item.addEventListener('dragstart', (e) => {
            resultDraggedArrayIndex = parseInt(e.currentTarget.dataset.arrayIndex);
            resultOriginalDraggedIndex = resultDraggedArrayIndex; // Save original position
            resultDraggedItemData = resultMediaItems[resultDraggedArrayIndex];

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

            e.dataTransfer.effectAllowed = 'move';
            const rect = e.currentTarget.getBoundingClientRect();
            e.dataTransfer.setDragImage(e.currentTarget, rect.width / 2, rect.height / 2);
        });

        item.addEventListener('dragend', async (e) => {
            e.currentTarget.style.opacity = '1';

            // Save reorder in background only if position changed
            console.log('🎯 Result dragend:', {resultOriginalDraggedIndex, resultDraggedArrayIndex});

            if (resultOriginalDraggedIndex !== null && resultDraggedArrayIndex !== resultOriginalDraggedIndex) {
                console.log('💾 Triggering result save...');
                await saveResultReorderInBackground();
            } else {
                console.log('⏭️ Skip result save');
            }

            resultDraggedItemData = null;
            resultDraggedArrayIndex = null;
            resultOriginalDraggedIndex = null;
        });

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

            if (resultDraggedArrayIndex === null) return;

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

            if (targetArrayIndex === resultDraggedArrayIndex) return;

            // INSTANT visual reorder
            const newMediaItems = [...resultMediaItems];
            const [movedItem] = newMediaItems.splice(resultDraggedArrayIndex, 1);
            newMediaItems.splice(targetArrayIndex, 0, movedItem);

            resultMediaItems = newMediaItems;
            resultDraggedArrayIndex = targetArrayIndex;

            refreshResultMediaGrid();
        });

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

async function saveResultReorderInBackground() {
    if (!window.currentResultPostId) return;

    try {
        // Extract original order values from current arrangement
        const newOrder = resultMediaItems.map(item => item.order);

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

        if (response.ok) {
            const result = await response.json();
            resultMediaItems = result.media_items || [];
        }
    } catch (error) {
        console.error('Background reorder failed:', error);
    }
}

function initResultMediaUpload() {
    if (resultMediaInitialized) return;
    resultMediaInitialized = true;

    const uploadZone = document.getElementById('resultMediaUploadZone');
    const fileInput = document.getElementById('resultMediaInput');

    if (!uploadZone) return;

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

    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('border-brand-highlight', 'bg-brand-highlight/5');
    });
    uploadZone.addEventListener('dragleave', () => {
        uploadZone.classList.remove('border-brand-highlight', 'bg-brand-highlight/5');
    });
    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('border-brand-highlight', 'bg-brand-highlight/5');
        if (e.dataTransfer.files[0]) handleResultMediaUpload(e.dataTransfer.files[0]);
    });
}

// ==================== INIT ====================
document.addEventListener('DOMContentLoaded', () => {
    loadData();
    initSpeechRecognition();
});
</script>
{% endblock %}
