function searchGame() {
    let input = document.getElementById("search").value.toLowerCase();
    let games = document.querySelectorAll(".game-card");

    games.forEach(game => {
        let title = game.querySelector(".game-title").innerText.toLowerCase();
        game.style.display = title.includes(input) ? "block" : "none";
    });
}
function filterGames() {
    let filterValue = document.getElementById("filter-select").value;
    let games = document.querySelectorAll(".game-card");

    games.forEach(game => {
        let rtpText = game.querySelector(".progress-bar-text").innerText;
        let rtp = parseFloat(rtpText.replace('%', '')) || 0;

        if (filterValue === "80plus") {
            game.style.display = (rtp >= 80) ? "block" : "none";
        } else {
            game.style.display = "block";
        }
    });
}

function getRandomPercentage() {
    return Math.floor(Math.random() * 41) + 60; // Angka antara 60 - 100
}


function getRandomTime() {
    let startHour = 21;
    let startMinute = Math.floor(Math.random() * 60);
    let duration = Math.floor(Math.random() * 41) + 20; // Durasi antara 20 - 60 menit
    let endMinute = startMinute + duration;
    let endHour = startHour;
    if (endMinute >= 60) {
        endMinute -= 60;
        endHour++;
    }
    return `${startHour}:${startMinute.toString().padStart(2, '0')} WIB - ${endHour}:${endMinute.toString().padStart(2, '0')} WIB`;
}

function getRandomPola() {
    const autoValues = [10, 20, 30, 50, 70, 100];
    let rows = '';
    for (let i = 0; i < 3; i++) {
        let isAuto = Math.random() > 0.5;
        let bet = isAuto ? autoValues[Math.floor(Math.random() * autoValues.length)] : Math.floor(Math.random() * 90) + 10;
        let result1 = Math.random() > 0.5 ? 'success' : 'fail';
        let result2 = Math.random() > 0.5 ? 'success' : 'fail';
        let result3 = Math.random() > 0.5 ? 'success' : 'fail';
        rows += `<tr>
                    <td>${isAuto ? "Auto" : "Manual"} ${bet}</td>
                    <td class="pola-result"><span class="${result1}"></span></td>
                    <td class="pola-result"><span class="${result2}"></span></td>
                    <td class="pola-result"><span class="${result3}"></span></td>
                 </tr>`;
    }
    return `<table class="pola-slot-table"><tbody>${rows}</tbody></table>`;
}



function updateAllGameData() {
    let index = 0;
    let currentTime = Date.now();
    
    // Gunakan path file sebagai key unik untuk setiap halaman
    let pageKey = `game-data-${window.location.pathname}`;

    while (document.getElementById(`rtp-bar-${index}`)) {
        let storedData = JSON.parse(localStorage.getItem(`${pageKey}-${index}`));

        if (!storedData || currentTime - storedData.timestamp > 10 * 60 * 1000) {
            let randomPercentage = getRandomPercentage();
            let randomTime = getRandomTime();
            let polaData = randomPercentage < 20 ? `<div class="pola-unavailable">Pola Tidak Tersedia!!</div>
                                                   <div>Tidak Disarankan Bermain</div>
                                                   <div>Game ini</div>` : getRandomPola();

            storedData = {
                rtp: randomPercentage,
                time: randomTime,
                pola: polaData,
                timestamp: currentTime
            };
            localStorage.setItem(`${pageKey}-${index}`, JSON.stringify(storedData));
        }

        let rtpBar = document.getElementById(`rtp-bar-${index}`);
        rtpBar.style.width = `${storedData.rtp}%`;
        rtpBar.classList.remove("green", "orange", "red");

        if (storedData.rtp >= 80) {
            rtpBar.classList.add("green");
        } else if (storedData.rtp >= 21) {
            rtpBar.classList.add("orange");
        } else {
            rtpBar.classList.add("red");
        }

        document.getElementById(`rtp-text-${index}`).innerText = `${storedData.rtp}%`;
        document.getElementById(`gacor-time-${index}`).innerText = storedData.time;
        document.getElementById(`pola-slot-${index}`).innerHTML = storedData.pola;
        index++;
    }
}



function openSimulasiPopup(id) {
    document.getElementById(`popup-${id}`).style.display = 'block';
}

function closeSimulasiPopup(id) {
    document.getElementById(`popup-${id}`).style.display = 'none';
}

function runSimulasi(id) {
    let bet = parseFloat(document.getElementById(`bet-input-${id}`).value) || 0;
    let modal = parseFloat(document.getElementById(`modal-input-${id}`).value) || 0;
    let rtp = parseFloat(document.getElementById(`rtp-text-${id}`).innerText) || 0;

    // Jika RTP < 20%, munculkan SweetAlert dan hentikan proses
    if (rtp < 20) {
        Swal.fire({
            icon: "error",
            title: "TIDAK TERSEDIA!",
            text: "TIDAK TERSEDIA POLA DAN SIMULASI, CARI GAME YANG LEBIH GACOR!",
            confirmButtonColor: "#d33"
        });
        return; // Stop eksekusi lebih lanjut
    }

    // Perhitungan Probabilitas yang lebih realistis
    let polaProbability = Math.random() * 20 + 40; // 40% - 60% sebagai baseline pola
    let finalProbability = Math.min(rtp * 0.7 + polaProbability * 0.3, 100); // Kombinasi RTP & Pola

    let potentialWinning = (modal * (finalProbability / 100) * (bet / 10)).toFixed(2);

    // Peringatan jika RTP < 80%
    let warningText = rtp < 80 ? `<p class="warning-text" style="color: red !important;">DISARANKAN MENCARI PERMAINAN DENGAN RTP YANG 80% KE ATAS BOS!</p>` : "";

    // Hasil Simulasi
    document.getElementById(`simulasi-result-${id}`).innerHTML = `
        <div class="simulation-result-container">
            <p>Probabilitas Kemenangan: <span class="probability-text">${rtp.toFixed(2)}%</span></p>
            <p>Potensi Kemenangan: <span class="winning-amount-text">Rp ${potentialWinning}</span></p>

            <canvas id="simulasi-chart-${id}" width="300" height="150"></canvas>

            ${warningText}

            <p class="info-text" style="text-align: left !important;">
                Probabilitas kemenangan menunjukkan kemungkinan Anda untuk menang berdasarkan RTP dan pola yang ada.<br>
            </p>
            <p class="info-text" style="text-align: left !important;">
                Potensi kemenangan dihitung berdasarkan modal dan bet yang Anda masukkan.
            </p>

            <div class="progress-bar-container">
                <div class="progress-bar" 
                    style="width: ${rtp}%; 
                            background-color: ${rtp >= 80 ? 'green' : rtp >= 21 ? 'orange' : 'red'};">
                    ${rtp.toFixed(2)}%
                </div>
            </div>
        </div>`;

    // Grafik Canvas dengan Chart.js
    let ctx = document.getElementById(`simulasi-chart-${id}`).getContext("2d");
    new Chart(ctx, {
        type: "bar",
        data: {
            labels: ["RTP", "Pola Probability", "Final Probability"],
            datasets: [{
                label: "Persentase",
                data: [rtp, polaProbability, finalProbability],
                backgroundColor: ["green", "orange", "blue"]
            }]
        },
        options: {
            scales: {
                y: { beginAtZero: true, max: 100 }
            }
        }
    });
}




updateAllGameData();