/**
 * RTP Slot Script - Modern Version
 * =============================================
 * 
 * Fitur:
 * - Auto-generate game cards dari config
 * - Seed-based random (semua user lihat nilai sama)
 * - 1 file HTML untuk semua provider
 * 
 * PENTING: File ini membutuhkan config.js untuk diload terlebih dahulu!
 * Config berisi: SITE_CONFIG, PROVIDERS, BANNERS, getCurrentProvider(), getProviderData(), getAllProviders()
 * 
 * =============================================
 */

// ============================================
// SEED-BASED RANDOM FUNCTIONS
// ============================================

var currentSeed = 0;
var seededRandom = null;

/**
 * Mendapatkan seed berdasarkan waktu
 */
function getTimeSeed() {
    var now = Date.now();
    return Math.floor(now / window.SITE_CONFIG.seedInterval);
}

/**
 * Mendapatkan seed unik per provider
 */
function getProviderSeed(providerSlug) {
    var providerOffset = 0;
    for (var i = 0; i < providerSlug.length; i++) {
        providerOffset += providerSlug.charCodeAt(i);
    }
    return getTimeSeed() + providerOffset;
}

/**
 * Seeded random generator (Mulberry32)
 */
function mulberry32(seed) {
    return function() {
        var t = seed += 0x6D2B79F5;
        t = Math.imul(t ^ t >>> 15, t | 1);
        t ^= t + Math.imul(t ^ t >>> 7, t | 61);
        return ((t ^ t >>> 14) >>> 0) / 4294967296;
    };
}

/**
 * Inisialisasi random generator
 */
function initSeededRandom(providerSlug) {
    currentSeed = getProviderSeed(providerSlug);
    seededRandom = mulberry32(currentSeed);
    
    var now = Date.now();
    var nextChange = (Math.floor(now / window.SITE_CONFIG.seedInterval) + 1) * window.SITE_CONFIG.seedInterval;
    var remainingMs = nextChange - now;
    var remainingMinutes = Math.floor(remainingMs / 60000);
    var remainingSeconds = Math.floor((remainingMs % 60000) / 1000);
    
    console.log('[RTP] Seed: ' + currentSeed + ' | Next update: ' + remainingMinutes + 'm ' + remainingSeconds + 's');
}

/**
 * Get seeded random number
 */
function getSeededRandomNumber(min, max) {
    if (!seededRandom) initSeededRandom(window.getCurrentProvider());
    return Math.floor(seededRandom() * (max - min + 1)) + min;
}

/**
 * Get seeded random boolean
 */
function getSeededRandomBool(threshold) {
    if (threshold === undefined) threshold = 0.5;
    if (!seededRandom) initSeededRandom(window.getCurrentProvider());
    return seededRandom() > threshold;
}

// ============================================
// RTP DATA GENERATORS
// ============================================

/**
 * Generate RTP value
 */
function generateRTP() {
    return getSeededRandomNumber(window.SITE_CONFIG.minRTP, window.SITE_CONFIG.maxRTP);
}

/**
 * Generate jam gacor
 */
function generateJamGacor() {
    var startHour = getSeededRandomNumber(0, 20);
    var duration = getSeededRandomNumber(2, 4);
    var endHour = Math.min(startHour + duration, 23);
    
    function formatHour(h) {
        return String(h).padStart(2, '0') + ':00';
    }
    
    return formatHour(startHour) + ' - ' + formatHour(endHour) + ' WIB';
}

/**
 * Generate pola slot
 */
function generatePolaSlot() {
    var autoValues = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
    var manualValues = [3, 5, 7, 9, 10, 12, 15];
    
    var checkIcon = '<i class="lni lni-checkmark-circle fw-bold text-success"></i>';
    var crossIcon = '<i class="lni lni-cross-circle fw-bold text-danger"></i>';
    
    var rows = [];
    
    for (var i = 0; i < 3; i++) {
        var isAuto = getSeededRandomBool(0.3);
        var label;
        
        if (isAuto) {
            var autoValue = autoValues[getSeededRandomNumber(0, autoValues.length - 1)];
            label = 'Auto ' + autoValue;
        } else {
            var manualValue = manualValues[getSeededRandomNumber(0, manualValues.length - 1)];
            label = 'Manual ' + manualValue;
        }
        
        var icon1 = getSeededRandomBool() ? checkIcon : crossIcon;
        var icon2 = getSeededRandomBool() ? checkIcon : crossIcon;
        var icon3 = getSeededRandomBool() ? checkIcon : crossIcon;
        
        rows.push('<td>' + label + '</td><td>' + icon1 + '</td><td>' + icon2 + '</td><td>' + icon3 + '</td>');
    }
    
    return rows;
}

