const games = [
    { name: "Hot Hot Fruit", image: "1.webp", rtp: 96 },
    { name: "Koi Gate", image: "2.webp", rtp: 95 },
    { name: "Laughing Buddha", image: "3.webp", rtp: 89 },
    { name: "5 Lucky Lions", image: "4.webp", rtp: 97 },
    { name: "Hey Sushi", image: "5.webp", rtp: 92 },
    { name: "TLantern Luck", image: "6.webp", rtp: 91 },
    { name: "Orbs of Atlantis", image: "7.webp", rtp: 65 },
    { name: "Fa Cai Shen", image: "8.webp", rtp: 68 },
    { name: "Wealth Inn", image: "9.webp", rtp: 88 },
    { name: "Fa Cai Shen Deluxe", image: "10.webp", rtp: 92 },
    { name: "Legendary Beasts", image: "11.webp", rtp: 90 },
    { name: "Super Fruit Blast", image: "12.webp", rtp: 67 },
    { name: "Pumpkin Patch", image: "13.webp", rtp: 79 },
    { name: "Lucky Lucky", image: "14.webp", rtp: 97 },
    { name: "Shamrock Quest", image: "15.webp", rtp: 92 },
    { name: "Koi Koi Treasures", image: "16.webp", rtp: 93 },
    { name: "Naughty Santa", image: "17.webp", rtp: 85 },
    { name: "Disco Beats", image: "18.webp", rtp: 90 },
    { name: "Jump!", image: "19.webp", rtp: 82 },
    { name: "Hot Hot Summer", image: "20.webp", rtp: 92 },
    { name: "Tuk Tuk Thailand", image: "21.webp", rtp: 84 },
    { name: "Japanese Mask", image: "22.webp", rtp: 90 },
    { name: "Carnival Cove", image: "23.webp", rtp: 66 },
    { name: "Hot Hot Halloween", image: "24.webp", rtp: 94 },
    { name: "Nuwa", image: "25.webp", rtp: 82 },
    { name: "Taberna De Los Muretos", image: "26.webp", rtp: 66 },
    { name: "Glory of Rome", image: "27.webp", rtp: 84 },
    { name: "Bomb Runner", image: "28.webp", rtp: 75 },
    { name: "Knockout Football Rush", image: "29.webp", rtp: 83 },
    { name: "Baba Yaga", image: "30.webp", rtp: 65 },
    { name: "Fortune Dogs", image: "31.webp", rtp: 76 },
    { name: "Naugthy Wukong", image: "32.webp", rtp: 68 },
    { name: "Lucky Durian", image: "33.webp", rtp: 69 },
    { name: "Siren's Spell", image: "34.webp", rtp: 71 },
    { name: "Atomic Kittens", image: "35.webp", rtp: 65 },
    { name: "Zeus Deluxe", image: "36.webp", rtp: 70 },
    { name: "Scopa", image: "37.webp", rtp: 73 },
    { name: "Santas Village", image: "38.webp", rtp: 87 },
    { name: "Calaveras Explosivas", image: "39.webp", rtp: 72 },
    { name: "Waltz Beauty", image: "40.webp", rtp: 70 },
    { name: "Soju Bomb", image: "41.webp", rtp: 69 },
    { name: "Dragon Castle", image: "42.webp", rtp: 94 },
    { name: "Haunted Harbor", image: "43.webp", rtp: 68 },
    { name: "Taiko Beats", image: "44.webp", rtp: 67 },
    { name: "Crystopia", image: "45.webp", rtp: 92 },
    { name: "Return To The Feature", image: "46.webp", rtp: 97 },
    { name: "Moo Moo Cow", image: "47.webp", rtp: 90 },
    { name: "Fire Rooster", image: "48.webp", rtp: 76 },
    { name: "Dragon's Realm", image: "49.webp", rtp: 88 },
    { name: "Fruity Halloween", image: "50.webp", rtp: 88 }
];

