<!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: 200px;
        }
        .box-container {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        .box {
            width: 100px;
            height: 120px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 100px;
            font-weight: bold;
            color: white;
            background-color: #007bff;
            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;
        }
        .buttons {
            margin-top: 20px;
        }
        .buttons button {
            padding: 10px 20px;
            font-size: 16px;
            font-weight: bold;
            color: white;
            background-color: #28a745;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .buttons button:disabled {
            background-color: #aaa;
            cursor: not-allowed;
        }
    </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="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 = 150;
    const UPPER_BOUND = 11800;
    let intervals = [];
    let isSpinning = false;
    let uiNum = "";

    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) {
            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 () => {
        $('#start-btn').on('click', function () {
            if (isSpinning) return;
            isSpinning = true;
            $(this).prop('disabled', true);
            $('#stop-btn').prop('disabled', false);
            $('.box').removeClass('final');
            generateRandomNum().then(() => {
                startAnimation();
            });
        });

        $('#stop-btn').on('click', function () {
            if (!isSpinning) return;
            isSpinning = false;
            $(this).prop('disabled', true);
            $('#start-btn').prop('disabled', false);
            generateRandomNum().then(() => {
                stopAnimation();
            });
        });

        $(document).on('keydown', function (event) {
            if (event.key === "ArrowRight") {
                $('#start-btn').trigger('click');
            } else if (event.key === "ArrowLeft") {
                $('#stop-btn').trigger('click');
            }
        });
    });
</script>
</body>
</html>
