/**
 * NEON SNAKE - Game Logic
 */

// ========================
// CONFIGURATION
// ========================


const GRID_SIZE = 20;
let tileCountX = 20;
let tileCountY = 20;

// Level Definitions
// Speed: Lower is faster (ms per frame)
// Target: Score needed to complete level
// Obstacles: 'none', 'box', 'cross', 'random'
const LEVEL_CONFIG = {
    // Phase 1: The Basics (Speed Up) - Cyan/Red Theme
    1: { speed: 150, target: 100, obstacles: 'none', bombRate: 0, wrapWalls: false, foodType: 'orb', bombType: 'mine' },
    2: { speed: 140, target: 150, obstacles: 'none', bombRate: 0.005, wrapWalls: false, foodType: 'orb', bombType: 'mine' },
    3: { speed: 130, target: 200, obstacles: 'none', bombRate: 0.01, wrapWalls: false, foodType: 'orb', bombType: 'mine' },
    
    // Phase 2: The Maze (Static Obstacles) - Gold/Purple Theme
    4: { speed: 120, target: 250, obstacles: 'box', bombRate: 0.015, wrapWalls: false, foodType: 'diamond', bombType: 'square' },
    5: { speed: 110, target: 300, obstacles: 'cross', bombRate: 0.02, wrapWalls: false, foodType: 'diamond', bombType: 'square' },
    6: { speed: 100, target: 350, obstacles: 'random', bombRate: 0.025, wrapWalls: false, foodType: 'diamond', bombType: 'square' },
    
    // Phase 3: Minefield (Heavy Bombs) - Pink/Orange Theme
    7: { speed: 95, target: 400, obstacles: 'random', bombRate: 0.05, wrapWalls: false, foodType: 'hexagon', bombType: 'pulse' },
    8: { speed: 90, target: 450, obstacles: 'random', bombRate: 0.08, wrapWalls: false, foodType: 'hexagon', bombType: 'pulse' },
    9: { speed: 85, target: 500, obstacles: 'random', bombRate: 0.1, wrapWalls: false, foodType: 'hexagon', bombType: 'pulse' },
    
    // Phase 4: Portal Jump (Wrap Walls) - Green/Yellow Theme
    10: { speed: 100, target: 600, obstacles: 'none', bombRate: 0.02, wrapWalls: true, foodType: 'star', bombType: 'cross' },
    11: { speed: 90, target: 650, obstacles: 'box', bombRate: 0.03, wrapWalls: true, foodType: 'star', bombType: 'cross' },
    12: { speed: 80, target: 700, obstacles: 'random', bombRate: 0.04, wrapWalls: true, foodType: 'star', bombType: 'cross' },
    
    // Phase 5: Moving Threat (Moving Obstacles) - Mixed Theme
    13: { speed: 90, target: 750, obstacles: 'moving-h', bombRate: 0.03, wrapWalls: false, foodType: 'orb', bombType: 'square' },
    14: { speed: 85, target: 800, obstacles: 'moving-v', bombRate: 0.04, wrapWalls: false, foodType: 'diamond', bombType: 'pulse' },
    15: { speed: 80, target: 850, obstacles: 'moving-random', bombRate: 0.05, wrapWalls: false, foodType: 'hexagon', bombType: 'cross' },
    
    // Phase 6: Speed Demon (High Speed) - High Contrast
    16: { speed: 60, target: 900, obstacles: 'none', bombRate: 0.05, wrapWalls: true, foodType: 'star', bombType: 'mine' },
    17: { speed: 50, target: 950, obstacles: 'random', bombRate: 0.06, wrapWalls: true, foodType: 'orb', bombType: 'square' },
    18: { speed: 45, target: 1000, obstacles: 'moving-random', bombRate: 0.07, wrapWalls: true, foodType: 'diamond', bombType: 'pulse' },
    
    // Phase 7: The Gauntlet - Chaos
    19: { speed: 40, target: 1200, obstacles: 'random', bombRate: 0.15, wrapWalls: false, foodType: 'hexagon', bombType: 'cross' },
    
    // Phase 8: Neon God (Ghost Mode) - Ultimate
    20: { speed: 35, target: 1500, obstacles: 'random', bombRate: 0.2, wrapWalls: true, ghostMode: true, foodType: 'star', bombType: 'mine' }
};

// ========================
// STATE MANAGEMENT
// ========================

let gameState = {
    currentLevel: 1,
    score: 0,
    status: 'menu', // menu, playing, paused, level-complete, game-over
    snake: [],
    velocity: { x: 0, y: 0 },
    nextVelocity: { x: 0, y: 0 },
    food: { x: 0, y: 0 },
    obstacles: [],
    bombs: [],
    startTime: 0,
    startTime: 0,
    lastFrameTime: 0,
    prevSnake: [] // For interpolation
};

let gameProgress = {
    unlockedLevels: 1,
    highScores: {} // { levelId: score }
};

// Load Progress
// const savedProgress = localStorage.getItem('neonSnakeProgress');
// if (savedProgress) {
//     gameProgress = JSON.parse(savedProgress);
// }
// Progress is now handled via API stats, but for level unlocking we might still need local storage or fetch it.
// For now, let's keep level unlocking local but stats from API.
const savedProgress = localStorage.getItem('neonSnakeProgress');
if (savedProgress) {
    gameProgress = JSON.parse(savedProgress);
}

