<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\Attributes\Defer;
use App\Support\Currency;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\Transaction;
use App\Models\Account;
use Livewire\Attributes\Title;
use App\Models\AccountCryptoBalance;
use App\Services\CryptoFiatSwapService;

new #[Defer] #[Title('Balance Swap')] class extends Component {
    // --------------------------
    // Properties
    // --------------------------
    public $accounts;
    public $cryptoBalances;

    public string $currencySymbol = '$';

    // Fiat swap
    public string $selectedFromAccount = '';
    public string $selectedToAccount = '';
    public string $fiatAmount = '';

    // Crypto swap
    public string $selectedCrypto = '';
    public string $cryptoAmount = '';
    public string $swapDirection = 'cryptoToFiat'; // 'cryptoToFiat' or 'fiatToCrypto'
    public ?string $rateError = null;

    // Idempotency
    public string $idempotencyKey;

    // --------------------------
    // Lifecycle
    // --------------------------
    public function mount(): void
    {
        $this->idempotencyKey = (string) Str::uuid();
        $this->loadAccounts();
    }

    protected function loadAccounts(): void
    {
        $user = auth()->user();
        $this->accounts = $user->profile?->accounts()->where('is_active', true)->get() ?? collect([]);
        $this->cryptoBalances = $user->profile?->accounts()->with('cryptoBalances')->get()->pluck('cryptoBalances')->flatten() ?? collect([]);
        $this->currencySymbol = $user->profile ? Currency::symbol($user->profile->currency) : '$';
    }

    // --------------------------
    // Validation
    // --------------------------
    protected function rules(): array
    {
        $accountIds = $this->accounts->pluck('id')->map(fn($id) => (string) $id)->toArray();

        return [
            'fiatAmount' => 'required|numeric|min:0.01',
            'selectedFromAccount' => ['required', Rule::in($accountIds)],
            'selectedToAccount' => ['required', Rule::in($accountIds)],
        ];
    }

    public function updated($property): void
    {
        $this->validateOnly($property);
    }

    // --------------------------
    // Computed Properties
    // --------------------------
    public function getAccountOptionsProperty(): array
    {
        return $this->accounts
            ->mapWithKeys(
                fn($acc) => [
                    (string) $acc->id => "{$acc->bank_account_type} - {$acc->masked_account_number} - {$this->currencySymbol}{$acc->available_balance}",
                ],
            )
            ->toArray();
    }

    public function getCryptoOptionsProperty(): array
    {
        return $this->cryptoBalances
            ->mapWithKeys(
                fn(AccountCryptoBalance $crypto) => [
                    (string) $crypto->id => $crypto->label() . ' - ' . $crypto->available_balance,
                ],
            )
            ->toArray();
    }

    public function getAccountLabelsProperty()
    {
        return $this->accounts->mapWithKeys(
            fn($account) => [
                (string) $account->id => "{$account->bank_account_type} - {$account->masked_account_number} - {$this->currencySymbol}{$account->available_balance}",
            ],
        );
    }

    public function getCurrentRateProperty(): string
    {
        $this->rateError = null;

        $crypto = $this->cryptoBalances->firstWhere('id', $this->selectedCrypto);

        if (!$crypto) {
            return '0';
        }

        $rate = $crypto->getRate();

        if (bccomp($rate, '0', 8) <= 0) {
            $this->rateError = 'Unable to fetch live exchange rate. Please try again.';
            return '0';
        }

        return $rate;
    }

    public function getEstimatedFiatProperty(): string
    {
        $crypto = $this->cryptoBalances->firstWhere('id', $this->selectedCrypto);
        if (!$crypto || !$this->cryptoAmount) {
            return '0.00';
        }

        $fiat = bcmul((string) $this->cryptoAmount, (string) $crypto->getRate(), 8);
        return number_format($fiat, 2, '.', '');
    }

    // --------------------------
    // Swap Methods
    // --------------------------
    public function balanceSwap(): void
    {
        $this->validate();

        $user = auth()->user();
        $amount = (string) $this->fiatAmount;

        $fromAccount = $this->accounts->firstWhere('id', $this->selectedFromAccount);
        $toAccount = $this->accounts->firstWhere('id', $this->selectedToAccount);

        if (!$fromAccount || !$toAccount) {
            $this->addError('transfer', 'Invalid account selection.');
            return;
        }

        if (!$fromAccount->is_active || !$toAccount->is_active) {
            $this->addError('transfer', 'One of the selected accounts is inactive.');
            return;
        }

        if (!$user->kyc_verified) {
            $this->addError('selectedToAccount', 'Complete KYC before swapping.');
            return;
        }

        if ($fromAccount->id === $toAccount->id) {
            $this->addError('selectedToAccount', 'Cannot transfer to the same account.');
            return;
        }

        if (bccomp($amount, (string) $fromAccount->available_balance, 2) === 1) {
            $this->addError('selectedFromAccount', 'Insufficient balance.');
            return;
        }

        $idempotencyKey = $this->idempotencyKey;

        try {
            DB::transaction(function () use ($fromAccount, $toAccount, $amount, $user, $idempotencyKey) {
                if (Transaction::where('idempotency_key', $idempotencyKey)->exists()) {
                    throw new \Exception('This swap has already been processed.');
                }

                $accounts = Account::whereIn('id', [$fromAccount->id, $toAccount->id])
                    ->lockForUpdate()
                    ->get()
                    ->keyBy('id');

                $from = $accounts[$fromAccount->id];
                $to = $accounts[$toAccount->id];

                $from->refresh();
                if (bccomp($amount, (string) $from->available_balance, 2) === 1) {
                    throw new \Exception('Insufficient available balance.');
                }

                $from->balance = bcsub((string) $from->balance, $amount, 2);
                $from->save();

                $to->balance = bcadd((string) $to->balance, $amount, 2);
                $to->save();

                $idKeyDebit = substr(md5($idempotencyKey . '-debit'), 0, 36);
                $idKeyCredit = substr(md5($idempotencyKey . '-credit'), 0, 36);

                Transaction::create([
                    'user_id' => $user->id,
                    'account_id' => $from->id,
                    'idempotency_key' => $idKeyDebit,
                    'type' => 'swap_debit',
                    'amount' => bcmul($amount, '-1', 2),
                    'status' => Transaction::STATUS_COMPLETED,
                    'balance_after' => $from->available_balance,
                    'description' => 'Internal balance swap (debit)',
                ]);

                Transaction::create([
                    'user_id' => $user->id,
                    'account_id' => $to->id,
                    'idempotency_key' => $idKeyCredit,
                    'type' => 'swap_credit',
                    'amount' => $amount,
                    'status' => Transaction::STATUS_COMPLETED,
                    'balance_after' => $to->available_balance,
                    'description' => 'Internal balance swap (credit)',
                ]);
            });
        } catch (\Throwable $e) {
            report($e);
            $this->addError('transfer', $e->getMessage() ?: 'Balance swap failed.');
            return;
        }

        $this->resetAfterSwap(['fiatAmount', 'selectedFromAccount', 'selectedToAccount'], 'Balance swapped successfully.');
    }

    public function swapCryptoFiat(CryptoFiatSwapService $service): void
    {
        if ($this->swapDirection === 'cryptoToFiat') {
            $this->swapCryptoToFiat($service);
        } else {
            $this->swapFiatToCrypto($service);
        }
    }

    protected function validateSwap(string $direction): array
    {
        $errors = [];

        $crypto = $this->cryptoBalances->firstWhere('id', $this->selectedCrypto);
        $account = $this->accounts->firstWhere('id', $this->selectedFromAccount);

        if (!$crypto) {
            $errors['selectedCrypto'] = 'Invalid crypto selection.';
        }
        if ($direction === 'fiatToCrypto' && !$account) {
            $errors['selectedFromAccount'] = 'Invalid account selection.';
        }

        if ($direction === 'cryptoToFiat' && $crypto && !$crypto->hasSufficientBalance((string) $this->cryptoAmount)) {
            $errors['cryptoAmount'] = 'Insufficient crypto balance.';
        }

        if ($direction === 'fiatToCrypto' && $account && bccomp((string) $this->fiatAmount, (string) $account->available_balance, 2) === 1) {
            $errors['fiatAmount'] = 'Insufficient fiat balance.';
        }

        if ($direction === 'fiatToCrypto' && isset($this->fiatAmount, $crypto)) {
            $cryptoAmount = bcdiv((string) $this->fiatAmount, $crypto->getRate(), 8);
            if (bccomp($cryptoAmount, '0.00000001', 8) === -1) {
                $errors['fiatAmount'] = 'Amount too small to convert to crypto.';
            }
        }

        return $errors;
    }
    public function swapCryptoToFiat(CryptoFiatSwapService $service): void
    {
        $errors = $this->validateSwap('cryptoToFiat');
        if ($errors) {
            foreach ($errors as $field => $message) {
                $this->addError($field, $message);
            }
            return;
        }

        $crypto = $this->cryptoBalances->firstWhere('id', $this->selectedCrypto);
        $account = $this->accounts->firstWhere('id', $this->selectedToAccount); // <- use selected account
        $amount = (string) $this->cryptoAmount;
        $idempotencyKey = $this->idempotencyKey;

        if (!$account) {
            $this->addError('selectedToAccount', 'Invalid account selection.');
            return;
        }

        try {
            DB::transaction(function () use ($service, $account, $crypto, $amount, $idempotencyKey) {
                $rate = $this->current_rate;

                if ($this->rateError) {
                    $this->addError('rate', $this->rateError);
                    return;
                }
                if (bccomp($rate, '0', 8) <= 0) {
                    throw new \Exception('Unable to fetch crypto rate.');
                }

                $service->swap($account, $crypto, $amount, $rate, $idempotencyKey);
            });
        } catch (\Throwable $e) {
            report($e);
            $this->addError('swap', 'Crypto swap failed. Try again.');
            return;
        }

        $this->resetAfterSwap(['selectedCrypto', 'cryptoAmount', 'selectedToAccount'], 'Crypto swapped successfully.');
    }

    public function swapFiatToCrypto(CryptoFiatSwapService $service): void
    {
        $errors = $this->validateSwap('fiatToCrypto');
        if ($errors) {
            foreach ($errors as $field => $message) {
                $this->addError($field, $message);
            }
            return;
        }

        $account = $this->accounts->firstWhere('id', $this->selectedFromAccount);
        $crypto = $this->cryptoBalances->firstWhere('id', $this->selectedCrypto);
        $amount = (string) $this->fiatAmount;
        $idempotencyKey = $this->idempotencyKey;

        try {
            $rate = $this->current_rate;

            if ($this->rateError) {
                $this->addError('rate', $this->rateError);
                return;
            }
            $service->swapToCrypto($account, $crypto, $amount, $rate, $idempotencyKey);
        } catch (\Throwable $e) {
            report($e);
            $this->addError('swap', 'Swap failed.');
            return;
        }

        $this->resetAfterSwap(['fiatAmount', 'selectedFromAccount', 'selectedCrypto'], 'Fiat converted to Crypto successfully.');
    }

    // --------------------------
    // Helper Methods
    // --------------------------
    protected function resetAfterSwap(array $fields = [], string $message = 'Swap successful.'): void
    {
        $this->idempotencyKey = (string) Str::uuid();
        $this->reset($fields);
        $this->rateError = null;
        $this->dispatch('showToast', message: $message, type: 'success');
        $this->loadAccounts();
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Swap Balance
</x-slot:title>


<div class="space-y-3 py-3">

    {{-- SKELETON PLACEHOLDER --}}
    @placeholder
        <div class="space-y-4">

            {{-- Tabs Skeleton --}}
            <div class="flex space-x-2">
                <div class="h-8 w-32 bg-gray-300 dark:bg-gray-600 rounded-xl animate-pulse"></div>
                <div class="h-8 w-32 bg-gray-300 dark:bg-gray-600 rounded-xl animate-pulse"></div>
            </div>

            {{-- Compact Cards Skeleton --}}
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">

                @for ($i = 0; $i < 3; $i++)
                    <div
                        class="relative p-4 rounded-xl flex justify-between items-center
                    bg-gray-200 dark:bg-gray-700 animate-pulse h-24">

                        {{-- Left Section Skeleton --}}
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
                            <div class="flex flex-col gap-1">
                                <div class="h-4 w-24 rounded bg-gray-300 dark:bg-gray-600"></div>
                                <div class="h-3 w-16 rounded bg-gray-300 dark:bg-gray-600"></div>
                            </div>
                        </div>

                        {{-- Right Section Skeleton --}}
                        <div class="flex flex-col items-end gap-1">
                            <div class="h-5 w-20 rounded bg-gray-300 dark:bg-gray-600"></div>
                            <div class="h-4 w-12 rounded bg-gray-300 dark:bg-gray-600"></div>
                            <div class="h-3 w-16 rounded bg-gray-300 dark:bg-gray-600"></div>
                        </div>

                    </div>
                @endfor

            </div>

            {{-- Select Inputs Skeleton --}}
            <div class="space-y-2">
                <div class="h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                <div class="h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
            </div>

            {{-- Amount Input Skeleton --}}
            <div class="h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>

            {{-- Preset Buttons Skeleton --}}
            <div class="flex flex-wrap gap-2">
                @for ($i = 0; $i < 4; $i++)
                    <div class="h-8 w-20 bg-gray-300 dark:bg-gray-600 rounded-xl animate-pulse"></div>
                @endfor
            </div>

            {{-- Swap Summary Skeleton --}}
            <div class="p-4 bg-gray-200 dark:bg-gray-700 rounded-2xl animate-pulse h-32"></div>

            {{-- Button Skeleton --}}
            <div class="h-10 bg-gray-300 dark:bg-gray-600 rounded-2xl animate-pulse"></div>

        </div>
    @endplaceholder


    <div class="space-y-3">
        {{-- Tabs and Content --}}

        <div x-data="{ tab: 'balance', direction: 'cryptoToFiat' }" class="space-y-4 relative overflow-hidden">

            <div class="relative inline-flex p-1 bg-gray-200 dark:bg-gray-700 rounded-lg">
                <!-- Sliding Background -->
                <div class="absolute top-0 left-0 h-full w-1/2 bg-sky-600 rounded-lg shadow transition-all duration-300"
                    :class="tab === 'balance' ? 'translate-x-0' : 'translate-x-full'">
                </div>

                <!-- Buttons -->
                <button @click="tab = 'balance'"
                    class="relative whites px-5 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 transition-colors"
                    :class="tab === 'balance' ? 'text-white dark:text-white' : ''">
                    💳 Internal Swap
                </button>

                <button @click="tab = 'crypto'"
                    class="relative px-5 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 transition-colors"
                    :class="tab === 'crypto' ? 'text-white dark:text-white' : ''">
                    🪙 Crypto Swap
                </button>
            </div>

            {{-- BALANCE SWAP --}}
            <div x-show="tab === 'balance'" x-transition:enter="transition transform duration-300 ease-out"
                x-transition:enter-start="-translate-x-6 opacity-0" x-transition:enter-end="translate-x-0 opacity-100"
                x-transition:leave="transition transform duration-200 ease-in"
                x-transition:leave-start="translate-x-0 opacity-100" x-transition:leave-end="-translate-x-6 opacity-0"
                x-cloak class="space-y-6 duration-300 delay-75 p-3">
                @include('partials.fiataccountcard')
                {{-- Fiat Account Cards --}}
                <div>
                    <x-select label="From Account" :options="$this->accountOptions" placeholder="Select Debit Account"
                        wire:model.lazy="selectedFromAccount" />
                </div>

                <div>
                    <x-select label="To Account" placeholder="Select Credit Account" :options="$this->accountOptions"
                        wire:model.lazy="selectedToAccount" />
                </div>

                <div class="space-y-2">
                    <div>
                        <x-input type="number" label="Amount" wire:model.lazy="fiatAmount" />
                    </div>

                    {{-- Preset Amount Buttons --}}
                    <div class="mt-3 flex flex-wrap gap-2">
                        @foreach ([100, 500, 1000, 5000] as $amt)
                            <button type="button" wire:click="$set('fiatAmount', {{ $amt }})"
                                class="px-4 py-2 rounded-xl text-sm font-semibold transition-all
                                {{ $fiatAmount == $amt ? 'bg-sky-600 text-white shadow-lg' : 'bg-white/20 dark:bg-gray-700/30 text-gray-800 dark:text-gray-200 hover:bg-sky-100 dark:hover:bg-sky-900/40' }}">
                                {{ $currencySymbol }}{{ $amt }}
                            </button>
                        @endforeach
                    </div>
                </div>

                {{-- Swap Summary --}}
                <div class="p-4 bg-white/30 dark:bg-gray-700/40 backdrop-blur-md rounded-2xl shadow-inner">
                    <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-2">Swap Summary</h3>

                    <ul class="text-sm text-gray-600 dark:text-gray-300 space-y-1">
                        <li class="flex justify-between">From:
                            <span
                                class="font-medium">{{ $this->accountLabels[(string) ($selectedFromAccount ?? '')] ?? '—' }}
                            </span>
                        </li>

                        <li class="flex justify-between">To:
                            <span
                                class="font-medium">{{ $this->accountLabels[(string) ($selectedToAccount ?? '')] ?? '—' }}
                            </span>
                        </li>
                        <li class="flex justify-between">Amount:
                            <span class="font-medium">{{ $fiatAmount ?? '—' }}</span>
                        </li>
                        <li class="flex justify-between">Fees:
                            <span
                                class="px-2 py-0.5 bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-100 rounded-full text-xs font-semibold">Free</span>
                        </li>
                        <li class="flex justify-between">Total:
                            <span class="font-medium">{{ $fiatAmount ?? '—' }}</span>
                        </li>
                    </ul>
                </div>

                <x-button wire:click="balanceSwap" class="w-full">Swap Balance</x-button>
            </div>

            {{-- CRYPTO SWAP --}}
            <div x-show="tab === 'crypto'" x-transition:enter="transition transform duration-300 ease-out"
                x-transition:enter-start="translate-x-6 opacity-0" x-transition:enter-end="translate-x-0 opacity-100"
                x-transition:leave="transition transform duration-200 ease-in"
                x-transition:leave-start="translate-x-0 opacity-100" x-transition:leave-end="translate-x-6 opacity-0"
                x-cloak class="space-y-6 duration-300 delay-75 p-3">

                @include('partials.cryptobalancecard')
                {{-- Crypto Wallet Cards --}}

                @if ($rateError)
                    <div
                        class="p-3 rounded-xl bg-red-50 border border-red-200 text-red-700 text-sm flex items-center gap-2">
                        <x-flux::icon.exclamation-triangle class="w-5 h-5" />
                        {{ $rateError }}
                    </div>
                @endif

                <div class="space-y-6">

                    {{-- Swap Direction Toggle --}}
                    <div class="flex justify-center mb-4">
                        <button @click="direction = direction === 'cryptoToFiat' ? 'fiatToCrypto' : 'cryptoToFiat'"
                            class="flex items-center justify-center w-10 h-10 rounded-full bg-sky-100 dark:bg-gray-700 shadow hover:scale-105 transition-transform">
                            <x-flux::icon.arrows-up-down variant="solid"
                                class="w-5 h-5 text-sky-600 dark:text-sky-300" />
                        </button>
                    </div>

                    {{-- CRYPTO → FIAT --}}
                    <div x-show="direction === 'cryptoToFiat'" x-cloak class="space-y-4">

                        {{-- Select Wallets --}}
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <x-select label="Crypto Wallet" placeholder="Select Wallet" :options="$this->cryptoOptions"
                                    wire:model.lazy="selectedCrypto"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>
                            <div>

                                <x-select label="To Account" placeholder="Select Credit Account" :options="$this->accountOptions"
                                    wire:model.lazy="selectedToAccount"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>
                        </div>

                        {{-- Amount Input --}}
                        <div>
                            <div>
                                <x-input type="number" label="Coin Amount (0.01)" wire:model.lazy="cryptoAmount"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>

                            {{-- Preset Buttons --}}
                            <div class="mt-3 flex flex-wrap gap-2">
                                @foreach ([0.01, 0.05, 0.1, 0.5] as $amt)
                                    <button type="button" wire:click="$set('cryptoAmount', {{ $amt }})"
                                        class="px-4 py-2 rounded-xl text-sm font-semibold transition-all
                                        {{ $cryptoAmount == $amt ? 'bg-sky-600 text-white shadow-lg' : 'bg-white/20 dark:bg-gray-700/30 text-gray-800 dark:text-gray-200 hover:bg-sky-100 dark:hover:bg-sky-900/40' }}">
                                        {{ $amt }}
                                    </button>
                                @endforeach
                            </div>
                        </div>

                        {{-- Swap Summary --}}
                        <div wire:key="swap-summary"
                            class="p-5 rounded-2xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md shadow-inner">
                            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-3">Swap Summary</h3>
                            <ul class="space-y-2 text-sm text-gray-600 dark:text-gray-300">
                                <li class="flex justify-between"><span>To:</span>
                                    <span
                                        class="font-medium">{{ $this->accountLabels[(string) ($selectedToAccount ?? '')] ?? '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Crypto:</span>
                                    <span
                                        class="font-medium">{{ $this->cryptoOptions[(string) $selectedCrypto] ?? '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Amount:</span>
                                    <span class="font-medium">{{ $cryptoAmount ?? '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Rate:</span>
                                    <span class="font-medium">
                                        <span wire:loading wire:target="selectedCrypto"
                                            class="animate-pulse text-gray-500">Loading...</span>
                                        <span wire:loading.remove wire:target="selectedCrypto">
                                            @if ($rateError)
                                                <span class="text-orange-600 font-semibold text-sm">Retrying...</span>
                                            @else
                                                {{ number_format((float) $this->current_rate, 2) }}
                                            @endif
                                        </span>
                                    </span>
                                </li>
                                <li class="flex justify-between"><span>Estimated Fiat:</span>
                                    <span class="font-medium">${{ $this->estimatedFiat ?? '0' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Fees:</span>
                                    <span
                                        class="px-2 py-0.5 bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-100 rounded-full text-xs font-semibold">Free</span>
                                </li>
                            </ul>
                        </div>

                        {{-- Swap Button --}}
                        <x-button wire:click="swapCryptoFiat" :disabled="$rateError !== null"
                            class="w-full py-3 rounded-xl bg-sky-600 hover:bg-sky-700 shadow-lg transition-all">
                            Swap to Fiat
                        </x-button>
                    </div>

                    {{-- FIAT → CRYPTO --}}
                    <div x-show="direction === 'fiatToCrypto'" x-cloak class="space-y-4">

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <x-select label="From Account" placeholder="Select Debit Account" :options="$this->accountOptions"
                                    wire:model.lazy="selectedFromAccount"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>

                            <div>
                                <x-select label="Crypto Wallet" placeholder="Select Credit Wallet" :options="$this->cryptoOptions"
                                    wire:model.lazy="selectedCrypto"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>
                        </div>

                        <div>
                            <div>
                                <x-input type="number" label="Amount" wire:model.lazy="fiatAmount"
                                    class="rounded-xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md" />
                            </div>

                            <div class="mt-3 flex flex-wrap gap-2">
                                @foreach ([100, 500, 1000, 5000] as $amt)
                                    <button type="button" wire:click="$set('fiatAmount', {{ $amt }})"
                                        class="px-4 py-2 rounded-xl text-sm font-semibold transition-all
                                        {{ $fiatAmount == $amt ? 'bg-sky-600 text-white shadow-lg' : 'bg-white/20 dark:bg-gray-700/30 text-gray-800 dark:text-gray-200 hover:bg-sky-100 dark:hover:bg-sky-900/40' }}">
                                        {{ $currencySymbol }}{{ $amt }}
                                    </button>
                                @endforeach
                            </div>
                        </div>

                        <div wire:key="swap-summary"
                            class="p-5 rounded-2xl bg-white/30 dark:bg-gray-800/40 backdrop-blur-md shadow-inner">
                            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-3">Swap Summary</h3>
                            <ul class="space-y-2 text-sm text-gray-600 dark:text-gray-300">
                                <li class="flex justify-between"><span>From:</span>
                                    <span
                                        class="font-medium">{{ $this->accountLabels[(string) ($selectedFromAccount ?? '')] ?? '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>To Crypto:</span>
                                    <span
                                        class="font-medium">{{ $this->cryptoOptions[(string) $selectedCrypto] ?? '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Amount:</span>
                                    <span
                                        class="font-medium">{{ $fiatAmount !== '' ? bcadd($fiatAmount, '0', 2) : '—' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Rate:</span>
                                    <span class="font-medium">
                                        <span wire:loading wire:target="selectedCrypto"
                                            class="animate-pulse text-gray-500">Loading...</span>
                                        <span wire:loading.remove
                                            wire:target="selectedCrypto">{{ $this->current_rate ?? '—' }}</span>
                                    </span>
                                </li>
                                <li class="flex justify-between"><span>Estimated Crypto:</span>
                                    <span
                                        class="font-medium">{{ $fiatAmount && $this->current_rate ? number_format($fiatAmount / $this->current_rate, 8) : '0' }}</span>
                                </li>
                                <li class="flex justify-between"><span>Fees:</span>
                                    <span
                                        class="px-2 py-0.5 bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-100 rounded-full text-xs font-semibold">Free</span>
                                </li>
                            </ul>
                        </div>

                        <x-button wire:click="swapFiatToCrypto" :disabled="$rateError !== null"
                            class="w-full py-3 rounded-xl bg-sky-600 hover:bg-sky-700 shadow-lg transition-all">
                            Swap to Crypto
                        </x-button>
                    </div>
                </div>

            </div>
        </div>
    </div>

</div>
