<script>
    $(document).ready(function () {
        'use strict';

        // Cache selectors
        const $depositMethodSelect = $('#deposit-method-select');
        const $manualDepositInfo = $('#manual-deposit-info');
        const $manualDepositRow = $('#manual-deposit-row');
        const $charge = $('#charge');
        const $amountLimit = $('#amount-limit');
        const $paymentMethod = $('.payment-method');
        const $conversionRate = $('.conversion-rate');
        const $depositAmount = $('#deposit-amount');
        const $amountDisplay = $('.amount');
        const $chargeDisplay = $('.charge');
        const $totalDisplay = $('.total');
        const $payAmountDisplay = $('.pay-amount');
        const siteCurrency = @json(setting('site_currency'));
        const depositMethodData = @json($depositMethods);
        let depositMethodDataItem;

        // Update deposit method details when selection changes
        $depositMethodSelect.on('change', function () {
            const depositMethod = $(this).val();

            depositMethodDataItem = depositMethodData.find(item => item.id == depositMethod);

            if (!depositMethodDataItem && depositMethod === 'user_balance') {
                $manualDepositInfo.html('');
                $manualDepositRow.html('');
                handleUserBalance()
            }

            if (depositMethodDataItem) {

                $manualDepositInfo.html('');
                $manualDepositRow.html('');

                if (depositMethodDataItem.type === 'manual') {
                    // Extract fields from depositMethodDataItem
                    let  fields = JSON.parse(depositMethodDataItem.fields);

                    // Check if fields is not an array, convert object to array
                    if (!Array.isArray(fields)) {
                        fields = Object.values(fields); // Convert object values to an array
                    }

                    // Generate the HTML using map and join for efficiency
                    const manualFieldsHtml = fields.map(field => {
                        // Generate validation attributes (e.g., required)
                        const validationAttributes = field.validation ? 'required' : '';

                        // Use a switch case to handle different field types
                        switch (field.type) {
                            case 'text':
                                return `
                                <div class="form-group">
                                    <label class="form-label" for="${field.name}">${field.name}</label>
                                    <input type="text" name="manual_data[${field.name}]" id="${field.name}" class="form-control" ${validationAttributes}>
                                </div>`;
                            case 'file':
                                return `
                                <div class="form-group">
                                    <label class="form-label" for="${field.name}">${field.name}</label>
                                    <input type="file" name="manual_data[${field.name}]" id="${field.name}" class="form-control" ${validationAttributes}>
                                </div>`;
                            default:
                                return ''; // Handle any other unsupported types
                        }
                    }).join(''); // Join the array into a single string

                    // Append the generated HTML to the cached target element
                    $manualDepositRow.html(manualFieldsHtml);

                    const depositInfoCard = `@include('frontend.user.deposit.partials._manual_method_info', ['info' => '${depositMethodDataItem.receive_payment_details}'])`;
                    $manualDepositInfo.html(depositInfoCard);

                }

                updateDepositDetails(depositMethodDataItem);
                const depositAmount = parseFloat($depositAmount.val()) || 0;
                depositAmountPreview(depositMethodDataItem, depositAmount);
            }
        });


        // Update deposit method UI
        function updateDepositDetails(depositMethodDataItem) {
            const chargeType = depositMethodDataItem.charge_type;
            const chargeValue = chargeType === 'fixed'
                ? `${depositMethodDataItem.charge} ${siteCurrency}`
                : `${depositMethodDataItem.charge}%`;

            $charge.text('Charge: ' + chargeValue);
            $amountLimit.text(`Min: ${depositMethodDataItem.min_deposit} ${siteCurrency} - Max: ${depositMethodDataItem.max_deposit} ${siteCurrency}`);
            $paymentMethod.text(depositMethodDataItem.name);
            $conversionRate.text(`1 ${siteCurrency} = ${depositMethodDataItem.conversion_rate} ${depositMethodDataItem.currency}`);
        }

        // Handle deposit amount and charge calculations
        function depositAmountPreview(depositMethodDataItem, depositAmount) {
            if (depositAmount > 0) {
                const charge = depositMethodDataItem.charge_type === 'percent'
                    ? (depositAmount * depositMethodDataItem.charge / 100)
                    : depositMethodDataItem.charge;

                // Update UI with calculated values
                $amountDisplay.text(depositAmount + ' ' + siteCurrency);
                $chargeDisplay.text(charge + ' ' + siteCurrency);
                const total = depositAmount + charge;
                $totalDisplay.text(total + ' ' + siteCurrency);
                const payAmount = total * depositMethodDataItem.conversion_rate;
                $payAmountDisplay.text(payAmount.toFixed(2) + ' ' + depositMethodDataItem.currency);
            }
        }

        // Handle user balance from
        function handleUserBalance() {
            const balance = parseFloat($depositAmount.val()) || 0;
            const zeroAmount = 0;

            const formattedBalance = balance + ' ' + siteCurrency;
            const formattedZero = zeroAmount + ' ' + siteCurrency;

            // Update the necessary fields
            $paymentMethod.text('User Balance');
            $amountDisplay.text(formattedBalance);
            $chargeDisplay.text(formattedZero);
            $totalDisplay.text(formattedBalance);
            $conversionRate.text('N/A');
            $payAmountDisplay.text(formattedBalance);
        }

        $('form').on('submit', function (e) {
            $('#progress-bar').removeClass('d-none');
        });
    });

</script>
