<script>
    'use strict';

    // Pass siteCurrency dynamically from Blade
    const siteCurrency = '{{ siteCurrency() }}';

    const exchangeInfo = {
        sourceWalletId: null,
        destinationWalletId: null,
        sourceCurrency: null,
        destinationCurrency: null,
        conversionRate: 1,
        defaultRate: 1,
        feeType: null,
        fee: 0,
        minLimit: 0,
        maxLimit: 0,
    };

    const selectors = {
        sourceWalletSelect: '.source-wallet-select',
        destinationWalletSelect: '.destination-wallet-select',
        amountInput: '.amount-input',
        sendAmountInfo: '.send-amount-info',
        toWalletWarning: '.to-wallet-warning',
        exchangeFee: '.exchange-fee',
        summaryAmount: '.summary-amount',
        summaryFee: '.summary-fee',
        summaryTotal: '.summary-total',
        defaultRate: '.default-summary-rate',
        exchangeRate: '.exchange-summary-rate',
        summaryDebited: '.summary-debited',
        summaryCredited: '.summary-credited',
    };

    // Cache DOM elements
    const $sourceWalletSelect = $(selectors.sourceWalletSelect);
    const $destinationWalletSelect = $(selectors.destinationWalletSelect);
    const $amountInput = $(selectors.amountInput);
    const $sendAmountInfo = $(selectors.sendAmountInfo);
    const $toWalletWarning = $(selectors.toWalletWarning);
    const $exchangeFee = $(selectors.exchangeFee);
    const $summaryAmount = $(selectors.summaryAmount);
    const $summaryFee = $(selectors.summaryFee);
    const $summaryTotal = $(selectors.summaryTotal);
    const $defaultRate = $(selectors.defaultRate);
    const $exchangeRate = $(selectors.exchangeRate);
    const $summaryDebited = $(selectors.summaryDebited);
    const $summaryCredited = $(selectors.summaryCredited);

    // Debounce function
    const debounce = (func, delay) => {
        let debounceTimer;
        return function () {
            const context = this;
            const args = arguments;
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => func.apply(context, args), delay);
        };
    };

    // Function to fetch currency conversion rate
    const fetchCurrencyRate = async (fromCurrency, toCurrency) => {
        try {
            const response = await fetch(`/currency-rate/${fromCurrency}/${toCurrency}`);
            const data = await response.json();
            return parseFloat(data.rate) || 1;
        } catch (error) {
            console.error('Error fetching exchange rate:', error);
            return 1;
        }
    };

    // Update fee display
    const updateFeeDisplay = () => {
        if (!exchangeInfo.fee || !exchangeInfo.feeType) {
            $exchangeFee.text('');
            return;
        }

        const feeText = exchangeInfo.feeType === 'percent'
            ? `${exchangeInfo.fee}%`
            : `${exchangeInfo.fee} ${siteCurrency}`;

        $exchangeFee.text(`Fee: ${feeText}`);
    };

    // Validate amount limits
    const validateAmountLimits = (amount) => {
        if (!amount) {
            $sendAmountInfo
                .text(`Min: ${exchangeInfo.minLimit} ${siteCurrency} | Max: ${exchangeInfo.maxLimit} ${siteCurrency}`)
                .removeClass('text-danger')
                .addClass('text-success');
            return false;
        }

        if (amount < exchangeInfo.minLimit || amount > exchangeInfo.maxLimit) {
            $sendAmountInfo
                .text(`Amount must be between ${exchangeInfo.minLimit} ${siteCurrency} and ${exchangeInfo.maxLimit} ${siteCurrency}`)
                .addClass('text-danger')
                .removeClass('text-success');
            return false;
        } else {
            $sendAmountInfo
                .text(`Min: ${exchangeInfo.minLimit} ${siteCurrency} | Max: ${exchangeInfo.maxLimit} ${siteCurrency}`)
                .removeClass('text-danger')
                .addClass('text-success');
            return true;
        }
    };

    // Check if wallets are not the same
    const checkWalletsNotSame = () => {
        if (exchangeInfo.sourceWalletId === exchangeInfo.destinationWalletId) {
            $toWalletWarning.text('Source and destination wallets cannot be the same.');
        } else {
            $toWalletWarning.text('');
        }
    };

    // Update summary
    const updateSummary = async () => {
        const amount = parseFloat($amountInput.val()) || null;

        if (!validateAmountLimits(amount)) {
            clearSummary();
            return;
        }

        if (!amount || !exchangeInfo.sourceCurrency || !exchangeInfo.destinationCurrency) {
            clearSummary();
            return;
        }

        exchangeInfo.conversionRate = await fetchCurrencyRate(exchangeInfo.sourceCurrency, exchangeInfo.destinationCurrency);

        exchangeInfo.defaultRate = parseFloat(
            $sourceWalletSelect.find(':selected').data('default-conversion-rate')
        ) || 1;

        const fee = exchangeInfo.feeType === 'percent'
            ? (parseFloat(exchangeInfo.fee) / 100) * amount
            : parseFloat(exchangeInfo.fee);

        const total = amount + fee;
        const debitedFromSourceWallet = (total * exchangeInfo.defaultRate).toFixed(2);
        const creditedToDestinationWallet = (amount * exchangeInfo.conversionRate).toFixed(2);

        $summaryAmount.text(`${amount.toFixed(2)} ${siteCurrency}`);
        $summaryFee.text(`${fee.toFixed(2)} ${siteCurrency}`);
        $summaryTotal.text(`${total.toFixed(2)} ${siteCurrency}`);
        $defaultRate.text(`1 ${siteCurrency} = ${exchangeInfo.defaultRate.toFixed(2)} ${exchangeInfo.sourceCurrency}`);
        $exchangeRate.text(`1 ${exchangeInfo.sourceCurrency} = ${exchangeInfo.conversionRate.toFixed(2)} ${exchangeInfo.destinationCurrency}`);
        $summaryDebited.text(`${debitedFromSourceWallet} ${exchangeInfo.sourceCurrency}`);
        $summaryCredited.text(`${creditedToDestinationWallet} ${exchangeInfo.destinationCurrency}`);
    };

    // Clear summary
    const clearSummary = () => {
        $summaryAmount.text('');
        $summaryFee.text('');
        $summaryTotal.text('');
        $defaultRate.text('');
        $exchangeRate.text('');
        $summaryDebited.text('');
        $summaryCredited.text('');
    };

    // Event listeners
    $sourceWalletSelect.on('change', function () {
        const selectedOption = $(this).find(':selected');
        exchangeInfo.sourceWalletId = selectedOption.val();
        exchangeInfo.sourceCurrency = selectedOption.data('currency');
        exchangeInfo.feeType = selectedOption.data('fee-type');
        exchangeInfo.fee = parseFloat(selectedOption.data('fee')) || 0;
        exchangeInfo.minLimit = parseFloat(selectedOption.data('min-limit')) || 0;
        exchangeInfo.maxLimit = parseFloat(selectedOption.data('max-limit')) || Infinity;

        validateAmountLimits(parseFloat($amountInput.val()) || null);
        updateFeeDisplay();
        updateSummary();
        checkWalletsNotSame();
    });

    $destinationWalletSelect.on('change', function () {
        const selectedOption = $(this).find(':selected');
        exchangeInfo.destinationWalletId = selectedOption.val();
        exchangeInfo.destinationCurrency = selectedOption.data('currency');

        checkWalletsNotSame();
        updateSummary();
    });

    $amountInput.on('keyup', debounce(updateSummary, 300));

</script>
