const soundActive = document.querySelector<HTMLAudioElement>('audio#active')!
const soundBounce = document.querySelector<HTMLAudioElement>('audio#bounce')!
const canvas = document.querySelector<HTMLCanvasElement>('canvas#sprites')!

if (canvas && soundActive && soundBounce) {
    const C = {
        TEXTURE_WIDTH: 68,
        TEXTURE_HEIGHT: 78,
        TEXTURE_SCALE: 0.5,
        RENDER_WIDTH: 256,
        RENDER_HEIGHT: 256,
        GRAVITY: 0.67,
        BOUNCE: 0.75,
        JUMP: 8,
        COUNT: 3,
    }
    const TEXTURE = new Image()
    const SPRITES = new Array()
    const OFFSET = (C.RENDER_WIDTH - C.COUNT * (C.TEXTURE_WIDTH * C.TEXTURE_SCALE)) / C.COUNT

    for (let i = 0; i < C.COUNT; i++) {
        SPRITES.push({
            x: OFFSET / 2 + OFFSET * i + C.TEXTURE_WIDTH * C.TEXTURE_SCALE * i,
            v: 0,
            y: 0,
        })
    }

    const ctx = canvas.getContext('2d')!
    TEXTURE.src = document.querySelector<HTMLLinkElement>('link[rel=texture')!.href
    canvas.style.imageRendering = 'pixelated'
    canvas.style.width = `${C.RENDER_WIDTH}px`
    canvas.style.height = `${C.RENDER_HEIGHT}px`
    canvas.width = C.RENDER_WIDTH
    canvas.height = C.RENDER_HEIGHT
    soundBounce.playbackRate = 2
    soundBounce.volume = 0.5

    canvas.addEventListener('click', () => {
        for (let i = 0; i < C.COUNT; i++) {
            SPRITES[i].v += C.JUMP + Math.random() * (C.JUMP / 2)
        }
    })

    setInterval(() => {
        ctx.clearRect(0, 0, C.RENDER_WIDTH, C.RENDER_HEIGHT)
        for (let i = 0; i < SPRITES.length; i++) {
            let oy = C.RENDER_HEIGHT - C.TEXTURE_HEIGHT * C.TEXTURE_SCALE
            let s = SPRITES[i]
            s.v -= C.GRAVITY
            s.y += s.v

            if (s.y < 0) {
                s.y = 0
                s.v = -s.v * C.BOUNCE
                if (Math.abs(s.v) < 0.8) {
                    s.v = 0
                } else {
                    soundBounce.currentTime = 0
                    soundBounce.play()
                }
            }

            ctx.drawImage(TEXTURE, s.x, oy - s.y, C.TEXTURE_WIDTH * C.TEXTURE_SCALE, C.TEXTURE_HEIGHT * C.TEXTURE_SCALE)
        }
    }, 1000 / 60)
}
