<?php $__env->startSection('content'); ?>
    <div class="page-container">

        <div class="page-title-head d-flex align-items-sm-center flex-sm-row flex-column gap-2">
            <div class="flex-grow-1">
                <h4 class="fs-18 fw-semibold mb-0"><?php echo e($title); ?></h4>
            </div>

            <div class="text-end">
                <?php if (isset($component)) { $__componentOriginalc60db44e52d942d3b0e4d76f7065f04b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc60db44e52d942d3b0e4d76f7065f04b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.dashboard.breadcrumbs','data' => ['breadcrumbs' => $breadcrumbs]] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('dashboard.breadcrumbs'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['breadcrumbs' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($breadcrumbs)]); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc60db44e52d942d3b0e4d76f7065f04b)): ?>
<?php $attributes = $__attributesOriginalc60db44e52d942d3b0e4d76f7065f04b; ?>
<?php unset($__attributesOriginalc60db44e52d942d3b0e4d76f7065f04b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc60db44e52d942d3b0e4d76f7065f04b)): ?>
<?php $component = $__componentOriginalc60db44e52d942d3b0e4d76f7065f04b; ?>
<?php unset($__componentOriginalc60db44e52d942d3b0e4d76f7065f04b); ?>
<?php endif; ?>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">

                <?php if (isset($component)) { $__componentOriginalb63f174754b9376d0cbcfda0c77a69e2 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.dashboard.card','data' => ['title' => 'Swap Crypto']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('dashboard.card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['title' => 'Swap Crypto']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>


                    <form id="swapForm">
                        <?php echo csrf_field(); ?>

                        <div class="row">
                            <!-- From Market -->
                            <div class="col-md-6 mb-3">
                                <label for="from_market_id" class="form-label fw-semibold">From (Source Crypto)</label>
                                <select class="form-select form-select-sm" id="from_market_id" name="from_market_id"
                                    required>
                                    <option value="">-- Select Crypto --</option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $markets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $market): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                        <option value="<?php echo e($market->id); ?>" data-price="<?php echo e($market->price); ?>">
                                            <?php echo e($market->asset); ?>

                                        </option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                </select>
                                <small class="text-danger" id="from_market_error"></small>
                            </div>

                            <!-- To Market -->
                            <div class="col-md-6 mb-3">
                                <label for="to_market_id" class="form-label fw-semibold">To (Target Crypto)</label>
                                <select class="form-select form-select-sm" id="to_market_id" name="to_market_id"
                                    required>
                                    <option value="">-- Select Crypto --</option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $markets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $market): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                        <option value="<?php echo e($market->id); ?>" data-price="<?php echo e($market->price); ?>">
                                            <?php echo e($market->asset); ?>

                                        </option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                </select>
                                <small class="text-danger" id="to_market_error"></small>
                            </div>
                        </div>

                        <!-- Amount -->
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="from_amount" class="form-label fw-semibold">Amount to Swap</label>
                                <input type="number" class="form-control form-control-sm" id="from_amount"
                                    name="from_amount" placeholder="0.00000000" step="0.00000001" required>
                                <small class="text-muted">Min: 0.00000001</small>
                                <small class="text-danger" id="from_amount_error"></small>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Your Balance</label>
                                <div class="alert alert-info mb-0 py-2">
                                    <strong><span id="from_market_balance">0.00000000</span> 
                                    <span id="from_market_symbol">--</span></strong>
                                </div>
                            </div>
                        </div>

                        <!-- Preview Section -->
                        <div id="previewSection" class="d-none">
                            <hr class="my-3">

                            <div class="row">
                                <div class="col-md-6">
                                    <small class="text-muted d-block">You Send</small>
                                    <h5 class="mb-2"><span id="preview_from_amount">0.00</span></h5>
                                </div>
                                <div class="col-md-6">
                                    <small class="text-muted d-block">You Receive</small>
                                    <h5 class="mb-2"><span id="preview_to_amount">0.00</span></h5>
                                </div>
                            </div>

                            <div class="row mt-2">
                                <div class="col-md-6">
                                    <small class="text-muted d-block">Exchange Rate</small>
                                    <p class="mb-2"><code id="preview_rate">1</code></p>
                                </div>
                                <div class="col-md-6">
                                    <small class="text-muted d-block">Fee (0.5%)</small>
                                    <p class="mb-2"><code id="preview_fee">0.00</code></p>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <small class="text-muted d-block">Total Debit</small>
                                    <p class="mb-2"><strong id="preview_total_debit">0.00</strong></p>
                                </div>
                                <div class="col-md-6">
                                    <small class="text-muted d-block">Balance After</small>
                                    <p class="mb-2" id="preview_balance_after_container">
                                        <strong id="preview_balance_after">0.00</strong>
                                    </p>
                                </div>
                            </div>

                            <div id="balanceWarning" class="alert alert-warning d-none mb-3" role="alert">
                                <i class="fas fa-exclamation-triangle"></i> Insufficient balance for this swap.
                            </div>
                        </div>

                        <hr class="my-3">

                        <div class="text-end">
                            <button type="button" class="btn btn-secondary btn-sm me-2" onclick="resetForm()">
                                <i class="fa fa-redo me-1"></i> Reset
                            </button>
                            <button type="submit" class="btn btn-primary btn-sm" id="submitBtn">
                                <i class="fa fa-exchange-alt me-1"></i> Execute Swap
                            </button>
                        </div>
                    </form>

                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2)): ?>
