const elemTimer = document.querySelector<HTMLParagraphElement>('p.layout-timer')!
const elemCheck = document.querySelector<HTMLButtonElement>('a#action-send')!
const soundSet = document.querySelector<HTMLAudioElement>('audio#audio-set')!
const soundDel = document.querySelector<HTMLAudioElement>('audio#audio-del')!
let secondsElapsed = 0

function timestamp() {
    const f = (s: number) => s.toString().padStart(2, '0')
    const h = Math.floor(secondsElapsed / 3600)
    const m = Math.floor((secondsElapsed % 3600) / 60)
    const s = Math.floor(secondsElapsed % 60)
    return `Time Spent: ${f(h)}:${f(m)}:${f(s)}`
}

setInterval(() => {
    secondsElapsed++
    elemTimer.textContent = timestamp()
}, 1000)

document.querySelector<HTMLDivElement>('div.layout-content')!.addEventListener(
    // Prevent annoying context menu popup whenever you miss a grid tile by 1 pixel
    'contextmenu',
    (e) => e.preventDefault(),
)

document.querySelectorAll('button.picross-button').forEach((e) => {
    // Initialize Buttons
    e.addEventListener('click', () => {
        e.classList.remove('state-ignore')
        e.classList.toggle('state-active') ? soundSet.play() : soundDel.play()
    })
    e.addEventListener('contextmenu', (ev) => {
        ev.preventDefault()
        e.classList.remove('state-active')
        e.classList.toggle('state-ignore')
        soundDel.play()
    })
})

elemCheck.addEventListener('click', () => {
    // Calculate Answer
    let given = 0
    const rows = document.querySelectorAll<HTMLDivElement>('div.picross-row')

    rows.forEach((childRow, rowIndex) => {
        let childIndex = 0
        for (const child of childRow.children) {
            if (child.nodeName === 'BUTTON') {
                if (child.classList.contains('state-active')) {
                    given += 1 << ((rowIndex - 3) * 9 + childIndex)
                }
                childIndex++
            }
        }
    })

    if (given !== 2560660350) {
        alert('Nope! Try Again')
        return
    }

    // Render Certificate
    const time = timestamp()
    const name = prompt('Congratulations you won! Please enter the name for your certificate:', 'Anon')

    document.querySelector<HTMLDivElement>('div.layout-document')!.style.display = 'block'
    document.querySelector<HTMLSpanElement>('span#date')!.textContent = new Date().toDateString()
    document.querySelector<HTMLSpanElement>('span#time')!.textContent = time
    document.querySelector<HTMLSpanElement>('span#name')!.textContent = name
    print()
    document.location.assign('/')
})
