<x-user-layout>
    <main class="w-full mx-auto p-4 pb-24 md:pb-4 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 mb-8 pb-4">
            <a href="{{ url()->previous() }}" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <h1 class="text-xl font-semibold text-center flex-1">Your Wallet Addresses</h1>
            <a href="{{ route('crypto.manage') }}" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white">
                <i class="fas fa-plus text-xl"></i>
            </a>
        </div>
    
        <!-- Search Bar -->
        <div class="relative mb-6">
            <i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            <input 
                type="text" 
                placeholder="Enter coin name" 
                id="search-input"
                class="w-full bg-transparent border border-gray-700 rounded-full py-3 pl-12 pr-4 text-gray-300 placeholder-gray-500 focus:outline-none focus:border-gray-600"
                onkeyup="filterCryptos()"
            >
        </div>
    
        <!-- Network Filter -->
        <div class="mb-6 flex flex-wrap gap-2">
            <button 
                class="filter-btn inline-block px-4 py-1 rounded-full text-sm bg-gray-800 text-white"
                data-network="all"
            >
                All Networks
            </button>
            @foreach(['TRC20', 'ERC20', 'BNB'] as $network)
                <button 
                    class="filter-btn inline-block px-4 py-1 rounded-full text-sm bg-gray-800 text-white"
                    data-network="{{ $network }}"
                >
                    {{ $network }}
                </button>
            @endforeach
        </div>
    
        <!-- Crypto Address List -->
        <div class="space-y-4" id="crypto-list">
            @forelse($activeCryptos as $crypto)
                <div class="flex items-center justify-between p-4 crypto-item" data-network="{{ $crypto['network'] ?? 'native' }}">
                    <div class="flex items-center flex-1">
                        <div class="w-10 h-10 rounded-full flex items-center justify-center mr-4">
                            @if(strtolower($crypto['symbol']) === 'usdt')
                                <!-- USDT Icon as Text -->
                                <span class="text-white font-bold">₮</span>
                            @else
                                <!-- Cryptocurrency Icon as Image -->
                                <img 
                                    src="{{ asset('images/' . strtolower($crypto['symbol']) . '-icon.png') }}" 
                                    alt="{{ $crypto['name'] }} Icon" 
                                    class="w-8 h-8 object-contain"
                                >
                            @endif
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <h3 class="font-semibold">{{ $crypto['name'] }}</h3>
                                @if($crypto['network'])
                                    <span class="text-xs bg-gray-200 dark:bg-gray-800 px-2 py-0.5 rounded">{{ strtoupper($crypto['network']) }}</span>
                                @endif
                            </div>
                            <p class="text-sm text-gray-400 font-mono">{{ \Illuminate\Support\Str::limit($crypto['address'], 15, '...') }}</p>
                        </div>
                    </div>
                    <button 
                        class="ml-4 text-gray-400 hover:text-white copy-btn" 
                        data-address="{{ $crypto['address'] }}"
                        aria-label="Copy {{ $crypto['name'] }} Address"
                    >
                        <i class="far fa-copy"></i>
                    </button>
                </div>
            @empty
                <p class="text-center text-gray-500">No active cryptocurrency addresses found.</p>
            @endforelse
        </div>
    </main>
</x-user-layout>

<!-- Optional: Success Message for Copying Address -->
<div id="copy-success" class="fixed top-10 right-4 bg-green-500 text-white px-4 py-2 rounded opacity-0 transition-opacity">
    Address copied to clipboard!
</div>

<!-- JavaScript for Search, Filter, and Copy Functionality -->
<script>
    // Function to filter cryptocurrencies based on search input and network filter
    function filterCryptos() {
        const searchInput = document.getElementById('search-input').value.toLowerCase();
        const filterButtons = document.querySelectorAll('.filter-btn');
        let activeNetwork = 'all';

        // Determine the active network filter
        filterButtons.forEach(btn => {
            if(btn.classList.contains('active')) {
                activeNetwork = btn.getAttribute('data-network');
            }
        });

        const cryptoItems = document.querySelectorAll('.crypto-item');

        cryptoItems.forEach(item => {
            const name = item.querySelector('h3').innerText.toLowerCase();
            const network = item.getAttribute('data-network').toLowerCase();

            const matchesSearch = name.includes(searchInput);
            const matchesNetwork = activeNetwork === 'all' || network === activeNetwork.toLowerCase();

            if(matchesSearch && matchesNetwork) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    }

    // Add event listeners to filter buttons
    document.querySelectorAll('.filter-btn').forEach(button => {
        button.addEventListener('click', function() {
            // Remove active class from all buttons
            document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active', 'bg-blue-500'));
            // Add active class to the clicked button
            this.classList.add('active', 'bg-blue-500');
            // Trigger the filter function
            filterCryptos();
        });
    });

    // Initialize the first filter button as active
    document.addEventListener('DOMContentLoaded', () => {
        const firstFilterBtn = document.querySelector('.filter-btn[data-network="all"]');
        if(firstFilterBtn) {
            firstFilterBtn.classList.add('active', 'bg-blue-500');
        }
    });

    // Copy to clipboard functionality
    document.querySelectorAll('.copy-btn').forEach(button => {
        button.addEventListener('click', function() {
            const address = this.getAttribute('data-address');
            navigator.clipboard.writeText(address).then(() => {
                const successMsg = document.getElementById('copy-success');
                successMsg.classList.remove('opacity-0');
                successMsg.classList.add('opacity-100');
                setTimeout(() => {
                    successMsg.classList.remove('opacity-100');
                    successMsg.classList.add('opacity-0');
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        });
    });
</script>
