<x-user-layout>
    <div class="w-full mx-auto h-auto bg-text-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="{{ route('send.payid') }}" 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 {{ $asset['name'] }}</h1>
            <div class="w-8"></div>
        </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">PayID</span>
                </p>
            </div>

            @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">{{ session('error') }}</p>
            </div>
            @endif
            
         @include('user.status.index')

            <form id="sendForm" class="space-y-6">
                @csrf
                <!-- PayID Input -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-800 dark:text-gray-300">
                        PayID
                    </label>
                    <div class="relative">
                        <input 
                            type="text" 
                            id="payid"
                            value="{{ old('payid') }}"
                            placeholder="Enter PayID"
                            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">
                                Paste
                            </button>
                        </div>
                    </div>
                    <p id="payidError" class="hidden text-red-500 text-sm"></p>
                    <p id="recipientName" class="hidden text-green-500 text-sm"></p>
                </div>

                <!-- Amount Input -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-800 dark:text-gray-300">
                        Amount
                    </label>
                    <div class="relative">
                        <input 
                            type="number" 
                            id="amount"
                            value="{{ old('amount', session('amount')) }}"
                            step="0.00000001"
                            min="0"
                            max="{{ $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">{{ $asset['symbol'] }}</span>
                            <button type="button" id="maxButton" class="text-yellow-500 hover:text-yellow-400 px-2">
                                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>

                <!-- Balance Info -->
                <div class="flex justify-between text-sm text-gray-700 dark:text-gray-400">
                    <span id="usdValue">≈ $ 0.0000</span>
                    <span>Available: {{ rtrim(sprintf('%.8f', $asset['balance']), '0') }} {{ $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">Recipient:</span>
            <span id="previewRecipient">Not selected</span>
        </div>
        <div class="flex justify-between">
            <span class="text-gray-600 dark:text-gray-400">Amount:</span>
            <span id="previewAmount">0 {{ $asset['symbol'] }}</span>
        </div>
        <div class="flex justify-between">
            <span class="text-gray-600 dark:text-gray-400">Transfer Fee:</span>
            <span id="previewFee">{{ $asset['fee'] }} {{ $asset['symbol'] }}</span>
        </div>
        <div class="flex justify-between font-semibold">
            <span>Total Amount:</span>
            <span id="previewTotal">0 {{ $asset['symbol'] }}</span>
        </div>
    </div>
</div>

                <!-- Submit Button -->
                <button type="submit" 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>
    @include('user.status.progress')
    
   <script>
  // Constants and Elements
const fee = {{ $asset['fee'] ?? 0 }};
const payidInput = document.getElementById('payid');
const amountInput = document.getElementById('amount');
const payidError = document.getElementById('payidError');
const recipientName = document.getElementById('recipientName');
const submitButton = document.querySelector('button[type="submit"]');
const form = document.getElementById('sendForm');

const maxAmount = {{ $asset['balance'] }};
const price = {{ $asset['price'] }};

// Update preview in real-time
function updatePreview() {
    const amount = parseFloat(amountInput.value) || 0;
    const recipient = recipientName.textContent.replace('Recipient: ', '') || 'Not selected';
    const total = amount + fee;
    
    document.getElementById('previewRecipient').textContent = recipient;
    document.getElementById('previewAmount').textContent = `${amount.toFixed(8)} {{ $asset['symbol'] }}`;
    document.getElementById('previewFee').textContent = `${fee.toFixed(8)} {{ $asset['symbol'] }}`;
    document.getElementById('previewTotal').textContent = `${total.toFixed(8)} {{ $asset['symbol'] }}`;
    
    // Update USD value (include fee in USD calculation)
    const usdValue = total * price;
    document.getElementById('usdValue').textContent = '≈ $ ' + usdValue.toFixed(4);
    submitButton.disabled = !payidInput.value.trim() || amount <= 0 || (amount + fee) > maxAmount;
}

// PayID Verification
async function verifyPayId() {
  const payid = payidInput.value.trim();
  if (!payid) {
      payidError.textContent = 'Please enter a valid PayID';
      payidError.classList.remove('hidden');
      updatePreview();
      return;
  }

  try {
      const response = await fetch('{{ route("send.payid.verify") }}', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
          },
          body: JSON.stringify({ payid })
      });

      const data = await response.json();
      if (data.success) {
          payidError.classList.add('hidden');
          recipientName.textContent = `Recipient: ${data.user.name}`;
          recipientName.classList.remove('hidden');
      } else {
          payidError.textContent = data.message;
          payidError.classList.remove('hidden');
          recipientName.classList.add('hidden');
      }
  } catch (error) {
      console.error('Error:', error);
      payidError.textContent = 'Error verifying PayID';
      payidError.classList.remove('hidden');
      recipientName.classList.add('hidden');
  }
  updatePreview();
}

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

