{% extends "base.html" %}

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

{% block content %}
<div class="max-w-4xl mx-auto">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-white">Post-Typen verwalten</h1>
            <p class="text-gray-400 mt-1">Definiere und konfiguriere deine Post-Kategorien</p>
        </div>
        <button onclick="openCreateModal()" class="btn-primary px-5 py-2.5 rounded-lg font-medium flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Neuer Post-Typ
        </button>
    </div>

    <!-- Strategy Info Banner -->
    {% if has_strategy %}
    <div class="bg-brand-highlight/10 border border-brand-highlight/30 rounded-xl p-4 mb-6">
        <div class="flex items-start gap-3">
            <svg class="w-5 h-5 text-brand-highlight flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <div>
                <p class="text-brand-highlight font-medium mb-1">Strategy Weight erklärt</p>
                <p class="text-gray-300 text-sm">
                    Der <strong>Strategy Weight</strong> steuert, wie stark die KI bei der Post-Generierung die Unternehmensstrategie berücksichtigt:
                    <span class="text-gray-400">0.0 = komplett ignorieren</span> |
                    <span class="text-gray-300">0.5 = ausgewogen</span> |
                    <span class="text-brand-highlight">1.0 = strikt befolgen</span>
                </p>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Empty State -->
    {% if not post_types_with_counts %}
    <div class="card-bg border rounded-xl p-12 text-center">
        <div class="w-20 h-20 bg-brand-highlight/20 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-10 h-10 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"/>
            </svg>
        </div>
        <h3 class="text-xl font-bold text-white mb-2">Noch keine Post-Typen definiert</h3>
        <p class="text-gray-400 mb-6">Erstelle deinen ersten Post-Typ, um mit der Kategorisierung zu beginnen.</p>
        <button onclick="openCreateModal()" class="btn-primary px-6 py-3 rounded-lg font-medium">
            Ersten Post-Typ erstellen
        </button>
    </div>
    {% endif %}

    <!-- Post Types List -->
    <div class="space-y-4" id="post-types-list">
        {% for item in post_types_with_counts %}
        {% set pt = item.post_type %}
        <div class="card-bg border rounded-xl p-6" data-post-type-id="{{ pt.id }}">
            <div class="flex items-start justify-between mb-4">
                <div class="flex-1">
                    <h3 class="text-lg font-bold text-white mb-1">{{ pt.name }}</h3>
                    {% if pt.description %}
                    <p class="text-gray-400 text-sm">{{ pt.description }}</p>
                    {% endif %}
                </div>
                <div class="flex gap-2">
                    <button onclick="editPostType('{{ pt.id }}', '{{ pt.name }}', '{{ pt.description or '' }}', {{ pt.strategy_weight }})"
                            class="px-3 py-2 text-sm text-gray-300 hover:text-white hover:bg-brand-bg-light rounded-lg transition-colors">
                        Bearbeiten
                    </button>
                    <button onclick="deletePostType('{{ pt.id }}')"
                            class="px-3 py-2 text-sm text-red-400 hover:text-red-300 hover:bg-red-900/20 rounded-lg transition-colors">
                        Löschen
                    </button>
                </div>
            </div>

            <!-- Strategy Weight Slider -->
            <div class="mb-4 bg-brand-bg/30 rounded-lg p-4 border border-brand-bg-light">
                <label class="text-sm font-medium text-gray-300 mb-3 block flex items-center justify-between">
                    <span>Strategy Weight</span>
                    <span class="text-brand-highlight font-bold text-lg" id="weight-value-{{ pt.id }}">{{ "%.1f"|format(pt.strategy_weight) }}</span>
                </label>
                <input type="range"
                       id="weight-{{ pt.id }}"
                       min="0"
                       max="1"
                       step="0.1"
                       value="{{ pt.strategy_weight }}"
                       onchange="updateStrategyWeight('{{ pt.id }}', this.value)"
                       class="w-full h-3 bg-brand-bg-dark rounded-lg appearance-none cursor-pointer slider">
                <div class="flex justify-between text-xs text-gray-400 mt-2">
                    <span>Ignorieren (0.0)</span>
                    <span>Ausgewogen (0.5)</span>
                    <span>Strikt (1.0)</span>
                </div>
            </div>

            <!-- Post Count -->
            <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="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>
                <span><strong>{{ item.post_count }}</strong> Posts zugeordnet</span>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Save All Button (Fixed) -->
    {% if post_types_with_counts %}
    <div class="fixed bottom-8 right-8 z-50">
        <button id="save-all-btn"
                onclick="saveAllChanges()"
                class="bg-brand-highlight hover:bg-brand-highlight-dark text-brand-bg-dark font-bold px-6 py-4 rounded-xl shadow-2xl flex items-center gap-3 transition-all disabled:opacity-50 disabled:cursor-not-allowed">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
            <span>Änderungen speichern</span>
        </button>
    </div>
    {% endif %}
