library CB-UI
library CB-Render
library CB-Input
library CB-Math
library CB-Library
library CB-Library.FPS
library CB-Library.Graphics
library CB-Library.Threaded

fn main() {
    init_window(800, 480, "ClosedBit Pong")
    set_background_color(0x071018)

    i32 width = 800
    i32 height = 480
    i32 paddleH = 92
    i32 playerY = 194
    i32 cpuY = 194
    i32 ballX = 400
    i32 ballY = 240
    i32 vx = 6
    i32 vy = 4
    u256 playerScore = 0
    u256 cpuScore = 0

    while (!should_close()) {
        handle_events()

        if (is_key_down("Up") || is_key_down("W")) {
            playerY -= 7
        }
        if (is_key_down("Down") || is_key_down("S")) {
            playerY += 7
        }

        playerY = CB-Math.clamp(playerY, 24, height - 24 - paddleH)

        if (ballY > cpuY + 46) {
            cpuY += 5
        }
        if (ballY < cpuY + 46) {
            cpuY -= 5
        }
        cpuY = CB-Math.clamp(cpuY, 24, height - 24 - paddleH)

        ballX += vx
        ballY += vy

        if (ballY <= 24 || ballY >= height - 24) {
            vy = 0 - vy
        }

        if (ballX <= 66 && vx < 0 && ballY >= playerY && ballY <= playerY + paddleH) {
            vx = 6
            ballX = 66
        }

        if (ballX >= width - 66 && vx > 0 && ballY >= cpuY && ballY <= cpuY + paddleH) {
            vx = 0 - 6
            ballX = width - 66
        }

        if (ballX < 0) {
            cpuScore += 1
            ballX = width / 2
            ballY = height / 2
            vx = 6
            vy = 4
        }

        if (ballX > width) {
            playerScore += 1
            ballX = width / 2
            ballY = height / 2
            vx = 0 - 6
            vy = 4
        }

        set_background_color(0x071018)
        draw_line(width / 2, 28, width / 2, height - 28, 0x28606A, 2)
        draw_rect(40, playerY, 16, paddleH, 0xCEE55C)
        draw_rect(width - 56, cpuY, 16, paddleH, 0xFF6B5B)
        draw_circle(ballX - 12, ballY - 12, 24, 0xF8FAF0)
        draw_text(28, 22, "Player", 0xCEE55C, 18)
        draw_text(width - 122, 22, "CPU", 0xFF6B5B, 18)
        draw_text(330, 22, "PONG", 0xF8FAF0, 22)
        swap_buffers_fast()
    }

    cleanup()
}
