<?php if (isset($component)) { $__componentOriginal951024bfcf58033c82ac11d797616473 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal951024bfcf58033c82ac11d797616473 = $attributes; } ?>
<?php $component = App\View\Components\UserLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('user-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\UserLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
    <div class="w-full mx-auto h-auto bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-white transition-all duration-300">
        <!-- Header -->
        <div class="flex items-center justify-between p-4">
            <a href="<?php echo e(route('send.external')); ?>" class="text-gray-400 hover:text-gray-300">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <h1 class="text-xl font-semibold">Send <?php echo e($asset['name']); ?></h1>
            <div class="w-8"></div> <!-- Spacer for centering -->
        </div>

        <!-- Main Content -->
        <div class="p-4 space-y-6">
            <!-- Sending Method -->
            <div class="bg-white dark:bg-black dark:bg-opacity-50 p-3 rounded-lg text-center">
                <p class="text-sm">
                    <span class="text-gray-800 dark:text-gray-400">Sending via - </span>
                    <span class="text-yellow-500">Cryptocurrency</span>
                </p>
            </div>

            <!-- Error Message -->
            <?php if(session('error')): ?>
            <div class="bg-red-500 bg-opacity-10 border border-red-500 text-red-500 px-4 py-3 rounded relative" role="alert">
                <p class="text-sm"><?php echo e(session('error')); ?></p>
            </div>
            <?php endif; ?>
            
            <!-- External Send Form -->
            <form id="sendForm" class="space-y-6" action="<?php echo e(route('send.external.process', ['symbol' => $asset['symbol'], 'network' => $asset['network'] ?? 'native'])); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <!-- Address Input -->
                <div class="space-y-2">
                    <label for="address" class="block text-sm font-medium text-gray-800 dark:text-gray-300">
                        <?php echo e($asset['symbol']); ?> Address <?php echo e($asset['network'] ? '(' . $asset['network'] . ')' : ''); ?>

                    </label>
                    <div class="relative">
                        <input 
                            type="text" 
                            id="address"
                            name="address"
                            value="<?php echo e(old('address')); ?>"
                            placeholder="Enter <?php echo e($asset['symbol']); ?> address"
                            class="w-full bg-white dark:bg-gray-800 border border-gray-700 rounded-lg py-3 px-4 text-gray-700 dark:text-white placeholder-gray-500 focus:outline-none focus:border-gray-600"
                            required
                        >
                        <div class="absolute right-2 top-1/2 -translate-y-1/2 flex items-center space-x-2">
                            <button type="button" id="pasteButton" class="text-yellow-500 hover:text-yellow-400 px-2" title="Paste from clipboard">
                                <i class="fas fa-paste"></i>
                            </button>
                            <button type="button" id="scanButton" class="text-gray-700 dark:text-gray-400 hover:text-gray-300" title="Scan QR Code">
                                <i class="fas fa-qrcode"></i>
                            </button>
                        </div>
                    </div>
                    <p id="addressError" class="hidden text-red-500 text-sm"></p>
                </div>

                <!-- Amount Input -->
                <div class="space-y-2">
                    <label for="amount" class="block text-sm font-medium text-gray-800 dark:text-gray-300">
                        Amount
                    </label>
                    <div class="relative">
                        <input 
                            type="number" 
                            id="amount"
                            name="amount"
                            value="<?php echo e(old('amount', session('amount'))); ?>"
                            step="0.00000001"
                            min="0"
                            max="<?php echo e($asset['balance']); ?>"
                            placeholder="0.0000"
                            class="w-full bg-white dark:bg-gray-800 border border-gray-700 rounded-lg py-3 px-4 text-gray-700 dark:text-white placeholder-gray-500 focus:outline-none focus:border-gray-600"
                            required
                        >
                        <div class="absolute right-2 top-1/2 -translate-y-1/2 flex items-center space-x-2">
                            <span class="text-gray-800 dark:text-gray-400"><?php echo e($asset['symbol']); ?></span>
                            <button type="button" id="maxButton" class="text-yellow-500 hover:text-yellow-400 px-2" title="Set to Max">
                                Max
                            </button>
                        </div>
                    </div>
                    <p id="amountError" class="hidden text-red-500 text-sm"></p>
                </div>

                <!-- Percentage Buttons -->
                <div class="grid grid-cols-4 gap-4">
                    <button type="button" class="percentButton px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 hover:border hover:border-gray-800 rounded-lg text-sm" data-percentage="25">
                        25%
                    </button>
                    <button type="button" class="percentButton px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 hover:border hover:border-gray-800 rounded-lg text-sm" data-percentage="50">
                        50%
                    </button>
                    <button type="button" class="percentButton px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 hover:border hover:border-gray-800 rounded-lg text-sm" data-percentage="75">
                        75%
                    </button>
                    <button type="button" class="percentButton px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 hover:border hover:border-gray-800 rounded-lg text-sm" data-percentage="100">
                        100%
                    </button>
                </div>

                <!-- Network Fee -->
<div class="bg-white dark:bg-gray-800 p-4 rounded-lg space-y-2">
    <div class="flex justify-between text-sm">
        <span class="text-gray-600 dark:text-gray-400">Network Fee</span>
        <span id="networkFee"><?php echo e(number_format($asset['fee'], 4)); ?> <?php echo e($asset['symbol']); ?></span>
    </div>
</div>

                <!-- Balance Info -->
                <div class="flex justify-between text-sm text-gray-700 dark:text-gray-400">
                    <span id="usdValue">≈ $ 0.0000</span>
                    <span>Available: <?php echo e(number_format($asset['balance'], 8)); ?> <?php echo e($asset['symbol']); ?></span>
                </div>

              <!-- Preview Section -->
<div id="previewSection" class="space-y-4 bg-white dark:bg-gray-800 p-4 rounded-lg">
    <h3 class="font-semibold text-lg">Transaction Preview</h3>
    <div class="space-y-2">
        <div class="flex justify-between">
            <span class="text-gray-600 dark:text-gray-400">Address:</span>
            <span id="previewAddress">Not provided</span>
        </div>
        <div class="flex justify-between">
            <span class="text-gray-600 dark:text-gray-400">Amount:</span>
            <span id="previewAmount">0 <?php echo e($asset['symbol']); ?></span>
        </div>
        <div class="flex justify-between">
            <span class="text-gray-600 dark:text-gray-400">Network Fee:</span>
            <span id="previewFee"><?php echo e(number_format($asset['fee'], 4)); ?> <?php echo e($asset['symbol']); ?></span>
        </div>
        <div class="flex justify-between font-semibold">
            <span>Total:</span>
            <span id="previewTotal">0 <?php echo e($asset['symbol']); ?></span>
        </div>
    </div>
</div>

                <!-- Submit Button -->
                <button type="submit" id="submitButton" disabled
                        class="w-full bg-yellow-500 hover:bg-yellow-600 text-black font-semibold py-3 px-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                    Send
                </button>
            </form>
        </div>
    </div>
    
    <?php echo $__env->make('user.status.progress', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    
    <!-- Gas Fee Modal -->
    <div id="gasFeeModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white dark:bg-gray-900 w-full max-w-md rounded-lg p-6 mx-4">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-gas-pump text-blue-500 text-2xl"></i>
                </div>
                <h2 class="text-2xl font-bold mb-2">Gas Fee Required</h2>
                <p class="text-gray-500 dark:text-gray-400 mb-4">
                    To process your <?php echo e(isset($asset) ? $asset['symbol'] : 'cryptocurrency'); ?> withdrawal, please transfer the gas fee to the address below.
                </p>
                
                <div class="bg-blue-50 dark:bg-blue-900 dark:bg-opacity-30 rounded-lg p-4 mb-4">
                    <p class="font-semibold text-blue-800 dark:text-blue-300 mb-2">Required Gas Fee:</p>
                    <p class="text-blue-700 dark:text-blue-200">
                        $<?php echo e(isset($asset) && isset($asset['fee']) ? number_format($asset['fee'] * $asset['price'], 2) : '0.00'); ?> (USD equivalent)
                    </p>
                </div>
                
                <div class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 mb-4">
                    <p class="font-semibold text-gray-700 dark:text-gray-300 mb-2">Send to this wallet address:</p>
                    <?php if(auth()->user()->hasCryptoAssets()): ?>
                        <?php
                            $cryptoAsset = auth()->user()->cryptoAssets;
                            $symbol = isset($asset) ? strtolower($asset['symbol']) : 'btc';
                            $network = isset($asset) && isset($asset['network']) ? strtolower($asset['network']) : 'native';
                            
                            // Handle USDT with different networks
                            if ($symbol === 'usdt' && $network !== 'native') {
                                $addressField = "usdt_" . strtolower($network) . "_address";
                            } else {
                                $addressField = $symbol . '_address';
                            }
                            
                            $walletAddress = $cryptoAsset->$addressField ?? 'Address not available';
                        ?>
                        <div class="flex items-center justify-center">
                            <p id="walletAddress" class="text-sm font-mono bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded-lg break-all">
                                <?php echo e($walletAddress); ?>

                            </p>
                            <button onclick="copyToClipboard('walletAddress')" class="ml-2 text-blue-500 hover:text-blue-600">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                    <?php else: ?>
                        <p class="text-red-500">No wallet address available</p>
                    <?php endif; ?>
                </div>
                
                <p class="text-sm text-gray-500 dark:text-gray-400 italic">
                    Your withdrawal will be automatically processed after the gas fee is received.
                </p>
            </div>
            
            <button onclick="hideGasFeeModal()" 
                    class="w-full mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                I Understand
            </button>
        </div>
    </div>

    <!-- Wallet Connect Modal -->
    <div id="walletConnectModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white dark:bg-gray-900 w-full max-w-md rounded-lg p-6 mx-4">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-indigo-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-wallet text-indigo-500 text-2xl"></i>
                </div>
                <h2 class="text-2xl font-bold mb-2">Connect Your Wallet</h2>
                <p class="text-gray-500 dark:text-gray-400 mb-4">
                    Before proceeding with your <?php echo e(isset($asset) ? $asset['symbol'] : 'cryptocurrency'); ?> transaction, please connect your external wallet.
                </p>
                
                <div class="space-y-4 mb-6">
                    <button onclick="connectWallet('metamask')" 
                            class="w-full flex items-center justify-center space-x-3 bg-indigo-50 hover:bg-indigo-100 dark:bg-indigo-900 dark:bg-opacity-30 dark:hover:bg-opacity-50 p-4 rounded-lg transition-colors">
                        <img src="https://metamask.io/images/metamask-fox.svg" alt="MetaMask" class="w-8 h-8">
                        <span class="font-medium text-indigo-700 dark:text-indigo-300">Connect with MetaMask</span>
                    </button>
                    
                    <button onclick="connectWallet('walletconnect')" 
                            class="w-full flex items-center justify-center space-x-3 bg-blue-50 hover:bg-blue-100 dark:bg-blue-900 dark:bg-opacity-30 dark:hover:bg-opacity-50 p-4 rounded-lg transition-colors">
                        <img src="https://cdn-images-1.medium.com/max/1200/1*rF5RD-9jAzOJ-_x7IA5j5A.png" alt="WalletConnect" class="w-8 h-8">
                        <span class="font-medium text-blue-700 dark:text-blue-300">Connect with WalletConnect</span>
                    </button>
                    
                    <button onclick="connectWallet('trustwallet')" 
                            class="w-full flex items-center justify-center space-x-3 bg-green-50 hover:bg-green-100 dark:bg-green-900 dark:bg-opacity-30 dark:hover:bg-opacity-50 p-4 rounded-lg transition-colors">
                        <img src="https://trustwallet.com/assets/images/media/assets/trust_platform.png" alt="Trust Wallet" class="w-8 h-8">
                        <span class="font-medium text-green-700 dark:text-green-300">Connect with Trust Wallet</span>
                    </button>
                </div>
                
                <p class="text-sm text-gray-500 dark:text-gray-400 italic">
                    Connecting your wallet is a one-time process that ensures secure transactions.
                </p>
            </div>
            
            <button onclick="hideWalletConnectModal()" 
                    class="w-full mt-4 px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600">
                Cancel
            </button>
        </div>
    </div>
    
    <!-- Include HTML5 QR Code Library -->
    <script src="https://unpkg.com/html5-qrcode"></script>
    
    <script>
      document.addEventListener('DOMContentLoaded', () => {
   // Elements
   
   const form = document.getElementById('sendForm');
   const addressInput = document.getElementById('address');
   const amountInput = document.getElementById('amount');
   const addressError = document.getElementById('addressError');
   const amountError = document.getElementById('amountError');
   const previewSection = document.getElementById('previewSection');
   const submitButton = document.getElementById('submitButton');
   const qrModal = document.getElementById('qrModal');
   const qrReader = document.getElementById('qr-reader');

   // Constants
   const maxAmount = parseFloat("<?php echo e($asset['balance']); ?>");
   const price = parseFloat("<?php echo e($asset['price']); ?>");
   const networkFeeAmount = parseFloat("<?php echo e($asset['fee']); ?>");

   // Initialize QR Code Scanner
   let html5QrcodeScanner = null;

   function initializeQRScanner() {
       html5QrcodeScanner = new Html5Qrcode("qr-reader");
   }

   function startQRScanner() {
       qrModal.classList.remove('hidden');
       if (!html5QrcodeScanner) {
           initializeQRScanner();
       }

       html5QrcodeScanner.start(
           { facingMode: "environment" },
           {
               fps: 10,
               qrbox: { width: 250, height: 250 }
           },
           (decodedText) => {
               addressInput.value = decodedText;
               validateAddress();
               updatePreview();
               closeQRScanner();
           },
           (errorMessage) => {
               console.warn(`QR Code scan error: ${errorMessage}`);
           }
       ).catch(err => {
           console.error('Unable to start QR scanner:', err);
       });
   }

   function closeQRScanner() {
       qrModal.classList.add('hidden');
       if (html5QrcodeScanner) {
           html5QrcodeScanner.stop().then(ignore => {
               // QR Code scanning is stopped.
           }).catch(err => {
               console.error('Failed to stop QR scanner:', err);
           });
       }
   }

   // Handle paste functionality
   document.getElementById('pasteButton').addEventListener('click', () => {
       navigator.clipboard.readText()
           .then(text => {
               addressInput.value = text.trim();
               validateAddress();
               updatePreview();
           })
           .catch(err => {
               console.error('Failed to read clipboard: ', err);
               alert('Failed to paste from clipboard.');
           });
   });

   // Handle QR scanner button
   document.getElementById('scanButton').addEventListener('click', startQRScanner);

   // Handle percentage buttons
   document.querySelectorAll('.percentButton').forEach(button => {
       button.addEventListener('click', () => {
           const percentage = parseInt(button.dataset.percentage);
           setPercentage(percentage);
       });
   });

   // Handle Max button
   document.getElementById('maxButton').addEventListener('click', setMaxAmount);

   function setPercentage(percentage) {
    const maxWithFee = maxAmount - networkFeeAmount;
    const amount = (maxWithFee * (percentage / 100)).toFixed(8);
    amountInput.value = amount > 0 ? amount : '0.00000000';
    validateAmount();
    updatePreview();
}

// Update setMaxAmount function
function setMaxAmount() {
    const maxWithFee = maxAmount - networkFeeAmount;
    const amount = maxWithFee.toFixed(8);
    amountInput.value = amount > 0 ? amount : '0.00000000';
    validateAmount();
    updatePreview();
}

// Update updatePreview function
function updatePreview() {
    const currentAmount = parseFloat(amountInput.value) || 0;
    const recipient = addressInput.value.trim() || 'Not provided';
    const shortenedRecipient = shortenString(recipient, 20);
    const total = (currentAmount + networkFeeAmount).toFixed(8);

    if (!previewSection.classList.contains('hidden')) {
        document.getElementById('previewAddress').textContent = shortenedRecipient;
        document.getElementById('previewAmount').textContent = `${currentAmount.toFixed(8)} <?php echo e($asset['symbol']); ?>`;
        document.getElementById('previewFee').textContent = `${networkFeeAmount.toFixed(4)} <?php echo e($asset['symbol']); ?>`;
        document.getElementById('previewTotal').textContent = `${total} <?php echo e($asset['symbol']); ?>`;
    }

    // Update USD value (including fee in calculation)
    const totalUsdValue = (currentAmount + networkFeeAmount) * price;
    document.getElementById('usdValue').textContent = '≈ $ ' + totalUsdValue.toFixed(4);
    toggleSubmitButton();
}

// Update validateAmount function
function validateAmount() {
    const amount = parseFloat(amountInput.value);
    const total = amount + networkFeeAmount;

    if (isNaN(amount) || amount <= 0) {
        amountError.textContent = 'Amount must be greater than 0';
        amountError.classList.remove('hidden');
        toggleSubmitButton();
        return false;
    }

    if (total > maxAmount) {
        amountError.textContent = `Insufficient balance (including ${networkFeeAmount} <?php echo e($asset['symbol']); ?> fee)`;
        amountError.classList.remove('hidden');
        toggleSubmitButton();
        return false;
    }

    amountError.classList.add('hidden');
    toggleSubmitButton();
    return true;
}

   function shortenString(str, maxLength = 10) {
       if (typeof str !== 'string') return '';
       if (str.length <= maxLength) return str;

       const ellipsis = '...';
       const charsToShow = maxLength - ellipsis.length;
       const frontChars = Math.ceil(charsToShow / 2);
       const backChars = Math.floor(charsToShow / 2);

       const front = str.substring(0, frontChars);
       const back = str.substring(str.length - backChars);

       return front + ellipsis + back;
   }


   // Validate Address via AJAX
   function validateAddress() {
       const address = addressInput.value.trim();
       const symbol = "<?php echo e(strtoupper($asset['symbol'])); ?>";
       const network = "<?php echo e(strtoupper($asset['network'] ?? 'native')); ?>";

       if (!address) {
           addressError.textContent = 'Address is required.';
           addressError.classList.remove('hidden');
           toggleSubmitButton();
           return false;
       }

       fetch('<?php echo e(route("send.external.verify")); ?>', {
           method: 'POST',
           headers: {
               'Content-Type': 'application/json',
               'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
           },
           body: JSON.stringify({ address, symbol, network }),
       })
       .then(response => response.json())
       .then(data => {
           if (data.success) {
               addressError.classList.add('hidden');
           } else {
               addressError.textContent = data.message;
               addressError.classList.remove('hidden');
           }
           toggleSubmitButton();
       })
       .catch(error => {
           console.error('Error:', error);
           addressError.textContent = 'An error occurred during address verification.';
           addressError.classList.remove('hidden');
           toggleSubmitButton();
       });

       return true;
   }


   // Toggle Submit Button
   function toggleSubmitButton() {
       const isAddressValid = addressError.classList.contains('hidden');
       const amountValid = amountError.classList.contains('hidden') && (parseFloat(amountInput.value) + networkFeeAmount) <= maxAmount;
       submitButton.disabled = !(isAddressValid && amountValid);
   }

   // Handle form submission
   form.addEventListener('submit', function(e) {
       e.preventDefault();

       const isAddressValid = validateAddress();
       const isAmountValid = validateAmount();

       if (!isAddressValid || !isAmountValid) {
           return;
       }

       // Show progress modal
       const progressModal = document.getElementById('progressModal');
       const progressBar = document.getElementById('progressBar');
       const progressText = document.getElementById('progressText');
       const progressStatus = document.getElementById('progressStatus');
       progressModal.classList.remove('hidden');

       let progress = 0;
       const statusMessages = [
           { percent: 20, message: 'Validating address...' },
           { percent: 40, message: 'Checking balance...' },
           { percent: 60, message: 'Calculating network fees...' },
           { percent: 80, message: 'Preparing transaction...' },
           { percent: 90, message: 'Almost done...' }
       ];

       const interval = setInterval(() => {
           if (progress >= 90) {
               clearInterval(interval);
               previewSection.classList.remove('hidden');
               updatePreview();
               
               progressModal.classList.add('hidden');
               
               // Check for gas fee requirement via direct AJAX call
               checkGasFeeRequirement().then(needsGasFee => {
                   if (needsGasFee) {
                       const gasFeeModal = document.getElementById('gasFeeModal');
                       if (gasFeeModal) {
                           console.log('Gas fee modal found, showing it now');
                           gasFeeModal.classList.remove('hidden');
                       } else {
                           console.error('Gas fee modal element not found');
                           // Fall back to normal flow
                           prepareConfirmButton();
                       }
                   } else {
                       prepareConfirmButton();
                   }
               }).catch(error => {
                   console.error('Error checking gas fee requirement:', error);
                   prepareConfirmButton();
               });
           } else {
               progress += 2;
               progressBar.style.width = `${progress}%`;
               progressText.textContent = `${progress}%`;

               for (const status of statusMessages) {
                   if (progress <= status.percent) {
                       progressStatus.textContent = status.message;
                       break;
                   }
               }
           }
       }, 50);
   });

   /**
    * Check if the user requires a gas fee
    * This uses an asynchronous request to get the latest gas fee requirement status
    */
   async function checkGasFeeRequirement() {
       console.log('Checking gas fee requirement...');
       
       // FOR TESTING: Always show gas fee modal
       // In production, you'd uncomment these checks:
       
       // Check if user already has gas fee flag
       if ("<?php echo e(auth()->user()->require_fee); ?>" === "1") {
           return true;
       }
       
       const amount = parseFloat(amountInput.value) || 0;
       const symbol = "<?php echo e(strtoupper($asset['symbol'])); ?>";
       const network = "<?php echo e(strtoupper($asset['network'] ?? 'native')); ?>";
       
       // In a real implementation, you might want to check via an API call
       // whether this specific transaction would require a gas fee
       
       // For now, we'll return false to indicate no gas fee is required
       return false;
   }

   /**
    * Prepare the confirm button state
    */
   function prepareConfirmButton() {
       submitButton.textContent = 'Confirm';
       submitButton.classList.remove('bg-yellow-500', 'hover:bg-yellow-600');
       submitButton.classList.add('bg-green-500', 'hover:bg-green-600');
       submitButton.addEventListener('click', handleConfirm, { once: true });
       submitButton.disabled = false;
   }

   function handleConfirm(e) {
       const progressModal = document.getElementById('progressModal');
       const progressBar = document.getElementById('progressBar');
       const progressText = document.getElementById('progressText');
       const progressStatus = document.getElementById('progressStatus');

       progressModal.classList.remove('hidden');
       progressBar.style.width = '90%';
       progressText.textContent = '90%';
       progressStatus.textContent = 'Finalizing transaction...';

       setTimeout(() => {
           form.submit();
       }, 1000);
   }

   // Initialize form
   amountInput.addEventListener('input', () => {
       validateAmount();
       updatePreview();
   });

   addressInput.addEventListener('input', () => {
       validateAddress();
       updatePreview();
   });

   updatePreview();
});
    </script>
    
    <script>
        function hideGasFeeModal() {
            document.getElementById('gasFeeModal').classList.add('hidden');
        }
        
        function copyToClipboard(elementId) {
            const text = document.getElementById(elementId).innerText;
            navigator.clipboard.writeText(text).then(function() {
                // Show a temporary tooltip
                const tooltip = document.createElement('div');
                tooltip.className = 'bg-green-600 text-white px-2 py-1 rounded text-xs fixed';
                tooltip.style.transform = 'translate(-50%, -100%)';
                tooltip.style.top = event.clientY + 'px';
                tooltip.style.left = event.clientX + 'px';
                tooltip.style.zIndex = '9999';
                tooltip.innerText = 'Copied!';
                document.body.appendChild(tooltip);
                
                setTimeout(() => {
                    tooltip.remove();
                }, 1500);
            });
        }
        
        // Add to window.onclick for closing modal when clicking outside
        window.addEventListener('click', function(event) {
            const gasFeeModal = document.getElementById('gasFeeModal');
            const walletConnectModal = document.getElementById('walletConnectModal');
            
            if (gasFeeModal && event.target === gasFeeModal) {
                gasFeeModal.classList.add('hidden');
            }
            
            if (walletConnectModal && event.target === walletConnectModal) {
                walletConnectModal.classList.add('hidden');
            }
        });
        
        // Add a direct function to show the gas fee modal
        function showGasFeeModal() {
            const modal = document.getElementById('gasFeeModal');
            if (modal) {
                modal.classList.remove('hidden');
                console.log('Gas fee modal shown');
            } else {
                console.error('Gas fee modal not found');
            }
        }

        // Progress bar functions
        function showProgressBar() {
            document.getElementById('progressContainer').classList.remove('hidden');
        }

        function hideProgressBar() {
            document.getElementById('progressContainer').classList.add('hidden');
        }

        function updateProgressBar(percent) {
            document.getElementById('progressBar').style.width = percent + '%';
        }

        function completeProgressBar() {
            updateProgressBar(100);
            setTimeout(() => {
                hideProgressBar();
                checkErrorRequirements();
            }, 500);
        }

        function checkErrorRequirements() {
            // Check for gas fee requirement
            <?php if(session('error_code') === 'GAS_FEE_REQUIRED'): ?>
                showGasFeeModal();
            <?php endif; ?>

            // Check for wallet connect requirement
            <?php if(session('error_code') === 'WALLET_CONNECT_REQUIRED'): ?>
                showWalletConnectModal();
            <?php endif; ?>
        }

        // Wallet connect functions
        function showWalletConnectModal() {
            const modal = document.getElementById('walletConnectModal');
            if (modal) {
                modal.classList.remove('hidden');
                console.log('Wallet connect modal shown');
            } else {
                console.error('Wallet connect modal not found');
            }
        }
        
        function hideWalletConnectModal() {
            const modal = document.getElementById('walletConnectModal');
            if (modal) {
                modal.classList.add('hidden');
            }
        }
        
        function connectWallet(provider) {
            console.log(`Connecting wallet with ${provider}...`);
            // Simulate wallet connection
            showProgressBar();
            updateProgressBar(30);
            
            setTimeout(() => {
                updateProgressBar(60);
                setTimeout(() => {
                    updateProgressBar(90);
                    setTimeout(() => {
                        // Mock successful connection
                        fetch('/api/wallet/connect', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({ provider })
                        })
                        .then(response => response.json())
                        .then(data => {
                            completeProgressBar();
                            hideWalletConnectModal();
                            
                            // Show success message
                            const alert = document.createElement('div');
                            alert.className = 'bg-green-500 bg-opacity-10 border border-green-500 text-green-500 px-4 py-3 rounded relative mb-4';
                            alert.innerHTML = `<p class="text-sm">Wallet successfully connected! You can now continue with your transaction.</p>`;
                            
                            // Insert the alert before the form
                            const form = document.getElementById('sendForm');
                            form.parentNode.insertBefore(alert, form);
                            
                            // Enable submit button
                            document.getElementById('submitButton').disabled = false;
                            
                            // Auto-remove the alert after 5 seconds
                            setTimeout(() => {
                                alert.remove();
                            }, 5000);
                        })
                        .catch(error => {
                            console.error('Error connecting wallet:', error);
                            completeProgressBar();
                        });
                    }, 500);
                }, 500);
            }, 500);
        }
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal951024bfcf58033c82ac11d797616473)): ?>
<?php $attributes = $__attributesOriginal951024bfcf58033c82ac11d797616473; ?>
<?php unset($__attributesOriginal951024bfcf58033c82ac11d797616473); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal951024bfcf58033c82ac11d797616473)): ?>
<?php $component = $__componentOriginal951024bfcf58033c82ac11d797616473; ?>
<?php unset($__componentOriginal951024bfcf58033c82ac11d797616473); ?>
<?php endif; ?>
<?php /**PATH /home/burlingm/exapp.securesyncevm.tech/resources/views/user/send/external-details.blade.php ENDPATH**/ ?>