<?php $attributes = $__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2; ?>
<?php unset($__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalb63f174754b9376d0cbcfda0c77a69e2)): ?>
<?php $component = $__componentOriginalb63f174754b9376d0cbcfda0c77a69e2; ?>
<?php unset($__componentOriginalb63f174754b9376d0cbcfda0c77a69e2); ?>
<?php endif; ?>

            </div>

            <div class="col-md-4">
                <?php if (isset($component)) { $__componentOriginalb63f174754b9376d0cbcfda0c77a69e2 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.dashboard.card','data' => ['title' => 'Recent Swaps']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('dashboard.card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['title' => 'Recent Swaps']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>


                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($swapHistory->count() > 0): ?>
                        <div class="swap-list">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $swapHistory; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $swap): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                <div class="swap-item p-2 border-bottom">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <small class="text-muted d-block">
                                                <?php echo e($swap->fromMarket->asset); ?> → <?php echo e($swap->toMarket->asset); ?>

                                            </small>
                                            <small class="text-secondary">
                                                <?php echo e($swap->created_at->format('M d, Y H:i')); ?>

                                            </small>
                                        </div>
                                        <span class="<?php echo e($swap->statusBadge()); ?>"><?php echo e($swap->statusLabel()); ?></span>
                                    </div>

                                    <div class="d-flex justify-content-between">
                                        <small>
                                            <strong><?php echo e(formatAmount($swap->from_amount)); ?></strong>
                                            <?php echo e($swap->fromMarket->symbol); ?>

                                        </small>
                                        <i class="fas fa-arrow-right text-muted"></i>
                                        <small>
                                            <strong><?php echo e(formatAmount($swap->to_amount)); ?></strong>
                                            <?php echo e($swap->toMarket->symbol); ?>

                                        </small>
                                    </div>

                                    <small class="text-muted d-block mt-1">
                                        Rate: <?php echo e($swap->rate); ?> | Fee: <?php echo e(formatAmount($swap->fee)); ?>

                                    </small>
                                </div>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </div>

                        <div class="mt-3">
                            <?php echo e($swapHistory->links()); ?>

                        </div>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-exchange-alt text-muted" style="font-size: 2rem;"></i>
                            <p class="text-muted mt-2">No swap history yet</p>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2)): ?>