// ========================
// DOM ELEMENTS
// ========================

const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const canvasContainer = document.getElementById('snake-canvas-container');

// Screens
const screens = {
    start: document.getElementById('start-screen'),
    game: document.getElementById('game-screen'),
    levelComplete: document.getElementById('level-complete-screen'),
    gameOver: document.getElementById('game-over-screen')
};

// HUD
const hud = {
    score: document.getElementById('score'),
    level: document.getElementById('level'),
    target: document.getElementById('target-score')
};

// ========================
// INITIALIZATION
// ========================

function resizeCanvas() {
    const wrapper = canvasContainer.parentElement;
    if (!wrapper) return;
    
    // Get full available space (subtracting padding)
    const style = window.getComputedStyle(wrapper);
    const paddingX = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
    const paddingY = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
    
    let availWidth = wrapper.clientWidth - paddingX;
    let availHeight = wrapper.clientHeight - paddingY;
    
    // Fallback
    if (availWidth <= 0 || availHeight <= 0) {
        availWidth = 800;
        availHeight = 600;
    }
    
    // Apply 1.5x aspect ratio constraint based on minimum dimension
    const minDim = Math.min(availWidth, availHeight);
    const maxDim = minDim * 1.5;
    
    // Constrain both dimensions
    let finalWidth = Math.min(availWidth, maxDim);
    let finalHeight = Math.min(availHeight, maxDim);
    
    // Calculate how many grid tiles fit
    tileCountX = Math.floor(finalWidth / GRID_SIZE);
    tileCountY = Math.floor(finalHeight / GRID_SIZE);
    
    // Minimum size
    if (tileCountX < 15) tileCountX = 15;
    if (tileCountY < 10) tileCountY = 10;
    
    // Exact pixel size (grid-snapped)
    const width = tileCountX * GRID_SIZE;
    const height = tileCountY * GRID_SIZE;
    
    // Set canvas resolution
    canvas.width = width;
    canvas.height = height;
    
    // Set container size to match canvas exactly (no padding)
    canvasContainer.style.width = `${width}px`;
    canvasContainer.style.height = `${height}px`;
}

function init() {
    // Listen for window resize
    window.addEventListener('resize', () => {
        if (gameState.status === 'playing') {
            // Only resize during gameplay to maintain game state
            resizeCanvas();
        }
    });
    
    // Event Listeners
    // document.getElementById('btn-play').addEventListener('click', () => {
    //     startLevel(gameState.currentLevel);
    // });
    
    // No separate level select button needed
    
    document.getElementById('btn-main-menu').addEventListener('click', quitGame);
    document.getElementById('btn-pause').addEventListener('click', togglePause);
    document.getElementById('btn-resume').addEventListener('click', togglePause);
    document.getElementById('btn-quit').addEventListener('click', quitGame);
    
    document.getElementById('btn-next-level').addEventListener('click', () => {
        startLevel(gameState.currentLevel + 1);
    });
    document.getElementById('btn-menu-complete').addEventListener('click', showMainMenu);
    
    document.getElementById('btn-retry').addEventListener('click', () => {
        startLevel(gameState.currentLevel);
    });
    document.getElementById('btn-menu-fail').addEventListener('click', showMainMenu);
    
    // Input Handling
    document.addEventListener('keydown', handleInput);
    setupTouchControls();
    
    // Initialize Menu
    updateMenuStats(); // This will now fetch from API
    renderLevelGrid();
    
    // Start Animation Loop
    requestAnimationFrame(gameLoop);
}

async function loadGameStats() {
    try {
        const response = await fetch('/api/sessions/game-stats/neon-snake');
        if (response.ok) {
            const data = await response.json();
            
            // Update wins/losses display
            const totalWinsEl = document.getElementById('total-wins');
            const totalLossesEl = document.getElementById('total-losses');
            
            if (totalWinsEl) totalWinsEl.textContent = data.totalWins || 0;
            if (totalLossesEl) totalLossesEl.textContent = data.totalLosses || 0;
        }
    } catch (error) {
        console.error('Error loading game stats:', error);
    }
}

async function updateMenuStats() {
    const levelsUnlockedEl = document.getElementById('menu-levels-unlocked');
    if (levelsUnlockedEl) levelsUnlockedEl.textContent = `${gameProgress.unlockedLevels}/20`;
    
    // Load wins/losses from API
    await loadGameStats();
    
    // Calculate total high score (keep local for now as it's level specific)
    let totalScore = 0;
    Object.values(gameProgress.highScores).forEach(score => totalScore += score);
    const highScoreEl = document.getElementById('menu-high-score');
    if (highScoreEl) highScoreEl.textContent = totalScore;
}

// Stats viewing
const viewStatsCard = document.getElementById('view-stats-card');
const closeStatsBtn = document.getElementById('close-stats-btn');
const statsScreen = document.getElementById('stats-screen');

if (viewStatsCard) {
    viewStatsCard.addEventListener('click', showStats);
    viewStatsCard.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
            showStats();
        }
    });
}

if (closeStatsBtn) {
    closeStatsBtn.addEventListener('click', () => {
        if (statsScreen) statsScreen.classList.add('hidden');
    });
}

