import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

Item {
    id: window
    width: 700
    height: 760

    property int columns: 10
    property int rows: 20
    property int cell: Math.max(22, Math.min(30, Math.floor((height - 80) / rows)))
    property var board: []
    property int score: 0
    property int lines: 0
    property int level: 1
    property bool running: true
    property bool gameOver: false
    property int pieceId: 0
    property var piece: []
    property int pieceX: 3
    property int pieceY: 0
    property int nextPiece: 0
    property color emptyCellColor: "#EDF1F5"
    property var colors: ["#00d9e7", "#3b82f6", "#f59e0b", "#f6d743", "#22c55e", "#a855f7", "#ef476f"]
    // Each tetromino is encoded as x, y pairs around a small local origin.
    property var shapes: [
        [0,1, 1,1, 2,1, 3,1], // I
        [0,0, 0,1, 1,1, 2,1], // J
        [2,0, 0,1, 1,1, 2,1], // L
        [0,0, 1,0, 0,1, 1,1], // O
        [1,0, 2,0, 0,1, 1,1], // S
        [1,0, 0,1, 1,1, 2,1], // T
        [0,0, 1,0, 1,1, 2,1]  // Z
    ]

    // The main menu calls this after the Loader creates the component.
    // Keyboard events belong to the playing field, not this outer Item.
    function activate() {
        game.forceActiveFocus()
    }

    function emptyBoard() {
        var cells = []
        for (var i = 0; i < columns * rows; ++i) cells.push(-1)
        return cells
    }

    function randomPiece() { return Math.floor(Math.random() * shapes.length) }

    function copyShape(id) { return shapes[id].slice(0) }

    function fits(testShape, x, y) {
        for (var i = 0; i < testShape.length; i += 2) {
            var bx = x + testShape[i]
            var by = y + testShape[i + 1]
            if (bx < 0 || bx >= columns || by >= rows) return false
            if (by >= 0 && board[by * columns + bx] !== -1) return false
        }
        return true
    }

    function spawn() {
        pieceId = nextPiece
        piece = copyShape(pieceId)
        nextPiece = randomPiece()
        pieceX = 3
        pieceY = 0
        if (!fits(piece, pieceX, pieceY)) {
            gameOver = true
            running = false
        }
    }

    function isPieceCell(x, y) {
        for (var i = 0; i < piece.length; i += 2)
            if (pieceX + piece[i] === x && pieceY + piece[i + 1] === y) return true
        return false
    }

    function cellColor(x, y) {
        if (!gameOver && isPieceCell(x, y)) return colors[pieceId]
        var value = board[y * columns + x]
        return value === -1 ? emptyCellColor : colors[value]
    }

    function move(dx) {
        if (running && fits(piece, pieceX + dx, pieceY)) {
            pieceX += dx
            board = board.slice(0) // refresh bindings
        }
    }

    function rotate() {
        if (!running || pieceId === 3) return
        var rotated = []
        var minX = 99, minY = 99
        for (var i = 0; i < piece.length; i += 2) {
            var x = -piece[i + 1]
            var y = piece[i]
            rotated.push(x, y)
            minX = Math.min(minX, x)
            minY = Math.min(minY, y)
        }
        for (var j = 0; j < rotated.length; j += 2) {
            rotated[j] -= minX
            rotated[j + 1] -= minY
        }
        // A small wall kick keeps rotations usable beside the edges.
        var kicks = [0, -1, 1, -2, 2]
        for (var k = 0; k < kicks.length; ++k) {
            if (fits(rotated, pieceX + kicks[k], pieceY)) {
                piece = rotated
                pieceX += kicks[k]
                board = board.slice(0)
                return
            }
        }
    }

    function clearLines() {
        var kept = []
        var cleared = 0
        for (var y = rows - 1; y >= 0; --y) {
            var full = true
            for (var x = 0; x < columns; ++x)
                if (board[y * columns + x] === -1) { full = false; break }
            if (full) cleared++
            else {
                // Add a whole row at once: unshifting individual cells reverses it.
                var row = []
                for (var c = 0; c < columns; ++c) row.push(board[y * columns + c])
                kept = row.concat(kept)
            }
        }
        while (kept.length < rows * columns) {
            var emptyRow = []
            for (var n = 0; n < columns; ++n) emptyRow.push(-1)
            kept = emptyRow.concat(kept)
        }
        if (cleared > 0) {
            var awards = [0, 100, 300, 500, 800]
            score += awards[cleared] * level
            lines += cleared
            level = Math.floor(lines / 10) + 1
        }
        board = kept
    }

    function lockPiece() {
        var next = board.slice(0)
        for (var i = 0; i < piece.length; i += 2) {
            var x = pieceX + piece[i]
            var y = pieceY + piece[i + 1]
            if (y >= 0) next[y * columns + x] = pieceId
        }
        board = next
        clearLines()
        spawn()
    }

    function step() {
        if (!running) return
        if (fits(piece, pieceX, pieceY + 1)) {
            pieceY++
            board = board.slice(0)
        } else lockPiece()
    }

    function hardDrop() {
        if (!running) return
        var distance = 0
        while (fits(piece, pieceX, pieceY + 1)) { pieceY++; distance++ }
        score += distance * 2
        lockPiece()
    }

    function togglePause() {
        if (!gameOver) {
            running = !running
            game.forceActiveFocus()
        }
    }

    function restart() {
        board = emptyBoard()
        score = 0
        lines = 0
        level = 1
        gameOver = false
        running = true
        nextPiece = randomPiece()
        spawn()
        game.forceActiveFocus()
    }

    Timer {
        interval: Math.max(100, 760 - (level - 1) * 65)
        repeat: true
        running: window.running
        onTriggered: window.step()
    }

    Component.onCompleted: restart()

    Rectangle {
        anchors.fill: parent
        color: "#E7ECF2"
        z: -1
    }

    RowLayout {
        anchors.centerIn: parent
        spacing: 30

        Item {
            id: game
            Layout.preferredWidth: columns * cell + 12
            Layout.preferredHeight: rows * cell + 12
            focus: true

            Keys.onPressed: function(event) {
                if (event.key === Qt.Key_Left || event.key === Qt.Key_A) move(-1)
                else if (event.key === Qt.Key_Right || event.key === Qt.Key_D) move(1)
                else if (event.key === Qt.Key_Down || event.key === Qt.Key_S) step()
                else if (event.key === Qt.Key_Up || event.key === Qt.Key_W) rotate()
                else if (event.key === Qt.Key_Space) hardDrop()
                else if (event.key === Qt.Key_P) togglePause()
                else if (event.key === Qt.Key_R) restart()
                else return
                event.accepted = true
            }

            Rectangle {
                anchors.fill: parent
                color: "#FFFFFF"
                border.color: "#788797"
                border.width: 2
                radius: 5
            }

            Grid {
                anchors.centerIn: parent
                columns: window.columns
                spacing: 1
                Repeater {
                    model: window.columns * window.rows
                    delegate: Rectangle {
                        required property int index
                        width: cell - 1
                        height: cell - 1
                        radius: 2
                        color: window.cellColor(index % columns, Math.floor(index / columns))
                        border.width: color === window.emptyCellColor ? 0 : 1
                        border.color: Qt.darker(color, 1.18)
                        Behavior on color { ColorAnimation { duration: 65 } }
                    }
                }
            }

            Rectangle {
                anchors.fill: parent
                visible: gameOver || !running
                color: "#FFFFFF"
                opacity: 0.92
                radius: 5
                Column {
                    anchors.centerIn: parent
                    spacing: 12
                    Label {
                        renderType: Text.NativeRendering
                        anchors.horizontalCenter: parent.horizontalCenter
                        text: gameOver ? "Игра окончена" : "Пауза"
                        color: "#111827"
                        font.pixelSize: 27
                        font.bold: true
                    }
                    BeautifulButton {
                        anchors.horizontalCenter: parent.horizontalCenter
                        lightTheme: true
                        text: gameOver ? "Новая игра" : "Продолжить"
                        onClicked: gameOver ? restart() : running = true
                    }
                }
            }
        }

        ColumnLayout {
            Layout.alignment: Qt.AlignTop
            spacing: 16
            Label { renderType: Text.NativeRendering; text: "ТЕТРИС"; color: "#111827"; font.pixelSize: 32; font.bold: true }
            Label { renderType: Text.NativeRendering; text: "Счёт  " + score; color: "#1F2D3D"; font.pixelSize: 19 }
            Label { renderType: Text.NativeRendering; text: "Линии  " + lines; color: "#1F2D3D"; font.pixelSize: 19 }
            Label { renderType: Text.NativeRendering; text: "Уровень  " + level; color: "#1F2D3D"; font.pixelSize: 19 }
            Label { renderType: Text.NativeRendering; text: "Следующая"; color: "#405164"; font.pixelSize: 15 }
            Item {
                Layout.preferredWidth: 130
                Layout.preferredHeight: 105
                Grid {
                    anchors.centerIn: parent
                    columns: 4
                    Repeater {
                        model: 16
                        delegate: Rectangle {
                            required property int index
                            width: 22; height: 22; radius: 3
                            property int px: index % 4
                            property int py: Math.floor(index / 4)
                            property bool filled: nextPiece >= 0 && shapes[nextPiece].some(function(v, i) {
                                return i % 2 === 0 && v === px && shapes[nextPiece][i + 1] === py
                            })
                            color: filled ? colors[nextPiece] : window.emptyCellColor
                            border.color: filled ? Qt.darker(color, 1.18) : color
                        }
                    }
                }
            }
            Rectangle { Layout.fillWidth: true; height: 1; color: "#D5DEE8" }
            Label { renderType: Text.NativeRendering; text: "Стрелки или A, D — движение\nСтрелка вверх или W — поворот\nСтрелка вниз или S — ускорение\nПробел — мгновенный сброс\nP — пауза\nR — новая игра"; color: "#405164"; font.pixelSize: 13; lineHeight: 1.3 }
            BeautifulButton {
                lightTheme: true
                text: running ? "Пауза" : "Продолжить"
                enabled: !gameOver
                onClicked: togglePause()
            }
            BeautifulButton {
                lightTheme: true
                text: "Новая игра"
                onClicked: restart()
            }
        }
    }
}
