@extends('frontend.layouts.app')

@section('content')

@php 
    $isLogin = auth()->check(); 
    $prefix = $isLogin ? '/secure' : '';
    
    $providers = get_providers(['other', 'others', 'OT']);
@endphp

@push('styles')
<style type="text/css">
.g8sggl *{box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box}.g8sggl .g8sggl-t{background-color:#383637;font-size:0;padding:3px 2px;margin-bottom:15px;position:relative}.g8sggl .g8sggl-t .ii{background-color:#0f0f0f;display:inline-block;width:130px;text-align:center;font-size:14px;margin:0 2px;background-repeat:no-repeat;background-position:top 5px center;background-size:80%;background-blend-mode:luminosity;position:relative;vertical-align:top}.g8sggl .g8sggl-t .ii .ii-tt{padding:60px 0 5px}.g8sggl .g8sggl-t .ii .ii-info{position:absolute;top:2px;right:2px;width:16px;height:16px;border-radius:50%;text-align:center;background-color:#666;color:#fff}.g8sggl .g8sggl-t .ii .ii-info .fa{font-size:10px;line-height:16px}.g8sggl .g8sggl-t .ii.aaa{background-color:#000;background-blend-mode:inherit}.g8sggl .g8sggl-t .ii:hover{background-color:#222;background-blend-mode:inherit}.g8sggl .g8sggl-c{background-color:#050505;font-size:0}.g8sggl .g8sggl-c .ll{display:inline-block;width:80%;white-space:nowrap;overflow-x:auto;position:relative}.g8sggl .g8sggl-c .ll .ii{font-size:14px;display:inline-block;padding:0 20px;line-height:40px;text-transform:uppercase}.g8sggl .g8sggl-c .rr{display:inline-block;width:20%;vertical-align:top}.g8sggl .g8sggl-c .ll .ii.aaa,.g8sggl .g8sggl-c .ll .ii:hover{background-color:#d9b300;color:#352c02}.g8sggl .g8sggl-b{background-color:#0f0f0f;padding:10px}.g8sggl .glmsg{font-size:14px;color:#fff;text-align:center;padding:10px 0}.g8sggl .glmsg .g8sgpopa{background-color:#d9b300; color:#352c02; display:inline-block; font-weight:bold; text-transform:uppercase; padding:8px 15px;}.g8sggl .glmsg .g8sgpopa:hover {background-color:#333333; color:#ffffff}.g8sggl .glbox{font-size:0;position:relative;z-index:0}.g8sggl .glbox .gl{display:inline-block;width:20%;font-size:14px;padding:8px}.g8sggl .glbox .gl.hh{display:none}.g8sggl .glbox .gl.ss-yes{display:inline-block!important}.g8sggl .glbox .gl.ss-no{display:none!important}.g8sggl .glbox .gl .glimg{position:relative;width:100%;padding-top:100%;background-size:100%;background-position:center;background-repeat:no-repeat;background-color:#050505;cursor:pointer;overflow:hidden}.g8sggl .glbox .gl .gltext{background-color:#d9b300;color:#352c02;padding:6px 10px;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.g8sggl .glbox .gl .glpic{position:absolute;width:100%;height:100%;top:50%;transform:translateY(-50%);z-index:1}.g8sggl .glbox .gl .glpic img{width:100%}.g8sggl .glbox .gl .hwrap{position:absolute;top:0;left:0;width:100%;height:100%;z-index:3;background:rgba(0,0,0,0.8);opacity:0}.g8sggl .glbox .gl .glimg:hover .hwrap{opacity:1}.g8sggl .glbox .gl .glbadge {width: 35%; position: absolute; left: 0px; top: 0px; z-index:2}.g8sggl .glbox .gl .glbadge img {max-width:100%; height:auto;}.g8sggl .glbox .gl .hwrap .hbox{position:absolute;width:80%;left:50%;top:50%;transform:translate(-50%,-50%)}.g8sggl .glbox .gl .hwrap .hbox .main{color:#352c02;background-color:#d9b300;text-align:center;width:100%;display:block;text-transform:uppercase;padding:8px;border-radius:20px}.g8sggl .glpagi{text-align:center;font-size:0;margin-top:15px;display:none}.g8sggl .glpagi .pagi{display:inline-block;font-size:10px;font-weight:bold;margin:2px;background-color:#000;width:20px;line-height:20px;text-align:center}.g8sggl .glpagi .pagi.aaa,.g8sggl .glpagi .pagi:hover{background-color:#d9b300;color:#352c02}.g8sggl .searchbar{font-size:12px}.g8sggl .searchbar input{background-color:#333;border:0;display:inline-block;width:100%;line-height:40px;padding:0 10px;outline:0;border-radius:0px;color:#ffffff}.g8sggl .searchbar input::placeholder{color:#ffffff}.g8sggl .searchbar button{background-color:#858585;border:0;display:inline-block;width:40px;height:40px;font-size:16px}.g8sggl .g8sggl-tarr{position:absolute;top:0;color:#352c02;height:100%;padding:0 8px;background-color:#d9b300;width:22px;font-size:16px;display:none}.g8sggl .g8sggl-tarr.l{left:0}.g8sggl .g8sggl-tarr.r{right:0}.g8sggl .g8sggl-tarr i{position:absolute;top:50%;left:50%;text-align:center;transform:translate(-50%,-50%)}.g8sggl .g8sggl-t .ii,.g8sggl .g8sggl-c .ll .ii,.g8sggl .glpagi .pagi{transition:.5s ease;cursor:pointer}.g8sggl .g8sggl-t .ww::-webkit-scrollbar,.g8sggl .g8sggl-c .ll .ww::-webkit-scrollbar{display:none}.g8sggl .g8sggl-t .ww,.g8sggl .g8sggl-c .ll .ww{-ms-overflow-style:none;scrollbar-width:none;white-space:nowrap;overflow-x:auto;text-align:left}

@media only screen and (max-width:768px){.g8sggl .g8sggl-t .ii{width:110px;font-size:12px}.g8sggl .g8sggl-t .ii .ii-tt{padding-top:50px}.g8sggl .g8sggl-c .ll{width:70%}.g8sggl .g8sggl-c .ll .ii{font-size:12px;padding:0 15px;line-height:34px}.g8sggl .g8sggl-c .rr{width:30%}.g8sggl .searchbar input{line-height:34px}.g8sggl .glbox .gl{font-size:12px}.g8sggl .glbox .gl .hwrap{display:none}}
@media only screen and (max-width:479px){.g8sggl .g8sggl-t .ii{width:90px}.g8sggl .g8sggl-t .ii .ii-tt{padding-top:44px}.g8sggl .g8sggl-c .ll{width:100%}.g8sggl .g8sggl-c .rr{width:100%}.g8sggl .searchbar input{text-align:center}.g8sggl .glbox .gl{width:33.33%; padding:5px;}.g8sggl .glbox .gl .gltext{padding:4px 10px}}
.g8sggl .g8sggl-t .ii .badge {position:absolute; width:34%; left:0px; top:0px;} .g8sggl .g8sggl-t .ii .badge img {max-width:100%;filter: grayscale(0.8);}.g8sggl .g8sggl-t .ii.aaa .badge img,.g8sggl .g8sggl-t .ii:hover .badge img {filter: none;}
.g8sggl .searchbar {position: relative;}
.g8sggl .searchbar img {position: absolute;width: 24px!important;transform: translateY(-50%);top: 50%;left: 3px;}
.g8sggl .searchbar input {padding: 0 10px 0 32px;}
.g8sggl .searchbar input::placeholder {color: #888888a1;}

/* GENERATE BACKGROUND PROVIDER DINAMIS */
@foreach($providers as $p)
.pvd.{{ strtolower($p->provider_code) }} { background-image: url('{{ $p->icon ?? "/assets/custom/img/default-provider.png" }}'); }
@endforeach
</style>
@endpush

    <div id="showM">
        <div class="overlap g8mmenu-close"></div>
        @include('frontend.partials.mobile.header')
        @include('frontend.partials.mobile.sidebar-menu')

        <div class="content" style="display: none;">
            <div class="nav__title single">Live Casino</div>
            <section class="box">
                <div class="box__detail s1">
                    
                    <div class="g8sggl">
                        <div class="g8sggl-t">
                            <div class="ww">
                                <div class="ii glpvd pvd all active" dd="all"><div class="ii-tt">All games</div></div>
                                @foreach($providers as $p)
                                    <div class="ii glpvd pvd {{ strtolower($p->provider_code) }}" dd="{{ strtolower($p->provider_code) }}">
                                        <div class="ii-tt">{{ $p->provider_name }}</div>
                                    </div>
                                @endforeach
                            </div>
                            <a href="javascript:void(0)" class="g8sggl-tarr l" me="l"><i class="fa fa-chevron-left"></i></a>
                            <a href="javascript:void(0)" class="g8sggl-tarr r" style="display: block;" me="r"><i class="fa fa-chevron-right"></i></a>
                        </div>
                        
                        <div class="g8sggl-c">
                            <div class="ll glcat">
                                <div class="ww">
                                    <div class="ii gocat aaa active" dd="all" ss="0">all</div>
                                    <div class="ii gocat" dd="hot" ss="0.2">hot</div>
                                </div>
                            </div>
                            <div class="rr">
                                <div class="searchbar">
                                    <img src="https://d1bkaj2gcjb1cb.cloudfront.net/common/assets/images/icon/i-search.png" alt="search">
                                    <input type="text" class="glsearch gsearch" placeholder="Cari Table/Game">
                                </div>
                            </div>
                        </div>
                        
                        <div class="g8sggl-b">
                            <div class="glmsg" style="display: none;">Loading ...</div>
                            <div class="glbox"></div>
                        </div>
                    </div>

                </div>
            </section>
        </div>
        <div class="loading-slots"></div>

        @include('frontend.partials.mobile.bottom-nav')
    </div>

    <div id="showD">
        @include('frontend.partials.desktop.header')

        <section class="slider">
            <section class="marquee">
                <div class="wrapper">
                    <div class="s-a" style="display: flex; width: 100%; align-items: center; overflow: hidden;">
                        <div class="marquee__bullhorn" style="margin-right: 10px;">
                            <i class="fas fa-bullhorn"></i>
                        </div>
                        <marquee style="width: 100%; flex: 1;" scrolldelay="150" behavior="scroll" onmouseover="this.stop();" onmouseout="this.start();" direction="left">{{ general()->title }}</marquee>
                    </div>
                </div>
            </section>
            <div class="swiper__img">
                <div style="padding-top: 37px;"></div>
                <img src="https://d1bkaj2gcjb1cb.cloudfront.net/common/assets/images/banner/category-v2/others.jpg" style="width: 100%; max-width: 1200px; margin: 0 auto; display: block;" alt="Banner">
            </div>
        </section>

        <div class="content" style="display: none;">
            <section class="featured">
                <div class="wrapper">
                    <div class="featured__detail">
                        <div class="featured__detail-content">
                            
                            <div class="g8sggl">
                                <div class="g8sggl-t">
                                    <div class="ww">
                                        <div class="ii glpvd pvd all active" dd="all"><div class="ii-tt">All games</div></div>
                                        @foreach($providers as $p)
                                            <div class="ii glpvd pvd {{ strtolower($p->provider_code) }}" dd="{{ strtolower($p->provider_code) }}">
                                                <div class="ii-tt">{{ $p->provider_name }}</div>
                                            </div>
                                        @endforeach
                                    </div>
                                    <a href="javascript:void(0)" class="g8sggl-tarr l" me="l"><i class="fa fa-chevron-left"></i></a>
                                    <a href="javascript:void(0)" class="g8sggl-tarr r" style="display: block;" me="r"><i class="fa fa-chevron-right"></i></a>
                                </div>
                                
                                <div class="g8sggl-c">
                                    <div class="ll glcat">
                                        <div class="ww">
                                            <div class="ii gocat aaa active" dd="all" ss="0">all</div>
                                            <div class="ii gocat" dd="hot" ss="0.2">hot</div>
                                        </div>
                                    </div>
                                    <div class="rr">
                                        <div class="searchbar">
                                            <img src="https://d1bkaj2gcjb1cb.cloudfront.net/common/assets/images/icon/i-search.png" alt="search">
                                            <input type="text" class="glsearch gsearch" placeholder="Cari Table/Game">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="g8sggl-b">
                                    <div class="glmsg" style="display: none;">Loading ...</div>
                                    <div class="glbox"></div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </section>
        </div>

        <section class="sidebar s-sidebar"></section>
        @include('frontend.partials.desktop.footer')
    </div>
@endsection

@push('scripts')
<script type="text/javascript">
    // Load Core Template Files Aman
    var loadScript = (e) => new Promise((resolve, reject) => {
        var s = document.createElement("script");
        s.src = e + '?' + Math.random();
        s.defer = true;
        s.onload = function() { resolve(true); };
        document.body.appendChild(s);
    });

    loadScript("{{ asset('func/jsx/global.js') }}").then(() => {
        loadScript("{{ asset('func/jsx/cms.js') }}").then(() => {
            [
                "{{ asset('assets/js/common.js') }}", 
                "{{ asset('assets/js/template.js') }}" 
            ].forEach(e => {
                var s = document.createElement("script");
                s.src = e + '?' + Math.random();
                s.defer = true;
                document.body.appendChild(s);
            });
        });
    });

    // FUNGSI UTAMA GAME LIVE CASINO
    window.loadMeIfReady = function() {
        let activeScreen = $('#showM').is(':visible') ? '#showM' : '#showD';
        
        if (activeScreen === '#showM') {
            $('#showM > .content').show();
            $('.loading-slots').hide();
        } else {
            $('#showD > .content').show();
        }

        // 1. INISIALISASI VARIABEL PENTING
        let isLogin = {{ auth()->check() ? 'true' : 'false' }};
        let prefix = "{{ auth()->check() ? '/secure' : '' }}";
        
        let activeSgFromUrl = "{{ $activeSg ?? '' }}"; 
        let currentProvider = activeSgFromUrl ? activeSgFromUrl.toLowerCase() : 'all'; 
        
        let currentPage = 1;
        let currentSearch = '';

        // 2. FUNGSI CEK SCROLLER PANAH (Muncul/Hilang Otomatis)
        function checkScroller() {
            let scroller = $(activeScreen + ' .g8sggl-t .ww');
            if (scroller.length === 0) return;

            let scrollLeft = scroller.scrollLeft();
            let scrollWidth = scroller[0].scrollWidth;
            let clientWidth = scroller[0].clientWidth;

            // Cek Panah Kiri
            if (scrollLeft > 0) {
                $(activeScreen + ' .g8sggl-tarr.l').fadeIn(200);
            } else {
                $(activeScreen + ' .g8sggl-tarr.l').fadeOut(200);
            }

            // Cek Panah Kanan
            if (scrollWidth - clientWidth > scrollLeft + 5) { // Toleransi 5px
                $(activeScreen + ' .g8sggl-tarr.r').fadeIn(200);
            } else {
                $(activeScreen + ' .g8sggl-tarr.r').fadeOut(200);
            }
        }

        // Deteksi scroll manual oleh user (geser jari di HP)
        $('.g8sggl-t .ww').on('scroll', function() {
            checkScroller();
        });

        // Panggil saat resize layar
        $(window).on('resize', checkScroller);

        // 3. AUTO SCROLL JIKA ADA PROVIDER DI URL
        if (currentProvider !== 'all') {
            setTimeout(() => {
                let targetTab = $(activeScreen + ' .g8sggl-t .glpvd[dd="' + currentProvider + '"]');
                if (targetTab.length > 0) {
                    targetTab[0].scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
                    checkScroller();
                }
            }, 300);
        }

        // 4. FUNGSI FETCH GAMES VIA AJAX
        function fetchGames(page, append = false) {
            let targetBox = $(activeScreen + ' .g8sggl .glbox');
            
            if (!append) targetBox.html('<div style="width:100%;text-align:center;padding:50px;"><i class="fa fa-spinner fa-spin fa-3x" style="color:#d9b300;"></i></div>');
            else $(activeScreen + ' .btn-loadm').html('<i class="fa fa-spinner fa-spin"></i> Loading...').prop('disabled', true);

            $.ajax({
                url: '/func/stl/getGameListAPI',
                type: 'GET',
                data: { providerName: currentProvider, page: page, search: currentSearch, type: 'others' },
                success: function(res) {
                    if (!append) { 
                        targetBox.empty(); 
                        $(activeScreen + ' .g8sggl-loadm').remove(); 
                    }

                    let games = res[1]; 
                    let hasMore = res[2]; 

                    if (!games || games.length === 0) {
                        if (!append) targetBox.html('<div style="text-align:center;width:100%;padding:30px;color:#fff;">Meja tidak ditemukan.</div>');
                        return;
                    }

                    let html = '';
                    games.forEach(g => {
                        let img = g[0] || '/assets/custom/img/default.png';
                        let name = g[1];
                        let code = g[2];
                        let prov = g[3];
                        let rtp = g[4] || 95;
                        
                        let actionClass = !isLogin ? 's-check-login' : 'play-game-btn';
                        let gameUrl = `${prefix}/shr/playGame?gc=other&gg=${prov}&gs=${code}`;
                        let actionAttr = isLogin ? `data-url="${gameUrl}"` : '';

                        html += `
                        <div class="gl ppp ss-yes">
                            <div class="glimg ${actionClass}" ${actionAttr} style="cursor:pointer;">
                                <div class="glpic">
                                    <img src="${img}" alt="${name}" loading="lazy" style="width: 100%; height: 100%; aspect-ratio: 1 / 1; object-fit: cover; display: block;" onerror="this.src='/assets/custom/img/default.png'">
                                </div>
                                <div class="hwrap"><div class="hbox"><a href="javascript:void(0)" class="main">Main</a></div></div>
                            </div>
                            <div class="rtp-container"><div class="green" style="width: ${rtp}%">&nbsp;</div><span>${rtp}%</span></div>
                            <div class="gltext" title="${name}">${name}</div>
                        </div>`;
                    });

                    targetBox.append(html);

                    // LOGIKA LOAD MORE BARU (Lebih Kokoh)
                    $(activeScreen + ' .g8sggl-loadm').remove(); // Selalu bersihkan tombol lama
                    if (hasMore) {
                        targetBox.after(`<div class="g8sggl-loadm" style="width:100%;text-align:center;margin-top:15px;padding-bottom:20px;"><button class="btn-loadm button button--yellow" style="padding:10px 30px;cursor:pointer;border-radius:25px;font-weight:bold;">Load More</button></div>`);
                    }
                },
                error: function() {
                    $(activeScreen + ' .btn-loadm').html('Load More').prop('disabled', false);
                    if(!append) targetBox.html('<div style="text-align:center;width:100%;padding:30px;color:red;">Gagal memuat permainan.</div>');
                }
            });
        }

        $(document).off('click', '.play-game-btn').on('click', '.play-game-btn', function(e) {
            e.preventDefault();
            let $btn = $(this);
            
            // 1. CEGAH DOUBLE CLICK: Jika sedang loading, abaikan klik dari pemain!
            if ($btn.hasClass('is-loading')) return; 

            let url = $btn.attr('data-url');
            
            // 2. Ubah UI tombol menjadi Loading
            $btn.addClass('is-loading');
            $btn.find('.main').html('<i class="fa fa-spinner fa-spin"></i> Load...');
            $btn.css('opacity', '0.7'); // Efek redup

            // 3. Proses Pindah Saldo & Buka Game via AJAX
            $.ajax({
                url: url,
                type: 'GET',
                success: function(res) {
                    // Kembalikan UI tombol seperti semula
                    $btn.removeClass('is-loading');
                    $btn.find('.main').html('Main');
                    $btn.css('opacity', '1');

                    if (res.success) {
                        // AUTO REFRESH SALDO DI HEADER WEB
                        if (res.balance) {
                            $('.g8-bal-total').html('IDR ' + res.balance);
                        }
                        
                        // Lempar ke URL Game
                        window.location.href = res.url; 
                    } else {
                        // Jika gagal, munculkan popup alert
                        if (typeof jAlert === "function") {
                            jAlert(res.message, 'Peringatan');
                        } else {
                            alert(res.message);
                        }
                    }
                },
                error: function() {
                    $btn.removeClass('is-loading');
                    $btn.find('.main').html('Main');
                    $btn.css('opacity', '1');
                    alert('Koneksi terputus. Silakan coba lagi beberapa saat.');
                }
            });
        });

        // Alert Belum Login
        $(document).on('click', '.s-check-login', function(e) {
            e.preventDefault();
            if (typeof jAlert === "function") {
                jAlert('Silahkan login atau mendaftar untuk masuk kedalam permainan.', 'Peringatan');
            } else {
                alert('Silahkan login atau mendaftar untuk masuk kedalam permainan.');
            }
        });

        // Klik Tab Provider
        $(document).on('click', '.g8sggl-t .glpvd', function() {
            $('.g8sggl-t .glpvd').removeClass('active aaa');
            let prov = $(this).attr('dd');
            $('.g8sggl-t .glpvd[dd="'+prov+'"]').addClass('active aaa');
            
            currentProvider = prov;
            currentPage = 1;
            $('.gsearch').val('');
            currentSearch = '';
            
            if($(window).width() <= 768) {
                this.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
            }
            fetchGames(currentPage, false);
        });

        // KLIK LOAD MORE (Event Delegated, Anti-Macet)
        $(document).off('click', '.btn-loadm').on('click', '.btn-loadm', function() {
            currentPage++;
            fetchGames(currentPage, true);
        });

        // Fungsi Search
        let st;
        $(document).on('keyup', '.gsearch', function() {
            let val = $(this).val();
            $('.gsearch').val(val); 
            currentSearch = val;
            currentPage = 1;
            clearTimeout(st);
            st = setTimeout(() => fetchGames(currentPage, false), 500);
        });

        // Scroller Panah (Dengan Animasi & Pengecekan)
        $(document).on('click', '.g8sggl-tarr.r', function() {
            let scroller = $(this).siblings('.ww');
            scroller.animate({ scrollLeft: scroller.scrollLeft() + 250 }, 300, function() {
                checkScroller();
            });
        });
        
        $(document).on('click', '.g8sggl-tarr.l', function() {
            let scroller = $(this).siblings('.ww');
            scroller.animate({ scrollLeft: scroller.scrollLeft() - 250 }, 300, function() {
                checkScroller();
            });
        });

        // Eksekusi Fetch Awal & Pengecekan Panah
        setTimeout(checkScroller, 500);
        fetchGames(1);
    };
</script>
@endpush