function showStats() {
    const statsTableBody = document.getElementById('stats-table-body');
    if (!statsTableBody || !statsScreen) return;
    
    // Fetch fresh stats from API and display
    fetch('/api/sessions/game-stats/neon-snake')
        .then(response => response.json())
        .then(data => {
            statsTableBody.innerHTML = '';
            
            // Use detailed stats from API if available
            const detailedStats = data.detailedStats || {};
            
            // Iterate through all 20 levels
            for (let level = 1; level <= 20; level++) {
                const stats = detailedStats[level];
                if (!stats) continue; // Skip if no data
                
                const row = document.createElement('tr');
                const bestTime = stats.bestTime ? formatTime(stats.bestTime) : '-';
                const bestScore = stats.bestScore || '-';
                
                row.innerHTML = `
                    <td>Level ${level}</td>
                    <td class="stat-highlight">${stats.completions || stats.wins || 0}</td>
                    <td>${bestTime}</td>
                    <td>${bestScore}</td>
                `;
                statsTableBody.appendChild(row);
            }
            
            statsScreen.classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
            statsScreen.classList.remove('hidden'); // Still show empty table
        });
}

function formatTime(seconds) {
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    return `${mins}:${secs}`;
}

function renderLevelGrid() {
    const grid = document.getElementById('level-grid');
    if (!grid) return;
    
    grid.innerHTML = '';
    
    for (let i = 1; i <= 20; i++) {
        const card = document.createElement('div');
        const isUnlocked = i <= gameProgress.unlockedLevels;
        const isCompleted = gameProgress.highScores[i] ? true : false;
        const isCurrent = i === gameProgress.unlockedLevels && !isCompleted;
        
        // Set classes based on state
        let classes = 'level-card';
        if (!isUnlocked) classes += ' locked';
        else if (isCurrent) classes += ' current';
        else if (isCompleted) classes += ' completed';
        
        card.className = classes;
        
        if (isUnlocked) {
            const highScore = gameProgress.highScores[i] || 0;
            card.innerHTML = `
                <span class="level-num">${i}</span>
                <div class="level-status">
                    ${isCompleted ? `
                        <div class="level-stars">
                            <i class="fas fa-star"></i>
                        </div>
                        ${highScore > 0 ? `<div class="level-score">${highScore}</div>` : ''}
                    ` : ''}
                </div>
            `;
            card.addEventListener('click', () => {
                startLevel(i);
            });
        } else {
            card.innerHTML = `<i class="fas fa-lock lock-icon"></i>`;
        }
        
        grid.appendChild(card);
    }
}

// No selectLevel needed anymore

function showScreen(screenName) {
    // Hide all screens
    Object.values(screens).forEach(screen => {
        if(screen) screen.classList.add('hidden');
    });
    
    // Show requested screen
    if(screens[screenName]) screens[screenName].classList.remove('hidden');
    
    // Toggle Footer: Show ONLY on start screen
    const footer = document.getElementById('app-footer');
    if (footer) {
        if (screenName === 'start') {
            footer.classList.remove('hidden');
        } else {
            footer.classList.add('hidden');
        }
    }
}

function showMainMenu() {
    gameState.status = 'menu';
    updateMenuStats();
    renderLevelGrid();
    showScreen('start');
}

// ========================
// GAME LOGIC
// ========================

function startLevel(levelId) {
    if (levelId > 20) return; // Game Complete?
    
    gameState.currentLevel = levelId;
    const config = LEVEL_CONFIG[levelId];
    
    // Show screen first
    showScreen('game');
    
    // Allow DOM to update, then resize and start
    requestAnimationFrame(() => {
        resizeCanvas();
        resetGame();
        
        // Update HUD
        hud.score.textContent = '0';
        hud.level.textContent = levelId;
        hud.target.textContent = config.target;
        
        // Hide Pause Overlay
        document.getElementById('pause-overlay').classList.add('hidden');
        
        // Portal Visuals
        const container = document.getElementById('snake-canvas-container');
        if (config.wrapWalls) {
            container.classList.add('portal-active');
        } else {
            container.classList.remove('portal-active');
        }
        
        // Start Loop
        requestAnimationFrame(gameLoop);
    });
    
    // Analytics
    if (typeof trackGameStart === 'function') {
        trackGameStart('neon-snake', { level: levelId });
    }
}

function spawnObstacles() {
    gameState.obstacles = [];
    const pattern = LEVEL_CONFIG[gameState.currentLevel].obstacles;
    
    if (pattern === 'none') return;
    
    const centerX = Math.floor(tileCountX / 2);
    const centerY = Math.floor(tileCountY / 2);
    
    if (pattern === 'box') {
        // Border box
        for (let x = 5; x < tileCountX - 5; x++) {
            gameState.obstacles.push({ x: x, y: 5 });
            gameState.obstacles.push({ x: x, y: tileCountY - 6 });
        }
        for (let y = 5; y < tileCountY - 5; y++) {
            gameState.obstacles.push({ x: 5, y: y });
            gameState.obstacles.push({ x: tileCountX - 6, y: y });
        }
    } else if (pattern === 'cross') {
        // Horizontal line
        for (let x = 5; x < tileCountX - 5; x++) {
            if (x < centerX - 2 || x > centerX + 2) {
                gameState.obstacles.push({ x: x, y: centerY });
            }
        }
        // Vertical line
        for (let y = 5; y < tileCountY - 5; y++) {
            if (y < centerY - 2 || y > centerY + 2) {
                gameState.obstacles.push({ x: centerX, y: y });
            }
        }
    } else if (pattern === 'random') {
        const count = 10 + (gameState.currentLevel * 2);
        for (let i = 0; i < count; i++) {
            let x, y;
            let attempts = 0;
            do {
                x = Math.floor(Math.random() * tileCountX);
                y = Math.floor(Math.random() * tileCountY);
                attempts++;
            } while (isOccupied(x, y) && attempts < 50);
            
            if (attempts < 50) {
                gameState.obstacles.push({ x, y });
            }
        }
    }
}

