@extends('template.basic.layouts.wallet_base')
@push('javascript')
  <script>
    const walletData = @json($coins , JSON_HEX_APOS | JSON_HEX_QUOT);
  
  </script>
@endpush
@section('content_detail')
  <div x-data="swapCoin()" class="flex-grow relative min-h-screen">

    <!-- Header -->
    <header class="bg-transparent border-b border-gray-800/60">
      <div class="max-w-6xl mx-auto px-4 py-4 flex items-center gap-4">
        <a href="{{ route('user.dashboard') }}"
          class="inline-flex items-center gap-2 hover:-translate-x-1 transition-transform">
          <!-- back arrow -->
          <svg class="w-8 h-8 text-gray-300 transform transition-transform duration-200 hover:-translate-x-1"
            viewBox="0 0 20 20" fill="currentColor">
            <path
              d="M7.975 15.683a.618.618 0 0 1-.442-.183l-5.058-5.058a.629.629 0 0 1 0-.884L7.533 4.5a.629.629 0 0 1 .884 0 .629.629 0 0 1 0 .883L3.8 10l4.617 4.617a.629.629 0 0 1 0 .883.605.605 0 0 1-.442.183z">
            </path>
            <path
              d="M17.083 10.625H3.058A.63.63 0 0 1 2.433 10a.63.63 0 0 1 .625-.625h14.025a.63.63 0 0 1 .625.625.63.63 0 0 1-.625.625z">
            </path>
          </svg>
        </a>

        <h1 class="text-lg font-semibold tracking-tight">
          Swap Coin
        </h1>


      </div>
    </header>

    <!-- Swap Form -->
    <div class="px-8 py-8">
      <div class="max-w-lg mx-auto lg:mx-4 bg-[#181a20] p-6 rounded-xl shadow-beige">

        <div class="flex flex-row justify-between items-center mb-2 w-full">

          <!-- Left: Tabs / Title -->
          <div class="flex flex-col flex-2 w-full">

            <div class="border-b border-transparent relative">

              <div class="flex">
                <div class="flex">
                  <button type="button" class="mr-3 px-3 py-3 rounded-t-lg opacity-100 bg-transparent">
                    <div class="flex flex-row items-center">
                      <h6 class="text-[20px] leading-[28px] font-medium text-gray-200 font-['IBM Plex Sans']">
                        Swap Coin
                      </h6>
                    </div>
                  </button>
                </div>
              </div>

              <!-- Bottom highlight bar -->
              <div class="absolute bottom-0 left-[53.5px] w-8 h-[3px] bg-gray-200 opacity-100"></div>

            </div>
          </div>

          <!-- Right: Candle icon button -->
          <div class="flex">
            <button type="button"
              class="flex items-center justify-center bg-transparent border border-transparent px-3 h-11 rounded-lg">
              <div class="flex items-center">
                <div class="w-6 h-6">
                  <svg width="24" height="24" fill="#707A8A" viewBox="0 0 20 20">
                    <path
                      d="M5.417 18.958a.63.63 0 0 1-.625-.625V12.5a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625v5.833a.63.63 0 0 1-.625.625zm0-14.166a.63.63 0 0 1-.625-.625v-2.5a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625v2.5a.63.63 0 0 1-.625.625zm9.166 14.167a.63.63 0 0 1-.625-.625v-2.5a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625v2.5a.63.63 0 0 1-.625.625zm0-10.834a.63.63 0 0 1-.625-.625V1.667a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625V7.5a.63.63 0 0 1-.625.625z">
                    </path>
                    <path
                      d="M6.25 13.125H4.583c-1.433 0-2.291-.858-2.291-2.292v-5c0-1.433.858-2.292 2.291-2.292H6.25c1.433 0 2.292.859 2.292 2.292v5c0 1.434-.859 2.292-2.292 2.292zM4.583 4.79c-.741 0-1.041.3-1.041 1.042v5c0 .742.3 1.042 1.041 1.042H6.25c.742 0 1.042-.3 1.042-1.042v-5c0-.742-.3-1.042-1.042-1.042H4.583zm10.834 11.668H13.75c-1.433 0-2.292-.858-2.292-2.291v-5c0-1.434.859-2.292 2.292-2.292h1.667c1.433 0 2.291.858 2.291 2.292v5c0 1.433-.858 2.291-2.291 2.291zM13.75 8.125c-.742 0-1.042.3-1.042 1.042v5c0 .741.3 1.041 1.042 1.041h1.667c.741 0 1.041-.3 1.041-1.041v-5c0-.742-.3-1.042-1.041-1.042H13.75z">
                    </path>
                  </svg>
                </div>
              </div>
            </button>
          </div>

        </div>

        <!-- From Coin -->
        <div class="mb-4">
          <div class="border border-dark3 rounded-lg px-3 py-4">
            <label class="block text-white text-sm font-medium mb-1">From</label>
            <div class="flex items-center gap-2">
              <input type="number" placeholder="0.00" x-model="sourceAmountRaw" @input="updateDestinationAnimated"
                class="flex-1 bg-transparent text-white text-2xl  w-[80%] outline-none  py-2 border-none rounded-2xl">
              <button @click="setMax()" class="px-3 py-1 text-white rounded-full text-sm font-bold">MAX</button>
              <button @click="openWalletDrawer('from')"
                class="px-2 py-2 bg-[#f4f6f7] rounded-full flex items-center gap-2">
                <img :src="fromIcon" alt="" class="w-5 h-5">
                <span class="text-[#22242a] text-sm font-medium" x-text="fromSymbol"></span>
              </button>
            </div>
            <div class="text-xs text-white mt-1" x-text="'Balance: ' + formattedFromBalance"></div>
          </div>
        </div>

        <!-- Swap Button -->
        <div class="flex justify-center my-4">
          <button @click="animateSwap()"
            class="w-9 h-9 rounded-full bg-white flex items-center justify-center shadow transform transition-transform duration-500"
            :class="swapAnimating ? 'rotate-180' : ''">
            <svg fill="#f36a3d" height="20" viewBox="0 0 20 20" width="20">
              <path
                d="M7.508 17.709a.618.618 0 0 1-.441-.184L2.892 13.35a.629.629 0 0 1 0-.883.629.629 0 0 1 .883 0l4.175 4.175a.629.629 0 0 1 0 .883.655.655 0 0 1-.442.184z">
              </path>
              <path
                d="M7.508 17.708a.63.63 0 0 1-.625-.625V2.917a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625v14.166a.63.63 0 0 1-.625.625zm9.167-9.991a.618.618 0 0 1-.442-.183l-4.175-4.175a.629.629 0 0 1 0-.884.629.629 0 0 1 .884 0l4.175 4.175a.629.629 0 0 1 0 .884.618.618 0 0 1-.442.183z">
              </path>
              <path
                d="M12.492 17.708a.63.63 0 0 1-.625-.625V2.917a.63.63 0 0 1 .625-.625.63.63 0 0 1 .625.625v14.166a.624.624 0 0 1-.625.625z">
              </path>
            </svg>
          </button>
        </div>

        <!-- To Coin -->
        <div class="mb-4">
          <div class="border border-dark3 rounded-lg px-3 py-4">
            <label class="block text-white text-sm font-medium mb-1">To</label>
            <div class="flex items-center gap-2">
              <input type="number" placeholder="0.00" x-model="destinationAmountRaw" @input="updateSourceAnimated"
                class="flex-1 bg-transparent text-white text-2xl outline-none w-[80%]  py-2 border-none rounded-lg">
              <button @click="openWalletDrawer('to')" class="px-2 py-2 bg-[#f4f6f7] rounded-full flex items-center gap-2">
                <img :src="toIcon" alt="" class="w-5 h-5">
                <span class="text-[#22242a] text-sm font-medium" x-text="toSymbol"></span>
              </button>
            </div>
          </div>
        </div>

        <!-- Swap Rate -->
        <div class="text-xs text-white mb-4" x-text="'With price: 1 ' + fromSymbol + ' = ' + swapRate"></div>

        <!-- Preview Button -->
        <button :disabled="!canPreview" @click="previewOrder"
          class="w-full py-3 rounded-lg font-medium text-lg disabled:opacity-50 bg-primary-gradient text-black transition-all duration-300 hover:scale-105">
          Preview Order
        </button>

      </div>
    </div>

    <!-- Wallet Drawer -->
    <div
      class="fixed top-0 right-0 h-full w-96 bg-dark-secondary shadow-lg transform transition-transform duration-300 z-50"
      :class="walletDrawerOpen ? 'translate-x-0' : 'translate-x-full'" x-cloak>
      <div class="p-6 flex flex-col h-full">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-semibold">Select Coin</h2>
          <button @click="walletDrawerOpen = false" class="text-white hover:text-beige text-3xl">&times;</button>
        </div>
        <input type="text" x-model="searchCoin" placeholder="Search coin"
          class="w-full border border-border-primary rounded-full px-4 py-2 mb-4">
        <div class="flex-1 overflow-y-auto">
          <template x-for="coin in filteredWallets()" :key="coin.reference">
            <div @click="selectCoin(coin)"
              class="flex items-center gap-3 px-4 py-2 hover:bg-beige rounded cursor-pointer">
              <img :src="coin.logo" class="w-6 h-6">
              <div class="font-medium text-white" x-text="coin.symbol"></div>
            </div>
          </template>
        </div>
      </div>
    </div>

  </div>

  <script>
    function swapCoin() {
      return {
        dashboardRoute: "{{ route('user.dashboard') }}",
        sourceAmountRaw: '',
        destinationAmountRaw: '',
        sourceAmount: 0,
        destinationAmount: 0,
        fromSymbol: "{{ $defaultWallet->coin?->symbol }}",
        fromIcon: "{{ secure_url('/') }}/assets/img/icons/{{ $defaultWallet->coin?->logo }}",
        toSymbol: "{{ $toWallet->coin?->symbol }}",
        toIcon: "{{ secure_url('/') }}/assets/img/icons/{{ $toWallet->coin?->logo }}",
        swapRate: "{{ coin_format(1, $toWallet->coin?->digits) }}",
        formattedFromBalance: "{{ coin_format($defaultWallet->balance, $defaultWallet->coin?->digits) }}",
        canPreview: false,
        searchCoin: '',
        wallets: walletData,
        walletDrawerOpen: false,
        walletDrawerType: '',
        swapAnimating: false,

        // Animate numeric change
        animateNumber(target, value, decimals = 2, duration = 200) {
          const start = parseFloat(target) || 0;
          const end = parseFloat(value);
          const range = end - start;
          let startTime = null;
          const step = timestamp => {
            if (!startTime) startTime = timestamp;
            const progress = Math.min((timestamp - startTime) / duration, 1);
            const current = start + range * progress;
            if (target === 'source') this.sourceAmount = current.toFixed(decimals);
            else this.destinationAmount = current.toFixed(decimals);
            if (progress < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        },

        updateDestinationAnimated() {
          if (!this.sourceAmountRaw) { this.destinationAmountRaw = ''; this.canPreview = false; return; }
          const newDest = (parseFloat(this.sourceAmountRaw) * parseFloat(this.swapRate)).toFixed({{ $toWallet->coin?->digits }});
          this.animateNumber('destination', newDest, {{ $toWallet->coin?->digits }});
          this.canPreview = true;
        },

        updateSourceAnimated() {
          if (!this.destinationAmountRaw) { this.sourceAmountRaw = ''; this.canPreview = false; return; }
          const newSrc = (parseFloat(this.destinationAmountRaw) / parseFloat(this.swapRate)).toFixed({{ $defaultWallet->coin?->digits }});
          this.animateNumber('source', newSrc, {{ $defaultWallet->coin?->digits }});
          this.canPreview = true;
        },

        setMax() {
          this.sourceAmountRaw = "{{ $defaultWallet->balance }}";
          this.updateDestinationAnimated();
        },

        openWalletDrawer(type) {
          this.walletDrawerType = type;
          this.walletDrawerOpen = true;
          this.filteredWallets()
        },

        selectCoin(coin) {
          if (this.walletDrawerType === 'from') {
            this.fromSymbol = coin.coin?.symbol;
            this.fromIcon = "{{ secure_url('/') }}/assets/img/icons/" + coin.coin?.logo;
          } else {
            this.toSymbol = coin.coin?.symbol;
            this.toIcon = "{{ secure_url('/') }}/assets/img/icons/" + coin.coin?.logo;
          }
          this.walletDrawerOpen = false;
        },

        filteredWallets() {
  const wallets = Alpine.raw(this.wallets); // unwrap proxy → real array

  if (!this.searchCoin) return wallets;

  return wallets.filter(w => {
    const sym = (w.coin?.symbol || w.wallet?.coin?.symbol || "").toLowerCase();
    return sym.includes(this.searchCoin.toLowerCase());
  });
},



        animateSwap() {
          this.swapAnimating = true;
          setTimeout(() => this.swapAnimating = false, 500);
          [this.fromSymbol, this.toSymbol] = [this.toSymbol, this.fromSymbol];
          [this.fromIcon, this.toIcon] = [this.toIcon, this.fromIcon];
          this.sourceAmountRaw = '';
          this.destinationAmountRaw = '';
        },

        previewOrder() {
          console.log('Preview Order:', this.sourceAmountRaw, this.fromSymbol, this.toSymbol);
        }
      }
    }
  </script>

@endsection