{% load static %}

<script>
    // Gemeinsame Funktionen für alle Spielseiten
    // Toast-Benachrichtigungen und WebSocket-Funktionen werden im globalen Scope definiert
    window.toast = {
        create(message, type = 'info') {
            const toastElement = document.createElement('div');
            toastElement.className = `toast toast-${type}`;
            toastElement.textContent = message;
            document.body.appendChild(toastElement);

            // Animation
            setTimeout(() => {
                toastElement.classList.add('show');
                setTimeout(() => {
                    toastElement.classList.remove('show');
                    setTimeout(() => toastElement.remove(), 300);
                }, 3000);
            }, 100);
        }
    };

    // WebSocket-Hilfsfunktionen
    window.wsUtil = {
        handleClose(e) {
            if (e.code !== 1000 && e.code !== 1001) {
                console.error('WebSocket closed unexpectedly', e.code);
            }
        }
    };

    // WebSocket-Initialisierung
    window.initializeGameSocket = function(gameCode) {
        const wsScheme = window.location.protocol === 'https:' ? 'wss' : 'ws';
        const gameSocket = new WebSocket(
            `${wsScheme}://${window.location.host}/ws/game/${gameCode}/`
        );

        gameSocket.onmessage = (e) => {
            const data = JSON.parse(e.data);
            if (data.type === 'player_left') {
                const message = data.was_kicked 
                    ? `${data.player_name} wurde wegen Inaktivität entfernt`
                    : `${data.player_name} hat das Spiel verlassen`;
                toast.create(message, data.was_kicked ? 'error' : 'warning');
            }
        };

        gameSocket.onclose = (e) => wsUtil.handleClose(e);

        return gameSocket;
    }
</script>

<style>
    .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        border-radius: 4px;
        color: white;
        opacity: 0;
        transition: opacity 0.3s ease-in-out;
        z-index: 9999;
        max-width: 300px;
    }

    .toast.show {
        opacity: 1;
    }

    .toast-info {
        background-color: #3498db;
    }

    .toast-success {
        background-color: #2ecc71;
    }

    .toast-warning {
        background-color: #f1c40f;
    }

    .toast-error {
        background-color: #e74c3c;
    }
</style>
