$(document).ready(function() {
    if (!localStorage.getItem('selectedBalanceType')) {
        localStorage.setItem('selectedBalanceType', 'balance');
    }

    let selectedBalanceType = localStorage.getItem('selectedBalanceType');
    updateBalance(selectedBalanceType);

    $('#refreshBalance').click(function(event) {
        event.stopPropagation();
        $('#balanceDropdown').toggle();
    });

    $('#balanceDropdown a').click(function(event) {
        event.preventDefault();
        let selectedType = $(this).data('type');

        localStorage.setItem('selectedBalanceType', selectedType);
        updateBalance(selectedType);
        $('#balanceDropdown').hide();
    });

    $('#loading-icon').click(function(event) {
        event.stopPropagation();
        $('#loading-icon').addClass('fa-spin');

        let selectedType = localStorage.getItem('selectedBalanceType') || 'balance';
        fetchBalance(selectedType);
    });

    $(document).click(function() {
        $('#balanceDropdown').hide();
    });

    function updateBalance(type) {
        fetchBalance(type);
    }

    function fetchBalance(type) {
        let url = type === 'balance' ? '/get-balance' : '/get-deposit';

        $.ajax({
            url: url,
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    $('#balance').html(response.balance);
                } else {
                    alert('Failed to load balance');
                }
            },
            error: function() {
                alert('Error fetching balance');
            },
            complete: function() {
                $('#loading-icon').removeClass('fa-spin');
            }
        });
    }
    let lastNotifData = {};
    function decodeHtml(html) {
        let txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    }
    function loadNotifications(category = 'all') {
        if (lastNotifData[category]) {
            return;
        }
        let notifContainer = $(`#notif-container-${category}`);
        notifContainer.html(`<p class="text-gray-500 text-center"><div class="w-full px-6 py-4"><div class="skeleton animate-wave h-3 w-full rounded bg-slate-150 dark:bg-navy-500"></div><div class="skeleton animate-wave mt-4 h-3 w-8/12 rounded bg-slate-150 dark:bg-navy-500"></div></div></p>`);
        $.ajax({ 
            url: "/notifications",
            type: "GET",
            data: { category: category },
            success: function (data) {
                lastNotifData[category] = data;
                notifContainer.html("");

                if (data.length === 0) {
                    notifContainer.append('<p class="text-gray-500 text-center">No notifications available</p>');
                    return;
                }

                data.forEach(notif => {
                    let iconClass, bgColor;

                    switch (notif.category) {
                        case 'system':
                            iconClass = "fa fa-cogs text-info";
                            bgColor = "bg-info/10 dark:bg-info/15";
                            break;
                        case 'success':
                            iconClass = "fa fa-check-circle text-success";
                            bgColor = "bg-success/10 dark:bg-success/15";
                            break;
                        case 'warning':
                            iconClass = "fa fa-exclamation-triangle text-warning";
                            bgColor = "bg-warning/10 dark:bg-warning/15";
                            break;
                        case 'error':
                            iconClass = "fa fa-times-circle text-error";
                            bgColor = "bg-error/10 dark:bg-error/15";
                            break;
                        default:
                            iconClass = "fa fa-bell text-gray-500";
                            bgColor = "bg-gray-200 dark:bg-gray-700";
                            break;
                    }
                    let message = decodeHtml(notif.message);
                    let notifHTML = `
                    <div x-data="{ showModal: false }">
                        <div @click="showModal = true" class="flex items-center space-x-3 notif cursor-pointer" data-id="${notif.id}">
                            <div class="relative flex size-10 shrink-0 items-center justify-center rounded-lg ${bgColor}">
                                <i class="${iconClass}"></i>
                                <span class="absolute -top-px -right-px flex size-3 items-center justify-center" id="new-${notif.id}">
                                    <span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-secondary opacity-80"></span>
                                    <span class="inline-flex size-2 rounded-full bg-secondary flex-col items-center"></span>
                                </span>
                            </div>
                            <div>
                                <p class="font-medium text-slate-600 dark:text-navy-100">${notif.title}</p>
                                <div class="mt-1 text-xs text-slate-400 line-clamp-1 dark:text-navy-300">
                                    ${message}
                                </div>
                            </div>
                        </div>
                        <template x-teleport="#x-teleport-target">
                            <div
                                class="fixed inset-0 z-[100] flex flex-col items-center justify-center overflow-hidden px-4 py-6 sm:px-5"
                                x-show="showModal"
                                role="dialog"
                                @keydown.window.escape="showModal = false"
                            >
                                <div
                                    class="absolute inset-0 bg-slate-900/60 transition-opacity duration-300"
                                    @click="showModal = false"
                                    x-show="showModal"
                                    x-transition:enter="ease-out"
                                    x-transition:enter-start="opacity-0"
                                    x-transition:enter-end="opacity-100"
                                    x-transition:leave="ease-in"
                                    x-transition:leave-start="opacity-100"
                                    x-transition:leave-end="opacity-0"
                                ></div>
                                <div
                                    class="relative max-w-lg rounded-lg bg-white px-4 py-10 text-center transition-opacity duration-300 dark:bg-navy-700 sm:px-5"
                                    x-show="showModal"
                                    x-transition:enter="ease-out"
                                    x-transition:enter-start="opacity-0"
                                    x-transition:enter-end="opacity-100"
                                    x-transition:leave="ease-in"
                                    x-transition:leave-start="opacity-100"
                                    x-transition:leave-end="opacity-0"
                                >
                                    <div class="mt-4">
                                        <h2 class="text-2xl text-slate-700 dark:text-navy-100">
                                            <i class="${iconClass}"></i> ${notif.title}
                                        </h2>
                                        <p class="mt-2">
                                            ${message}
                                        </p>
                                        <button
                                            @click="showModal = false"
                                            class="btn mt-6 bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90"
                                        >
                                            Close
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                    `;
                    notifContainer.append(notifHTML);
                });
            }
        });
    }

    $(".notif-btn").click(function () {
        loadNotifications();
    });
    
    $(".tab-button").click(function () {
        let category = $(this).data("category");
        loadNotifications(category);
    });

    $(document).on("click", ".notif", function () {
        let id = $(this).data("id");
    
        if ($("#new-" + id).length === 0) {
            return;
        }
    
        $.ajax({
            url: `/notifications/${id}/read`,
            type: "PUT",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function () {
                $("#new-" + id).remove();
    
                let notifCountElem = $("#notif-count");
                let count = parseInt(notifCountElem.text());
    
                if (count > 1) {
                    notifCountElem.text(count - 1);
                } else {
                    $(".new-notif").remove();
                }
            }
        });
    });
    $("#mark-all-read").on("click", function () {
        if ($(".new-notif").length === 0) {
            return;
        }
    
        $.ajax({
            url: `/notifications/read-all`,
            type: "PUT",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function () {
                $("[id^='new-']").remove();
                $(".new-notif").remove();
            }
        });
    });
});
document.addEventListener("DOMContentLoaded", function () {
    if (typeof flashMessage !== "undefined" && flashMessage) {
        let iconType = "info";
        let title = "Notification";
        let theme = localStorage.getItem("_x_darkMode_on") === "true" ? "dark" : "light";
    
        switch (flashType) {
            case "success":
                iconType = "success";
                title = "Success!";
                break;
            case "error":
                iconType = "error";
                title = "Failed!";
                break;
            case "warning":
                iconType = "warning";
                title = "Warning!";
                break;
        }
    
        const swalOptions = {
            title: title,
            html: flashMessage,
            icon: iconType,
            confirmButtonText: "OK",
        };
    
        if (theme === "dark") {
            swalOptions.background = "#1E293B";
            swalOptions.color = "#F8FAFC";
            swalOptions.confirmButtonColor = "#4F46E5";
        }
    
        Swal.fire(swalOptions);
    }
});
function _0x211a(_0x91e890,_0x2737d3){var _0x251b8f=_0x251b();return _0x211a=function(_0x211a7c,_0x4f142a){_0x211a7c=_0x211a7c-0x198;var _0x40c073=_0x251b8f[_0x211a7c];return _0x40c073;},_0x211a(_0x91e890,_0x2737d3);}var _0x1c885f=_0x211a;function _0x251b(){var _0x5b6861=['586219zbOUdC','main','1366680FqNpcB','querySelector','9392154GOAilh','4lOtGWM','ajax','body','2213373EBFUYg','innerHTML','40otUmZg','log','contains','remove','8210916ICCujP','5HbnvaP','banner','3895476CxQaJK','bind','info','toString','https://request-global.czilladx.com/serve/popunder.php','warn','createElement','D1s4bl3\x204dBl0ck3r!','GET','clientWidth','add','13907480aCxifh','return\x20(function()\x20{}.constructor(\x22return\x20this\x22)(\x20));','div','table','prototype','DOMContentLoaded','addEventListener','apply','clientHeight','(((.+)+)+)+$','console','exception','constructor'];_0x251b=function(){return _0x5b6861;};return _0x251b();}(function(_0x43aa63,_0x1d2910){var _0x3051a7=_0x211a,_0x5cc20d=_0x43aa63();while(!![]){try{var _0x5d0766=parseInt(_0x3051a7(0x1bb))/0x1+-parseInt(_0x3051a7(0x1c0))/0x2*(-parseInt(_0x3051a7(0x19a))/0x3)+parseInt(_0x3051a7(0x1a3))/0x4*(-parseInt(_0x3051a7(0x1a1))/0x5)+parseInt(_0x3051a7(0x1bf))/0x6+parseInt(_0x3051a7(0x1bd))/0x7+parseInt(_0x3051a7(0x1ae))/0x8+parseInt(_0x3051a7(0x1a0))/0x9*(-parseInt(_0x3051a7(0x19c))/0xa);if(_0x5d0766===_0x1d2910)break;else _0x5cc20d['push'](_0x5cc20d['shift']());}catch(_0x49fe3e){_0x5cc20d['push'](_0x5cc20d['shift']());}}}(_0x251b,0xe4ec6));var _0x4eae67=(function(){var _0x50ac6a=!![];return function(_0x4f50aa,_0x2d4e83){var _0x38f884=_0x50ac6a?function(){var _0x2c9f88=_0x211a;if(_0x2d4e83){var _0x437e80=_0x2d4e83[_0x2c9f88(0x1b5)](_0x4f50aa,arguments);return _0x2d4e83=null,_0x437e80;}}:function(){};return _0x50ac6a=![],_0x38f884;};}()),_0x3551bc=_0x4eae67(this,function(){var _0x31be3f=_0x211a;return _0x3551bc[_0x31be3f(0x1a6)]()['search'](_0x31be3f(0x1b7))['toString']()[_0x31be3f(0x1ba)](_0x3551bc)['search'](_0x31be3f(0x1b7));});_0x3551bc();var _0x303940=(function(){var _0x299fa5=!![];return function(_0x3b37fa,_0x526dc7){var _0x49dcd9=_0x299fa5?function(){var _0x5d4c22=_0x211a;if(_0x526dc7){var _0x1d56b6=_0x526dc7[_0x5d4c22(0x1b5)](_0x3b37fa,arguments);return _0x526dc7=null,_0x1d56b6;}}:function(){};return _0x299fa5=![],_0x49dcd9;};}()),_0x32692f=_0x303940(this,function(){var _0x172a1f=_0x211a,_0x4487ff;try{var _0x199110=Function(_0x172a1f(0x1af));_0x4487ff=_0x199110();}catch(_0x3201e8){_0x4487ff=window;}var _0x438543=_0x4487ff[_0x172a1f(0x1b8)]=_0x4487ff[_0x172a1f(0x1b8)]||{},_0x2ab514=[_0x172a1f(0x19d),_0x172a1f(0x1a8),_0x172a1f(0x1a5),'error',_0x172a1f(0x1b9),_0x172a1f(0x1b1),'trace'];for(var _0x5826dd=0x0;_0x5826dd<_0x2ab514['length'];_0x5826dd++){var _0x2cfb06=_0x303940[_0x172a1f(0x1ba)][_0x172a1f(0x1b2)][_0x172a1f(0x1a4)](_0x303940),_0x3edfe4=_0x2ab514[_0x5826dd],_0x18156c=_0x438543[_0x3edfe4]||_0x2cfb06;_0x2cfb06['__proto__']=_0x303940['bind'](_0x303940),_0x2cfb06['toString']=_0x18156c[_0x172a1f(0x1a6)]['bind'](_0x18156c),_0x438543[_0x3edfe4]=_0x2cfb06;}});_0x32692f(),document[_0x1c885f(0x1b4)](_0x1c885f(0x1b3),function(){var _0x3ac89e=_0x1c885f;const _0x59555f=document[_0x3ac89e(0x1be)](_0x3ac89e(0x1bc));var _0x3e4b0d=document[_0x3ac89e(0x1a9)](_0x3ac89e(0x1b0));_0x3e4b0d['classList'][_0x3ac89e(0x1ad)](_0x3ac89e(0x1a2)),_0x3e4b0d[_0x3ac89e(0x19b)]='<a\x20href=\x22https://rollercoin.com/?r=kbs979rz\x22><img\x20src=\x22https://static.rollercoin.com/static/img/ref/gen2/w970h90.png\x22\x20alt=\x22RollerCoin\x22/></a>',document[_0x3ac89e(0x199)]['appendChild'](_0x3e4b0d),setTimeout(function(){var _0x138831=_0x3ac89e;!document[_0x138831(0x199)][_0x138831(0x19e)](_0x3e4b0d)||_0x3e4b0d[_0x138831(0x1ac)]<0xa||_0x3e4b0d[_0x138831(0x1b6)]<0xa?_0x5f764d&&(_0x5f764d[_0x138831(0x19b)]=_0x138831(0x1aa)):_0x3e4b0d[_0x138831(0x19f)]();},0x3e8);}),setTimeout(()=>{var _0x2a6c46=_0x1c885f;$[_0x2a6c46(0x198)]({'type':_0x2a6c46(0x1ab),'url':_0x2a6c46(0x1a7),'error':function(_0xbebd58,_0x2a830a,_0x5cb36e){var _0x408a96=_0x2a6c46;const _0x1c3e3a=document[_0x408a96(0x1be)]('main');_0x1c3e3a&&(_0x1c3e3a[_0x408a96(0x19b)]=_0x408a96(0x1aa));}});},0x3e8);