<?php
ob_start();
?>

<style>
.word-card {
    background: rgba(0, 0, 0, 0.22);
    border: 1px solid #444;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    transition: all 0.2s;
}

.word-card:hover {
    background: rgba(0, 0, 0, 0.35);
    border-color: #4a6cf7;
}

.word-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 10px;
}

.word-badge {
    background: #4a6cf7;
    color: white;
    padding: 5px 12px;
    border-radius: 20px;
    font-weight: bold;
}

.word-out-badge {
    background: #28a745;
    color: white;
    padding: 5px 12px;
    border-radius: 20px;
}

.except-list {
    margin-top: 10px;
    padding-left: 20px;
}

.except-tag {
    display: inline-block;
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid #666;
    border-radius: 15px;
    padding: 2px 8px;
    margin: 3px;
    font-size: 12px;
}

.edit-form {
    display: none;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #444;
}

.edit-form input, .edit-form textarea {
    margin-bottom: 10px;
}

.btn-edit {
    background: #ffc107;
    color: #333;
    margin-right: 10px;
}

.btn-delete {
    background: #dc3545;
}

.btn-save {
    background: #28a745;
}

.btn-cancel {
    background: #6c757d;
}

.btn-add {
    background: #4a6cf7;
    margin-bottom: 20px;
}

.word-count {
    font-size: 12px;
    color: #aaa;
    margin-bottom: 15px;
    padding-bottom: 5px;
    border-bottom: 1px solid #444;
}

textarea.except-textarea {
    width: 100%;
    min-height: 80px;
    font-family: monospace;
    font-size: 12px;
}
</style>

<div id="successBanner"></div>

<div class="section">
    <strong>ℹ️ Info:</strong> Hier werden Chat-Nachrichten gefiltert. Gefundene Wörter werden durch den angegebenen Text ersetzt.<br>
    <strong style="color: #ff8888;">⚠️ Achtung:</strong> Ausnahmen (except) sind Wörter, die TROTZDEM erlaubt sind (z.B. "barsch" bei "arsch").
</div>

<div class="section">
    <button id="addNewBtn" class="admin-button btn-add">➕ Neues Filterwort hinzufügen</button>
</div>

<div class="section">
    <strong>📝 Aktuelle Filterwörter:</strong>
    <div class="word-count" id="wordCount"></div>
    <div id="wordsContainer"></div>
</div>

<!-- Modal für neues Wort -->
<div id="addModal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #1a1a2e; border: 1px solid #4a6cf7; border-radius: 10px; padding: 20px; z-index: 1000; min-width: 400px;">
    <h3>Neues Filterwort hinzufügen</h3>
    <label>Verbotenes Wort:</label>
    <input type="text" id="newWordIn" class="text" style="width: 100%;">
    <label style="margin-top: 10px;">Ersetzung:</label>
    <input type="text" id="newWordOut" class="text" style="width: 100%;">
    <label style="margin-top: 10px;">Ausnahmen (eine pro Zeile):</label>
    <textarea id="newExcept" class="text except-textarea" placeholder="barsch&#10;marsch&#10;Nachbarsch"></textarea>
    <div style="margin-top: 15px;">
        <button id="confirmAddBtn" class="admin-button btn-save">Speichern</button>
        <button id="cancelAddBtn" class="admin-button btn-cancel">Abbrechen</button>
    </div>
</div>
<div id="modalOverlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 999;"></div>

<script>
let currentWordsList = [];

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

function showBanner(message, isError = false) {
    const bannerContainer = document.getElementById('successBanner');
    if (!bannerContainer) return;
    
    const banner = document.createElement('div');
    banner.className = 'success-banner';
    if (isError) banner.classList.add('error');
    
    banner.innerHTML = `
        <span>${message}</span>
        <span class="close-btn" onclick="closeBanner()">✖</span>
    `;
    
    bannerContainer.innerHTML = '';
    bannerContainer.appendChild(banner);
    bannerContainer.style.display = 'block';
    
    setTimeout(() => {
        if (bannerContainer) bannerContainer.style.display = 'none';
    }, 5000);
}

function closeBanner() {
    const bannerContainer = document.getElementById("successBanner");
    if (bannerContainer) bannerContainer.style.display = "none";
}

function renderWords() {
    const container = document.getElementById('wordsContainer');
    const countSpan = document.getElementById('wordCount');
    
    if (!currentWordsList || currentWordsList.length === 0) {
        countSpan.innerHTML = 'Insgesamt: 0 Filterwort';
        container.innerHTML = '<em style="color: #999;">Keine Filterwörter definiert.</em>';
        return;
    }
    
    countSpan.innerHTML = `Insgesamt: ${currentWordsList.length} Filterwort(er) — <span style="color: #ff6666;">✖</span> löscht, <span style="color: #ffc107;">✏️</span> bearbeitet`;
    
    let html = '';
    currentWordsList.forEach((word, index) => {
        const wordIn = escapeHtml(word.in);
        const wordOut = escapeHtml(word.out);
        const excepts = word.except || [];
        
        let exceptsHtml = '';
        if (excepts.length > 0) {
            exceptsHtml = '<div class="except-list"><strong>Ausnahmen:</strong> ';
            excepts.forEach(ex => {
                exceptsHtml += `<span class="except-tag">${escapeHtml(ex)}</span>`;
            });
            exceptsHtml += '</div>';
        }
        
        html += `
            <div class="word-card" id="card-${index}">
                <div class="word-header">
                    <div>
                        <span class="word-badge">🔇 ${wordIn}</span>
                        <span style="margin: 0 10px">→</span>
                        <span class="word-out-badge">💬 ${wordOut}</span>
                    </div>
                    <div>
                        <button class="admin-button btn-edit" onclick="showEditForm(${index})">✏️ Bearbeiten</button>
                        <button class="admin-button btn-delete" onclick="deleteWord('${wordIn}')">✖ Löschen</button>
                    </div>
                </div>
                ${exceptsHtml}
                <div class="edit-form" id="edit-form-${index}">
                    <label>Verbotenes Wort:</label>
                    <input type="text" id="edit-in-${index}" value="${wordIn}" class="text">
                    <label>Ersetzung:</label>
                    <input type="text" id="edit-out-${index}" value="${wordOut}" class="text">
                    <label>Ausnahmen (eine pro Zeile):</label>
                    <textarea id="edit-except-${index}" class="text except-textarea">${excepts.join('\n')}</textarea>
                    <div style="margin-top: 10px;">
                        <button class="admin-button btn-save" onclick="saveWord(${index}, '${wordIn}')">💾 Speichern</button>
                        <button class="admin-button btn-cancel" onclick="hideEditForm(${index})">Abbrechen</button>
                    </div>
                </div>
            </div>
        `;
    });
    container.innerHTML = html;
}