// ===== UTILITY FUNCTIONS =====
const getColor = (rtp) => {
    if (rtp >= 90) return "#2ecc71"; // hijau untuk RTP tinggi
    if (rtp >= 80) return "#f1c40f"; // kuning untuk RTP sedang
    if (rtp >= 70) return "#e67e22"; // oranye untuk RTP rendah
    return "#e74c3c"; // merah untuk RTP sangat rendah
};

const generateJamGacor = () => {
    const startHour = Math.floor(Math.random() * 22);
    const endHour = startHour + 2;
    const format = (h) => String(h).padStart(2, "0") + ":00";
    return `${format(startHour)} - ${format(endHour)}`;
};

// ===== DOM ELEMENTS =====
const gameGrid = document.getElementById("gameGrid");
const searchInput = document.getElementById("searchGame");
const btnSemua = document.getElementById("btnSemua");
const btnPopuler = document.getElementById("btnPopuler");
const btnWinrate = document.getElementById("btnWinrate");
const hamburger = document.getElementById('hamburger');
const navMenu = document.getElementById('navMenu');
const closeBtn = document.getElementById('closeBtn');
const darkToggle = document.getElementById('darkModeToggle');
const scrollBtn = document.getElementById("scrollToTopBtn");

// ===== GAME RENDERING =====
function renderGames(gameList) {
    gameGrid.innerHTML = "";
    
    if (gameList.length === 0) {
        gameGrid.innerHTML = `
            <div class="no-games-found">
                <i class="fas fa-search"></i>
                <h3>Game tidak ditemukan</h3>
                <p>Coba kata kunci lain atau filter berbeda</p>
            </div>
        `;
        return;
    }

    gameList.forEach((game, index) => {
        const card = document.createElement("div");
        card.className = "game-card fade-in";
        
        const jamGacor = generateJamGacor();

        card.innerHTML = `
            <div class="game-image-wrapper">
                <img src="assets/${game.image}" alt="${game.name}" class="game-image" onerror="this.src='https://via.placeholder.com/300x180/1a2540/ffffff?text=Game+Image'">
                <a href="https://wk168.pro/sgk" class="play-btn">
                    <i class="fas fa-play"></i>
                    MAIN SEKARANG
                </a>
            </div>
            <div class="game-content">
                <h3 class="game-title">${game.name}</h3>
                <div class="game-info">
                    <span class="game-provider">${game.provider || 'Habanero'}</span>
                    <span class="rtp-badge">RTP ${game.rtp}%</span>
                </div>
                <div class="rtp-bar">
                    <div class="rtp-bar-fill" style="width: ${game.rtp}%; background-color: ${getColor(game.rtp)}">
                        <div class="warp-bg"></div>
                        <span class="rtp-value">${game.rtp}%</span>
                    </div>
                </div>
                <div class="jam-gacor-slot">
                    <i class="fas fa-clock"></i>
                    JAM GACOR: <strong>${jamGacor}</strong>
                </div>
            </div>
        `;

        gameGrid.appendChild(card);
    });
}

function getRTPClass(rtp) {
    if (rtp >= 95) return 'high-rtp';
    if (rtp >= 90) return 'medium-rtp';
    return 'low-rtp';
  }

// ===== FILTER FUNCTIONS =====
btnSemua.addEventListener('click', () => {
    setActiveFilter(btnSemua);
    const shuffledGames = [...games].sort(() => 0.5 - Math.random()).slice(0, 50);
    renderGames(shuffledGames);
});

btnPopuler.addEventListener('click', () => {
    setActiveFilter(btnPopuler);
    const populerGames = games.filter(g => 
        /Olympus|Mahjong|Princess|Bonanza|Fortune|Dragon|Tiger/i.test(g.name)
    );
    renderGames(populerGames);
});

btnWinrate.addEventListener('click', () => {
    setActiveFilter(btnWinrate);
    const highWinrate = games.filter(g => g.rtp >= 90);
    renderGames(highWinrate);
});

searchInput.addEventListener("input", (e) => {
    const keyword = e.target.value.toLowerCase();
    const result = games.filter(g => 
        g.name.toLowerCase().includes(keyword) || 
        (g.provider && g.provider.toLowerCase().includes(keyword))
    );
    renderGames(result);
});

