{% extends "company_base.html" %}
{% block title %}Post-Typen - {{ employee_name }} - {{ session.company_name }}{% endblock %}

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

    <!-- Header -->
    <div class="mb-6">
        <div class="flex items-center gap-3 mb-4">
            <a href="/company/manage/posts?employee_id={{ employee_id }}" onclick="return handleBackNavigation(event)" class="text-gray-400 hover:text-white transition-colors">
                <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="M10 19l-7-7m0 0l7-7m-7 7h18"/>
                </svg>
            </a>
            <div class="flex-1">
                <h1 class="text-2xl font-bold text-white">Post-Typen von {{ employee_name }}</h1>
                <p class="text-gray-400 mt-1">Definiere und konfiguriere die 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>
    </div>

    <!-- 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 den ersten Post-Typ für {{ employee_name }}.</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"></div>

    <!-- Initial data from server -->
    <div id="initial-post-types" style="display:none;" data-json="{{ post_types_json | escape }}"></div>
</div>

<script>
const INITIAL_POST_TYPES = {{ post_types_json | safe }};
const EMPLOYEE_ID = "{{ employee_id }}";

// ========== MODAL FUNCTIONS ==========

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;

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

function selectPredefinedType(typeName) {
    const descriptions = {
        'Tough 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] || '';
    document.getElementById('modal-step-1').classList.add('hidden');
    document.getElementById('edit-form').classList.remove('hidden');
}

function goToCustomType() {
    document.getElementById('edit-name').value = '';
    document.getElementById('edit-description').value = '';
    document.getElementById('modal-step-1').classList.add('hidden');
    document.getElementById('edit-form').classList.remove('hidden');
}

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

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

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

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

    const activePostTypes = postTypesState.filter(pt => pt._status !== 'deleted');
    const duplicateName = activePostTypes.find(pt => {
        if (isEditMode && id && pt.id === id) return false;
        return pt.name.toLowerCase() === name.toLowerCase();
    });
    if (duplicateName) {
        showToast(`Ein Post-Typ mit dem Namen "${duplicateName.name}" existiert bereits`, 'error');
        return;
    }

    if (isEditMode && id) {
        updatePostTypeState(id, name, description, strategyWeight);
    } else {
        createPostTypeState(name, description, strategyWeight);
    }
    closeEditModal();
}

// ========== TOAST ==========

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>

    <!-- 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()"
                disabled
                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 %}