/**
 * Get RTP color
 */
function getRTPColor(rtp) {
    if (rtp >= 85) return '#00ce00ff';
    if (rtp >= 70) return '#dada0dff';
    if (rtp >= 60) return '#ffa500';
    return '#ff0000';
}

/**
 * Generate rating stars HTML
 */
function generateRatingStars(rating) {
    var stars = '';
    for (var i = 0; i < rating; i++) {
        stars += '<i class="lni lni-star-fill text-warning"></i> ';
    }
    return stars;
}

// ============================================
// HTML GENERATORS
// ============================================

/**
 * Generate HTML untuk satu game card
 */
function generateGameCardHTML(gameIndex, imageUrl, providerData) {
    var rtp = generateRTP();
    var jamGacor = generateJamGacor();
    var pola = generatePolaSlot();
    
    // Tentukan apakah game ini "HOT" (RTP tinggi)
    var isHot = rtp >= 85;
    var hotBadge = isHot ? '<div class="hot-game"></div>' : '';
    
    return '<div class="col-lg-4 col-6">' +
        '<div data-prov="' + providerData.slug + '" class="rtp-card animate__animated animate__bounceIn">' +
            hotBadge +
            '<div class="row g-1">' +
                '<div class="col-lg-6 align-self-center">' +
                    '<div class="place-img-rtp">' +
                        '<button onclick="location.href=\'' + window.SITE_CONFIG.playLink + '\';" class="btn-play shadow">' +
                            '<i class="lni lni-heart-fill"></i> Mari Bermain' +
                        '</button>' +
                        '<img class="lazy shadow rtp-card-img" ' +
                             'src="banner/loading.gif" ' +
                             'data-src="' + imageUrl + '" ' +
                             'alt="' + providerData.name + ' game ' + gameIndex + '">' +
                    '</div>' +
                '</div>' +
                '<div class="col-lg-6">' +
                    '<div class="pola-wrapper shadow text-center align-self-center">' +
                        '<h4><i class="lni lni-bar-chart"></i> Pola Slot:</h4>' +
                        '<hr>' +
                        '<table class="table-pola text-center">' +
                            '<tbody>' +
                                '<tr id="pola-slot-1-' + gameIndex + '">' + pola[0] + '</tr>' +
                                '<tr id="pola-slot-2-' + gameIndex + '">' + pola[1] + '</tr>' +
                                '<tr id="pola-slot-3-' + gameIndex + '">' + pola[2] + '</tr>' +
                            '</tbody>' +
                        '</table>' +
                        '<h5 class="mt-3 fw-bold" id="jam-gacor-' + gameIndex + '">' +
                            '<i class="lni lni-alarm-clock"></i> ' + jamGacor +
                        '</h5>' +
                        '<div class="percent">' +
                            '<p id="percent-txt-' + gameIndex + '" style="z-index: 15">' + rtp + '%</p>' +
                            '<div id="percent-bar-' + gameIndex + '" ' +
                                 'class="percent-bar" ' +
                                 'role="progressbar" ' +
                                 'aria-valuemin="0" ' +
                                 'aria-valuemax="100" ' +
                                 'aria-valuenow="' + rtp + '" ' +
                                 'style="width: ' + rtp + '%; background-color: ' + getRTPColor(rtp) + '">' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>' +
    '</div>';
}

/**
 * Generate semua game cards untuk provider
 */
function generateAllGameCards(providerSlug) {
    var providerData = window.getProviderData(providerSlug);
    
    if (!providerData || !providerData.games || providerData.games.length === 0) {
        console.error('[RTP] Provider "' + providerSlug + '" not found or has no games');
        return '<div class="col-12 text-center"><p>Provider tidak ditemukan</p></div>';
    }
    
    // Init seeded random untuk konsistensi
    initSeededRandom(providerSlug);
    
    var cardsHTML = '';
    
    for (var i = 0; i < providerData.games.length; i++) {
        var imageUrl = providerData.games[i];
        var gameIndex = i + 1;
        cardsHTML += generateGameCardHTML(gameIndex, imageUrl, providerData);
    }
    
    console.log('[RTP] Generated ' + providerData.games.length + ' game cards for ' + providerData.name);
    
    return cardsHTML;
}