function setActiveFilter(activeBtn) {
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    activeBtn.classList.add('active');
}

// ===== RTP UPDATE SYSTEM =====
function animateRTPValue(start, end, duration, onUpdate) {
    const startTime = performance.now();

    function animate(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        const currentValue = Math.round(start + (end - start) * progress);
        onUpdate(currentValue);

        if (progress < 1) {
            requestAnimationFrame(animate);
        }
    }

    requestAnimationFrame(animate);
}

function updateRTP() {
    const bars = document.querySelectorAll(".rtp-bar-fill");
    const values = document.querySelectorAll(".rtp-value");

    bars.forEach((bar, i) => {
        const text = values[i];
        const current = parseInt(text.textContent.replace('%', '')) || 0;
        const newRtp = Math.floor(Math.random() * (98 - 65 + 1)) + 65;

        animateRTPValue(current, newRtp, 1000, (val) => {
            text.textContent = val + "%";
            bar.style.width = val + "%";
            bar.style.backgroundColor = getColor(val);
            
            // Update RTP badge juga
            const gameCard = bar.closest('.game-card');
            if (gameCard) {
                const rtpBadge = gameCard.querySelector('.rtp-badge');
                if (rtpBadge) {
                    rtpBadge.textContent = `RTP ${val}%`;
                }
            }
        });
    });
}

// ===== NAVIGATION & UI CONTROLS =====
hamburger.addEventListener('click', () => {
    navMenu.classList.add('active');
    hamburger.classList.add('active');
    document.body.style.overflow = 'hidden';
});

closeBtn.addEventListener('click', () => {
    navMenu.classList.remove('active');
    hamburger.classList.remove('active');
    document.body.style.overflow = '';
});

// Dark mode toggle
darkToggle.addEventListener('change', () => {
    document.body.setAttribute('data-theme', darkToggle.checked ? 'dark' : 'light');
    localStorage.setItem('theme', darkToggle.checked ? 'dark' : 'light');
});

// Scroll to top
window.addEventListener("scroll", () => {
    if (window.scrollY > 200) {
        scrollBtn.classList.add('show');
    } else {
        scrollBtn.classList.remove('show');
    }
});

scrollBtn.addEventListener("click", () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
});

// ===== DATE & TIME UPDATES =====
function updateDateTime() {
    const hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];
    const bulan = [
        "Januari", "Februari", "Maret", "April", "Mei", "Juni",
        "Juli", "Agustus", "September", "Oktober", "November", "Desember"
    ];

    const now = new Date();
    const tanggal = `${hari[now.getDay()]}, ${now.getDate()} ${bulan[now.getMonth()]} ${now.getFullYear()}`;
    const waktu = now.toLocaleTimeString("id-ID", { 
        hour: "2-digit", 
        minute: "2-digit", 
        second: "2-digit" 
    });
    
    const rtpEl = document.getElementById("rtpTanggal");
    if (rtpEl) rtpEl.textContent = `Update RTP: ${tanggal} | ${waktu}`;
}

// ===== PARTICLE BACKGROUND =====
function createParticles() {
    const particlesContainer = document.getElementById('particles');
    const particleCount = 50;

    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // Random position
        particle.style.left = Math.random() * 100 + 'vw';
        particle.style.top = Math.random() * 100 + 'vh';
        
        // Random size
        const size = Math.random() * 3 + 1;
        particle.style.width = size + 'px';
        particle.style.height = size + 'px';
        
        // Random animation delay and duration
        particle.style.animationDelay = Math.random() * 6 + 's';
        particle.style.animationDuration = (Math.random() * 10 + 10) + 's';
        
        particlesContainer.appendChild(particle);
    }
}

// ===== FLOATING PLAYER COUNTER =====
class FloatingPlayerCounter {
    constructor() {
        this.minPlayers = 500;
        this.maxPlayers = 2500;
        this.currentPlayers = 0;
        this.updateInterval = null;
        this.isInitialized = false;
    }

