@php use App\Enums\MethodType; @endphp
<script>
    $(document).ready(function () {
        'use strict';

        // DOM Elements
        const elements = {
            depositMethodList: $('.deposit-method-list'),
            depositMethodInfo: $('.deposit-method-info'),
            depositAmountInfo: $('.deposit-amount-info'),
            walletSelect: $('.wallet-select'),
            depositInput: $('.deposit-amount'),
            summary: {
                methodName: $('.summary-method-name'),
                amount: $('.summary-amount'),
                charge: $('.summary-charge'),
                total: $('.summary-total'),
                rate: $('.summary-rate'),
                added: $('.wallet-added'),
                payable: $('.summary-payable'),
            },
        };

        const templates = {
            defaultOption: `<option disabled selected>{{ __('Select Deposit Method') }}</option>`,
            noMethodOption: `<option disabled selected>{{ __('Select Another Wallet') }}</option>`,
        };

        let depositMethods = [];
        let selectedMethod = null;
        const siteCurrency = '{{ siteCurrency() }}';
        let walletCurrency = null;
        
      
        
        if (elements.walletSelect.val() !== null) {
            walletAjaxRequest(elements.walletSelect.val());
        }

        /**
         * Update deposit methods dropdown and info
         * @param {Array} methods
         */
        const updateDepositMethods = (methods) => {
            const {depositMethodList, depositMethodInfo} = elements;

            if (methods.length) {
                depositMethodList.html(templates.defaultOption);
                methods.forEach(method =>
                    depositMethodList.append(`<option value="${method.id}">${method.name}</option>`)
                );
                depositMethodInfo.text('');
            } else {
                depositMethodList.html(templates.noMethodOption);
                depositMethodInfo.text('{{ __('No Payment Method Available For This Wallet') }}');
            }
        };

        /**
         * Update deposit amount info and summary details
         * @param {number} amount
         */
        const updateDepositAmountInfo = (amount) => {
            if (!selectedMethod) return;

            const {min_deposit, max_deposit} = selectedMethod;
            const {depositAmountInfo} = elements;

            if (amount < min_deposit || amount > max_deposit) {
                depositAmountInfo.text(`{{ __('Amount must be between') }} ${min_deposit} ${siteCurrency} {{ __('and') }} ${max_deposit} ${siteCurrency}`);
                resetSummary();
            } else {
                depositAmountInfo.text(`{{ __('Min Deposit') }}: ${min_deposit} ${siteCurrency}, {{ __('Max Deposit') }}: ${max_deposit} ${siteCurrency}`);
                updateSummary(amount);
            }
        };

        /**
         * Update summary details
         * @param {number} amount
         */
        const updateSummary = (amount) => {
            if (!selectedMethod) {
                resetSummary();
                return;
            }

            const charge = selectedMethod.charge_type === 'percent'
                ? (amount * selectedMethod.charge) / 100
                : selectedMethod.charge;
            const total = amount + charge;
            const conversionRate = parseFloat(selectedMethod.conversion_rate) || 1;
            const walletAdded = amount * conversionRate;
            const payable = total * conversionRate;

            const {summary} = elements;
            summary.methodName.text(selectedMethod.name);
            summary.amount.text(`${amount.toFixed(2)} ${siteCurrency}`);
            summary.charge.text(`${charge.toFixed(2)} ${siteCurrency}`);
            summary.total.text(`${total.toFixed(2)} ${siteCurrency}`);
            summary.rate.text(`1${siteCurrency} = ${conversionRate.toFixed(2)} ${walletCurrency}`);
            summary.added.text(`${walletAdded.toFixed(2)} ${walletCurrency}`);
            summary.payable.text(`${payable.toFixed(2)} ${walletCurrency}`);
        };

        /**
         * Reset summary details
         */
        const resetSummary = () => {
            const {summary} = elements;
            Object.values(summary).forEach(el => el.text('{{ __('N/A') }}'));
        };

        // Event Handlers
        elements.walletSelect.on('change', function () {
            const walletId = $(this).val();
            walletAjaxRequest(walletId);
        });
        
        
        

        elements.depositMethodList.on('change', function () {
            const paymentMethodId = $(this).val();
            selectedMethod = depositMethods.find(method => method.id == paymentMethodId);
            walletCurrency = selectedMethod?.currency;

            if (selectedMethod) {
                const chargeInfo = selectedMethod.charge_type === 'percent'
                    ? `{{ __('Charge') }}: ${selectedMethod.charge}%`
                    : `{{ __('Charge') }}: ${selectedMethod.charge} ${siteCurrency}`;
                elements.depositMethodInfo.text(chargeInfo);
                updateDepositAmountInfo(parseFloat(elements.depositInput.val()) || 0);
                $('#manual-deposit-credentials').html('');
                
                if (selectedMethod.type === `{{ MethodType::MANUAL }}`) {

                    $.ajax({
                        url: `{{ route('user.deposit.credentials', ':method') }}`.replace(':method', paymentMethodId),
                        method: 'GET',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: (data) => {
                            // Insert the rendered view into the DOM
                            $('#manual-deposit-credentials').html(data);
                        },
                    })

                }
            }
        });

        elements.depositInput.on('keyup', function () {
            const amount = parseFloat($(this).val()) || 0;
            updateDepositAmountInfo(amount);
        });
        
        function walletAjaxRequest(walletId) {
            const url = `{{ route('user.wallet.supported-payment-methods', ':wallet') }}`.replace(':wallet', walletId);
            
            $.ajax({
                url,
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: (data) => {
                    depositMethods = data;
                    updateDepositMethods(data);
                    selectedMethod = null;
                    resetSummary();
                },
                error: () => {
                    alert('{{ __('Failed to load payment methods. Please try again later.') }}');
                }
            });
        }
    });

</script>
