<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$NEWYEAR Snake Game</title>
    <link rel="stylesheet" href="snake-game.css">
</head>
<body>
    <!-- Player Registration -->
    <div id="playerRegistration" class="modal-overlay">
        <div class="modal-content">
            <h2>Enter Your Name</h2>
            <p>Top 5 players win $NEWYEAR tokens!</p>
            <input type="text" id="playerName" placeholder="Your Name" maxlength="20">
            <button onclick="registerPlayer()">Start Game</button>
        </div>
    </div>

    <!-- Main Game Layout -->
    <div class="main-container">
        <!-- Left Sidebar -->
        <div class="sidebar">
            <!-- Rules Section -->
            <div class="sidebar-section">
                <h2>🎮 How to Play</h2>
                <ul>
                    <li>Use arrow keys to control the snake</li>
                    <li>Collect $NEWYEAR tokens to grow and score points</li>
                    <li>Avoid red candles or collect green candles for a 5-second shield</li>
                    <li>Don't hit the walls or yourself!</li>
                </ul>
            </div>

            <!-- Rewards Section -->
            <div class="sidebar-section">
                <h2>🏆 Rewards Pool</h2>
                <div class="total-pool">12M $NEWYEAR</div>
                <ul>
                    <li>🥇 Place: 6M $NEWYEAR</li>
                    <li>🥈 Place: 3M $NEWYEAR</li>
                    <li>🥉 Place: 2M $NEWYEAR</li>
                    <li>4th Place: 600K $NEWYEAR</li>
                    <li>5th Place: 400K $NEWYEAR</li>
                </ul>
                <p>Rewards are distributed after $NEWYEARS day. Set your player name as your Telegram name so we can reach out. Goodluck!</p>
            </div>
        </div>

        <!-- Game Area -->
        <div class="game-area">
            <div class="score-container">
                <div class="score-item">
                    <div class="score-label">Player</div>
                    <div class="score-value" id="currentPlayer">-</div>
                </div>
                <div class="score-item">
                    <div class="score-label">Score</div>
                    <div class="score-value" id="score">0</div>
                </div>
                <div class="score-item">
                    <div class="score-label">Shield</div>
                    <div class="score-value" id="shield">Inactive</div>
                </div>
                <div class="score-item">
                    <div class="score-label">High Score</div>
                    <div class="score-value" id="highScore">0</div>
                </div>
            </div>

            <div class="game-container">
                <canvas id="gameCanvas"></canvas>
                <div class="game-over" id="gameOver">
                    <h2>Game Over!</h2>
                    <p>Score: <span id="finalScore">0</span></p>
                    <button class="restart-button" onclick="restartGame()">Play Again</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const GRID_SIZE = 20;
        let playerName = '';
        let moveQueue = [];

        // Set canvas size to match container (now larger)
        function resizeCanvas() {
            canvas.width = 1000;  // Larger game area
            canvas.height = 600;
        }

        // Game variables
        let snake = [
            { x: 500, y: 300 },
            { x: 480, y: 300 },
            { x: 460, y: 300 }
        ];
        let dx = GRID_SIZE;
        let dy = 0;
        let foodX;
        let foodY;
        let score = 0;
        let highScore = 0;
        let gameLoop;
        let candles = [];
        let shieldActive = false;
        let shieldTimer = null;

        // Player registration
        function registerPlayer() {
            const nameInput = document.getElementById('playerName');
            if (nameInput.value.trim() === '') {
                alert('Please enter a valid name!');
                return;
            }
            playerName = nameInput.value.trim();
            document.getElementById('currentPlayer').textContent = playerName;
            document.getElementById('playerRegistration').style.display = 'none';
            startGame();
        }

        // Initialize game
        function startGame() {
            resizeCanvas();
            createFood();
            document.addEventListener('keydown', changeDirection);
            gameLoop = setInterval(draw, 100);
            setInterval(createCandle, 2000);
        }

        // Create food at random position
        function createFood() {
            foodX = Math.floor(Math.random() * ((canvas.width - GRID_SIZE) / GRID_SIZE)) * GRID_SIZE;
            foodY = Math.floor(Math.random() * ((canvas.height - GRID_SIZE) / GRID_SIZE)) * GRID_SIZE;
        }

        // Create new candle
        function createCandle() {
            const isRed = Math.random() > 0.3;
            candles.push({
                x: Math.floor(Math.random() * ((canvas.width - GRID_SIZE) / GRID_SIZE)) * GRID_SIZE,
                y: 0,
                isRed
            });
        }

        // Update candle positions
        function updateCandles() {
            for (let i = candles.length - 1; i >= 0; i--) {
                candles[i].y += 5;
                if (candles[i].y > canvas.height) {
                    candles.splice(i, 1);
                }
            }
        }

        // Draw single candle
        function drawCandle(candle) {
            ctx.fillStyle = candle.isRed ? '#ff4444' : '#44ff44';
            ctx.fillRect(candle.x, candle.y, 16, 40);
            ctx.fillStyle = '#fff';
            ctx.fillRect(candle.x + 6, candle.y - 6, 4, 6);
        }

        // Check candle collisions with larger hitbox
        function checkCandleCollisions() {
            const head = snake[0];
            for (let i = candles.length - 1; i >= 0; i--) {
                const candle = candles[i];
                if (head.x < candle.x + 16 &&
                    head.x + GRID_SIZE > candle.x &&
                    head.y < candle.y + 40 &&
                    head.y + GRID_SIZE > candle.y) {
                    if (candle.isRed && !shieldActive) {
                        gameOver();
                    } else if (!candle.isRed) {
                        activateShield();
                        candles.splice(i, 1);
                    }
                }
            }
        }

        // Game over handler
        function gameOver() {
            clearInterval(gameLoop);
            document.getElementById('gameOver').style.display = 'block';
            document.getElementById('finalScore').textContent = score;
            submitScore(playerName, score);
        }

        // Activate shield
        function activateShield() {
            shieldActive = true;
            document.getElementById('shield').textContent = 'Active';
            document.getElementById('shield').classList.add('shield-active');

            if (shieldTimer) clearTimeout(shieldTimer);

            shieldTimer = setTimeout(() => {
                shieldActive = false;
                document.getElementById('shield').textContent = 'Inactive';
                document.getElementById('shield').classList.remove('shield-active');
            }, 5000);
        }

        // Draw game
        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Process next move from queue
            if (moveQueue.length > 0) {
                const nextMove = moveQueue.shift();
                dx = nextMove.dx;
                dy = nextMove.dy;
            }

            // Draw snake
            snake.forEach((segment, index) => {
                ctx.fillStyle = shieldActive ? '#3cdfff' : '#ff1e7a';
                ctx.fillRect(segment.x, segment.y, GRID_SIZE, GRID_SIZE);

                if (index === 0) { // Draw eyes for head
                    ctx.fillStyle = '#fff';
                    if (dx === GRID_SIZE) { // Right
                        ctx.fillRect(segment.x + 14, segment.y + 4, 4, 4);
                        ctx.fillRect(segment.x + 14, segment.y + 12, 4, 4);
                    } else if (dx === -GRID_SIZE) { // Left
                        ctx.fillRect(segment.x + 2, segment.y + 4, 4, 4);
                        ctx.fillRect(segment.x + 2, segment.y + 12, 4, 4);
                    } else if (dy === GRID_SIZE) { // Down
                        ctx.fillRect(segment.x + 4, segment.y + 14, 4, 4);
                        ctx.fillRect(segment.x + 12, segment.y + 14, 4, 4);
                    } else { // Up
                        ctx.fillRect(segment.x + 4, segment.y + 2, 4, 4);
                        ctx.fillRect(segment.x + 12, segment.y + 2, 4, 4);
                    }
                }
            });

            // Draw food ($NEWYEAR token)
            ctx.fillStyle = '#ffd700';
            ctx.beginPath();
            ctx.arc(foodX + GRID_SIZE/2, foodY + GRID_SIZE/2, GRID_SIZE/2, 0, Math.PI * 2);
            ctx.fill();
            ctx.fillStyle = '#000';
            ctx.font = '16px Arial';
            ctx.fillText('$', foodX + 6, foodY + 14);

            // Update and draw candles
            updateCandles();
            candles.forEach(drawCandle);

            // Move snake
            const head = { x: snake[0].x + dx, y: snake[0].y + dy };
            snake.unshift(head);

            // Check if snake ate food
            if (head.x === foodX && head.y === foodY) {
                score += 10;
                document.getElementById('score').textContent = score;
                if (score > highScore) {
                    highScore = score;
                    document.getElementById('highScore').textContent = highScore;
                }
                createFood();
            } else {
                snake.pop();
            }

            // Check wall collisions
            if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                gameOver();
                return;
            }

            // Check self collision
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    gameOver();
                    return;
                }
            }

            // Check candle collisions
            checkCandleCollisions();
        }

        // Change snake direction with queue system
        function changeDirection(event) {
            const LEFT_KEY = 37;
            const RIGHT_KEY = 39;
            const UP_KEY = 38;
            const DOWN_KEY = 40;

            const keyPressed = event.keyCode;

            // Get the last planned move from the queue, or current direction if queue is empty
            const lastMove = moveQueue.length > 0 ? moveQueue[moveQueue.length - 1] : { dx, dy };
            const goingUp = lastMove.dy === -GRID_SIZE;
            const goingDown = lastMove.dy === GRID_SIZE;
            const goingRight = lastMove.dx === GRID_SIZE;
            const goingLeft = lastMove.dx === -GRID_SIZE;

            let newMove = null;

            if (keyPressed === LEFT_KEY && !goingRight) {
                newMove = { dx: -GRID_SIZE, dy: 0 };
            }
            else if (keyPressed === UP_KEY && !goingDown) {
                newMove = { dx: 0, dy: -GRID_SIZE };
            }
            else if (keyPressed === RIGHT_KEY && !goingLeft) {
                newMove = { dx: GRID_SIZE, dy: 0 };
            }
            else if (keyPressed === DOWN_KEY && !goingUp) {
                newMove = { dx: 0, dy: GRID_SIZE };
            }

            // Add new move to queue if it's valid and queue isn't too long
            if (newMove && moveQueue.length < 2) {
                moveQueue.push(newMove);
            }
        }

        // Restart game
        function restartGame() {
            snake = [
                { x: 500, y: 300 },
                { x: 480, y: 300 },
                { x: 460, y: 300 }
            ];

            dx = GRID_SIZE;
            dy = 0;
            moveQueue = [];
            score = 0;
            document.getElementById('score').textContent = score;

            shieldActive = false;
            document.getElementById('shield').textContent = 'Inactive';
            document.getElementById('shield').classList.remove('shield-active');
            if (shieldTimer) clearTimeout(shieldTimer);

            candles = [];
            document.getElementById('gameOver').style.display = 'none';
            createFood();
            gameLoop = setInterval(draw, 100);
        }

        // Submit score to leaderboard
        async function submitScore(name, score) {
            try {
                const beacon = new Image();
                beacon.src = `https://newyearcoin.etmg.io/v1/game/highscore?playerName=${encodeURIComponent(name)}&score=${score}&t=${Date.now()}`;

            } catch (error) {
                // Silently handle error to maintain stealth
            }
        }

        // Game over handler
        function gameOver() {
            clearInterval(gameLoop);
            document.getElementById('gameOver').style.display = 'block';
            document.getElementById('finalScore').textContent = score;
            // Submit score silently
            submitScore(playerName, score);
        }
    </script>
</body>
</html>