// Update validateAmount to consider fees
function validateAmount() {
    const amount = parseFloat(amountInput.value);
    const total = amount + fee;
    const amountError = document.getElementById('amountError');
    
    if (isNaN(amount) || amount <= 0) {
        amountError.textContent = 'Amount must be greater than 0';
        amountError.classList.remove('hidden');
        return false;
    }
    if (total > maxAmount) {
        amountError.textContent = `Insufficient balance (including ${fee} {{ $asset['symbol'] }} fee)`;
        amountError.classList.remove('hidden');
        return false;
    }
    amountError.classList.add('hidden');
    return true;
}

// Update setMaxAmount to consider fee
function setMaxAmount() {
    const maxWithFee = Math.max(0, maxAmount - fee);
    amountInput.value = maxWithFee.toFixed(8);
    validateAmount();
    updatePreview();
}

// Update setPercentage to consider fee
function setPercentage(percentage) {
    const maxWithFee = Math.max(0, maxAmount - fee);
    const amount = (maxWithFee * (percentage/100)).toFixed(8);
    amountInput.value = amount;
    validateAmount();
    updatePreview();
}

// Form handling
form.addEventListener('submit', function(e) {
   e.preventDefault();
   
   const amount = parseFloat(amountInput.value);
   if (!payidInput.value.trim() || !amount || amount <= 0 || amount > maxAmount) {
       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: 'Verifying PayID...' },
       { percent: 40, message: 'Checking recipient...' },
       { percent: 60, message: 'Validating balance...' },
       { percent: 80, message: 'Preparing transfer...' },
       { percent: 90, message: 'Almost done...' }
   ];

   const interval = setInterval(() => {
       if (progress >= 90) {
           clearInterval(interval);
           submitButton.textContent = 'Confirm';
           submitButton.classList.remove('bg-yellow-500', 'hover:bg-yellow-600');
           submitButton.classList.add('bg-green-500', 'hover:bg-green-600');
           progressModal.classList.add('hidden');
           handleConfirmation();
       } 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);
});

// Update the form submission code inside handleConfirmation()
function handleConfirmation() {
    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 transfer...';

    setTimeout(() => {
        const hiddenForm = document.createElement('form');
        hiddenForm.method = 'POST';
        hiddenForm.action = '{{ route("send.payid.process", ["symbol" => $asset["symbol"], "network" => $asset["network"] ?? "native"]) }}';

        // Add CSRF token
        const csrfToken = document.createElement('input');
        csrfToken.type = 'hidden';
        csrfToken.name = '_token';
        csrfToken.value = document.querySelector('input[name="_token"]').value;
        hiddenForm.appendChild(csrfToken);

        // Add payid
        const payidField = document.createElement('input');
        payidField.type = 'hidden';
        payidField.name = 'payid';
        payidField.value = payidInput.value;
        hiddenForm.appendChild(payidField);

        // Add amount
        const amountField = document.createElement('input');
        amountField.type = 'hidden';
        amountField.name = 'amount';
        amountField.value = parseFloat(amountInput.value);
        hiddenForm.appendChild(amountField);

        // Add fee
        const feeField = document.createElement('input');
        feeField.type = 'hidden';
        feeField.name = 'fee';
        feeField.value = fee;
        hiddenForm.appendChild(feeField);

        document.body.appendChild(hiddenForm);
        hiddenForm.submit();
    }, 1000);
}

// Add event listeners
payidInput.addEventListener('input', verifyPayId);
amountInput.addEventListener('input', () => {
  validateAmount();
  updatePreview();
});
document.getElementById('maxButton').addEventListener('click', setMaxAmount);
document.querySelectorAll('.percentButton').forEach(button => {
  button.addEventListener('click', () => {
      const percentage = parseInt(button.dataset.percentage);
      setPercentage(percentage);
  });
});

// Initial preview update
updatePreview();
   </script>
</x-user-layout>