document.addEventListener('DOMContentLoaded', function() {
    const statusElement = document.getElementById('status');
    const chatMessages = document.getElementById('chatMessages');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');

    let socket;
    let userId = 'user_' + Math.floor(Math.random() * 10000);

    function connect() {
        updateStatus('connecting', 'Verbindung wird hergestellt...');

        // WebSocket-Verbindung herstellen
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const host = window.location.host;
        socket = new WebSocket(`${protocol}//${host}/chat/websocket`);

        socket.onopen = function() {
            updateStatus('connected', 'Verbunden');
            enableChat();
        };

        socket.onmessage = function(event) {
            const message = JSON.parse(event.data);
            handleMessage(message);
        };

        socket.onclose = function() {
            updateStatus('disconnected', 'Verbindung getrennt');
            disableChat();

            // Nach 5 Sekunden erneut verbinden
            setTimeout(connect, 5000);
        };

        socket.onerror = function(error) {
            console.error('WebSocket Error:', error);
            addMessage('system', 'Fehler bei der Verbindung.');
        };
    }

    function updateStatus(state, text) {
        statusElement.className = 'connection-status status-' + state;
        statusElement.textContent = text;
    }

    function enableChat() {
        messageInput.disabled = false;
        sendButton.disabled = false;
        messageInput.focus();
    }

    function disableChat() {
        messageInput.disabled = true;
        sendButton.disabled = true;
    }

    function handleMessage(message) {
        switch(message.type) {
            case 'system':
                addMessage('system', message.message);
                break;

            case 'user_joined':
            case 'user_left':
                addMessage('system', message.message);
                break;

            case 'chat_message':
                const isOwnMessage = message.user_id === userId;
                addMessage(isOwnMessage ? 'self' : 'user', message.message);
                break;

            case 'error':
                addMessage('system', 'Fehler: ' + message.error);
                break;
        }
    }

    function addMessage(type, text) {
        const messageElement = document.createElement('div');
        messageElement.className = 'message ' + type;
        messageElement.textContent = text;

        chatMessages.appendChild(messageElement);

        // Automatisch nach unten scrollen
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function sendMessage() {
        const text = messageInput.value.trim();
        if (!text || !socket || socket.readyState !== WebSocket.OPEN) return;

        const message = {
            type: 'chat_message',
            message: text
        };

        socket.send(JSON.stringify(message));
        messageInput.value = '';
        messageInput.focus();
    }

    // Event-Listener
    sendButton.addEventListener('click', sendMessage);

    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // Initialisierung
    connect();
});