</div>

<!-- Create/Edit Modal (Wizard-Style) -->
<div id="edit-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden items-center justify-center z-50">
    <div class="bg-brand-bg-dark border border-gray-600 rounded-xl p-8 w-full max-w-3xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold text-white" id="modal-title">Neuer Post-Typ</h2>
            <button onclick="closeEditModal()" class="text-gray-400 hover:text-white">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <!-- Step 1: Choose Predefined or Custom -->
        <div id="modal-step-1" class="modal-step">
            <p class="text-gray-400 mb-6">Wähle einen vorgefertigten Post-Typ oder erstelle einen eigenen</p>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <button type="button" onclick="selectPredefinedType('Thought Leadership')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Thought Leadership</h3>
                    <p class="text-sm text-gray-400">Meinungsbeiträge und Einblicke zu Branchenthemen, eigene Perspektiven und Expertenwissen</p>
                </button>
                <button type="button" onclick="selectPredefinedType('Company Updates')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Company Updates</h3>
                    <p class="text-sm text-gray-400">Neuigkeiten über das Unternehmen, Meilensteine, Produktankündigungen und Teamerfolge</p>
                </button>
                <button type="button" onclick="selectPredefinedType('Educational Content')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Educational Content</h3>
                    <p class="text-sm text-gray-400">Tutorials, How-Tos, Tipps & Tricks, Wissen teilen und Mehrwert bieten</p>
                </button>
                <button type="button" onclick="selectPredefinedType('Personal Story')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Personal Story</h3>
                    <p class="text-sm text-gray-400">Persönliche Erfahrungen, Learnings, Karrieremomente und authentische Geschichten</p>
                </button>
                <button type="button" onclick="selectPredefinedType('Industry News')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Industry News</h3>
                    <p class="text-sm text-gray-400">Aktuelle Branchennews, Trends, Marktentwicklungen und relevante Ereignisse</p>
                </button>
                <button type="button" onclick="selectPredefinedType('Engagement Post')" class="predefined-type-card p-6 bg-brand-bg/50 hover:bg-brand-bg border-2 border-transparent hover:border-brand-highlight rounded-xl text-left transition-all">
                    <h3 class="text-lg font-bold text-white mb-2">Engagement Post</h3>
                    <p class="text-sm text-gray-400">Umfragen, Fragen an die Community, Diskussionsanregungen und interaktive Inhalte</p>
                </button>
            </div>

            <div class="border-t border-brand-bg-light pt-6">
                <button type="button" onclick="goToCustomType()" class="w-full p-6 bg-brand-highlight/10 hover:bg-brand-highlight/20 border-2 border-brand-highlight/30 hover:border-brand-highlight rounded-xl text-center transition-all">
                    <svg class="w-8 h-8 mx-auto mb-2 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    <p class="text-white font-medium">Eigenen Post-Typ erstellen</p>
                </button>
            </div>

            <div class="flex justify-end gap-3 mt-6">
                <button type="button"
                        onclick="closeEditModal()"
                        class="px-6 py-2.5 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-colors">
                    Abbrechen
                </button>
            </div>
        </div>

        <!-- Step 2: Configure Type -->
        <form id="edit-form" onsubmit="submitPostType(event)" class="modal-step hidden">
            <input type="hidden" id="edit-id" value="">

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-300 mb-2">Name *</label>
                <input type="text"
                       id="edit-name"
                       required
                       minlength="3"
                       class="w-full input-bg border rounded-lg px-4 py-3 text-white text-lg"
                       placeholder="z.B. Thought Leadership">
            </div>

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-300 mb-2">Beschreibung</label>
                <textarea id="edit-description"
                          rows="4"
                          class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                          placeholder="Beschreibe, worum es bei diesem Post-Typ geht..."></textarea>
            </div>

            <div class="mb-6 bg-brand-bg/30 rounded-lg p-5 border border-brand-bg-light">
                <label class="block text-sm font-medium text-gray-300 mb-3 flex items-center justify-between">
                    <span>Strategy Weight</span>
                    <span class="text-brand-highlight font-bold text-xl" id="modal-weight-value">0.5</span>
                </label>
                <input type="range"
                       id="edit-weight"
                       min="0"
                       max="1"
                       step="0.1"
                       value="0.5"
                       oninput="updateModalWeightDisplay(this.value)"
                       class="w-full h-3 bg-brand-bg-dark rounded-lg appearance-none cursor-pointer slider">
                <div class="flex justify-between text-xs text-gray-400 mt-2">
                    <span>Ignorieren (0.0)</span>
                    <span>Ausgewogen (0.5)</span>
                    <span>Strikt (1.0)</span>
                </div>
            </div>

            <div class="flex gap-3">
                <button type="button"
                        onclick="backToStep1()"
                        class="px-6 py-3 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-colors">
                    Zurück
                </button>
                <button type="submit"
                        class="flex-1 px-6 py-3 bg-brand-highlight hover:bg-brand-highlight-dark text-brand-bg-dark font-bold rounded-lg transition-colors">
                    Post-Typ erstellen
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="delete-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden items-center justify-center z-50">
    <div class="bg-brand-bg-dark border border-red-500/50 rounded-xl p-6 w-full max-w-md mx-4">
        <div class="flex items-start gap-4 mb-6">
            <div class="w-12 h-12 bg-red-500/20 rounded-lg flex items-center justify-center flex-shrink-0">
                <svg class="w-6 h-6 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                </svg>
            </div>
            <div>
                <h2 class="text-xl font-bold text-white mb-2">Post-Typ löschen?</h2>
                <p class="text-gray-300" id="delete-message">Möchtest du diesen Post-Typ wirklich löschen?</p>
            </div>
        </div>

        <input type="hidden" id="delete-id" value="">

        <div class="flex gap-3">
            <button onclick="closeDeleteModal()"
                    class="flex-1 px-4 py-2.5 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-colors">
                Abbrechen
            </button>
            <button onclick="confirmDelete()"
                    class="flex-1 px-4 py-2.5 bg-red-600 hover:bg-red-500 text-white font-medium rounded-lg transition-colors">
                Trotzdem löschen
            </button>
        </div>
    </div>