function spawnFood() {
    let x, y;
    let valid = false;
    let attempts = 0;
    
    while (!valid && attempts < 50) {
        x = Math.floor(Math.random() * tileCountX);
        y = Math.floor(Math.random() * tileCountY);
        
        if (!isOccupied(x, y)) {
            valid = true;
        }
        attempts++;
    }
    
    // Fallback if full (unlikely)
    if (!valid) {
        x = 0; y = 0; 
    }
    
    gameState.food = { x, y };
}

function isOccupied(x, y) {
    // Check Snake
    for (let segment of gameState.snake) {
        if (segment.x === x && segment.y === y) return true;
    }
    // Check Obstacles
    for (let obs of gameState.obstacles) {
        if (obs.x === x && obs.y === y) return true;
    }
    // Check Bombs
    for (let bomb of gameState.bombs) {
        if (bomb.x === x && bomb.y === y) return true;
    }
    return false;
}

function resetGame() {
    const startX = Math.floor(tileCountX / 2);
    const startY = Math.floor(tileCountY / 2);
    
    gameState.snake = [
        { x: startX, y: startY },
        { x: startX, y: startY + 1 },
        { x: startX, y: startY + 2 }
    ];
    // Initialize prevSnake to match current snake
    gameState.prevSnake = JSON.parse(JSON.stringify(gameState.snake));
    gameState.velocity = { x: 0, y: -1 };
    gameState.nextVelocity = { x: 0, y: -1 };
    gameState.score = 0;
    gameState.startTime = Date.now();
    gameState.lastFrameTime = 0; // Use 0 for DOMHighResTimeStamp comparison
    gameState.status = 'playing';
    
    // Update HUD
    hud.score.textContent = '0';
    hud.level.textContent = gameState.currentLevel;
    hud.target.textContent = LEVEL_CONFIG[gameState.currentLevel].target;
    
    spawnObstacles();
    spawnFood();
    gameState.bombs = []; // Clear bombs
    
    // Hide cursor
    canvas.style.cursor = 'none';
}

function gameLoop(timestamp) {
    if (gameState.status === 'playing') {
        const config = LEVEL_CONFIG[gameState.currentLevel];
        
        // Calculate time since last update
        const timeSinceLastUpdate = timestamp - gameState.lastFrameTime;
        
        // Update logic if enough time has passed
        if (timeSinceLastUpdate > config.speed) {
            update();
            gameState.lastFrameTime = timestamp;
        }
        
        // Calculate interpolation factor (0.0 to 1.0)
        // This represents how far we are between the previous frame and the next frame
        let alpha = (timestamp - gameState.lastFrameTime) / config.speed;
        if (alpha > 1) alpha = 1;
        if (alpha < 0) alpha = 0;
        
        draw(alpha);
    }
    requestAnimationFrame(gameLoop);
}

function update() {
    // Save current state for interpolation
    gameState.prevSnake = JSON.parse(JSON.stringify(gameState.snake));

    // Move Snake
    gameState.velocity = gameState.nextVelocity;
    // Move Snake
    const head = { x: gameState.snake[0].x + gameState.velocity.x, y: gameState.snake[0].y + gameState.velocity.y };
    
    // Handle Wall Collision / Wrapping
    const config = LEVEL_CONFIG[gameState.currentLevel];
    
    if (config.wrapWalls) {
        // Wrap around
        if (head.x < 0) head.x = tileCountX - 1;
        if (head.x >= tileCountX) head.x = 0;
        if (head.y < 0) head.y = tileCountY - 1;
        if (head.y >= tileCountY) head.y = 0;
    } else {
        // Die on wall hit
        if (head.x < 0 || head.x >= tileCountX || head.y < 0 || head.y >= tileCountY) {
            gameOver();
            return;
        }
    }
    
    // Check Self Collision
    for (let i = 0; i < gameState.snake.length; i++) {
        if (head.x === gameState.snake[i].x && head.y === gameState.snake[i].y) {
            gameOver();
            return;
        }
    }
    
    // Check Obstacle Collision
    for (let obs of gameState.obstacles) {
        if (head.x === obs.x && head.y === obs.y) {
            gameOver();
            return;
        }
    }
    
    // Update Moving Obstacles
    updateMovingObstacles();
    
    // Bomb Collision
    for (let bomb of gameState.bombs) {
        if (head.x === bomb.x && head.y === bomb.y) {
            gameOver();
            return;
        }
    }
    
    gameState.snake.unshift(head);
    
    // Eat Food
    if (head.x === gameState.food.x && head.y === gameState.food.y) {
        gameState.score += 10;
        hud.score.textContent = gameState.score;
        spawnFood();
        
        // Check Level Complete
        // Check Level Complete
        if (gameState.score >= config.target) {
            levelComplete();
            return;
        }
    } else {
        gameState.snake.pop();
    }
    
    // Bomb Spawning
    // Bomb Spawning
    if (Math.random() < config.bombRate) {
        spawnBomb();
    }
    
    // Bomb Aging
    gameState.bombs = gameState.bombs.filter(b => {
        b.age++;
        return b.age < 50; // Bomb lifespan in frames
    });
}