/**
 * Generate provider dropdown menu
 */
function generateProviderDropdown(currentProviderSlug) {
    var providers = window.getAllProviders();
    var current = window.getProviderData(currentProviderSlug);
    
    var menuItems = '';
    for (var i = 0; i < providers.length; i++) {
        var prov = providers[i];
        var isActive = prov.slug === currentProviderSlug ? 'active' : '';
        menuItems += '<a href="?prov=' + prov.slug + '" role="menuitem" class="' + isActive + '">' + prov.name + '</a>\n';
    }
    
    return '<div class="provider-dropdown" id="providerDropdown">' +
        '<button class="provider-btn" type="button" aria-haspopup="true" aria-expanded="false" aria-controls="providerMenu">' +
            current.name +
            '<span class="caret"> 🔻</span>' +
        '</button>' +
        '<div class="provider-menu" id="providerMenu" role="menu">' +
            menuItems +
        '</div>' +
    '</div>';
}

/**
 * Generate banner slides
 */
function generateBannerSlides() {
    var slidesHTML = '';
    
    for (var i = 0; i < window.BANNERS.length; i++) {
        var bannerUrl = window.BANNERS[i];
        slidesHTML += '<div class="swiper-slide">' +
            '<img src="' + bannerUrl + '" loading="lazy" class="slider-img rounded" alt="slider ' + i + '">' +
            '<div class="swiper-lazy-preloader"></div>' +
        '</div>';
    }
    
    return slidesHTML;
}



// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * Scroll ke atas
 */
function goUp() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

/**
 * Update waktu display - Modern Version
 */
function updateTimeDisplay() {
    var now = new Date();
    var months = ["Januari", "Februari", "Maret", "April", "Mei", "Juni",
                  "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
    var days = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];
    var day = days[now.getDay()];
    var date = String(now.getDate()).padStart(2, '0');
    var month = months[now.getMonth()];
    var year = now.getFullYear();
    var hours = String(now.getHours()).padStart(2, '0');
    var minutes = String(now.getMinutes()).padStart(2, '0');
    var seconds = String(now.getSeconds()).padStart(2, '0');
    
    // Format modern: "Kamis, 30 Januari 2026 | 17:03:45 WIB"
    var timeString = day + ', ' + date + ' ' + month + ' ' + year + ' | ' + hours + ':' + minutes + ':' + seconds + ' WIB';
    
    var timeDisplay = document.getElementById('timeDisplay');
    if (timeDisplay) {
        timeDisplay.textContent = timeString;
    }
}

// ============================================
// SCROLL HANDLER
// ============================================

window.onscroll = function() {
    var btnUp = document.getElementById('btn-up');
    if (btnUp) {
        if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
            btnUp.style.display = 'block';
            btnUp.style.opacity = '1';
        } else {
            btnUp.style.opacity = '0';
            setTimeout(function() {
                if (document.body.scrollTop <= 100 && document.documentElement.scrollTop <= 100) {
                    btnUp.style.display = 'none';
                }
            }, 300);
        }
    }
};

// ============================================
// INITIALIZATION
// ============================================