</div>

<style>
/* Custom slider styles */
.slider {
    -webkit-appearance: none;
    appearance: none;
}

.slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: linear-gradient(135deg, #facc15 0%, #fbbf24 100%);
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(250, 204, 21, 0.4);
    border: 3px solid #1a1f1f;
    transition: all 0.2s ease;
}

.slider::-webkit-slider-thumb:hover {
    box-shadow: 0 4px 12px rgba(250, 204, 21, 0.6);
    transform: scale(1.1);
}

.slider::-moz-range-thumb {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: linear-gradient(135deg, #facc15 0%, #fbbf24 100%);
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(250, 204, 21, 0.4);
    border: 3px solid #1a1f1f;
    transition: all 0.2s ease;
}

.slider::-moz-range-thumb:hover {
    box-shadow: 0 4px 12px rgba(250, 204, 21, 0.6);
    transform: scale(1.1);
}

.slider::-webkit-slider-track {
    background: linear-gradient(to right, #4b5563 0%, #facc15 50%, #10b981 100%);
    border-radius: 8px;
}

.slider::-moz-range-track {
    background: linear-gradient(to right, #4b5563 0%, #facc15 50%, #10b981 100%);
    border-radius: 8px;
}
</style>

<script>
// State Management
let originalPostTypes = []; // Original state from backend
let currentPostTypes = []; // Current working state
let tempIdCounter = 0; // For temporary IDs of new post types
let hasUnsavedChanges = false;
let hasStructuralChanges = false;
let isEditMode = false;
let currentEditId = null;

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    loadInitialState();
    setupBeforeUnloadWarning();
});

// Load initial state from DOM
function loadInitialState() {
    const postTypeCards = document.querySelectorAll('[data-post-type-id]');
    originalPostTypes = [];

    postTypeCards.forEach(card => {
        const id = card.dataset.postTypeId;
        const name = card.querySelector('h3').textContent.trim();
        const description = card.querySelector('p.text-gray-400')?.textContent.trim() || '';
        const weightValue = card.querySelector('[id^="weight-value-"]').textContent.trim();
        const weight = parseFloat(weightValue);
        const postCount = parseInt(card.querySelector('strong').textContent);

        originalPostTypes.push({
            id: id,
            name: name,
            description: description,
            strategy_weight: weight,
            post_count: postCount,
            is_new: false,
            is_deleted: false,
            is_modified: false
        });
    });

    // Clone for working state
    currentPostTypes = JSON.parse(JSON.stringify(originalPostTypes));
    updateSaveButtonState();
}

// Setup warning when leaving page with unsaved changes
function setupBeforeUnloadWarning() {
    window.addEventListener('beforeunload', (e) => {
        if (hasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
}

// Open create modal
function openCreateModal() {
    document.getElementById('modal-title').textContent = 'Neuer Post-Typ';
    document.getElementById('edit-id').value = '';
    document.getElementById('edit-name').value = '';
    document.getElementById('edit-description').value = '';
    document.getElementById('edit-weight').value = '0.5';
    updateModalWeightDisplay(0.5);
    isEditMode = false;
    currentEditId = null;

    // Show step 1, hide step 2
    document.getElementById('modal-step-1').classList.remove('hidden');
    document.getElementById('edit-form').classList.add('hidden');

    document.getElementById('edit-modal').classList.remove('hidden');
    document.getElementById('edit-modal').classList.add('flex');
}

// Select predefined type
function selectPredefinedType(typeName) {
    const descriptions = {
        'Thought Leadership': 'Meinungsbeiträge und Einblicke zu Branchenthemen, eigene Perspektiven und Expertenwissen',
        'Company Updates': 'Neuigkeiten über das Unternehmen, Meilensteine, Produktankündigungen und Teamerfolge',
        'Educational Content': 'Tutorials, How-Tos, Tipps & Tricks, Wissen teilen und Mehrwert bieten',
        'Personal Story': 'Persönliche Erfahrungen, Learnings, Karrieremomente und authentische Geschichten',
        'Industry News': 'Aktuelle Branchennews, Trends, Marktentwicklungen und relevante Ereignisse',
        'Engagement Post': 'Umfragen, Fragen an die Community, Diskussionsanregungen und interaktive Inhalte'
    };

    document.getElementById('edit-name').value = typeName;
    document.getElementById('edit-description').value = descriptions[typeName] || '';

    // Go to step 2
    document.getElementById('modal-step-1').classList.add('hidden');
    document.getElementById('edit-form').classList.remove('hidden');
}

// Go to custom type
function goToCustomType() {
    document.getElementById('edit-name').value = '';
    document.getElementById('edit-description').value = '';

    // Go to step 2
    document.getElementById('modal-step-1').classList.add('hidden');
    document.getElementById('edit-form').classList.remove('hidden');
}

// Back to step 1
function backToStep1() {
    document.getElementById('modal-step-1').classList.remove('hidden');
    document.getElementById('edit-form').classList.add('hidden');
}

// Edit post type
function editPostType(id, name, description, weight) {
    document.getElementById('modal-title').textContent = 'Post-Typ bearbeiten';
    document.getElementById('edit-id').value = id;
    document.getElementById('edit-name').value = name;
    document.getElementById('edit-description').value = description;
    document.getElementById('edit-weight').value = weight;
    updateModalWeightDisplay(weight);
    isEditMode = true;
    currentEditId = id;

    // Skip step 1 when editing, go straight to form
    document.getElementById('modal-step-1').classList.add('hidden');
    document.getElementById('edit-form').classList.remove('hidden');

    document.getElementById('edit-modal').classList.remove('hidden');
    document.getElementById('edit-modal').classList.add('flex');
}

// Close edit modal
function closeEditModal() {
    document.getElementById('edit-modal').classList.add('hidden');
    document.getElementById('edit-modal').classList.remove('flex');
}

// Update modal weight display
function updateModalWeightDisplay(value) {
    document.getElementById('modal-weight-value').textContent = parseFloat(value).toFixed(1);
}

// Submit post type (create or update)
async function submitPostType(event) {
    event.preventDefault();

    const id = document.getElementById('edit-id').value;
    const name = document.getElementById('edit-name').value.trim();
    const description = document.getElementById('edit-description').value.trim();
    const strategyWeight = parseFloat(document.getElementById('edit-weight').value);

    if (name.length < 3) {
        showToast('Name muss mindestens 3 Zeichen lang sein', 'error');
        return;
    }

    try {
        const data = {
            name: name,
            description: description || null,
            strategy_weight: strategyWeight
        };

        let response;
        if (isEditMode && id) {
            // Update existing
            response = await fetch(`/api/employee/post-types/${id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
        } else {
            // Create new
            response = await fetch('/api/employee/post-types', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
        }

        const result = await response.json();

        if (result.success) {
            // Mark that structural changes happened (only for create, not edit)
            if (!isEditMode) {
                hasStructuralChanges = true;
                localStorage.setItem('postTypesStructuralChanges', 'true');
            }
            showToast(isEditMode ? 'Post-Typ aktualisiert' : 'Post-Typ erstellt', 'success');
            closeEditModal();
            setTimeout(() => window.location.reload(), 500);
        } else {
            showToast(result.error || 'Ein Fehler ist aufgetreten', 'error');
        }
    } catch (error) {
        console.error('Error submitting post type:', error);
        showToast('Verbindungsfehler beim Speichern', 'error');
    }
}

// Update strategy weight
function updateStrategyWeight(id, value) {
    const numValue = parseFloat(value);
    document.getElementById(`weight-value-${id}`).textContent = numValue.toFixed(1);
    changedWeights.set(id, numValue);

    // Update button text and highlight
    updateSaveButtonText();
}

// Delete post type
async function deletePostType(id) {
    try {
        // First check how many posts are affected
        const response = await fetch(`/api/employee/post-types/${id}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            // Mark that structural changes happened
            hasStructuralChanges = true;
            localStorage.setItem('postTypesStructuralChanges', 'true');

            if (result.affected_posts > 0) {
                // Show confirmation modal
                document.getElementById('delete-id').value = id;
                document.getElementById('delete-message').textContent =
                    `Dieser Post-Typ hat ${result.affected_posts} zugeordnete Posts. Wirklich löschen?`;
                document.getElementById('delete-modal').classList.remove('hidden');
                document.getElementById('delete-modal').classList.add('flex');
            } else {
                // Direct delete
                showToast('Post-Typ gelöscht', 'success');
                setTimeout(() => window.location.reload(), 1000);
            }
        } else {
            showToast(result.error || 'Fehler beim Löschen', 'error');
        }
    } catch (error) {
        console.error('Error deleting post type:', error);
        showToast('Verbindungsfehler', 'error');
    }
}

// Confirm delete from modal
async function confirmDelete() {
    const id = document.getElementById('delete-id').value;
    closeDeleteModal();

    // Delete was already done, just reload
    showToast('Post-Typ gelöscht', 'success');
    setTimeout(() => window.location.reload(), 1000);
}

// Close delete modal
function closeDeleteModal() {
    document.getElementById('delete-modal').classList.add('hidden');
    document.getElementById('delete-modal').classList.remove('flex');
}

// Update save button text based on what changed
function updateSaveButtonText() {
    const saveBtn = document.getElementById('save-all-btn');
    if (!saveBtn) return;

    const btnText = saveBtn.querySelector('span');
    if (!btnText) return;

    if (hasStructuralChanges) {
        btnText.textContent = 'Speichern & Re-Kategorisieren';
        saveBtn.classList.add('ring-4', 'ring-brand-highlight/50');
    } else if (changedWeights.size > 0) {
        btnText.textContent = 'Änderungen speichern';
        saveBtn.classList.add('ring-4', 'ring-brand-highlight/50');
    } else {
        btnText.textContent = 'Änderungen speichern';
        saveBtn.classList.remove('ring-4', 'ring-brand-highlight/50');
    }
}

// Save all changes (smart save - only re-categorize if structural changes)
async function saveAllChanges() {
    const saveBtn = document.getElementById('save-all-btn');
    if (!saveBtn) return;

    // Check if there are any changes to save
    if (changedWeights.size === 0 && !hasStructuralChanges) {
        showToast('Keine Änderungen zu speichern', 'info');
        return;
    }

    saveBtn.disabled = true;

    try {
        // Save all weight changes first
        if (changedWeights.size > 0) {
            const updatePromises = Array.from(changedWeights.entries()).map(([id, weight]) => {
                return fetch(`/api/employee/post-types/${id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ strategy_weight: weight })
                });
            });

            await Promise.all(updatePromises);
        }

        // Trigger save-all with structural changes flag
        const response = await fetch('/api/employee/post-types/save-all', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                has_structural_changes: hasStructuralChanges
            })
        });

        const result = await response.json();

        if (result.success) {
            changedWeights.clear();
            hasStructuralChanges = false;
            localStorage.removeItem('postTypesStructuralChanges');
            saveBtn.classList.remove('ring-4', 'ring-brand-highlight/50');

            if (result.recategorized) {
                showToast('Änderungen gespeichert - Rekategorisierung läuft...', 'success');
                console.log('Re-categorization started:', result.categorization_job_id);
                console.log('Analysis started:', result.analysis_job_id);
            } else {
                showToast('Änderungen gespeichert', 'success');
                console.log('Only weights updated, no re-categorization');
            }

            // Reload to show updated values
            setTimeout(() => window.location.reload(), 1000);
        } else {
            showToast(result.error || 'Unbekannter Fehler', 'error');
            saveBtn.disabled = false;
        }
    } catch (error) {
        console.error('Error saving changes:', error);
        showToast('Verbindungsfehler: ' + error.message, 'error');
        saveBtn.disabled = false;
    }
}

// Toast notification system
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    const colors = {
        success: 'bg-green-600 border-green-500',
        error: 'bg-red-600 border-red-500',
        info: 'bg-blue-600 border-blue-500',
        warning: 'bg-yellow-600 border-yellow-500'
    };

    const icons = {
        success: '<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>',
        error: '<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="M6 18L18 6M6 6l12 12"/></svg>',
        info: '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>',
        warning: '<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 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>'
    };

    toast.className = `fixed bottom-8 right-8 ${colors[type]} text-white px-6 py-4 rounded-xl shadow-2xl border-2 z-50 flex items-center gap-3 transform transition-all duration-300 translate-y-0 opacity-100`;
    toast.innerHTML = `
        ${icons[type]}
        <span class="font-medium">${message}</span>
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('translate-y-2', 'opacity-0');
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}
</script>

{% endblock %}
