// WebSocket network client for Kafaball

class Network {
    constructor() {
        this.ws = null;
        this.playerId = null;
        this.handlers = {};
        this.connected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
    }

    connect() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const url = `${protocol}//${window.location.host}`;

        this.ws = new WebSocket(url);

        this.ws.onopen = () => {
            this.connected = true;
            this.reconnectAttempts = 0;
            console.log('Connected to server');
            this.emit('connected');
        };

        this.ws.onmessage = (event) => {
            try {
                const msg = JSON.parse(event.data);
                this.emit(msg.type, msg.data);
            } catch (e) {
                console.error('Failed to parse message:', e);
            }
        };

        this.ws.onclose = () => {
            this.connected = false;
            console.log('Disconnected from server');
            this.emit('disconnected');

            // Attempt to reconnect
            if (this.reconnectAttempts < this.maxReconnectAttempts) {
                this.reconnectAttempts++;
                const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
                setTimeout(() => this.connect(), delay);
            }
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }

    send(type, data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({ type, data }));
        }
    }

    on(event, handler) {
        if (!this.handlers[event]) {
            this.handlers[event] = [];
        }
        this.handlers[event].push(handler);
    }

    off(event, handler) {
        if (this.handlers[event]) {
            this.handlers[event] = this.handlers[event].filter(h => h !== handler);
        }
    }

    emit(event, data) {
        if (this.handlers[event]) {
            for (const handler of this.handlers[event]) {
                handler(data);
            }
        }
    }

    setName(name) {
        this.send('set_name', { name });
    }

    createRoom(roomName, maxPlayers, password) {
        this.send('create_room', { roomName, maxPlayers, password });
    }

    joinRoom(roomId, password) {
        this.send('join_room', { roomId, password });
    }

    leaveRoom() {
        this.send('leave_room', {});
    }

    setTeam(team) {
        this.send('set_team', { team });
    }

    adminSetTeam(playerId, team) {
        this.send('admin_set_team', { playerId, team });
    }

    giveAdmin(playerId) {
        this.send('give_admin', { playerId });
    }

    kickPlayer(playerId) {
        this.send('kick_player', { playerId });
    }

    startGame() {
        this.send('start_game', {});
    }

    stopGame() {
        this.send('stop_game', {});
    }

    sendInput(input) {
        this.send('input', input);
    }

    sendChat(message) {
        this.send('chat', { message });
    }

    getRooms() {
        this.send('get_rooms', {});
    }
}

// Global instance
const network = new Network();
