// State management - all changes happen in memory until Save
let postTypesState = [];
let originalPostTypesJSON = '';
let hasUnsavedChanges = false;
let isEditMode = false;
let currentEditId = null;
let tempIdCounter = 0;

// Initialize state from server data
function initializeState() {
    const initialData = document.getElementById('initial-post-types');
    if (!initialData) return;

    try {
        const data = JSON.parse(initialData.textContent);
        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', // 'existing', 'new', 'modified', 'deleted'
            _originalWeight: item.post_type.strategy_weight
        }));
        originalPostTypesJSON = JSON.stringify(postTypesState);
        renderPostTypesList();
        updateSaveButton();
    } catch (e) {
        console.error('Failed to initialize state:', e);
    }
}

// Check if there are unsaved changes
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();
}

// Render the post types list from state
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 deinen ersten Post-Typ, um mit der Kategorisierung zu beginnen.</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="editPostTypeState('${pt.id}')"
                                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="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('');
}

// Update save button state
function updateSaveButton() {
    const saveBtn = document.getElementById('save-all-btn');
    if (!saveBtn) return;

    const activeTypes = postTypesState.filter(pt => pt._status !== 'deleted');
    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');
    }
}

// Create new post type (only in state)
function createPostTypeState(name, description, strategyWeight) {
    const tempId = `temp_${++tempIdCounter}`;
    postTypesState.push({
        id: tempId,
        name: name,
        description: description,
        strategy_weight: strategyWeight,
        post_count: 0,
        _status: 'new',
        _originalWeight: strategyWeight
    });

    renderPostTypesList();
    checkForChanges();
    showToast('Post-Typ hinzugefügt (noch nicht gespeichert)', 'info');
}

// Edit post type (only in state)
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');
}

// Update post type in state
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();
    showToast('Post-Typ aktualisiert (noch nicht gespeichert)', 'info');
}

// Delete post type (only in state)
function deletePostTypeState(id) {
    const activeTypes = postTypesState.filter(pt => pt._status !== 'deleted');

    // Prevent deleting last post type
    if (activeTypes.length === 1) {
        showToast('Du musst mindestens einen Post-Typ behalten!', 'error');
        return;
    }

    const postType = postTypesState.find(pt => pt.id === id);
    if (!postType) return;

    if (postType.post_count > 0) {
        if (!confirm(`Dieser Post-Typ hat ${postType.post_count} zugeordnete Posts. Wirklich löschen?`)) {
            return;
        }
    }

    if (postType._status === 'new') {
        // Remove completely if it was never saved
        postTypesState = postTypesState.filter(pt => pt.id !== id);
    } else {
        // Mark as deleted
        postType._status = 'deleted';
    }

    renderPostTypesList();
    checkForChanges();
    showToast('Post-Typ gelöscht (noch nicht gespeichert)', 'info');
}

// Update strategy weight in state
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();
}

// Save all changes to database
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('Du musst mindestens einen Post-Typ behalten!', '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/employee/post-types/${pt.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/employee/post-types', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    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/employee/post-types/${pt.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    name: pt.name,
                    description: pt.description,
                    strategy_weight: pt.strategy_weight
                })
            });
        }

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

        const saveAllResult = await saveAllResponse.json();

        if (saveAllResult.success) {
            if (saveAllResult.recategorized) {
                showToast('Änderungen gespeichert - Rekategorisierung läuft...', 'success');
            } else {
                showToast('Änderungen erfolgreich gespeichert', 'success');
            }

            // Reload page to get fresh data
            setTimeout(() => window.location.reload(), 1000);
        } else {
            throw new Error(saveAllResult.error || 'Save failed');
        }

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

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

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

    // Warn before leaving with unsaved changes
    window.addEventListener('beforeunload', (e) => {
        if (hasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
});
