<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animals at War - Lobby</title>
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
</head>
<body>
    <div id="lobby" class="container">
        <h1>Animals at War</h1>
        <div class="form-group">
            <input type="text" id="nickname" placeholder="Enter your nickname" maxlength="20">
        </div>
        <div class="actions">
            <button id="btn-create" class="btn btn-primary">Create New Game</button>
        </div>
        <div id="room-info" class="hidden">
            <p>Share this link with your friend:</p>
            <input type="text" id="share-link" readonly>
            <button id="btn-copy" class="btn btn-secondary">Copy Link</button>
        </div>
        <div id="error-msg" class="error"></div>
    </div>

    <script>
        const socket = io();
        const nicknameInput = document.getElementById('nickname');
        const btnCreate = document.getElementById('btn-create');
        const roomInfo = document.getElementById('room-info');
        const shareLink = document.getElementById('share-link');
        const btnCopy = document.getElementById('btn-copy');
        const errorMsg = document.getElementById('error-msg');

        btnCreate.onclick = () => {
            const nickname = nicknameInput.value.trim();
            if (!nickname) {
                errorMsg.innerText = "Please enter a nickname";
                return;
            }
            socket.emit('create_game', { nickname: nickname });
        };

        socket.on('game_created', (data) => {
            const url = window.location.origin + '/game/' + data.room_id;
            shareLink.value = url;
            roomInfo.classList.remove('hidden');
            // Store token for reconnection
            localStorage.setItem('player_token', data.player_token);
            localStorage.setItem('current_room', data.room_id);
            window.location.href = url;
        });

        btnCopy.onclick = () => {
            shareLink.select();
            document.execCommand('copy');
            alert('Link copied to clipboard!');
        };

        socket.on('error', (data) => {
            errorMsg.innerText = data.message;
        });
    </script>
</body>
</html>
