import React, { useState, useEffect, Fragment, useRef, useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useWallet } from '../context/WalletContext';
import { walletAPI } from '../api/wallet';
import { useTranslation } from 'react-i18next';
import TokenIcon from '../components/TokenIcon';
import { Menu, Transition } from '@headlessui/react';

const DEFAULT_VISIBLE_TOKENS = ['TRX', 'BTC', 'ETH', 'BNB', 'SOL'];

const ManageCryptoPage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { userId, refreshSession, activeWallet } = useWallet();
  const [tokens, setTokens] = useState([
    { symbol: 'TRX', name: 'Tron', network: 'Tron', visible: true },
    { symbol: 'BTC', name: 'Bitcoin', network: 'Bitcoin', visible: true },
    { symbol: 'ETH', name: 'Ethereum', network: 'Ethereum', visible: true },
    { symbol: 'BNB', name: 'Binance Coin', network: 'BNB Smart Chain', visible: true },
    { symbol: 'SOL', name: 'Solana', network: 'Solana', visible: true },
    { symbol: 'TON', name: 'Toncoin', network: 'The Open Network', visible: true },
    { symbol: 'USDT', name: 'Tether USD', network: 'Tron', visible: true },
    { symbol: 'XRP', name: 'Ripple', network: 'Ripple', visible: true },
    { symbol: 'DOGE', name: 'Dogecoin', network: 'Dogecoin', visible: true },
    { symbol: 'ARB', name: 'Arbitrum', network: 'Ethereum', visible: true },
    { symbol: 'STRK', name: 'Starknet', network: 'Ethereum', visible: true },
    { symbol: 'ADA', name: 'Cardano', network: 'Cardano', visible: true },
    { symbol: 'SUI', name: 'Sui', network: 'Sui', visible: true },
    { symbol: 'DOT', name: 'Polkadot', network: 'Polkadot', visible: true },
    { symbol: 'SHIB', name: 'Shiba Inu', network: 'Ethereum', visible: true },
    { symbol: 'USDTERC', name: 'USDT', network: 'Ethereum', visible: true },
    { symbol: 'ZEC', name: 'Zcash', network: 'Zcash', visible: true },
    { symbol: 'NOT', name: 'Notcoin', network: 'The Open Network', visible: true },
    { symbol: 'BLUM', name: 'BLUM', network: 'The Open Network', visible: true },
    { symbol: 'XLM', name: 'Stellar', network: 'Stellar', visible: true },
    { symbol: 'HYPE', name: 'Hyperliquid', network: 'Solana', visible: true },
    { symbol: 'UNI', name: 'Uniswap', network: 'Ethereum', visible: true },
    { symbol: 'NEAR', name: 'NEAR Protocol', network: 'NEAR Protocol', visible: true },
    { symbol: 'PEPE', name: 'Pepe', network: 'Ethereum', visible: true },
    { symbol: 'ATOM', name: 'Cosmos', network: 'Cosmos', visible: true },
    { symbol: 'DASH', name: 'Dash', network: 'Dash', visible: true },
    { symbol: 'CAKE', name: 'PancakeSwap', network: 'Binance Smart Chain', visible: true },
    { symbol: 'ZK', name: 'zkSync', network: 'Ethereum', visible: true },
    { symbol: 'HBAR', name: 'Hedera', network: 'Solana', visible: true },
    { symbol: 'LTC', name: 'Litecoin', network: 'Litecoin', visible: true },
    { symbol: 'LINK', name: 'Chainlink', network: 'Ethereum', visible: true },
    { symbol: 'APT', name: 'Aptos', network: 'Aptos', visible: true },
    { symbol: 'LDO', name: 'Lido DAO', network: 'Ethereum', visible: true },
    { symbol: 'AAVE', name: 'Aave', network: 'Ethereum', visible: true },
    { symbol: 'AVAX', name: 'Avalanche', network: 'Avalanche', visible: true },
    { symbol: 'ASTER', name: 'Aster', network: 'Ethereum', visible: true },
    { symbol: 'FIL', name: 'Filecoin', network: 'Filecoin', visible: true },
    { symbol: 'PAXG', name: 'PAX Gold', network: 'Ethereum', visible: true },
    { symbol: 'USDC', name: 'USD Coin', network: 'Ethereum', visible: true },
    { symbol: 'XAUt', name: 'Tether Gold', network: 'Ethereum', visible: true },
    { symbol: 'TRUMP', name: 'TRUMP', network: 'Solana', visible: true },
    { symbol: 'OP', name: 'Optimism', network: 'Optimism', visible: true },
    { symbol: 'DCR', name: 'Decred', network: 'Decred', visible: true },
    { symbol: 'SAND', name: 'The Sandbox', network: 'Ethereum', visible: true },
    { symbol: 'INJ', name: 'Injective', network: 'Injective', visible: true },
    { symbol: 'MNT', name: 'Mantle', network: 'Mantle', visible: true },
    { symbol: 'XMR', name: 'Monero', network: 'Monero', visible: true },
    { symbol: 'KAS', name: 'Kaspa', network: 'Kaspa', visible: true },
    { symbol: 'ENS', name: 'Ethereum Name Service', network: 'Ethereum', visible: true },
    { symbol: 'CC', name: 'Canton', network: 'Canton', visible: true },
    { symbol: 'XPL', name: 'Plasma', network: 'Plasma', visible: true },
    { symbol: 'LAYER', name: 'Solayer', network: 'Solayer', visible: true },
    { symbol: 'BERA', name: 'Berachain', network: 'Berachain', visible: true },
    { symbol: 'WLFI', name: 'WLFI', network: 'Ethereum', visible: true },
    { symbol: 'ICP', name: 'Internet Computer', network: 'Internet Computer', visible: true },
    { symbol: 'JUP', name: 'Jupiter', network: 'Solana', visible: true },
    { symbol: 'USD1', name: 'World Liberty Financial USD', network: 'Solana', visible: true },
    { symbol: 'ZERO', name: 'Zero', network: 'Ethereum', visible: true },
    { symbol: 'ETC', name: 'Ethereum Classic', network: 'Ethereum', visible: true },
    { symbol: 'XCH', name: 'Chia', network: 'Chia', visible: true },
    { symbol: 'VON', name: 'Vameon', network: 'Vameon', visible: true },
    { symbol: 'ETHZK', name: 'Ethereum', network: 'zkSync', visible: false },
    { symbol: 'ENA', name: 'Ethena', network: 'Ethereum', visible: true },
    { symbol: 'ETHFI', name: 'ether.fi', network: 'Ethereum', visible: true },
    { symbol: 'GRASS', name: 'Grass', network: 'Solana', visible: true },
    { symbol: 'OKB', name: 'OKB', network: 'Ethereum', visible: true },
    { symbol: 'BCH', name: 'Bitcoin Cash', network: 'Bitcoin Cash', visible: true },
    { symbol: 'TAO', name: 'Bittensor', network: 'Bittensor', visible: true },
    { symbol: 'SKR', name: 'Seeker', network: 'Solana', visible: false },
    { symbol: 'TORN', name: 'Tornado Cash', network: 'Ethereum', visible: false },
    { symbol: 'NFLXON', name: 'Netflix', network: 'Ethereum', visible: false },
    { symbol: 'NVDAON', name: 'NVIDIA', network: 'Ethereum', visible: false },
    { symbol: 'AAPL', name: 'Apple', network: 'Ethereum', visible: false },
    { symbol: 'TSLA', name: 'Tesla', network: 'Ethereum', visible: false },
    { symbol: 'MSFT', name: 'Microsoft', network: 'Ethereum', visible: false },
    { symbol: 'AMZN', name: 'Amazon', network: 'Ethereum', visible: false },
    { symbol: 'ENSO', name: 'Enso', network: 'Ethereum', visible: false },
  ]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [pendingCount, setPendingCount] = useState(0); // Количество ожидающих изменений
  const [message, setMessage] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedNetwork, setSelectedNetwork] = useState({ name: 'Все сети', icon: null, iconUrl: null });
  const saveTimeoutsRef = useRef({}); // Объект с таймерами для каждого токена
  const pendingChangesRef = useRef(new Set()); // Набор токенов, ожидающих сохранения

  // Список доступных сетей с иконками
  const networks = [
    { name: 'Все сети', icon: null, iconUrl: null },
    { name: 'Tron', icon: 'TRX', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png' },
    { name: 'Bitcoin', icon: 'BTC', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1.png' },
    { name: 'Ethereum', icon: 'ETH', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png' },
    { name: 'BNB Smart Chain', icon: 'BNB', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png' },
    { name: 'Binance Smart Chain', icon: 'CAKE', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/7186.png' },
    { name: 'Solana', icon: 'SOL', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png' },
    { name: 'The Open Network', icon: 'TON', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11419.png' },
    { name: 'Ripple', icon: 'XRP', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/52.png' },
    { name: 'Dogecoin', icon: 'DOGE', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/74.png' },
    { name: 'Cardano', icon: 'ADA', iconUrl: 'https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/cardano/info/logo.png' },
    { name: 'Sui', icon: 'SUI', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/20947.png' },
    { name: 'Polkadot', icon: 'DOT', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/6636.png' },
    { name: 'Zcash', icon: 'ZEC', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1437.png' },
    { name: 'Stellar', icon: 'XLM', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/512.png' },
    { name: 'NEAR Protocol', icon: 'NEAR', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/6535.png' },
    { name: 'Cosmos', icon: 'ATOM', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/3794.png' },
    { name: 'Dash', icon: 'DASH', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/131.png' },
    { name: 'Litecoin', icon: 'LTC', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/2.png' },
    { name: 'Aptos', icon: 'APT', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/21794.png' },
    { name: 'Avalanche', icon: 'AVAX', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png' },
    { name: 'Filecoin', icon: 'FIL', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/2280.png' },
    { name: 'Optimism', icon: 'OP', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png' },
    { name: 'Decred', icon: 'DCR', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1168.png' },
    { name: 'Injective', icon: 'INJ', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/7226.png' },
    { name: 'Mantle', icon: 'MNT', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/27075.png' },
    { name: 'Monero', icon: 'XMR', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/328.png' },
    { name: 'Kaspa', icon: 'KAS', iconUrl: 'https://s2.coinmarketcap.com/static/img/coins/64x64/20396.png' },
    { name: 'Canton', icon: 'CC', iconUrl: '/coins/cc.png' },
    { name: 'Plasma', icon: 'XPL', iconUrl: '/coins/xpl.png' },
    { name: 'Solayer', icon: 'LAYER', iconUrl: '/coins/layer.png' },
    { name: 'Berachain', icon: 'BERA', iconUrl: '/coins/bera.png' },
    { name: 'Internet Computer', icon: 'ICP', iconUrl: '/coins/icp.png' },
    { name: 'Chia', icon: 'XCH', iconUrl: '/coins/chia.png' }
  ];

  const walletBalanceMap = useMemo(() => {
    const map = {};
    (activeWallet?.tokens || []).forEach((token) => {
      const symbol = token.tokenInfo?.symbol;
      if (!symbol) return;
      const balanceValue = parseFloat(token.balance) || 0;
      map[symbol] = balanceValue;
      map[symbol.toUpperCase()] = balanceValue;
      map[symbol.toLowerCase()] = balanceValue;
    });
    return map;
  }, [activeWallet?.tokens]);

  const loadTokenVisibility = useCallback(async (balanceSnapshot = {}) => {
    if (!userId) return;

    try {
      const response = await walletAPI.getTokenVisibility(userId);
      const visibilityMap = response.success && response.data ? response.data : {};

      const resolveMapValue = (map, symbol) => {
        if (!symbol || !map) return undefined;
        return (
          map[symbol] ??
          map[symbol.toUpperCase()] ??
          map[symbol.toLowerCase()]
        );
      };

      setTokens((prevTokens) =>
        prevTokens.map((token) => {
          const symbol = token.symbol;
          const visibilityEntry = resolveMapValue(visibilityMap, symbol);
          const balanceValue = resolveMapValue(balanceSnapshot, symbol) || 0;

          const shouldShow = balanceValue > 0
            ? true
            : (typeof visibilityEntry === 'boolean'
                ? visibilityEntry
                : DEFAULT_VISIBLE_TOKENS.includes(symbol));

          return { ...token, visible: shouldShow };
        })
      );
    } catch (error) {
      console.error('Failed to load token visibility:', error);
    }
  }, [userId]);

  useEffect(() => {
    if (!userId) return;
    refreshSession();
  }, [userId, refreshSession]);

  useEffect(() => {
    if (!userId) return;
    let isMounted = true;

    const syncVisibility = async () => {
      setLoading(true);
      try {
        await loadTokenVisibility(walletBalanceMap);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    syncVisibility();

    return () => {
      isMounted = false;
    };
  }, [userId, walletBalanceMap, loadTokenVisibility]);

  // Очищаем все таймеры при размонтировании компонента
  useEffect(() => {
    return () => {
      Object.values(saveTimeoutsRef.current).forEach(timeout => {
        if (timeout) clearTimeout(timeout);
      });
    };
  }, []);

  const handleOpenToken = (symbol) => {
    if (!symbol) return;
    navigate(`/currency/${symbol}`);
  };

  const handleToggle = async (symbol) => {
    if (!userId) return;

    // Мгновенно обновляем UI
    const updatedTokens = tokens.map((token) =>
      token.symbol === symbol ? { ...token, visible: !token.visible } : token
    );
    setTokens(updatedTokens);

    // Добавляем токен в список ожидающих изменений
    pendingChangesRef.current.add(symbol);
    setPendingCount(pendingChangesRef.current.size);
    setSaving(true);

    // Очищаем предыдущий таймер для ЭТОГО токена (если есть)
    if (saveTimeoutsRef.current[symbol]) {
      clearTimeout(saveTimeoutsRef.current[symbol]);
    }

    // Устанавливаем новый таймер для ЭТОГО токена (debounce 800 мс)
    saveTimeoutsRef.current[symbol] = setTimeout(async () => {
      try {
        console.log(`[Toggle] Saving ${symbol}...`);
      await walletAPI.toggleToken(userId, symbol);
        
        // Удаляем токен из списка ожидающих
        pendingChangesRef.current.delete(symbol);
        setPendingCount(pendingChangesRef.current.size);
      
        // Если больше нет ожидающих изменений, обновляем сессию и показываем сообщение
        if (pendingChangesRef.current.size === 0) {
      await refreshSession();
          setMessage(`Изменения сохранены`);
          setTimeout(() => setMessage(''), 2000);
          setSaving(false);
        }
    } catch (error) {
      console.error('Failed to toggle token:', error);
        pendingChangesRef.current.delete(symbol);
        setPendingCount(pendingChangesRef.current.size);
        
        if (pendingChangesRef.current.size === 0) {
          setSaving(false);
        }
        
        setMessage(`Ошибка сохранения ${symbol}. ${error.message || 'Попробуйте позже'}`);
      setTimeout(() => setMessage(''), 3000);
      
        // Откатываем изменения при ошибке
      setTokens((prevTokens) =>
        prevTokens.map((token) =>
          token.symbol === symbol ? { ...token, visible: !token.visible } : token
        )
      );
      } finally {
        // Очищаем таймер из объекта
        delete saveTimeoutsRef.current[symbol];
    }
    }, 800); // Ждём 800 мс после последнего переключения этого токена
  };

  const handleSaveAll = async () => {
    if (!userId) return;

    setSaving(true);
    setMessage('');

    try {
      for (const token of tokens) {
        const response = await walletAPI.getTokenVisibility(userId);
        const currentVisibility = response.data?.[token.symbol] ?? true;
        
        if (currentVisibility !== token.visible) {
          await walletAPI.toggleToken(userId, token.symbol);
        }
      }

      setMessage('All changes saved successfully!');
      setTimeout(() => setMessage(''), 3000);
      
      await refreshSession();
    } catch (error) {
      console.error('Failed to save changes:', error);
      setMessage('Failed to save some changes');
      setTimeout(() => setMessage(''), 3000);
    } finally {
      setSaving(false);
    }
  };

  // Фильтрация токенов по поисковому запросу и сети
  const filteredTokens = tokens.filter((token) => {
    // Фильтр по поиску
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      const matchesSearch = 
        token.symbol.toLowerCase().includes(query) ||
        token.name.toLowerCase().includes(query);
      if (!matchesSearch) return false;
    }
    
    // Фильтр по сети
    if (selectedNetwork.name !== 'Все сети') {
      return token.network === selectedNetwork.name;
    }
    
    return true;
  });

  if (loading) {
    return (
      <div className="min-h-screen bg-[#1b1b1c]">
        <div className="flex items-center justify-center h-64">
          <div className="text-xl text-gray-400">Загрузка...</div>
        </div>
        </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#1b1b1c]">
      {/* Header */}
      <div className="px-4 py-4 bg-[#1b1b1c] mobile-safe-area">
        <div className="max-w-md mx-auto container-mobile">
          <div className="flex items-center justify-between mb-6">
            <button
              onClick={() => navigate('/')}
              className="p-2 hover:bg-gray-700 rounded-lg transition-colors"
            >
              <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
            </button>
            <div className="flex items-center space-x-2">
              <h1 className="text-xl font-bold text-white">Поиск</h1>
              {saving && pendingCount > 0 && (
                <span className="text-xs text-[#48ff91] bg-[#48ff91]/10 px-2 py-1 rounded animate-pulse">
                  {pendingCount > 1 ? `Сохранение (${pendingCount})...` : 'Сохранение...'}
                </span>
              )}
            </div>
            <div className="w-10"></div>
          </div>

          {/* Search Bar */}
          <div className="relative mb-6">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
            <input
              type="text"
              placeholder="Название токена или адрес контракта"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-[#242426] text-white pl-10 pr-4 py-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#48ff91]"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                <svg className="w-5 h-5 text-gray-400 hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>

           {/* Network Filter */}
          <Menu as="div" className="relative mb-4">
            <Menu.Button className="flex items-center justify-between w-full p-3 bg-[#242426] rounded-lg hover:bg-gray-700 transition-colors">
              <div className="flex items-center space-x-3">
                {selectedNetwork.iconUrl ? (
                  <div className="w-6 h-6 rounded-full overflow-hidden flex-shrink-0">
                    <img 
                      src={selectedNetwork.iconUrl} 
                      alt={selectedNetwork.icon} 
                      className="w-full h-full object-cover"
                    />
                  </div>
                ) : (
                  <svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                  </svg>
                )}
                <span className="text-white font-medium">{selectedNetwork.name}</span>
              </div>
              <svg className="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
              </svg>
            </Menu.Button>

            <Transition
              as={Fragment}
              enter="transition ease-out duration-100"
              enterFrom="transform opacity-0 scale-95"
              enterTo="transform opacity-100 scale-100"
              leave="transition ease-in duration-75"
              leaveFrom="transform opacity-100 scale-100"
              leaveTo="transform opacity-0 scale-95"
            >
              <Menu.Items className="absolute left-0 right-0 mt-2 origin-top rounded-lg bg-[#1b1b1c] shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none border border-gray-800 z-50 overflow-visible">
                <div className="py-1">
                  {networks.map((network) => (
                    <Menu.Item key={network.name}>
                      {({ active }) => (
                        <button
                          onClick={() => setSelectedNetwork(network)}
                          className={`${
                            active ? 'bg-gray-700' : ''
                          } ${
                            selectedNetwork.name === network.name ? 'bg-gray-700' : ''
                          } group flex w-full items-center justify-between px-4 py-3 text-sm overflow-visible`}
                        >
                          <div className="flex items-center space-x-3">
                            {network.iconUrl ? (
                              <div className="w-6 h-6 flex-shrink-0">
                                <img 
                                  src={network.iconUrl} 
                                  alt={network.icon} 
                                  className="w-full h-full object-cover rounded-full"
                                />
                              </div>
                            ) : (
                              <svg className="w-6 h-6 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 919-9" />
                              </svg>
                            )}
                            <span className="text-gray-300">{network.name}</span>
                          </div>
                          {selectedNetwork.name === network.name && (
                            <svg className="w-5 h-5 text-[#48ff91] flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                            </svg>
                          )}
                        </button>
                      )}
                    </Menu.Item>
                  ))}
                </div>
              </Menu.Items>
            </Transition>
          </Menu>
          </div>
        </div>

      {/* Tokens List */}
      <div className="px-4 mobile-safe-area pb-24">
        <div className="max-w-md mx-auto container-mobile">
        {message && (
            <div className="mb-4 bg-[#48ff91]/10 border border-[#48ff91]/30 rounded-lg p-3 text-[#48ff91] text-sm">
            {message}
          </div>
        )}

          <div className="border-t border-gray-800">
            {filteredTokens.length > 0 ? (
              filteredTokens.map((token) => {
                // Для USDTERC отображаем "USDT" и badge "ERC-20"
                const displaySymbol = token.symbol === 'USDTERC' ? 'USDT' : token.symbol;
                const displayBadge = token.symbol === 'USDTERC' ? 'ERC-20' : token.name;
                
                return (
                <div
                  key={token.symbol}
                  className="flex items-center justify-between py-4 px-4 hover:bg-gray-800/30 transition-colors border-b border-gray-800"
                >
                  <button
                    type="button"
                    onClick={() => handleOpenToken(token.symbol)}
                    className="flex items-center space-x-4 flex-1 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-[#48ff91] rounded-lg pr-4"
                  >
                    <TokenIcon symbol={token.symbol} size="w-12 h-12" />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <h3 className="text-lg font-semibold text-white">{displaySymbol}</h3>
                        <span className="text-xs text-gray-200 bg-gray-700 px-2 py-1 rounded-full">
                          {displayBadge}
                        </span>
                      </div>
                      <p className="text-sm text-gray-500">{token.name}</p>
                    </div>
                  </button>

                  {/* Toggle Switch */}
                  <button
                    onClick={() => handleToggle(token.symbol)}
                    className={`relative inline-flex h-8 w-14 items-center rounded-full transition-colors ${
                      token.visible ? 'bg-[#48ff91]' : 'bg-gray-700'
                    }`}
                  >
                    <span
                      className={`inline-block h-6 w-6 transform rounded-full bg-white transition-transform ${
                        token.visible ? 'translate-x-7' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>
                );
              })
            ) : (
              <div className="text-center py-12">
                <svg className="w-16 h-16 text-gray-600 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <p className="text-gray-400 text-lg mb-2">Токены не найдены</p>
                <p className="text-gray-500 text-sm">Попробуйте изменить запрос</p>
          </div>
            )}
          </div>
        </div>
        </div>
      </div>
  );
};

export default ManageCryptoPage;
