(function ($) {
    "use strict";

    /* ===================================
        General
     ====================================== */

    // Add Funds
    $(document).on('submit', '#gn-deposit-funds-form', function (e) {
        e.preventDefault();

        let _this = $(this);
        let proceed = true;

        // Sanitize the amount input
        let amountInput = _this.find('input[name="amount"]');
        let sanitizedValue = amountInput.val().replace(/[^0-9]/g, '');
        amountInput.val(sanitizedValue);

        let form_data = new FormData(_this[0]);
        form_data.append('action', 'gigneo_deposit_funds');
        form_data.append('security', GigneoCommon.security);

        // Fields validation
        proceed = window.GigneoRequiredFormFields.init(_this, proceed);

        if (proceed) {
            let submit_btn = _this.find('button[type="submit"]');

            submit_btn.addClass('gn-loading');

            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    submit_btn.removeClass('gn-loading');
                    if (response.success && response.data.message) {
                        GigneoAlert.toast({
                            icon: 'success',
                            title: GigneoCommon.success,
                            text: response.data.message
                        });

                        if (response.data.redirect) {
                            window.location.href = response.data.redirect;
                        }
                    }
                    else {
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: response
                        });
                    }
                },
                error: function (xhr) {
                    submit_btn.removeClass('gn-loading');
                    let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                    GigneoAlert.toast({
                        icon: 'error',
                        title: GigneoCommon.error,
                        text: error_message
                    });
                }
            });
        }
    });

    // Withdraw Funds
    $(document).on('submit', '#gn-withdraw-funds-form', function (e) {
        e.preventDefault();

        let _this = $(this);
        let proceed = true;

        // Sanitize the amount input
        let amountInput = _this.find('input[name="amount"]');
        let sanitizedValue = parseInt(amountInput.val().replace(/[^0-9]/g, ''), 10) || 0;
        amountInput.val(sanitizedValue);

        let form_data = new FormData(_this[0]);
        form_data.append('action', 'gigneo_withdraw_funds');
        form_data.append('security', GigneoCommon.security);

        // Fields validation
        proceed = window.GigneoRequiredFormFields.init(_this, proceed);

        if (proceed) {
            let submit_btn = _this.find('button[type="submit"]');

            submit_btn.addClass('gn-loading');

            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    submit_btn.removeClass('gn-loading');
                    if (response.success && response.data.message) {
                        GigneoAlert.toast({
                            icon: 'success',
                            title: GigneoCommon.success,
                            text: response.data.message
                        });
                    } else {
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: response.data.message
                        });
                    }

                    location.reload();
                },
                error: function (xhr) {
                    submit_btn.removeClass('gn-loading');
                    let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                    GigneoAlert.toast({
                        icon: 'error',
                        title: GigneoCommon.error,
                        text: error_message
                    });
                }
            });
        }
    });

    $(document).on('keydown input', '#gn-withdraw-funds-amount, #gn-withdraw-funds-form input.gn-payout-radio', function (e) {
        if (e.key && ['.', ',', 'e', 'E', '-', '+'].includes(e.key)) {
            e.preventDefault();
            return false;
        }

        let wallet_balance = parseFloat($('#gn-wallet-balance').val()) || 0;
        let submit_btn = $('#gn-withdraw-funds-form button[type="submit"]');

        // Get amount
        let amount = parseFloat($('#gn-withdraw-funds-amount').val()) || 0;

        // Get selected payout method
        let selected_method = $('#gn-withdraw-funds-form input.gn-payout-radio:checked');

        // Get commissions (ensure numbers, default to 0 if not set)
        let fixed_commission = parseFloat(selected_method.data('gn-commission-fixed')) || 0;
        let percent_commission = parseFloat(selected_method.data('gn-commission-percentage')) || 0;

        // Calculate total commission
        let total_commission = fixed_commission;
        if (percent_commission > 0 && amount > 0) {
            total_commission += (amount * (percent_commission / 100));
        }

        // Calculate final amount
        let final_amount = amount - total_commission;

        // Update UI
        $('#gn-withdrawal-requested').text(GigneoPrice.format(amount, true));
        $('#gn-withdrawal-fee').text(GigneoPrice.format(total_commission, true));
        $('#gn-withdrawal-final-amount').text(GigneoPrice.format(final_amount, true));

        if (wallet_balance < amount) {
            submit_btn.attr('disabled', 'disabled');
        } else {
            submit_btn.removeAttr('disabled');
        }

    });

    /* ===================================
        Overview
     ====================================== */

    $(document).on('change', '#gn-per-page', function () {
        let _this = $(this).val();
        let currentUrl = window.location.href;

        var newUrl = new URL(currentUrl);
        newUrl.searchParams.set('per_page', _this);
        window.location.href = newUrl.toString();
    });

    // Auto-submit on select change
    $(document).on('change', '.gn-account-invoice-form select, .gn-account-history-form select', function () {
        $(this).closest('form').submit();
    });

    if ($('#gn-account-overview-wrapper').length) {

        let half_doughnut_chart = $('#gn-half-doughnut-chart');
        if (half_doughnut_chart.length) {
            let ctx2 = half_doughnut_chart[0].getContext('2d');

            let total = parseFloat(half_doughnut_chart.data('gn-total-percentage')) || 100;
            let completed = parseFloat(half_doughnut_chart.data('gn-completed-percentage')) || 0;

            let chartData = {
                datasets: [{
                    data: [completed, total - completed],
                    backgroundColor: [GigneoCommon.primary_color || '#7B4BFD', '#f4f0fa'],
                    borderWidth: 0,
                    borderRadius: 20,
                    cutout: '80%',
                }]
            };

            new Chart(ctx2, {
                type: 'doughnut',
                data: chartData,
                options: {
                    rotation: -90,
                    circumference: 180,
                    responsive: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: { enabled: false }
                    },
                    hover: { mode: null }
                }
            });
        }

    }

    /* ===================================
        Earning
    ====================================== */

    if ($('#gn-account-earning-wrapper').length) {
        // Bar Charts
        let earning_bar_instance = null;

        // Init Earning Chart
        initBarChart('#gn-earning-bar-chart-canvas', '#gn-earning-duration', earning_bar_instance);

    }


    /* ===================================
       Spending
    ====================================== */

    if ($('#gn-account-spending-wrapper').length) {
        // Bar Charts
        let spending_bar_instance = null;

        // Init Spending Chart
        initBarChart('#gn-spending-bar-chart-canvas', '#gn-spending-duration', spending_bar_instance);

    }

    /* ===================================
        Wallet
    ====================================== */

    if ($('#gn-account-wallet-wrapper').length) {

        //Service Remove
        $('.gn-cancel-withdrawal-request').on('click', function (e) {
            e.preventDefault();
            let _this = $(this);
            let _id = _this.data('gn-id');

            _this.parents('.gn-modal-wrapper').removeClass('gn-active');

            GigneoAlert.confirm({
                title: GigneoCommon.confirmation_title,
                text: GigneoCommon.cancel_confirmation_desc,
                confirmButtonText: GigneoCommon.cancel,
                icon: 'error',
                showLoaderOnConfirm: false,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    const confirmBtn = Swal.getConfirmButton();
                    confirmBtn.classList.add('gn-loading');
                    confirmBtn.disabled = true;

                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: GigneoCommon.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'gigneo_cancel_withdrawal_request',
                                id: _id,
                                security: GigneoCommon.security,
                            },
                            success: function (response) {
                                if (response.success) {
                                    if (response.data.message) {
                                        GigneoAlert.toast({
                                            icon: 'success',
                                            title: GigneoCommon.success,
                                            text: response.data.message
                                        });
                                    }
                                    window.location.reload();
                                } else {
                                    GigneoAlert.toast({
                                        icon: 'error',
                                        title: GigneoCommon.error,
                                        text: response.data && response.data.message ? response.data.message : ''
                                    });
                                }
                            },
                            error: function (response) {
                                GigneoAlert.toast({
                                    icon: 'error',
                                    title: GigneoCommon.error,
                                    text: response.responseJSON && response.responseJSON.data && response.responseJSON.data.message ? response.responseJSON.data.message : ''
                                });
                            }
                        });
                    });
                }
            });

        });

        // Line Charts
        let wallet_overview_line_instance = null;

        // Init Earning Chart
        initLineChart('#gn-wallet-overview-line-chart-canvas', '#gn-wallet-duration', wallet_overview_line_instance);

    }


    /* ===================================
        Credits
    ====================================== */

    if ($('#gn-account-credit-wrapper').length) {

        // Bar Charts
        let credit_bar_instance = null;

        // Init Spending Chart
        initBarChart('#gn-credit-bar-chart-canvas', '#gn-credit-duration', credit_bar_instance);

        //Add Credits
        $(document).ready(function () {
            let buy_credits_proceed = false;
            let total_credits = 0;
            let total_amount = 0;
            let buy_credit_form = $(document).find('#gn-purchase-credits-form');
            let per_credit_rate = buy_credit_form.find('input[name="per_credit_rate"]').val() || 0;

            let total_credit_selector = buy_credit_form.find('#gn-total-credit-purchase');
            let total_amount_selector = buy_credit_form.find('#gn-total-credit-amount');

            $(document).on('keydown input', '#gn-total-purchase-credits', function (e) {
                if (e.key && ['.', ',', 'e', 'E', '-', '+'].includes(e.key)) {
                    e.preventDefault();
                    return false;
                }
                let _this = $(this);
               
                per_credit_rate = parseFloat(per_credit_rate);
                total_credits = parseFloat(_this.val()) || 0;
                total_amount = total_credits * per_credit_rate;

                total_credit_selector.html(total_credits);
                total_amount_selector.html(GigneoPrice.format(total_amount, true));

            });

            // Buy Credits
            buy_credit_form.on('submit', function (e) {
                e.preventDefault();

                let _this = $(this);
                

                // Sanitize the amount input
                let amountInput = _this.find('input[name="credits"]');
                let sanitizedValue = amountInput.val().replace(/[^0-9]/g, '');
                amountInput.val(sanitizedValue);

                let form_data = new FormData(_this[0]);
                form_data.append('action', 'gigneo_buy_credits');
                form_data.append('security', GigneoCommon.security);

                if (total_credits > 0) {
                    buy_credits_proceed = true;
                } else {
                    buy_credits_proceed = false;
                }

                // Fields validation
                buy_credits_proceed = window.GigneoRequiredFormFields.init(_this, buy_credits_proceed);

                if (buy_credits_proceed) {
                    let submit_btn = _this.find('button[type="submit"]');

                    submit_btn.addClass('gn-loading').attr('disabled', true);

                    $.ajax({
                        url: GigneoCommon.ajax_url,
                        method: 'POST',
                        data: form_data,
                        contentType: false,
                        processData: false,
                        success: function (response) {
                            if (response.success && response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }
                            location.reload();
                        },
                        error: function (xhr) {
                            submit_btn.removeClass('gn-loading').attr('disabled', false);
                            location.reload();
                            let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: error_message
                            });
                        }
                    });
                }
            });
        });

        //Credit Plan
        $('.gn-purchase-credit-plan-form').on('submit', function (e) {
            e.preventDefault();

            let _this = $(this);

            let proceed = window.GigneoRequiredFormFields.init(_this);

            if (!proceed) {
                return false;
            }


            let submit_btn = _this.find('button[type="submit"]');
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_buy_credit_plan');
            form_data.append('security', GigneoCommon.security);

            submit_btn.addClass('gn-loading');

            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    submit_btn.removeClass('gn-loading');
                    if (response.success && response.data.message) {
                        GigneoAlert.toast({
                            icon: 'success',
                            title: GigneoCommon.success,
                            text: response.data.message
                        });
                    }

                    location.reload();
                },
                error: function (xhr) {
                    submit_btn.removeClass('gn-loading');
                    let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                    GigneoAlert.toast({
                        icon: 'error',
                        title: GigneoCommon.error,
                        text: error_message
                    });
                }
            });

        });
    }

    /* ===================================
        Charts
    ====================================== */

    function initBarChart(chartSelector, selectSelector, instanceRef) {
        if (typeof Chart === 'undefined') {
            return;
        }

        const $chartEl = $(chartSelector);
        const rawData = $chartEl.data('gn-chart');

        if (!$chartEl.length || !rawData) {
            return;
        }

        const chartDataSet = typeof rawData === 'object' ? rawData : JSON.parse(rawData);
        const $durationSelect = $(selectSelector);

        function buildChart(durationKey) {
            const ctx = $chartEl[0].getContext('2d');
            const dataSet = chartDataSet[durationKey] || chartDataSet['last_12_months'];

            if (instanceRef) {
                instanceRef.destroy();
            }

            instanceRef = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: Array.isArray(dataSet.labels) ? dataSet.labels : Object.values(dataSet.labels),
                    datasets: Array.isArray(dataSet.datasets) ? dataSet.datasets : Object.values(dataSet.datasets)
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: { color: '#555', font: { size: 12 } }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1000,
                                callback: value => GigneoPrice.format(value, true),
                                font: { size: 12 }
                            },
                            grid: { display: false }
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 5,
                                boxHeight: 5,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgb(var(--gigneo-dark-color))',
                            titleColor: '#fff',
                            cornerRadius: 8,
                            padding: 10,
                            displayColors: false,
                            callbacks: {
                                label: context => `${context.dataset.label}: ${GigneoPrice.format(context.parsed.y, true)}`
                            }
                        }
                    }
                }
            });
        }

        // Initial render
        buildChart($durationSelect.val());

        // On duration change
        $durationSelect.on('change', function () {
            buildChart($(this).val());
        });
    }

    function initLineChart(chartSelector, selectSelector, instanceRef) {
        if (typeof Chart === 'undefined') {
            return;
        }

        const $chartEl = $(chartSelector);
        const rawData = $chartEl.data('gn-chart');

        if (!$chartEl.length || !rawData) {
            return;
        }

        const chartDataSet = typeof rawData === 'object' ? rawData : JSON.parse(rawData);
        const $durationSelect = $(selectSelector);

        function buildChart(durationKey) {
            const ctx = $chartEl[0].getContext('2d');
            const dataSet = chartDataSet[durationKey] || chartDataSet['last_12_months'];

            if (instanceRef) {
                instanceRef.destroy();
            }

            instanceRef = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: dataSet.labels,
                    datasets: dataSet.datasets.map(dataset => ({
                        ...dataset,
                        pointRadius: 0,
                        pointStyle: 'circle',
                        pointBackgroundColor: dataset.backgroundColor,
                        pointBorderWidth: 0,
                        fill: false,
                        tension: 0.4,
                        borderWidth: 1,
                    }))
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    elements: {
                        point: {
                            hitRadius: 50,
                            hoverRadius: 4,
                            hoverBorderWidth: 1,
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            grid: { display: false },
                            ticks: { color: '#555', font: { size: 12 } }
                        },
                        y: {
                            display: true,
                            ticks: {
                                stepSize: 1000,
                                callback: value => GigneoPrice.format(value, true),
                                font: { size: 12 }
                            },
                            grid: { display: false }
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 5,
                                boxHeight: 5,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgb(var(--gigneo-dark-color))',
                            titleColor: '#fff',
                            cornerRadius: 8,
                            padding: 10,
                            displayColors: false,
                            callbacks: {
                                label: context => `${context.dataset.label}: ${GigneoPrice.format(context.parsed.y, true)}`
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    hover: {
                        mode: 'nearest',
                        intersect: true
                    }
                }
            });
        }

        // Initial render
        buildChart($durationSelect.val());

        // On duration change
        $durationSelect.on('change', function () {
            buildChart($(this).val());
        });
    }

}(jQuery));