import { Game } from '../modules/game.js';

document.addEventListener('DOMContentLoaded', () => {
    const gameBoard = document.getElementById('game-board');
    const scoreDisplay = document.getElementById('score');
    let gridSize = 4;
    let board = [];
    let score = 0;
    let touchStartX = 0, touchStartY = 0, touchEndX = 0, touchEndY = 0;

    function initializeBoard() {
        gameBoard.innerHTML = '';
        for (let i = 0; i < gridSize * gridSize; i++) {
            const tile = document.createElement('div');
            tile.className = 'tile';
            gameBoard.appendChild(tile);
        }
        board = Array(gridSize * gridSize).fill(0);
        addNumber(); addNumber(); updateBoard();
    }

    function updateBoard() {
        const tiles = gameBoard.children;
        for (let i = 0; i < board.length; i++) {
            const val = board[i];
            tiles[i].textContent = val === 0 ? '' : val;
            tiles[i].className = 'tile' + (val > 0 ? ' tile-' + val : '');
        }
        scoreDisplay.textContent = score;
    }

    function addNumber() {
        const available = board.map((v, i) => v === 0 ? i : -1).filter(i => i !== -1);
        if (available.length > 0) {
            board[available[Math.floor(Math.random() * available.length)]] = Math.random() < 0.9 ? 2 : 4;
        }
    }

    function moveRow(row) {
        let arr = row.filter(v => v);
        for (let i = 0; i < arr.length - 1; i++) {
            if (arr[i] === arr[i+1]) { arr[i] *= 2; score += arr[i]; arr[i+1] = 0; }
        }
        arr = arr.filter(v => v);
        return arr.concat(Array(gridSize - arr.length).fill(0));
    }

    function move(dir) {
        let changed = false;
        if (dir === 'left' || dir === 'right') {
            for (let i = 0; i < gridSize; i++) {
                const start = i * gridSize;
                let row = board.slice(start, start + gridSize);
                if (dir === 'right') row.reverse();
                let newRow = moveRow(row);
                if (dir === 'right') newRow.reverse();
                if (JSON.stringify(board.slice(start, start + gridSize)) !== JSON.stringify(newRow)) changed = true;
                board.splice(start, gridSize, ...newRow);
            }
        } else { // up, down
            for (let i = 0; i < gridSize; i++) {
                let col = [board[i], board[i+4], board[i+8], board[i+12]];
                if (dir === 'down') col.reverse();
                let newCol = moveRow(col);
                if (dir === 'down') newCol.reverse();
                if (JSON.stringify([board[i], board[i+4], board[i+8], board[i+12]]) !== JSON.stringify(newCol)) changed = true;
                for (let j = 0; j < 4; j++) board[i + j*4] = newCol[j];
            }
        }
        return changed;
    }

    function handleMove(dir) {
        if (move(dir)) {
            addNumber(); updateBoard();
            if (isGameOver()) {
                Game.showSuccessModal({
                    gameType: 'GAME_2048', contextId: null,
                    successMessage: `최종 점수 ${score}점!`, primaryScore: score
                });
            }
        }
    }

    function isGameOver() {
        if (!board.includes(0)) {
            for (let i=0; i<gridSize; i++) {
                for (let j=0; j<gridSize; j++) {
                    let c = board[i*4+j];
                    if ((j<3 && c===board[i*4+j+1]) || (i<3 && c===board[(i+1)*4+j])) return false;
                }
            }
            return true;
        }
        return false;
    }

    document.addEventListener('keydown', e => {
        const map = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
        if (map[e.key]) handleMove(map[e.key]);
    });

    gameBoard.addEventListener('touchstart', e => { touchStartX = e.changedTouches[0].screenX; touchStartY = e.changedTouches[0].screenY; });
    gameBoard.addEventListener('touchmove', e => e.preventDefault(), { passive: false });
    gameBoard.addEventListener('touchend', e => {
        let dx = e.changedTouches[0].screenX - touchStartX;
        let dy = e.changedTouches[0].screenY - touchStartY;
        if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 30) handleMove(dx > 0 ? 'right' : 'left');
        else if (Math.abs(dy) > 30) handleMove(dy > 0 ? 'down' : 'up');
    });

    initializeBoard();
});