        var chartCache = JSON.parse(sessionStorage.getItem("chartCache")) || [];
        if (!Array.isArray(chartCache)) {
            chartCache = [];
        }
        
        function loadChart() {
            $("#chart").html('<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>');
            let dateRange = document.getElementById("date_range").value;
            let eventType = document.getElementById("event_type").value;
            let dates = dateRange.split(" to ");
            let startDate = dates[0]?.trim() || new Date().toISOString().split('T')[0];
            let endDate = dates[1]?.trim() || startDate;
        
            let cachedData = chartCache.find(entry => 
                entry.startDate === startDate && 
                entry.endDate === endDate && 
                entry.eventType === eventType
            );
        
            if (cachedData) {
                updateChartFromCache(cachedData.data);
                return;
            }
        
            $.ajax({
                url: "/chart/load",
                type: "GET",
                data: { start_date: startDate, end_date: endDate, event_type: eventType },
                dataType: "json",
                success: function (data) {
                    chartCache.push({ startDate, endDate, eventType, data });
        
                    sessionStorage.setItem("chartCache", JSON.stringify(chartCache));
        
                    let categories = data.map(item => item.date);
                    let values = data.map(item => Math.round(item.count));
                    let rewards = data.map(item => parseFloat(((item.total_reward || 0) * currencyRate).toFixed(currencyRounds)));
        
                    updateChart(categories, values, rewards);
                },
                error: function () {
                    console.error("Error fetching chart data.");
                }
            });
        }
        
        function updateChartFromCache(data) {
            let categories = data.map(item => item.date);
            let values = data.map(item => Math.round(item.count));
            let rewards = data.map(item => parseFloat(((item.total_reward || 0) * currencyRate).toFixed(currencyRounds)));
        
            updateChart(categories, values, rewards);
        }
    
        function updateChartFromCache(data) {
            let categories = data.map(item => item.date);
            let values = data.map(item => Math.round(item.count));
            let rewards = data.map(item => parseFloat(((item.total_reward || 0) * currencyRate).toFixed(currencyRounds)));
        
            updateChart(categories, values, rewards);
        }
    
        function updateChart(categories, values, rewards) {
            $("#chart").html('');
            let options = {
                series: [
                    { name: "Count", data: values },
                    { name: "Earned", data: rewards }
                ],
                chart: {
                    type: "area",
                    stacked: false,
                    height: 350,
                    toolbar: { show: false }
                },
                dataLabels: { enabled: false },
                markers: { size: 0 },
                fill: {
                    type: "gradient",
                    gradient: {
                        shadeIntensity: 1,
                        inverseColors: false,
                        opacityFrom: 0.35,
                        opacityTo: 0.05,
                        stops: [20, 100, 100, 100]
                    }
                },
                tooltip: {
                    shared: true,
                    y: {
                        formatter: function (value, { seriesIndex }) {
                            if (seriesIndex === 0) {
                                return value.toFixed(0);
                            } else {
                                return value.toLocaleString() + " " + currencyName;
                            }
                        }
                    }
                },
                legend: { position: "top", horizontalAlign: "left" },
                xaxis: { categories: categories }
            };
    
            if (window.chartInstance) {
                window.chartInstance.updateOptions(options);
            } else {
                window.chartInstance = new ApexCharts(document.getElementById("chart"), options);
                window.chartInstance.render();
            }
        }
    $(document).ready(function() {
        loadChart();
        
        function calculateAmount(rate) {
            let amount = parseFloat(document.querySelector('input[name="amount"]').value) || 0;
    
            if (amount <= 0) {
                document.querySelector('input[name="estimated"]').value = '0.00';
                return;
            }
    
            let amountUsd = amount / currencyRate;
            let feeAmount = (feeType === 'percentage') ? (amountUsd * feeValue) / 100 : feeValue;
            let amountAfterFee = amountUsd - feeAmount;
            let amountFinal = amountAfterFee / rate;
            document.querySelector('input[name="estimated"]').value = amountFinal.toFixed(8);
        }
        let cachedRates = {};
        
        function fetchRate() {
            let methodId = $('select[name="method"]').val();
        
            if (methodId) {
                if (cachedRates[methodId]) {
                    calculateAmount(cachedRates[methodId]);
                    return;
                }
        
                $.ajax({
                    url: '/withdraw/get-rate',
                    type: 'GET',
                    data: { method_id: methodId },
                    success: function (response) {
                        if (response.rate) {
                            cachedRates[methodId] = response.rate;
                            calculateAmount(response.rate);
                        }
                    },
                    error: function () {
                        console.log("Error fetching rate");
                    }
                });
            }
        }
    
        function updateAddressPlaceholder() {
            let walletType = $('select[name="method"]').find(':selected').data('wallet');
    
            if (walletType) {
                let formattedWallet = walletType.charAt(0).toUpperCase() + walletType.slice(1);
    
                if (formattedWallet === 'Faucetpay') {
                    $('#addressLabel').text(formattedWallet + " Email");
                    $('#address').attr('placeholder', "Enter your " + formattedWallet + " Email");
                } else if (formattedWallet === 'Cwallet') {
                    $('#addressLabel').text(formattedWallet + " ID");
                    $('#address').attr('placeholder', "Enter your " + formattedWallet + " ID");
                }
            }
        }
    
        $('select[name="method"]').change(function () {
            updateAddressPlaceholder();
            fetchRate();
        });
        updateAddressPlaceholder();
        let debounceTimer;
        $('input[name="amount"]').on('input', function () {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(fetchRate, 500);
        });
        function refreshBalance(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');
                }
            });
        }
        $(document).on('click', '#withdraw-btn', function(e) {
            e.preventDefault();
        
            let amount = $('input[name="amount"]').val();
            let methodId = $('select[name="method"]').val();
            let Address = $('input[name="address"]').val();
            let theme = localStorage.getItem("_x_darkMode_on") === "true" ? "dark" : "light";
            let selectedBalanceType = localStorage.getItem('selectedBalanceType');
            
            if (!amount || !methodId || !Address) {
                let swalOptions = {
                    icon: "error",
                    title: "Failed!",
                    html: `<p>Please fill all required fields.</p>`,
                    toast: true,
                    position: "bottom-end",
                    showConfirmButton: false,
                    customClass: {
                        popup: "toast-popup",
                        title: "toast-title",
                        content: "toast-content"
                    },
                    showCloseButton: true,
                    closeButtonHtml: "<i class='fas fa-times'></i>"
                };
                        
                if (theme === "dark") {
                    swalOptions.background = "#1E293B";
                    swalOptions.color = "#F8FAFC";
                    swalOptions.confirmButtonColor = "#4F46E5";
                }
                        
                Swal.fire(swalOptions);
                return;
            }
        
            $.ajax({
                url: '/withdraw/process-withdraw',
                type: 'POST',
                data: {
                    amount: amount,
                    method_id: methodId,
                    address: Address,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        let swalOptions = {
                            icon: "success",
                            title: "Success!",
                            html: `<p>${response.message}</p>`,
                            toast: true,
                            position: "bottom-end",
                            showConfirmButton: false,
                            customClass: {
                                popup: "toast-popup",
                                title: "toast-title",
                                content: "toast-content"
                            },
                            showCloseButton: true,
                            closeButtonHtml: "<i class='fas fa-times'></i>"
                        };
                        
                        if (theme === "dark") {
                            swalOptions.background = "#1E293B";
                            swalOptions.color = "#F8FAFC";
                            swalOptions.confirmButtonColor = "#4F46E5";
                        }

                        Swal.fire(swalOptions);
                        if(selectedBalanceType == 'balance') {
                            refreshBalance(selectedBalanceType);
                        }
                        loadWdHistory();
                    } else {
                        let swalOptions = {
                            icon: "error",
                            title: "Failed!",
                            html: `<p>${response.error}</p>`,
                            toast: true,
                            position: "bottom-end",
                            showConfirmButton: false,
                            customClass: {
                                popup: "toast-popup",
                                title: "toast-title",
                                content: "toast-content"
                            },
                            showCloseButton: true,
                            closeButtonHtml: "<i class='fas fa-times'></i>"
                        };
                        
                        if (theme === "dark") {
                            swalOptions.background = "#1E293B";
                            swalOptions.color = "#F8FAFC";
                            swalOptions.confirmButtonColor = "#4F46E5";
                        }
                        
                        Swal.fire(swalOptions);
                    }
                },
                error: function(xhr) {
                    alert("Error processing withdraw");
                }
            });
        });
        function loadWdHistory(page = 1) {
          $.ajax({
            url: "/withdraw/history",
            type: "GET",
            data: { page: page },
            dataType: "json",
            beforeSend: function () {
                $("#withdraw-history").html('<tr><td colspan="8" class="text-center py-4"><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></td></tr>');
            },
            success: function (data) {
                var html = "";
                if (data.records.length > 0) {
                    data.records.forEach(function (item) {
                      html += `
                        <tr class="border-y border-transparent border-b-slate-200 dark:border-b-navy-500">
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">
                              ${item.method}
                          </td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.address}</td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">
                              <span class="badge bg-${item.status.color} text-white">
                                ${item.status.text}
                              </span>
                          </td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.transaction}</td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.crypto}</td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.amount}</td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.fee}</td>
                          <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.date}</td>
                        </tr>`;
                    });
              } else {
                html = '<tr><td colspan="8" class="text-center py-4">No data available</td></tr>';
              }
              $("#withdraw-history").html(html);
    
            var paginationHtml = `
                <ol class="pagination">
                    <li class="rounded-l-full bg-slate-150 dark:bg-navy-500">
                        <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.prev_page}" ${data.prev_page ? "" : "disabled"}>
                            <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                            </svg>
                        </a>
                    </li>`;
            
            var startPage = Math.max(1, data.current_page - 2);
            var endPage = Math.min(data.total_pages, startPage + 4);
            
            if (startPage > 1) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="1">1</a>
                </li>`;
                if (startPage > 2) {
                    paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
                }
            }
            
            for (var i = startPage; i <= endPage; i++) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 ${i === data.current_page ? 'bg-primary px-3 leading-tight text-white transition-colors hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90' : 'leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90'}" data-page="${i}">${i}</a>
                </li>`;
            }
            
            if (endPage < data.total_pages) {
                if (endPage < data.total_pages - 1) {
                    paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
                }
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.total_pages}">${data.total_pages}</a>
                </li>`;
            }
            
            paginationHtml += `
                <li class="rounded-r-full bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.next_page}" ${data.next_page ? "" : "disabled"}>
                        <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                        </svg>
                    </a>
                </li>
            </ol>`;
            
            $("#pagination").html(paginationHtml);
    
            },
          });
        }
    
        loadWdHistory();
    
        $(document).on("click", ".pagination-btn", function (e) {
          e.preventDefault();
          var page = $(this).data("page");
          if (page) loadWdHistory(page);
        });
    });