function spawnBomb() {
    let valid = false;
    let attempts = 0;
    let bomb = {};
    
    while (!valid && attempts < 10) {
        bomb = {
            x: Math.floor(Math.random() * tileCountX),
            y: Math.floor(Math.random() * tileCountY)
        };
        
        valid = true;
        // Check snake collision (give some buffer)
        for (let part of gameState.snake) {
            if (Math.abs(bomb.x - part.x) < 2 && Math.abs(bomb.y - part.y) < 2) valid = false;
        }
        // Check food collision
        if (bomb.x === gameState.food.x && bomb.y === gameState.food.y) valid = false;
        
        // Check obstacle collision
        for (let obs of gameState.obstacles) {
            if (bomb.x === obs.x && bomb.y === obs.y) valid = false;
        }
        
        attempts++;
    }
    
    if (valid) {
        gameState.bombs.push(bomb);
        // Remove bomb after 5 seconds
        setTimeout(() => {
            const index = gameState.bombs.indexOf(bomb);
            if (index > -1) gameState.bombs.splice(index, 1);
        }, 5000);
    }
}

function spawnObstacles() {
    gameState.obstacles = [];
    const pattern = LEVEL_CONFIG[gameState.currentLevel].obstacles;
    
    if (pattern === 'none') return;
    
    // Static Patterns
    if (pattern === 'box') {
        // Draw box with gaps (Four Corners style)
        for (let x = 5; x < tileCountX - 5; x++) {
            // Top & Bottom gaps
            if (x < tileCountX/2 - 2 || x > tileCountX/2 + 2) {
                gameState.obstacles.push({ x: x, y: 5, type: 'static' });
                gameState.obstacles.push({ x: x, y: tileCountY - 6, type: 'static' });
            }
        }
        for (let y = 5; y < tileCountY - 5; y++) {
            // Left & Right gaps
            if (y < tileCountY/2 - 2 || y > tileCountY/2 + 2) {
                gameState.obstacles.push({ x: 5, y: y, type: 'static' });
                gameState.obstacles.push({ x: tileCountX - 6, y: y, type: 'static' });
            }
        }
    } else if (pattern === 'cross') {
        for (let x = 5; x < tileCountX - 5; x++) {
            if (x !== Math.floor(tileCountX/2)) 
                gameState.obstacles.push({ x: x, y: Math.floor(tileCountY/2), type: 'static' });
        }
        for (let y = 5; y < tileCountY - 5; y++) {
            if (y !== Math.floor(tileCountY/2))
                gameState.obstacles.push({ x: Math.floor(tileCountX/2), y: y, type: 'static' });
        }
    } else if (pattern === 'random') {
        const count = gameState.currentLevel * 2;
        for (let i = 0; i < count; i++) {
            gameState.obstacles.push({
                x: Math.floor(Math.random() * tileCountX),
                y: Math.floor(Math.random() * tileCountY),
                type: 'static'
            });
        }
    }
    
    // Moving Patterns
    else if (pattern === 'moving-h') {
        for (let y = 4; y < tileCountY - 4; y += 4) {
            gameState.obstacles.push({ 
                x: 2, y: y, 
                type: 'moving', 
                dx: 1, dy: 0, 
                min: 1, max: tileCountX - 2 
            });
        }
    } else if (pattern === 'moving-v') {
        for (let x = 4; x < tileCountX - 4; x += 4) {
            gameState.obstacles.push({ 
                x: x, y: 2, 
                type: 'moving', 
                dx: 0, dy: 1, 
                min: 1, max: tileCountY - 2 
            });
        }
    } else if (pattern === 'moving-random') {
        const count = 5;
        for (let i = 0; i < count; i++) {
            gameState.obstacles.push({
                x: Math.floor(Math.random() * (tileCountX - 4)) + 2,
                y: Math.floor(Math.random() * (tileCountY - 4)) + 2,
                type: 'moving',
                dx: Math.random() > 0.5 ? 1 : -1,
                dy: 0,
                min: 1, max: tileCountX - 2
            });
        }
    }
}

function updateMovingObstacles() {
    // Only move every few frames to make it fair
    if (Date.now() % 200 > 50) return;

    for (let obs of gameState.obstacles) {
        if (obs.type === 'moving') {
            obs.x += obs.dx;
            obs.y += obs.dy;
            
            // Bounce logic
            if (obs.dx !== 0) {
                if (obs.x >= obs.max || obs.x <= obs.min) obs.dx *= -1;
            }
            if (obs.dy !== 0) {
                if (obs.y >= obs.max || obs.y <= obs.min) obs.dy *= -1;
            }
        }
    }
}