    init() {
        if (this.isInitialized) return;
        
        this.currentPlayers = this.generatePlayerCount();
        this.updateDisplay();
        this.startAutoUpdate();
        this.isInitialized = true;
        
        // Close button functionality
        const closeBtn = document.getElementById('floatingClose');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                this.hideCounter();
            });
        }
    }

    generatePlayerCount() {
        const baseCount = Math.floor(Math.random() * (this.maxPlayers - this.minPlayers)) + this.minPlayers;
        const now = new Date();
        const hour = now.getHours();
        
        let timeMultiplier = 1;
        if (hour >= 18 || hour <= 6) {
            timeMultiplier = 1.3; // Peak hours
        } else if (hour >= 12 && hour <= 14) {
            timeMultiplier = 1.1; // Lunch time
        }
        
        return Math.floor(baseCount * timeMultiplier);
    }

    updateDisplay() {
        const playerCountElements = document.querySelectorAll('#playerCount');
        if (playerCountElements.length > 0) {
            const formattedCount = this.currentPlayers.toLocaleString();
            playerCountElements.forEach(element => {
                element.textContent = formattedCount;
            });
        }
    }

    updatePlayerCount() {
        const newTarget = this.generatePlayerCount();
        const difference = newTarget - this.currentPlayers;
        const step = Math.sign(difference) * Math.ceil(Math.abs(difference) / 10);
        
        this.animateCountChange(step, newTarget);
    }

    animateCountChange(step, target) {
        const animate = () => {
            this.currentPlayers += step;
            
            if ((step > 0 && this.currentPlayers >= target) || 
                (step < 0 && this.currentPlayers <= target)) {
                this.currentPlayers = target;
                this.updateDisplay();
                return;
            }
            
            this.updateDisplay();
            setTimeout(animate, 50);
        };
        
        animate();
    }

    startAutoUpdate() {
        this.updateInterval = setInterval(() => {
            this.updatePlayerCount();
        }, 30000); // Update every 30 seconds
    }

    hideCounter() {
        const counter = document.querySelector('.floating-player-counter');
        if (counter) {
            counter.style.display = 'none';
        }
    }

    destroy() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
        this.isInitialized = false;
    }
}

// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    // Initialize theme
    const savedTheme = localStorage.getItem('theme') || 'light';
    document.body.setAttribute('data-theme', savedTheme);
    darkToggle.checked = savedTheme === 'dark';

    // Render initial games
    renderGames(games.slice(0, 50));

    // Initialize systems
    updateDateTime();
    setInterval(updateDateTime, 1000);
    
    createParticles();
    
    // Initialize player counter
    window.floatingPlayerCounter = new FloatingPlayerCounter();
    window.floatingPlayerCounter.init();

    // Start RTP updates
    setInterval(updateRTP, 10000);

    // Update RTP stats in header
    updateRTPStats();

    console.log('SAMOSIR88 RTP Platform initialized successfully');
});

// Update RTP statistics
function updateRTPStats() {
    const totalGames = games.length;
    const averageRTP = Math.round(games.reduce((sum, game) => sum + game.rtp, 0) / totalGames);
    const highestRTP = Math.max(...games.map(game => game.rtp));

    document.getElementById('rtpGames').textContent = totalGames;
    document.getElementById('rtpAverage').textContent = averageRTP + '%';
    document.getElementById('rtpHigh').textContent = highestRTP + '%';
}

// Enhanced RTP update with player activity
function enhanceRTPUpdateWithPlayerActivity() {
    const originalUpdateRTP = updateRTP;
    
    updateRTP = function() {
        originalUpdateRTP();
        
        if (window.floatingPlayerCounter && Math.random() > 0.7) {
            const smallChange = Math.floor(Math.random() * 21) - 10;
            window.floatingPlayerCounter.currentPlayers += smallChange;
            
            window.floatingPlayerCounter.currentPlayers = Math.max(
                window.floatingPlayerCounter.minPlayers,
                Math.min(window.floatingPlayerCounter.maxPlayers, window.floatingPlayerCounter.currentPlayers)
            );
            
            window.floatingPlayerCounter.updateDisplay();
        }
    };
}

enhanceRTPUpdateWithPlayerActivity();