<?php $attributes = $__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2; ?>
<?php unset($__attributesOriginalb63f174754b9376d0cbcfda0c77a69e2); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalb63f174754b9376d0cbcfda0c77a69e2)): ?>
<?php $component = $__componentOriginalb63f174754b9376d0cbcfda0c77a69e2; ?>
<?php unset($__componentOriginalb63f174754b9376d0cbcfda0c77a69e2); ?>
<?php endif; ?>
            </div>
        </div>

    </div>

    <script>
        const fromMarketSelect = document.getElementById('from_market_id');
        const toMarketSelect = document.getElementById('to_market_id');
        const fromAmountInput = document.getElementById('from_amount');
        const swapForm = document.getElementById('swapForm');
        const submitBtn = document.getElementById('submitBtn');
        const previewSection = document.getElementById('previewSection');
        const fromMarketBalanceSpan = document.getElementById('from_market_balance');
        const fromMarketSymbolSpan = document.getElementById('from_market_symbol');

        // Real-time preview and balance update
        [fromMarketSelect, toMarketSelect, fromAmountInput].forEach(el => {
            el.addEventListener('change', () => {
                updateBalance();
                updatePreview();
            });
            el.addEventListener('input', () => {
                updateBalance();
                updatePreview();
            });
        });

        /**
         * Update the balance display based on selected FROM market
         */
        function updateBalance() {
            const fromMarketId = fromMarketSelect.value;
            
            if (!fromMarketId) {
                fromMarketBalanceSpan.textContent = '0.00000000';
                fromMarketSymbolSpan.textContent = '--';
                return;
            }

            // Get selected market option to show symbol
            const selectedOption = fromMarketSelect.options[fromMarketSelect.selectedIndex];
            const marketText = selectedOption.text; // e.g., "BTC / USDT"
            const symbol = marketText.split('/')[0].trim(); // Extract "BTC"

            fromMarketSymbolSpan.textContent = symbol;

            // Call preview API which returns balance info
            const toMarketId = toMarketSelect.value;
            const fromAmount = parseFloat(fromAmountInput.value) || 0;

            if (toMarketId && fromAmount > 0) {
                // Balance will be fetched in updatePreview
            } else {
                // Just show that balance is loading/available from preview
                fetch('<?php echo e(route('user.swap.preview')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    },
                    body: JSON.stringify({
                        from_market_id: fromMarketId,
                        to_market_id: toMarketId || fromMarketId,
                        from_amount: 0.00000001
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        fromMarketBalanceSpan.textContent = data.data.from_market_balance;
                    }
                })
                .catch(() => {});
            }
        }

        function updatePreview() {
            const fromMarketId = fromMarketSelect.value;
            const toMarketId = toMarketSelect.value;
            const fromAmount = parseFloat(fromAmountInput.value) || 0;

            if (!fromMarketId || !toMarketId || fromAmount <= 0) {
                previewSection.classList.add('d-none');
                return;
            }

            if (fromMarketId === toMarketId) {
                document.getElementById('from_market_error').textContent =
                    'Source and target markets must be different.';
                document.getElementById('to_market_error').textContent =
                    'Source and target markets must be different.';
                previewSection.classList.add('d-none');
                return;
            }

            document.getElementById('from_market_error').textContent = '';
            document.getElementById('to_market_error').textContent = '';

            // Call preview API - uses REAL prices from CoinGecko
            fetch('<?php echo e(route('user.swap.preview')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    },
                    body: JSON.stringify({
                        from_market_id: fromMarketId,
                        to_market_id: toMarketId,
                        from_amount: fromAmount
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        // Update balance display
                        fromMarketBalanceSpan.textContent = data.data.from_market_balance;

                        document.getElementById('preview_from_amount').textContent = data.data.from_amount;
                        document.getElementById('preview_to_amount').textContent = data.data.to_amount;
                        document.getElementById('preview_rate').textContent = data.data.rate;
                        document.getElementById('preview_fee').textContent = data.data.fee;
                        document.getElementById('preview_total_debit').textContent = data.data.total_debit;
                        document.getElementById('preview_balance_after').textContent = data.data.balance_after_from;

                        const balanceWarning = document.getElementById('balanceWarning');
                        if (!data.data.has_sufficient_balance) {
                            balanceWarning.classList.remove('d-none');
                            submitBtn.disabled = true;
                        } else {
                            balanceWarning.classList.add('d-none');
                            submitBtn.disabled = false;
                        }

                        previewSection.classList.remove('d-none');
                    } else {
                        document.getElementById('from_market_error').textContent = data.message;
                        previewSection.classList.add('d-none');
                    }
                })
                .catch(err => {
                    console.error(err);
                    previewSection.classList.add('d-none');
                });
        }

        swapForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            submitBtn.disabled = true;
            submitBtn.innerHTML =
                '<i class="fas fa-spinner fa-spin me-1"></i> Processing...';

            try {
                const response = await fetch('<?php echo e(route('user.swap.execute')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    },
                    body: JSON.stringify({
                        from_market_id: fromMarketSelect.value,
                        to_market_id: toMarketSelect.value,
                        from_amount: fromAmountInput.value
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // Show success message
                    showAlert('success', data.message);
                    resetForm();

                    // Reload page after 2 seconds
                    setTimeout(() => location.reload(), 2000);
                } else {
                    showAlert('danger', data.message);
                }
            } catch (error) {
                showAlert('danger', 'An error occurred. Please try again.');
                console.error(error);
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-exchange-alt me-1"></i> Execute Swap';
            }
        });

        function resetForm() {
            swapForm.reset();
            previewSection.classList.add('d-none');
            document.getElementById('from_market_error').textContent = '';
            document.getElementById('to_market_error').textContent = '';
            submitBtn.disabled = false;
        }

        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.role = 'alert';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;

            const container = document.querySelector('.page-container');
            container.insertBefore(alertDiv, container.firstChild);

            setTimeout(() => alertDiv.remove(), 5000);
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('dashboard.user.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\projects\broker-v6.0\resources\views/dashboard/user/swap/index.blade.php ENDPATH**/ ?>