function draw(alpha = 1.0) {
    // Clear Canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw Obstacles - Dark Purple theme
    ctx.fillStyle = 'rgba(20, 20, 50, 0.8)'; 
    ctx.strokeStyle = '#fc00ff'; // Magenta border
    ctx.lineWidth = 2;
    ctx.shadowBlur = 10;
    ctx.shadowColor = 'rgba(252, 0, 255, 0.4)';
    
    for (let obs of gameState.obstacles) {
        const x = obs.x * GRID_SIZE;
        const y = obs.y * GRID_SIZE;
        ctx.fillRect(x, y, GRID_SIZE, GRID_SIZE);
        ctx.strokeRect(x, y, GRID_SIZE, GRID_SIZE);
    }
    
    // Draw Food - Varied Designs
    const fx = gameState.food.x * GRID_SIZE + GRID_SIZE/2;
    const fy = gameState.food.y * GRID_SIZE + GRID_SIZE/2;
    const config = LEVEL_CONFIG[gameState.currentLevel];
    
    // Pulse animation
    const pulse = Math.sin(Date.now() / 200) * 2;
    
    ctx.shadowBlur = 20;
    
    if (config.foodType === 'diamond') {
        // Gold Diamond
        ctx.shadowColor = '#ffd700';
        ctx.fillStyle = '#ffd700';
        
        ctx.save();
        ctx.translate(fx, fy);
        ctx.rotate(Date.now() / 1000);
        ctx.beginPath();
        ctx.rect(-5, -5, 10, 10);
        ctx.fill();
        
        // Outer outline
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.rect(-7 - pulse/2, -7 - pulse/2, 14 + pulse, 14 + pulse);
        ctx.stroke();
        ctx.restore();
        
    } else if (config.foodType === 'hexagon') {
        // Pink Hexagon
        ctx.shadowColor = '#ff00ff';
        ctx.fillStyle = '#ff00ff';
        
        ctx.beginPath();
        for (let i = 0; i < 6; i++) {
            const angle = (Math.PI / 3) * i;
            const r = 7;
            const x = fx + Math.cos(angle) * r;
            const y = fy + Math.sin(angle) * r;
            if (i === 0) ctx.moveTo(x, y);
            else ctx.lineTo(x, y);
        }
        ctx.closePath();
        ctx.fill();
        
        // Inner dot
        ctx.fillStyle = '#ffffff';
        ctx.beginPath();
        ctx.arc(fx, fy, 2, 0, Math.PI*2);
        ctx.fill();
        
    } else if (config.foodType === 'star') {
        // Green Star
        ctx.shadowColor = '#00ff00';
        ctx.fillStyle = '#00ff00';
        
        ctx.save();
        ctx.translate(fx, fy);
        ctx.rotate(Date.now() / 1500);
        
        ctx.beginPath();
        for (let i = 0; i < 5; i++) {
            const angle = (Math.PI * 2 * i) / 5 - Math.PI / 2;
            const x = Math.cos(angle) * 8;
            const y = Math.sin(angle) * 8;
            if (i === 0) ctx.moveTo(x, y);
            else ctx.lineTo(x, y);
            
            const innerAngle = angle + Math.PI / 5;
            const ix = Math.cos(innerAngle) * 4;
            const iy = Math.sin(innerAngle) * 4;
            ctx.lineTo(ix, iy);
        }
        ctx.closePath();
        ctx.fill();
        ctx.restore();
        
    } else {
        // Default: Cyan Orb
        ctx.shadowColor = '#00f5ff';
        
        // Core
        ctx.fillStyle = '#ffffff';
        ctx.beginPath();
        ctx.arc(fx, fy, 4, 0, Math.PI*2);
        ctx.fill();
        
        // Outer Shell
        ctx.strokeStyle = '#00f5ff';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(fx, fy, 6 + pulse, 0, Math.PI*2);
        ctx.stroke();
    }
    
    // Draw Bombs - Varied Designs
    for (let bomb of gameState.bombs) {
        const bx = bomb.x * GRID_SIZE + GRID_SIZE/2;
        const by = bomb.y * GRID_SIZE + GRID_SIZE/2;
        
        if (config.bombType === 'square') {
            // Purple Glitch Square
            ctx.shadowColor = '#a855f7';
            ctx.shadowBlur = 15;
            ctx.fillStyle = '#a855f7';
            
            ctx.save();
            ctx.translate(bx, by);
            ctx.rotate(Date.now() / 500);
            ctx.fillRect(-6, -6, 12, 12);
            
            // Glitch effect
            if (Math.random() > 0.8) {
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(-4, -4, 8, 8);
            }
            ctx.restore();
            
        } else if (config.bombType === 'pulse') {
            // Orange Pulse Mine
            ctx.shadowColor = '#ffaa00';
            ctx.shadowBlur = 15;
            
            const r = 6 + Math.sin(Date.now() / 100) * 2;
            
            ctx.strokeStyle = '#ffaa00';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(bx, by, r, 0, Math.PI*2);
            ctx.stroke();
            
            ctx.fillStyle = '#ffffff';
            ctx.beginPath();
            ctx.arc(bx, by, 3, 0, Math.PI*2);
            ctx.fill();
            
        } else if (config.bombType === 'cross') {
            // Yellow Spinning Cross
            ctx.shadowColor = '#ffff00';
            ctx.shadowBlur = 15;
            ctx.strokeStyle = '#ffff00';
            ctx.lineWidth = 3;
            
            ctx.save();
            ctx.translate(bx, by);
            ctx.rotate(Date.now() / 300);
            
            ctx.beginPath();
            ctx.moveTo(-6, -6);
            ctx.lineTo(6, 6);
            ctx.moveTo(6, -6);
            ctx.lineTo(-6, 6);
            ctx.stroke();
            ctx.restore();
            
        } else {
            // Default: Red Spiked Mine
            ctx.shadowColor = '#ff3366';
            ctx.shadowBlur = 15;
            ctx.fillStyle = '#ff3366';
            
            // Draw Spiked Shape
            ctx.beginPath();
            const spikes = 8;
            const outerRadius = 8;
            const innerRadius = 4;
            
            for (let i = 0; i < spikes * 2; i++) {
                const r = (i % 2 === 0) ? outerRadius : innerRadius;
                const a = (Math.PI * i) / spikes + (Date.now() / 1000);
                const x = bx + Math.cos(a) * r;
                const y = by + Math.sin(a) * r;
                if (i === 0) ctx.moveTo(x, y);
                else ctx.lineTo(x, y);
            }
            ctx.closePath();
            ctx.fill();
            
            // Warning Center
            ctx.fillStyle = '#ffffff';
            ctx.beginPath();
            ctx.arc(bx, by, 2, 0, Math.PI*2);
            ctx.fill();
        }
    }
    
    // Draw Snake with smooth interpolation and realistic design
    if (gameState.snake.length > 0) {
        ctx.shadowBlur = 15;
        const config = LEVEL_CONFIG[gameState.currentLevel];

        // Helper to get interpolated position
        const getInterpPos = (curr, prev) => {
            // Handle wrapping interpolation
            let dx = curr.x - prev.x;
            let dy = curr.y - prev.y;
            
            // If wrapped, don't interpolate across screen
            if (Math.abs(dx) > 1) dx = 0;
            if (Math.abs(dy) > 1) dy = 0;
            
            return {
                x: (prev.x + dx * alpha) * GRID_SIZE + GRID_SIZE/2,
                y: (prev.y + dy * alpha) * GRID_SIZE + GRID_SIZE/2
            };
        };

        // Draw Body (from tail to head)
        for (let i = gameState.snake.length - 1; i >= 0; i--) {
            const segment = gameState.snake[i];
            const prevSegment = gameState.prevSnake[i] || segment;
            
            const pos = getInterpPos(segment, prevSegment);
            
            // Gradient from cyan (head) to magenta (tail)
            const ratio = i / gameState.snake.length;
            
            // Ghost Mode: Fade out body
            if (config.ghostMode && i > 0 && i < gameState.snake.length - 1) {
                ctx.globalAlpha = 0.1;
            } else {
                ctx.globalAlpha = 1.0;
            }
            
            if (i === 0) {
                // HEAD DESIGN
                ctx.fillStyle = '#00f5ff';
                ctx.shadowColor = '#00f5ff';
                
                // Draw Head Circle
                ctx.beginPath();
                ctx.arc(pos.x, pos.y, GRID_SIZE/2 + 2, 0, Math.PI*2);
                ctx.fill();
                
                // Draw Eyes
                // Determine direction based on velocity
                let angle = 0;
                if (gameState.velocity.x === 1) angle = 0;
                else if (gameState.velocity.x === -1) angle = Math.PI;
                else if (gameState.velocity.y === 1) angle = Math.PI/2;
                else if (gameState.velocity.y === -1) angle = -Math.PI/2;
                
                ctx.save();
                ctx.translate(pos.x, pos.y);
                ctx.rotate(angle);
                
                // White Sclera
                ctx.fillStyle = 'white';
                ctx.shadowBlur = 0;
                ctx.beginPath();
                ctx.arc(4, -4, 3, 0, Math.PI*2); // Right eye
                ctx.arc(4, 4, 3, 0, Math.PI*2);  // Left eye
                ctx.fill();
                
                // Black Pupils
                ctx.fillStyle = 'black';
                ctx.beginPath();
                ctx.arc(5, -4, 1.5, 0, Math.PI*2);
                ctx.arc(5, 4, 1.5, 0, Math.PI*2);
                ctx.fill();
                
                ctx.restore();
                
            } else {
                // BODY DESIGN
                const r = Math.floor(0 + ratio * (252 - 0));
                const g = Math.floor(245 - ratio * (245 - 0));
                const b = 255; 
                
                ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
                ctx.shadowColor = `rgba(${r}, ${g}, ${b}, 0.6)`;
                
                // Tapered Tail
                let size = GRID_SIZE/2;
                if (i > gameState.snake.length - 4) {
                    size *= (gameState.snake.length - i) / 4;
                }
                
                ctx.beginPath();
                ctx.arc(pos.x, pos.y, size, 0, Math.PI*2);
                ctx.fill();
                
                // Connect segments to prevent gaps
                if (i > 0) {
                    const nextSeg = gameState.snake[i-1];
                    const prevNextSeg = gameState.prevSnake[i-1] || nextSeg;
                    const nextPos = getInterpPos(nextSeg, prevNextSeg);
                    
                    // Only connect if not wrapped
                    if (Math.abs(segment.x - nextSeg.x) <= 1 && Math.abs(segment.y - nextSeg.y) <= 1) {
                        ctx.beginPath();
                        ctx.moveTo(pos.x, pos.y);
                        ctx.lineTo(nextPos.x, nextPos.y);
                        ctx.strokeStyle = `rgb(${r}, ${g}, ${b})`;
                        ctx.lineWidth = size * 2;
                        ctx.stroke();
                    }
                }
            }
            
            ctx.globalAlpha = 1.0; // Reset alpha
        }
    }
}