<!-- Posts Modal -->
<div id="posts-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-4xl 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="posts-modal-title">Posts verwalten</h2>
            <button onclick="closePostsModal()" 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>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div>
                <h3 class="text-lg font-semibold text-white mb-3">Vorhandene Posts</h3>
                <div id="posts-modal-list" class="space-y-3"></div>
            </div>
            <div>
                <h3 class="text-lg font-semibold text-white mb-3">Post manuell hinzufügen</h3>
                <form onsubmit="addManualPostToType(event)" class="space-y-4">
                    <input type="hidden" id="manual-post-type-id" value="">
                    <textarea id="manual-post-text" rows="10"
                              class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                              placeholder="Füge hier einen bestehenden Beispielpost ein. Er wird direkt diesem Post-Typ zugeordnet."></textarea>
                    <p class="text-sm text-gray-400">Dieser Post wird gespeichert und bei einer manuell gestarteten Re-Analyse mit berücksichtigt.</p>
                    <div class="flex justify-end gap-3">
                        <button type="button" onclick="closePostsModal()" class="px-5 py-2.5 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-colors">Schließen</button>
                        <button type="submit" class="btn-primary px-5 py-2.5 rounded-lg font-medium">Post hinzufügen</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</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('Tough 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">Tough 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. Tough 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 speichern
                </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>

<!-- Confirmation Modal -->
<div id="confirmation-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-md mx-4 animate-scale-in">
        <div class="flex items-start gap-4 mb-6">
            <div id="confirmation-icon" class="w-12 h-12 rounded-full flex items-center justify-center flex-shrink-0"></div>
            <div class="flex-1">
                <h3 id="confirmation-title" class="text-xl font-bold text-white mb-2"></h3>
                <p id="confirmation-message" class="text-gray-300 text-sm"></p>
            </div>
        </div>
        <div class="flex gap-3">
            <button onclick="closeConfirmationModal()" class="flex-1 px-4 py-2.5 bg-brand-bg-light hover:bg-brand-bg text-white font-medium rounded-lg transition-colors border border-gray-600">Abbrechen</button>
            <button id="confirmation-confirm-btn" onclick="executeConfirmation()" class="flex-1 px-4 py-2.5 font-medium rounded-lg transition-colors">Bestätigen</button>
        </div>
    </div>
</div>

<style>
@keyframes scale-in {
    from { opacity: 0; transform: scale(0.9); }
    to { opacity: 1; transform: scale(1); }
}
.animate-scale-in { animation: scale-in 0.2s ease-out; }
.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::-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 postTypesState = [];
let originalPostTypesJSON = '';
let hasUnsavedChanges = false;
let isEditMode = false;
let currentEditId = null;
let tempIdCounter = 0;
let isIntentionalNavigation = false;
let confirmationCallback = null;

function initializeState() {
    if (typeof INITIAL_POST_TYPES === 'undefined') {
        showToast('Fehler: Daten konnten nicht geladen werden', 'error');
        return;
    }
    try {
        const data = INITIAL_POST_TYPES;
        if (!Array.isArray(data)) throw new Error('Data is not an array');
        postTypesState = data.map(item => ({
            id: item.post_type.id,
            name: item.post_type.name,
            description: item.post_type.description,
            strategy_weight: item.post_type.strategy_weight,
            post_count: item.post_count,
            _status: 'existing',
            _originalWeight: item.post_type.strategy_weight
        }));
        originalPostTypesJSON = JSON.stringify(postTypesState);
        renderPostTypesList();
        updateSaveButton();
    } catch (e) {
        showToast('Fehler beim Laden der Post-Typen: ' + e.message, 'error');
    }
}

function checkForChanges() {
    const currentJSON = JSON.stringify(postTypesState.map(pt => ({
        id: pt.id, name: pt.name, description: pt.description,
        strategy_weight: pt.strategy_weight, _status: pt._status
    })));
    hasUnsavedChanges = currentJSON !== originalPostTypesJSON;
    updateSaveButton();
}

function renderPostTypesList() {
    const container = document.getElementById('post-types-list');
    if (!container) return;
    const activePostTypes = postTypesState.filter(pt => pt._status !== 'deleted');
    if (activePostTypes.length === 0) {
        container.innerHTML = `
            <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 den ersten Post-Typ.</p>
            </div>`;
        return;
    }
    container.innerHTML = activePostTypes.map(pt => {
        const isNew = pt._status === 'new';
        const isModified = pt._status === 'modified';
        const statusBadge = isNew
            ? '<span class="text-xs bg-green-600/20 text-green-400 px-2 py-1 rounded ml-2">Neu</span>'
            : isModified
            ? '<span class="text-xs bg-yellow-600/20 text-yellow-400 px-2 py-1 rounded ml-2">Geändert</span>'
            : '';
        return `
            <div class="card-bg border rounded-xl p-6 ${isNew ? 'border-green-500/50' : isModified ? 'border-yellow-500/50' : ''}" 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">${escapeHtml(pt.name)}${statusBadge}</h3>
                        ${pt.description ? `<p class="text-gray-400 text-sm">${escapeHtml(pt.description)}</p>` : ''}
                    </div>
                    <div class="flex gap-2">
                        <button onclick="openPostsModal('${pt.id}')"
                                ${String(pt.id).startsWith('temp_') ? 'disabled' : ''}
                                class="px-3 py-2 text-sm text-brand-highlight hover:text-yellow-300 hover:bg-brand-highlight/10 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed">
                            Posts
                        </button>
                        <button onclick="editPostTypeState('${pt.id}')"
                                class="px-3 py-2 text-sm text-blue-400 hover:text-blue-300 hover:bg-blue-900/20 rounded-lg transition-colors">
                            Bearbeiten
                        </button>
                        <button onclick="deletePostTypeState('${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>
                <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}">${pt.strategy_weight.toFixed(1)}</span>
                    </label>
                    <input type="range" id="weight-${pt.id}" min="0" max="1" step="0.1" value="${pt.strategy_weight}"
                           oninput="updateStrategyWeightState('${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>
                <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>${pt.post_count || 0}</strong> Posts zugeordnet</span>
                </div>
            </div>`;
    }).join('');
}

function updateSaveButton() {
    const saveBtn = document.getElementById('save-all-btn');
    if (!saveBtn) return;
    const hasStructuralChanges = postTypesState.some(pt => pt._status === 'new' || pt._status === 'deleted');
    const hasWeightChanges = postTypesState.some(pt => pt._status === 'modified' || (pt._status === 'existing' && pt.strategy_weight !== pt._originalWeight));
    if (hasUnsavedChanges || hasStructuralChanges || hasWeightChanges) {
        saveBtn.disabled = false;
        saveBtn.classList.add('ring-4', 'ring-brand-highlight/50');
        const btnText = saveBtn.querySelector('span');
        if (btnText) btnText.textContent = hasStructuralChanges ? 'Speichern & Re-Kategorisieren' : 'Änderungen speichern';
    } else {
        saveBtn.disabled = true;
        saveBtn.classList.remove('ring-4', 'ring-brand-highlight/50');
    }
}

function createPostTypeState(name, description, strategyWeight) {
    const tempId = `temp_${++tempIdCounter}`;
    postTypesState.push({ id: tempId, name, description, strategy_weight: strategyWeight, post_count: 0, _status: 'new', _originalWeight: strategyWeight });
    renderPostTypesList();
    checkForChanges();
}

function editPostTypeState(id) {
    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;
    document.getElementById('modal-title').textContent = 'Post-Typ bearbeiten';
    document.getElementById('edit-id').value = id;
    document.getElementById('edit-name').value = postType.name;
    document.getElementById('edit-description').value = postType.description || '';
    document.getElementById('edit-weight').value = postType.strategy_weight;
    updateModalWeightDisplay(postType.strategy_weight);
    isEditMode = true;
    currentEditId = id;
    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');
}

function updatePostTypeState(id, name, description, strategyWeight) {
    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;
    postType.name = name;
    postType.description = description;
    postType.strategy_weight = strategyWeight;
    if (postType._status === 'existing') postType._status = 'modified';
    renderPostTypesList();
    checkForChanges();
}

function deletePostTypeState(id) {
    const activeTypes = postTypesState.filter(pt => pt._status !== 'deleted');
    if (activeTypes.length === 1) {
        showToast('Mindestens ein Post-Typ muss erhalten bleiben!', 'error');
        return;
    }
    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;
    if (postType.post_count > 0) {
        showConfirmation({
            type: 'danger',
            title: 'Post-Typ löschen?',
            message: `Dieser Post-Typ hat ${postType.post_count} zugeordnete Posts. Beim Speichern werden diese Posts neu kategorisiert.`,
            confirmText: 'Löschen',
            onConfirm: () => performDelete(id)
        });
    } else {
        performDelete(id);
    }
}

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

function performDelete(id) {
    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;
    if (postType._status === 'new') {
        postTypesState = postTypesState.filter(pt => pt.id !== id);
    } else {
        postType._status = 'deleted';
    }
    renderPostTypesList();
    checkForChanges();
}

function updateStrategyWeightState(id, value) {
    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;
    const numValue = parseFloat(value);
    postType.strategy_weight = numValue;
    document.getElementById(`weight-value-${id}`).textContent = numValue.toFixed(1);
    if (postType._status === 'existing' && numValue !== postType._originalWeight) postType._status = 'modified';
    checkForChanges();
}

let currentPostsModalPostTypeId = null;
let currentPostsModalPostTypeName = '';

async function openPostsModal(postTypeId) {
    if (String(postTypeId).startsWith('temp_')) {
        showToast('Bitte zuerst speichern, bevor du manuelle Posts verwaltest.', 'warning');
        return;
    }

    const postType = postTypesState.find(pt => pt.id === postTypeId);
    currentPostsModalPostTypeId = postTypeId;
    currentPostsModalPostTypeName = postType ? postType.name : 'Post-Typ';

    document.getElementById('posts-modal-title').textContent = `Posts in ${currentPostsModalPostTypeName}`;
    document.getElementById('manual-post-type-id').value = postTypeId;
    document.getElementById('manual-post-text').value = '';
    document.getElementById('posts-modal').classList.remove('hidden');
    document.getElementById('posts-modal').classList.add('flex');

    await loadPostsForModal(postTypeId);
}

function closePostsModal() {
    document.getElementById('posts-modal').classList.add('hidden');
    document.getElementById('posts-modal').classList.remove('flex');
    currentPostsModalPostTypeId = null;
    currentPostsModalPostTypeName = '';
}

async function loadPostsForModal(postTypeId) {
    const container = document.getElementById('posts-modal-list');
    container.innerHTML = '<p class="text-gray-400">Lade Posts...</p>';

    try {
        const response = await fetch(`/api/company/manage/post-types/${postTypeId}/posts?employee_id=${EMPLOYEE_ID}`);
        const result = await response.json();
        if (!result.success) throw new Error(result.error || 'Posts konnten nicht geladen werden');

        const posts = result.posts || [];
        if (!posts.length) {
            container.innerHTML = '<p class="text-gray-400">Noch keine Posts in diesem Post-Typ.</p>';
            return;
        }

        container.innerHTML = posts.map(post => `
            <div class="border border-brand-bg-light rounded-lg p-4 bg-brand-bg/30">
                <div class="flex items-start justify-between gap-4 mb-3">
                    <div class="text-xs text-gray-400">
                        ${post.post_date ? new Date(post.post_date).toLocaleString('de-DE') : 'Kein Datum'}
                        ${post.classification_method ? ` · ${escapeHtml(post.classification_method)}` : ''}
                    </div>
                    <button onclick="deletePostFromModal('${post.id}')"
                            class="px-3 py-1.5 text-xs text-red-400 hover:text-red-300 hover:bg-red-900/20 rounded-lg transition-colors">
                        Löschen
                    </button>
                </div>
                <div class="text-sm text-gray-200 whitespace-pre-wrap">${escapeHtml(post.post_text)}</div>
            </div>
        `).join('');
    } catch (error) {
        container.innerHTML = `<p class="text-red-400">Fehler: ${escapeHtml(error.message)}</p>`;
    }
}

async function addManualPostToType(event) {
    event.preventDefault();
    const postTypeId = document.getElementById('manual-post-type-id').value;
    const postText = document.getElementById('manual-post-text').value.trim();

    if (postText.length < 20) {
        showToast('Bitte einen aussagekräftigen Post mit mindestens 20 Zeichen eingeben.', 'error');
        return;
    }

    try {
        const response = await fetch('/api/company/manage/post-types/posts', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ employee_id: EMPLOYEE_ID, post_type_id: postTypeId, post_text: postText })
        });
        const result = await response.json();
        if (!result.success) throw new Error(result.error || 'Post konnte nicht hinzugefügt werden');

        const postType = postTypesState.find(pt => pt.id === postTypeId);
        if (postType) postType.post_count = (postType.post_count || 0) + 1;
        renderPostTypesList();
        document.getElementById('manual-post-text').value = '';
        await loadPostsForModal(postTypeId);
        showToast('Post hinzugefügt. Er wird bei der nächsten manuellen Re-Analyse mit berücksichtigt.', 'success');
    } catch (error) {
        showToast(`Fehler beim Hinzufügen: ${error.message}`, 'error');
    }
}