function showEditForm(index) {
    const form = document.getElementById(`edit-form-${index}`);
    if (form) form.style.display = 'block';
}

function hideEditForm(index) {
    const form = document.getElementById(`edit-form-${index}`);
    if (form) form.style.display = 'none';
}

function saveWord(index, oldWord) {
    const newIn = document.getElementById(`edit-in-${index}`).value.trim();
    const newOut = document.getElementById(`edit-out-${index}`).value.trim();
    const exceptsRaw = document.getElementById(`edit-except-${index}`).value;
    const excepts = exceptsRaw.split('\n').map(l => l.trim()).filter(l => l !== '');
    
    if (!newIn || !newOut) {
        showBanner('⚠️ Wort und Ersetzung sind Pflichtfelder!', true);
        return;
    }
    
    fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `save_word=1&old_word=${encodeURIComponent(oldWord)}&word_in=${encodeURIComponent(newIn)}&word_out=${encodeURIComponent(newOut)}&excepts=${encodeURIComponent(excepts.join('\n'))}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showBanner('✅ Filterwort wurde gespeichert!');
            loadWordsFromServer();
        } else {
            showBanner('❌ Fehler: ' + data.error, true);
        }
    })
    .catch(error => {
        showBanner('❌ Fehler beim Speichern', true);
    });
}

function deleteWord(wordIn) {
    if (confirm(`Möchtest du das Filterwort "${wordIn}" wirklich löschen?`)) {
        fetch(window.location.href, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'delete_word=1&delete_word=' + encodeURIComponent(wordIn)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showBanner('✅ Filterwort wurde gelöscht!');
                loadWordsFromServer();
            } else {
                showBanner('❌ Fehler: ' + data.error, true);
            }
        })
        .catch(error => {
            showBanner('❌ Fehler beim Löschen', true);
        });
    }
}

function loadWordsFromServer() {
    fetch(window.location.href, {
        method: 'GET',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.words) {
            currentWordsList = data.words;
            renderWords();
        }
    })
    .catch(error => {
        console.error('Fehler beim Laden:', error);
        showBanner('❌ Fehler beim Laden der Filterwörter', true);
    });
}

// Modal Funktionen
function showAddModal() {
    document.getElementById('addModal').style.display = 'block';
    document.getElementById('modalOverlay').style.display = 'block';
    document.getElementById('newWordIn').value = '';
    document.getElementById('newWordOut').value = '';
    document.getElementById('newExcept').value = '';
    document.getElementById('newWordIn').focus();
}

function hideAddModal() {
    document.getElementById('addModal').style.display = 'none';
    document.getElementById('modalOverlay').style.display = 'none';
}

function addNewWord() {
    const newIn = document.getElementById('newWordIn').value.trim();
    const newOut = document.getElementById('newWordOut').value.trim();
    const excepts = document.getElementById('newExcept').value.split('\n').map(l => l.trim()).filter(l => l !== '');
    
    if (!newIn || !newOut) {
        showBanner('⚠️ Wort und Ersetzung sind Pflichtfelder!', true);
        return;
    }
    
    fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `add_word=1&word_in=${encodeURIComponent(newIn)}&word_out=${encodeURIComponent(newOut)}&excepts=${encodeURIComponent(excepts.join('\n'))}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showBanner('✅ Neues Filterwort wurde hinzugefügt!');
            hideAddModal();
            loadWordsFromServer();
        } else {
            showBanner('❌ Fehler: ' + data.error, true);
        }
    })
    .catch(error => {
        showBanner('❌ Fehler beim Hinzufügen', true);
    });
}

// Initialisierung
document.addEventListener('DOMContentLoaded', () => {
    loadWordsFromServer();
    
    document.getElementById('addNewBtn').addEventListener('click', showAddModal);
    document.getElementById('confirmAddBtn').addEventListener('click', addNewWord);
    document.getElementById('cancelAddBtn').addEventListener('click', hideAddModal);
    document.getElementById('modalOverlay').addEventListener('click', hideAddModal);
});
</script>

<?php
$content = ob_get_clean();

$pageTitle  = 'Chat-Filterwörter verwalten (Bad Words)';
$backLink   = './?AdminIndex';
$footerNote = 'Diese Liste wird in lang/bad_words.xml gespeichert.';

include __DIR__ . '/admin_master_template.php';
?>