// ========================
// GAME END STATES
// ========================

function levelComplete() {
    gameState.status = 'level-complete';
    
    // Calculate Bonus
    const timeBonus = Math.max(0, 1000 - Math.floor((Date.now() - gameState.startTime) / 1000));
    const totalScore = gameState.score + timeBonus;
    
    // Update Progress
    if (gameState.currentLevel === gameProgress.unlockedLevels) {
        gameProgress.unlockedLevels++;
    }
    
    // Save High Score
    const currentHigh = gameProgress.highScores[gameState.currentLevel] || 0;
    if (totalScore > currentHigh) {
        gameProgress.highScores[gameState.currentLevel] = totalScore;
    }
    
    localStorage.setItem('neonSnakeProgress', JSON.stringify(gameProgress));
    
    // Update UI
    document.getElementById('complete-level-num').textContent = gameState.currentLevel;
    document.getElementById('complete-score').textContent = gameState.score;
    document.getElementById('complete-bonus').textContent = timeBonus;
    document.getElementById('complete-total').textContent = totalScore;
    
    showScreen('levelComplete');
    
    if (typeof trackGameEnd === 'function') {
        trackGameEnd('neon-snake', Date.now() - gameState.startTime, {
            result: 'win',
            level: gameState.currentLevel,
            score: totalScore
        });
    }
}

