import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
    cors: {
        origin: "*", // Allow connections from any mobile device on local network
        methods: ["GET", "POST"]
    }
});

// Serve static files from 'dist' (production) or 'public' (dev partial)
// In a real setup, Vite handles dev serving, but this server handles the sockets.
app.use(express.static(join(__dirname, 'dist')));

// Game State Storage (In-Memory for now)
const LOBBIES = {
    // "lobbyCode": { hostSocket: id, players: [{id, name, charId}] }
};

io.on('connection', (socket) => {
    console.log('Client connected:', socket.id);

    // --- HOST EVENTS (PC) ---
    socket.on('HOST_GAME', () => {
        const lobbyCode = generateLobbyCode();
        LOBBIES[lobbyCode] = {
            hostSocket: socket.id,
            players: []
        };
        socket.join(lobbyCode);
        socket.emit('LOBBY_CREATED', { code: lobbyCode });
        console.log(`Lobby ${lobbyCode} created by ${socket.id}`);
    });

    // --- PLAYER EVENTS (MOBILE) ---
    socket.on('JOIN_GAME', ({ code, name }) => {
        const lobby = LOBBIES[code.toUpperCase()];
        if (lobby) {
            lobby.players.push({ id: socket.id, name, charId: null });
            socket.join(code.toUpperCase());

            // Notify Host
            io.to(lobby.hostSocket).emit('PLAYER_JOINED', { id: socket.id, name });
            // Confirm to Player
            socket.emit('JOIN_SUCCESS', { code: code.toUpperCase() });
            console.log(`Player ${name} joined lobby ${code}`);
        } else {
            socket.emit('ERROR', { message: "Lobby not found" });
        }
    });

    socket.on('PLAYER_ACTION', ({ code, action, data }) => {
        const lobby = LOBBIES[code];
        if (lobby) {
            // Forward directly to Host
            io.to(lobby.hostSocket).emit('PLAYER_ACTION', { playerId: socket.id, action, data });
        }
    });

    socket.on('disconnect', () => {
        console.log('Client disconnected:', socket.id);
        // Handle cleanup (remove player from lobby, notify host)
    });
});

function generateLobbyCode() {
    return Math.random().toString(36).substring(2, 6).toUpperCase();
}

const PORT = 3001;
httpServer.listen(PORT, () => {
    console.log(`Game Server running on http://localhost:${PORT}`);
});
