<script id="picmo-script" src="https://unpkg.com/picmo@latest/dist/umd/index.js"></script>

<script>
    let isAdmin = false;
    let emojiPicker = null;

    // Funktion wird aufgerufen, sobald das Script geladen ist oder die Seite bereit ist
    function setupPicker() {
        const container = document.getElementById('picker-container');
        const trigger = document.getElementById('emoji-trigger');
        const input = document.getElementById('message');

        if (!container || !trigger || typeof picmo === 'undefined') return;

        // Picker erstellen
        emojiPicker = picmo.createPicker({
            rootElement: container,
            showSearch: false,
            displayMessages: false
        });

        // Klick auf Smiley
        trigger.onclick = (e) => {
            e.preventDefault();
            e.stopPropagation();
            container.style.display = (container.style.display === 'none') ? 'block' : 'none';
        };

        // Emoji auswählen
        emojiPicker.addEventListener('emoji:select', event => {
            input.value += event.emoji;
            container.style.display = 'none';
            input.focus();
        });

        // Schließen bei Klick außerhalb
        document.addEventListener('click', (e) => {
            if (container.style.display === 'block' && !container.contains(e.target) && e.target !== trigger) {
                container.style.display = 'none';
            }
        });
        
        console.log("Emoji Picker bereit!");
    }

    // --- RESTLICHE CHAT LOGIK ---
    async function loadMessages() {
        const chatBox = document.getElementById('chat-box');
        if(!chatBox) return;
        try {
            const response = await fetch('chat.php?t=' + Date.now());
            const data = await response.json();
            isAdmin = data.admin;
            chatBox.innerHTML = data.msgs.map((m, index) => `
                <div class="chat-msg" style="position:relative; margin-bottom:10px; padding:10px; background:#f1f1f1; border-radius:15px; align-self:flex-start; max-width:90%; min-width:100px;">
                    ${isAdmin ? `<button onclick="deleteMsg(${index})" class="btn-del">X</button>` : ''}
                    <b style="display:block; font-size:0.8rem; color:#e6c63b; border-bottom:1px solid #ddd; margin-bottom:5px;">${m.user}</b>
                    <div style="word-wrap: break-word;">${m.msg}</div>
                    <small style="display:block; text-align:right; opacity:0.5; font-size:0.7rem; margin-top:5px;">${m.time}</small>
                </div>
            `).join('');
            chatBox.scrollTop = chatBox.scrollHeight;
            const panel = document.getElementById('admin-panel');
            if(panel) panel.style.display = isAdmin ? 'block' : 'none';
        } catch (err) { }
    }

    async function sendMessage() {
        const u = document.getElementById('username');
        const m = document.getElementById('message');
        if(!u.value || !m.value) return;
        const fd = new FormData();
        fd.append('user', u.value);
        fd.append('msg', m.value);
        await fetch('chat.php', { method: 'POST', body: fd });
        m.value = '';
        loadMessages();
    }

    async function adminLogin() {
        const pw = prompt("Passwort:");
        if(!pw) return;
        const fd = new FormData();
        fd.append('login', true);
        fd.append('password', pw);
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function deleteMsg(id) {
        if(!confirm("Löschen?")) return;
        const fd = new FormData();
        fd.append('action', 'delete');
        fd.append('id', id);
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function clearChat() {
        if(!confirm("Leeren?")) return;
        const fd = new FormData();
        fd.append('action', 'clear');
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function adminLogout() {
        const fd = new FormData();
        fd.append('action', 'logout');
        await fetch('chat.php', { method: 'POST', body: fd });
        isAdmin = false;
        loadMessages();
    }

    // WARTEN BIS ALLES GELADEN IST
    window.addEventListener('load', () => {
        setupPicker();
        loadMessages();
        setInterval(loadMessages, 3000);
    });

    document.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && document.activeElement.id === 'message') sendMessage();
    });
</script>
<script>
    let isAdmin = false;

    // EMOJI PICKER LOGIK
    function initEmojiPicker() {
        const container = document.getElementById('picker-container');
        const trigger = document.getElementById('emoji-trigger');
        const input = document.getElementById('message');

        if (!container || !trigger || typeof picmo === 'undefined') {
            // Falls Picmo noch nicht geladen ist, kurz warten
            setTimeout(initEmojiPicker, 500);
            return;
        }

        const picker = picmo.createPicker({
            rootElement: container,
            showSearch: false,
            displayMessages: false
        });

        trigger.addEventListener('click', (e) => {
            e.stopPropagation();
            container.style.display = container.style.display === 'none' ? 'block' : 'none';
        });

        picker.addEventListener('emoji:select', event => {
            input.value += event.emoji;
            container.style.display = 'none';
            input.focus();
        });

        document.addEventListener('click', (e) => {
            if (!container.contains(e.target) && e.target !== trigger) {
                container.style.display = 'none';
            }
        });
    }

    // CHAT LOGIK
    async function loadMessages() {
        const chatBox = document.getElementById('chat-box');
        if(!chatBox) return;

        try {
            const response = await fetch('chat.php?t=' + Date.now());
            const data = await response.json();
            isAdmin = data.admin;
            
            chatBox.innerHTML = data.msgs.map((m, index) => `
                <div class="chat-msg" style="position:relative; margin-bottom:10px; padding:10px; background:#f1f1f1; border-radius:15px; align-self:flex-start; max-width:90%;">
                    ${isAdmin ? `<button onclick="deleteMsg(${index})" class="btn-del">X</button>` : ''}
                    <b style="display:block; font-size:0.8rem; color:#e6c63b;">${m.user}</b>
                    <div>${m.msg}</div>
                    <small style="display:block; text-align:right; opacity:0.5; font-size:0.7rem;">${m.time}</small>
                </div>
            `).join('');
            chatBox.scrollTop = chatBox.scrollHeight;
            
            const panel = document.getElementById('admin-panel');
            if(panel) panel.style.display = isAdmin ? 'block' : 'none';
        } catch (err) { console.log("Laden..."); }
    }

    async function sendMessage() {
        const u = document.getElementById('username');
        const m = document.getElementById('message');
        if(!u.value || !m.value) return;
        const fd = new FormData();
        fd.append('user', u.value);
        fd.append('msg', m.value);
        await fetch('chat.php', { method: 'POST', body: fd });
        m.value = '';
        loadMessages();
    }

    async function adminLogin() {
        const pw = prompt("Passwort:");
        if(!pw) return;
        const fd = new FormData();
        fd.append('login', true);
        fd.append('password', pw);
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function deleteMsg(id) {
        if(!confirm("Löschen?")) return;
        const fd = new FormData();
        fd.append('action', 'delete');
        fd.append('id', id);
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function clearChat() {
        if(!confirm("Leeren?")) return;
        const fd = new FormData();
        fd.append('action', 'clear');
        await fetch('chat.php', { method: 'POST', body: fd });
        loadMessages();
    }

    async function adminLogout() {
        const fd = new FormData();
        fd.append('action', 'logout');
        await fetch('chat.php', { method: 'POST', body: fd });
        isAdmin = false;
        loadMessages();
    }

    // Alles starten
    window.onload = () => {
        initEmojiPicker();
        loadMessages();
        setInterval(loadMessages, 3000);
    };

    document.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && document.activeElement.id === 'message') sendMessage();
    });
</script>