async function computeProof(challenge, difficulty) {
    let nonce = 0;
    const leadingZeros = '0'.repeat(difficulty);

    while (true) {
        const candidate = `${challenge}:${nonce}`;
        const hash = new TextEncoder().encode(candidate);
        const hashArrayBuffer = await crypto.subtle.digest('SHA-256', hash);
        const hashHex = Array.from(new Uint8Array(hashArrayBuffer))
            .map(b => b.toString(16).padStart(2, '0'))
            .join('');

        if (hashHex.startsWith(leadingZeros)) {
            return nonce;
        }
        nonce++;
        await new Promise(resolve => setTimeout(resolve, 0));  // Yield control to avoid freezing the UI
    }
}

function startPow() {
    const element = document.querySelector('#start-pow');
    element.addEventListener('click', async () => {
        const difficulty = parseInt(element.getAttribute('data-pow-d'), 10);
        const challenge = element.getAttribute('data-pow-c');
        const id = element.getAttribute('data-pow');

        const spinner = document.querySelector('#pow-spinner');
        spinner.classList.remove('hidden');
        element.classList.remove('bg-blue-900');
        element.classList.add('bg-gray-700');
        const text = document.querySelector('#pow-text');
        text.innerText = 'Computing...';

        try {
            const nonce = await computeProof(challenge, difficulty);

            spinner.classList.add('hidden');

            const url = `/api/g/pow/verify/${id}/${nonce}`;
            const response = await fetch(url);
            const data = await response.json();

            if (data.valid) {
                element.classList.remove('bg-gray-700');
                element.classList.remove('cursor-pointer');
                element.classList.add('bg-lime-700');
                element.classList.add('disabled');
                text.innerText = '✅ Verified!';

                // Show submit button
                const submit = document.querySelector('#submit-btn');
                submit.classList.remove('hidden');

                // Set pow-nonce form input value to nonce
                const nonceInput = document.querySelector('#pow-nonce');
                nonceInput.value = nonce;
            } else {
                element.classList.remove('bg-gray-700');
                element.classList.add('bg-red-700');
                text.innerText = '❌ Failed!';
            }
        } catch (error) {
            console.error('Error:', error);
            spinner.classList.add('hidden');
            text.innerText = 'An error occurred!';
        }
    });
}