document.addEventListener('DOMContentLoaded', function() {
    // Cek apakah config.js sudah diload
    if (typeof window.SITE_CONFIG === 'undefined' || typeof window.PROVIDERS === 'undefined' || typeof window.BANNERS === 'undefined') {
        console.error('[RTP] ERROR: config.js must be loaded before rtp.js!');
        return;
    }
    
    var $ = window.jQuery || window.$;
    var Swiper = window.Swiper;
    
    // Get current provider dari URL
    var currentProvider = window.getCurrentProvider();
    console.log('[RTP] Current provider: ' + currentProvider);
    
    // ----------------------------------------
    // 1. Set Site Logo dari Config
    // ----------------------------------------
    var siteLogo = document.getElementById('siteLogo');
    if (siteLogo && window.SITE_CONFIG.siteLogo) {
        siteLogo.src = window.SITE_CONFIG.siteLogo;
        siteLogo.alt = window.SITE_CONFIG.siteName || 'Logo';
    }
    
    // ----------------------------------------
    // 1b. Set Site Info dari Config
    // ----------------------------------------
    var infoSiteName = document.getElementById('infoSiteName');
    if (infoSiteName) {
        infoSiteName.textContent = window.SITE_CONFIG.siteName;
    }
    
    var infoDaftarLink = document.getElementById('infoDaftarLink');
    if (infoDaftarLink && window.SITE_CONFIG.playLink) {
        infoDaftarLink.href = window.SITE_CONFIG.playLink;
    }
    
    // ----------------------------------------
    // 2. Generate Banner Slides
    // ----------------------------------------
    var swiperWrapper = document.querySelector('.swiper-wrapper');
    if (swiperWrapper) {
        swiperWrapper.innerHTML = generateBannerSlides();
    }
    
    // ----------------------------------------
    // 3. Generate Provider Dropdown
    // ----------------------------------------
    var dropdownContainer = document.querySelector('.icon-prov');
    if (dropdownContainer) {
        // Cek apakah sudah ada selector-label (desain baru)
        var selectorLabel = dropdownContainer.querySelector('.selector-label');
        if (selectorLabel) {
            // Desain baru: masukkan dropdown setelah label
            var existingDropdown = dropdownContainer.querySelector('.provider-dropdown');
            if (existingDropdown) existingDropdown.remove();
            selectorLabel.insertAdjacentHTML('afterend', generateProviderDropdown(currentProvider));
        } else {
            // Fallback desain lama
            dropdownContainer.innerHTML = '<p>Pilih Provider : </p>' + generateProviderDropdown(currentProvider);
        }
    }
    
    // ----------------------------------------
    // 4. Generate Game Cards
    // ----------------------------------------
    var gameContainer = document.getElementById('game-container');
    if (gameContainer) {
        gameContainer.innerHTML = generateAllGameCards(currentProvider);
    }
    
    // ----------------------------------------
    // 5. Init Swiper
    // ----------------------------------------
    if (Swiper) {
        new Swiper('.slider', {
            slidesPerView: 1,
            spaceBetween: 10,
            loop: true,
            autoplay: {
                delay: 3000,
                disableOnInteraction: false,
            },
            lazy: {
                loadPrevNext: true,
            }
        });
    }
    
    // ----------------------------------------
    // 6. Init Lazy Loading
    // ----------------------------------------
    if ($ && $.fn && $.fn.lazy) {
        $('.lazy').lazy({
            effect: 'fadeIn',
            effectTime: 500,
            threshold: 0
        });
    }
    
    // ----------------------------------------
    // 7. Init Time Display
    // ----------------------------------------
    updateTimeDisplay();
    setInterval(updateTimeDisplay, 1000);
    
    // ----------------------------------------
    // 8. Hide Go Up Button
    // ----------------------------------------
    var btnUp = document.getElementById('btn-up');
    if (btnUp) btnUp.style.display = 'none';
    
    // ----------------------------------------
    // 9. Provider Dropdown Toggle (menggunakan pattern dari drop.js)
    // ----------------------------------------
    var dropdown = document.getElementById('providerDropdown');
    
    if (dropdown) {
        var btn = dropdown.querySelector('.provider-btn');
        var menu = dropdown.querySelector('.provider-menu');
        var links = menu ? menu.querySelectorAll('a') : [];
        
        var openDropdown = function() {
            dropdown.classList.add('is-open');
            btn.setAttribute('aria-expanded', 'true');
        };
        
        var closeDropdown = function() {
            dropdown.classList.remove('is-open');
            btn.setAttribute('aria-expanded', 'false');
        };
        
        var toggleDropdown = function() {
            dropdown.classList.contains('is-open') ? closeDropdown() : openDropdown();
        };
        
        // Toggle saat klik tombol
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleDropdown();
        });
        
        // Tutup saat klik di luar dropdown
        document.addEventListener('click', function(e) {
            if (!dropdown.contains(e.target)) closeDropdown();
        });
        
        // Tutup saat tekan ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeDropdown();
                btn.focus();
            }
        });
        
        // Tutup setelah pilih item
        for (var i = 0; i < links.length; i++) {
            links[i].addEventListener('click', closeDropdown);
        }
    }
    
    console.log('[RTP] Initialization complete!');
});
