<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>U & I - Lucky Draw</title>
    <style>
        @font-face {
            font-family: 'digital-7';
            src: url('asset/digital-7.ttf') format('woff');
        }
        body {
            font-family: digital-7;
            text-align: center;
            background-color: #000;
            margin: 0;
            padding: 0;
        }
        .container {
            margin-top: -50px;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
        .box-container {
            margin: auto;
            display: flex;
            justify-content: center;
            gap: 20px;
        }
        .box {
            width: 200px;
            height: 240px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 200px;
            font-weight: bold;
            color: white;
            background-color: #E11167;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, background-color 0.3s ease;
        }
        .box.final {
            background-color: #28a745;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="box-container">
        <div class="box" id="box1">0</div>
        <div class="box" id="box2">0</div>
        <div class="box" id="box3">0</div>
        <div class="box" id="box4">0</div>
        <div class="box" id="box5">0</div>
    </div>
    <div class="buttons">
<!--        <button id="toggle-btn">Start</button>-->
        <!--<button id="start-btn">Start</button>
        <button id="stop-btn" disabled>Stop</button>-->
    </div>
</div>

<script src="asset/jquery-3.6.0.min.js"></script>
<script>
    const REVEAL_DELAY = 1500;
    const UPPER_BOUND = 11800;
    const START_STOP_DELAY = 1000;
    let intervals = [];
    let isSpinning = false;
    let uiNum = "";
    let canPressStart = true;

    async function generateRandomNum() {
        uiNum = generateRandomNumber().toString().padStart(5, '0');
        try {
            const timestamp = new Date().getTime();
            const response = await $.getJSON(`conf/config.json?t=${timestamp}`);
            console.log('resp: ' + response['uiNum']);
            uiNum = response.uiNum ? response.uiNum.toString().padStart(5, '0') : uiNum;
        } catch (error) {
            console.error('Error loading config.json:', error);
        }
    }

    function generateRandomNumber() {
        return Math.floor(Math.random() * UPPER_BOUND) + 1;
    }

    function startAnimation() {
        intervals = $('.box').map(function (index, box) {
            $(box).removeClass('final');
            let speed = 100; //(- index * 50);
            return setInterval(() => {
                $(box).text(Math.floor(Math.random() * 10));
            }, speed);
        }).get();
    }

    function stopAnimation() {
        const digits = uiNum.split('');
        const order = [0, 1, 2, 3, 4].sort(() => Math.random() - 0.5);
        order.forEach((index, delayIndex) => {
            setTimeout(() => {
                clearInterval(intervals[index]);
                $(`.box:eq(${index})`).text(digits[index]).addClass('final');
            }, delayIndex * REVEAL_DELAY);
        });
        resetConfig();
    }

    function resetConfig() {
        $.get('api/resetConfig.php', function (response) {
            response = JSON.parse(response);
            console.log('Config updated successfully!');
            console.log('Updated ui Number:', response.uiNum);
        }).fail(function (error) {
            console.error('Error updating config:', error.responseText);
        });
    }

    $(document).ready(async () => {
        $(document).on('keydown', async function (event) {

            if (event.key === "PageUp") {
                if (!canPressStart) return; // If we can't press start, do nothing

                canPressStart = false;

                // Start the spinning process
                if (!isSpinning) {
                    setTimeout(() => {
                        canPressStart = true;
                    }, START_STOP_DELAY);

                    isSpinning = true;
                    await generateRandomNum();
                    startAnimation();
                } else {
                    setTimeout(() => {
                        canPressStart = true;
                    }, 6 * REVEAL_DELAY);

                    // Stop the spinning process if already started
                    await generateRandomNum(); // Fetch or generate the number before stopping
                    stopAnimation();
                    isSpinning = false;
                    canPressStart = false;
                }
            } else if (event.keyCode === 116) {
                event.preventDefault();
            }
        });
    });

</script>
</body>
</html>
