// Simpler approach to show 3s 'Get ready...' and then start dynamic loop

let lastGrid = [];
let currentGrid = [];
let gameStartTime = null;

// Linear formula: from 3s down to 1s over 60s
function getInterval(secondsElapsed) {
    return Math.max(1, -secondsElapsed / 30 + 3);
}

function renderGrid(grid) {
    const gridDiv = document.getElementById('grid');
    gridDiv.innerHTML = '';
    grid.forEach((num, idx) => {
        const cell = document.createElement('button');
        cell.textContent = num;
        cell.onclick = () => guess(idx);
        gridDiv.appendChild(cell);
    });
}

function initGame() {
    // 1) Fetch grid once
    fetch('/get_grid')
        .then(r => r.json())
        .then(grid => {
            currentGrid = [...grid];
            renderGrid(currentGrid);

            // 2) Show 'Get ready...' for 3s
            const feedback = document.getElementById('feedback');
            feedback.textContent = "⏳ Get ready...";

            setTimeout(() => {
                feedback.textContent = "";

                // 3) Now start the game
                lastGrid = [...currentGrid];
                gameStartTime = Date.now();
                startStats();
                startDynamicLoop();
            }, 3000);
        })
        .catch(err => {
            console.error('Init fetch error:', err);
        });
}

function startDynamicLoop() {
    // Repeatedly fetch grid at decreasing intervals
    function loop() {
        const secondsElapsed = (Date.now() - gameStartTime) / 1000;
        const nextInterval = getInterval(secondsElapsed);
        fetchGrid();
        setTimeout(loop, nextInterval * 1000);
    }
    loop();
}

function fetchGrid() {
    fetch('/get_grid')
        .then(r => r.json())
        .then(grid => {
            lastGrid = [...currentGrid];
            currentGrid = [...grid];
            renderGrid(currentGrid);
        })
        .catch(err => {
            console.error('Fetch grid error:', err);
        });
}

function guess(idx) {
    const feedback = document.getElementById('feedback');
    if (lastGrid.length === 9 && currentGrid[idx] !== lastGrid[idx]) {
        feedback.textContent = "✅ Correct!";
        incrementCorrect();
    } else {
        feedback.textContent = "❌ Try again!";
        incrementWrong();
    }
    setTimeout(() => feedback.textContent = "", 1500);
}

// Kick off
initGame();

