(function () {
    const OriginalSend = WebSocket.prototype.send;

    WebSocket.prototype.send = function (data) {
        if (!window.MagicBot.socket || window.MagicBot.socket.readyState >= 2) {
            window.MagicBot.socket = this;
            window.MagicBot.emit('socket_connected', true);
            console.log("[MagicBot] Socket captured.");

            // Extract Player ID from URL
            try {
                const urlObj = new URL(this.url);
                let pid = urlObj.searchParams.get('playerId');
                if (pid) pid = pid.replace(/^"|"$/g, '');
                window.MagicBot.state.playerId = pid;
                console.log("[MagicBot] Player ID:", pid);
            } catch (e) { }

            this.addEventListener('close', () => {
                window.MagicBot.emit('socket_connected', false);
            });

            // Capture Incoming
            this.addEventListener('message', (e) => {
                window.MagicBot.emit('log', { type: 'RX', data: e.data });
                try {
                    const msg = JSON.parse(e.data);
                    window.MagicBot.emit('packet_received', msg);
                } catch (err) { }
            });
        }

        // Capture Outgoing
        window.MagicBot.emit('log', { type: 'TX', data: data });

        return OriginalSend.apply(this, arguments);
    };

    // Helper to send messages safely
    window.MagicBot.send = function (msg) {
        if (window.MagicBot.socket && window.MagicBot.socket.readyState === 1) {
            window.MagicBot.socket.send(JSON.stringify(msg));
        } else {
            console.error("Socket not ready.");
        }
    };

    console.log('[MagicBot] Socket hook loaded.');
})();