async function deletePostFromModal(postId) {
    if (!currentPostsModalPostTypeId) return;

    try {
        const response = await fetch(`/api/company/manage/post-types/${currentPostsModalPostTypeId}/posts/${postId}?employee_id=${EMPLOYEE_ID}`, {
            method: 'DELETE'
        });
        const result = await response.json();
        if (!result.success) throw new Error(result.error || 'Post konnte nicht gelöscht werden');

        const postType = postTypesState.find(pt => pt.id === currentPostsModalPostTypeId);
        if (postType && postType.post_count > 0) postType.post_count -= 1;
        renderPostTypesList();
        await loadPostsForModal(currentPostsModalPostTypeId);
        showToast('Post gelöscht.', 'success');
    } catch (error) {
        showToast(`Fehler beim Löschen: ${error.message}`, 'error');
    }
}

async function saveAllChanges() {
    const saveBtn = document.getElementById('save-all-btn');
    if (!saveBtn) return;
    const activeTypes = postTypesState.filter(pt => pt._status !== 'deleted');
    if (activeTypes.length === 0) {
        showToast('Mindestens ein Post-Typ muss erhalten bleiben!', 'error');
        return;
    }
    saveBtn.disabled = true;
    showToast('Speichere Änderungen...', 'info');
    try {
        const hasStructuralChanges = postTypesState.some(pt => pt._status === 'new' || pt._status === 'deleted');

        // 1. Delete removed post types
        const deletedTypes = postTypesState.filter(pt => pt._status === 'deleted' && !pt.id.startsWith('temp_'));
        for (const pt of deletedTypes) {
            await fetch(`/api/company/manage/post-types/${pt.id}?employee_id=${EMPLOYEE_ID}`, { method: 'DELETE' });
        }

        // 2. Create new post types
        const newTypes = postTypesState.filter(pt => pt._status === 'new');
        for (const pt of newTypes) {
            const response = await fetch('/api/company/manage/post-types', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ employee_id: EMPLOYEE_ID, name: pt.name, description: pt.description, strategy_weight: pt.strategy_weight })
            });
            const result = await response.json();
            if (!result.success) throw new Error(result.error || 'Failed to create post type');
        }

        // 3. Update modified post types
        const modifiedTypes = postTypesState.filter(pt => pt._status === 'modified' && !pt.id.startsWith('temp_'));
        for (const pt of modifiedTypes) {
            await fetch(`/api/company/manage/post-types/${pt.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ employee_id: EMPLOYEE_ID, name: pt.name, description: pt.description, strategy_weight: pt.strategy_weight })
            });
        }

        // 4. Trigger save-all / re-categorization
        const saveAllResponse = await fetch('/api/company/manage/post-types/save-all', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ employee_id: EMPLOYEE_ID, has_structural_changes: hasStructuralChanges })
        });
        const saveAllResult = await saveAllResponse.json();

        if (saveAllResult.success) {
            postTypesState = postTypesState.filter(pt => pt._status !== 'deleted');
            postTypesState.forEach(pt => { pt._status = 'existing'; pt._originalWeight = pt.strategy_weight; });
            originalPostTypesJSON = JSON.stringify(postTypesState);
            hasUnsavedChanges = false;
            renderPostTypesList();
            updateSaveButton();
            showToast(saveAllResult.recategorized ? 'Gespeichert – Rekategorisierung läuft im Hintergrund' : 'Änderungen gespeichert', 'success');
        } else {
            throw new Error(saveAllResult.error || 'Save failed');
        }
    } catch (error) {
        showToast('Fehler beim Speichern: ' + error.message, 'error');
        saveBtn.disabled = false;
    }
}

// ========== CONFIRMATION MODAL ==========
function showConfirmation(options) {
    const modal = document.getElementById('confirmation-modal');
    const icon = document.getElementById('confirmation-icon');
    const title = document.getElementById('confirmation-title');
    const message = document.getElementById('confirmation-message');
    const confirmBtn = document.getElementById('confirmation-confirm-btn');
    title.textContent = options.title || 'Bestätigung';
    message.textContent = options.message || 'Bist du sicher?';
    const iconType = options.type || 'warning';
    if (iconType === 'danger') {
        icon.className = 'w-12 h-12 rounded-full flex items-center justify-center flex-shrink-0 bg-red-500/20';
        icon.innerHTML = `<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>`;
        confirmBtn.className = 'flex-1 px-4 py-2.5 font-medium rounded-lg transition-colors bg-red-600 hover:bg-red-500 text-white';
    } else {
        icon.className = 'w-12 h-12 rounded-full flex items-center justify-center flex-shrink-0 bg-yellow-500/20';
        icon.innerHTML = `<svg class="w-6 h-6 text-yellow-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>`;
        confirmBtn.className = 'flex-1 px-4 py-2.5 font-medium rounded-lg transition-colors bg-brand-highlight hover:bg-yellow-500 text-black';
    }
    confirmBtn.textContent = options.confirmText || 'Bestätigen';
    confirmationCallback = options.onConfirm || null;
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closeConfirmationModal() {
    document.getElementById('confirmation-modal').classList.add('hidden');
    document.getElementById('confirmation-modal').classList.remove('flex');
    confirmationCallback = null;
}

function executeConfirmation() {
    if (confirmationCallback) confirmationCallback();
    closeConfirmationModal();
}

function handleBackNavigation(event) {
    if (hasUnsavedChanges) {
        event.preventDefault();
        showConfirmation({
            type: 'warning',
            title: 'Ungespeicherte Änderungen',
            message: 'Du hast ungespeicherte Änderungen. Wenn du jetzt zurückgehst, gehen diese verloren.',
            confirmText: 'Trotzdem zurück',
            onConfirm: () => {
                isIntentionalNavigation = true;
                window.location.href = `/company/manage/posts?employee_id=${EMPLOYEE_ID}`;
            }
        });
        return false;
    }
    return true;
}

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

document.addEventListener('DOMContentLoaded', () => {
    initializeState();
    window.addEventListener('beforeunload', (e) => {
        if (hasUnsavedChanges && !isIntentionalNavigation) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
});
</script>

{% endblock %}
