<style>
#ms-game { text-align: center; max-width: 600px; margin: 0 auto; }
#ms-board { display: inline-grid; gap: 2px; background: #007700; border: 3px solid #00ff00; padding: 4px; margin: 12px 0; }
.ms-cell {
    width: 28px; height: 28px; background: #000; border: 1px solid #007700;
    display: flex; align-items: center; justify-content: center;
    font-size: .85rem; font-weight: bold; cursor: pointer;
    user-select: none; font-family: 'Courier New', monospace;
}
.ms-cell.revealed { background: #111; cursor: default; }
.ms-cell.flagged { background: #001a00; color: #ff6600; cursor: pointer; }
.ms-cell.mine-boom { background: #330000; color: #ff4444; }
.ms-cell.mine-revealed { background: #111; }
.n1{color:#00aaff;} .n2{color:#00ff00;} .n3{color:#ff6600;} .n4{color:#0000ff;}
.n5{color:#ff0000;} .n6{color:#00ffff;} .n7{color:#ff00ff;} .n8{color:#ffffff;}
#ms-info { display: flex; justify-content: space-between; font-size: 1rem; margin: 6px 0; }
#ms-msg { font-size: 1.2rem; font-weight: bold; min-height: 2rem; color: #00ff00; }
</style>

<div id="ms-game">
    <h4 style="color:#00ff00;"><i class="bi bi-bomb"></i> MINESWEEPER</h4>
    <div id="ms-info">
        <span>💣 <span id="ms-mines">0</span></span>
        <span id="ms-msg"></span>
        <span>⏱ <span id="ms-time">0</span>s</span>
    </div>
    <div id="ms-board"></div>
    <div class="d-flex justify-content-center gap-3 mt-2">
        <button class="btn btn-primary btn-sm" onclick="startMs(9,9,10)">Easy</button>
        <button class="btn btn-primary btn-sm" onclick="startMs(16,16,40)">Medium</button>
        <button class="btn btn-primary btn-sm" onclick="startMs(16,30,99)">Hard</button>
    </div>
    <p style="color:#007700; font-size:.8rem; margin-top:6px;">Left-click to reveal • Right-click to flag</p>
</div>

<script>
(function() {
    var ROWS, COLS, MINES, board, revealed, flagged, started, timer, gameOver;

    window.startMs = function(r, c, m) {
        clearInterval(timer);
        ROWS=r; COLS=c; MINES=m;
        started=false; gameOver=false;
        document.getElementById('ms-time').textContent='0';
        document.getElementById('ms-msg').textContent='';
        document.getElementById('ms-mines').textContent=MINES;

        board = Array.from({length:ROWS}, function(){ return Array(COLS).fill(0); });
        revealed = Array.from({length:ROWS}, function(){ return Array(COLS).fill(false); });
        flagged = Array.from({length:ROWS}, function(){ return Array(COLS).fill(false); });

        render();
    };

    function placeMines(avoidR, avoidC) {
        var placed = 0;
        while (placed < MINES) {
            var r = Math.floor(Math.random()*ROWS);
            var c = Math.floor(Math.random()*COLS);
            if (board[r][c] === -1) continue;
            if (Math.abs(r-avoidR) <= 1 && Math.abs(c-avoidC) <= 1) continue;
            board[r][c] = -1;
            placed++;
        }
        for (var rr=0;rr<ROWS;rr++) for (var cc=0;cc<COLS;cc++) {
            if (board[rr][cc]===-1) continue;
            var cnt=0;
            neighbors(rr,cc).forEach(function(n){ if(board[n[0]][n[1]]===-1) cnt++; });
            board[rr][cc]=cnt;
        }
    }

    function neighbors(r,c) {
        var nb=[];
        for(var dr=-1;dr<=1;dr++) for(var dc=-1;dc<=1;dc++) {
            if(dr===0&&dc===0) continue;
            var nr=r+dr, nc=c+dc;
            if(nr>=0&&nr<ROWS&&nc>=0&&nc<COLS) nb.push([nr,nc]);
        }
        return nb;
    }

    function reveal(r,c) {
        if (revealed[r][c]||flagged[r][c]) return;
        revealed[r][c]=true;
        if (board[r][c]===0) neighbors(r,c).forEach(function(n){ reveal(n[0],n[1]); });
    }

    function render() {
        var bd = document.getElementById('ms-board');
        bd.style.gridTemplateColumns='repeat('+COLS+',28px)';
        bd.innerHTML='';
        for(var r=0;r<ROWS;r++) for(var c=0;c<COLS;c++) {
            var cell=document.createElement('div');
            cell.className='ms-cell';
            var rr=r, cc=c;
            if (revealed[r][c]) {
                cell.classList.add('revealed');
                if (board[r][c]===-1) { cell.classList.add('mine-boom'); cell.textContent='💣'; }
                else if (board[r][c]>0) { cell.textContent=board[r][c]; cell.classList.add('n'+board[r][c]); }
            } else if (flagged[r][c]) {
                cell.classList.add('flagged'); cell.textContent='🚩';
            } else {
                cell.textContent='';
            }
            cell.addEventListener('click', function(ev){ handleClick(rr,cc); });
            cell.addEventListener('contextmenu', function(ev){ ev.preventDefault(); handleFlag(rr,cc); });
            bd.appendChild(cell);
        }
    }

    function handleClick(r,c) {
        if (gameOver||revealed[r][c]||flagged[r][c]) return;
        if (!started) { started=true; placeMines(r,c); var t=0; timer=setInterval(function(){ t++; document.getElementById('ms-time').textContent=t; },1000); }
        if (board[r][c]===-1) { boom(r,c); return; }
        reveal(r,c);
        render();
        checkWin();
    }

    function handleFlag(r,c) {
        if (gameOver||revealed[r][c]) return;
        flagged[r][c]=!flagged[r][c];
        var rem=MINES;
        for(var rr=0;rr<ROWS;rr++) for(var cc=0;cc<COLS;cc++) if(flagged[rr][cc]) rem--;
        document.getElementById('ms-mines').textContent=rem;
        render();
    }

    function boom(r,c) {
        clearInterval(timer);
        gameOver=true;
        revealed[r][c]=true;
        for(var rr=0;rr<ROWS;rr++) for(var cc=0;cc<COLS;cc++) if(board[rr][cc]===-1) revealed[rr][cc]=true;
        render();
        document.getElementById('ms-msg').textContent='💥 BOOM! Game over.';
        document.getElementById('ms-msg').style.color='#ff4444';
    }

    function checkWin() {
        var unrevealed=0;
        for(var rr=0;rr<ROWS;rr++) for(var cc=0;cc<COLS;cc++) if(!revealed[rr][cc]) unrevealed++;
        if (unrevealed===MINES) {
            clearInterval(timer);
            gameOver=true;
            var t=parseInt(document.getElementById('ms-time').textContent)||1;
            var score=Math.round(MINES*100/t);
            document.getElementById('ms-msg').textContent='🎉 YOU WIN! Score: '+score;
            document.getElementById('ms-msg').style.color='#00ff00';
            fetch(window.location.pathname.replace('/play','/') + 'score', {
                method:'POST', headers:{'Content-Type':'application/json'},
                body: JSON.stringify({score:score})
            }).catch(function(){});
        }
    }

    startMs(9,9,10);
})();
</script>