function gameOver() {
    gameState.status = 'game-over';
    
    document.getElementById('fail-score').textContent = gameState.score;
    document.getElementById('fail-high-score').textContent = gameProgress.highScores[gameState.currentLevel] || 0;
    
    showScreen('gameOver');
    
    if (typeof trackGameEnd === 'function') {
        trackGameEnd('neon-snake', Date.now() - gameState.startTime, {
            result: 'loss',
            level: gameState.currentLevel,
            score: gameState.score
        });
    }
}

function togglePause() {
    if (gameState.status === 'playing') {
        gameState.status = 'paused';
        document.getElementById('pause-overlay').classList.remove('hidden');
    } else if (gameState.status === 'paused') {
        gameState.status = 'playing';
        document.getElementById('pause-overlay').classList.add('hidden');
    }
}

function quitGame() {
    gameState.status = 'menu';
    showMainMenu();
}

// ========================
// INPUT HANDLING
// ========================

function handleInput(e) {
    if (gameState.status !== 'playing') return;
    
    if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {
        e.preventDefault();
    }
    
    switch(e.key) {
        case 'ArrowUp':
        case 'w':
        case 'W':
            if (gameState.velocity.y === 0) gameState.nextVelocity = { x: 0, y: -1 };
            break;
        case 'ArrowDown':
        case 's':
        case 'S':
            if (gameState.velocity.y === 0) gameState.nextVelocity = { x: 0, y: 1 };
            break;
        case 'ArrowLeft':
        case 'a':
        case 'A':
            if (gameState.velocity.x === 0) gameState.nextVelocity = { x: -1, y: 0 };
            break;
        case 'ArrowRight':
        case 'd':
        case 'D':
            if (gameState.velocity.x === 0) gameState.nextVelocity = { x: 1, y: 0 };
            break;
        case 'Escape':
            togglePause();
            break;
    }
}

function setupTouchControls() {
    const btnUp = document.getElementById('btn-up');
    const btnDown = document.getElementById('btn-down');
    const btnLeft = document.getElementById('btn-left');
    const btnRight = document.getElementById('btn-right');
    
    const handleTouch = (dir) => {
        if (gameState.status !== 'playing') return;
        switch(dir) {
            case 'up': if (gameState.velocity.y === 0) gameState.nextVelocity = { x: 0, y: -1 }; break;
            case 'down': if (gameState.velocity.y === 0) gameState.nextVelocity = { x: 0, y: 1 }; break;
            case 'left': if (gameState.velocity.x === 0) gameState.nextVelocity = { x: -1, y: 0 }; break;
            case 'right': if (gameState.velocity.x === 0) gameState.nextVelocity = { x: 1, y: 0 }; break;
        }
    };
    
    btnUp.addEventListener('touchstart', (e) => { e.preventDefault(); handleTouch('up'); });
    btnDown.addEventListener('touchstart', (e) => { e.preventDefault(); handleTouch('down'); });
    btnLeft.addEventListener('touchstart', (e) => { e.preventDefault(); handleTouch('left'); });
    btnRight.addEventListener('touchstart', (e) => { e.preventDefault(); handleTouch('right'); });
}

// Start Game
init();

// Back to Portal button
const backToPortalBtn = document.getElementById('back-to-portal-btn');
if (backToPortalBtn) {
    backToPortalBtn.addEventListener('click', () => {
        window.location.href = '/';
    });
}
