import { createBoard, markTile, revealTile, checkLose, checkWin, STATUS } from "./minesweeper.js"

const SIZE = 10;
const MINES = 10;

var board = createBoard(SIZE, MINES);

const boardElement = document.getElementsByClassName("board")[0];
const resultElement = document.getElementsByClassName("subtext")[0];
const mineCount = document.querySelector("[data-mine-count]");
mineCount.innerText = MINES

boardElement.style.setProperty('--size', SIZE);

board.forEach(row => {
    row.forEach(tile => {
        boardElement.append(tile.element)
        tile.element.addEventListener('click', () => {
            revealTile(tile, board);
            checkGameEnds(board);
        })
        tile.element.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            markTile(tile);
            mineCount.innerText = MINES - listMinesLeft();
        })
    })
})

function listMinesLeft() {
    return board.reduce((count, row) => {
        return count + row.filter(tile => tile.status == STATUS.MARKED).length
    }, 0);
}

function checkGameEnds(board) {
    if (checkWin(board, MINES) || checkLose(board)) {
        boardElement.addEventListener('click', e => e.stopImmediatePropagation());
        boardElement.addEventListener('contextmenu', e => e.stopImmediatePropagation());
    }

    if (checkWin(board, MINES)) {
        resultElement.innerHTML = "You win!";
        console.log("yes");
    }
    if (checkLose(board)) {
        resultElement.innerHTML = "You lose";
    }
}