import { useState, useEffect, useRef } from 'react';
import { CreditCard, Plus, ScanLine, SmartphoneNfc, X, Eye, EyeOff, Copy, Check,
         Lock, Unlock, Settings2, Shield, ShieldOff, AlertTriangle, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { fetchUserData, createCard, blockCard, updateCardLimits } from '../../api/mockApi';
import { useNotifications } from '../../context/NotificationsContext';
import toast from 'react-hot-toast';

const CARD_SETTINGS_KEY = 'iosco_card_settings';
const defaultSettings = { online_payments: true, atm_withdrawals: true, international: false, nfc: true };

const CURRENCIES = ['USD', 'EUR', 'RUB', 'GBP', 'JPY'];

const FlipCard = ({ card, color }) => {
    const [flipped, setFlipped] = useState(false);
    const [cvvVisible, setCvvVisible] = useState(false);
    const [copied, setCopied] = useState(false);
    const fmt = (num) => num ? num.match(/.{1,4}/g).join(' ') : '•••• •••• •••• ••••';
    const handleCopy = (e) => { e.stopPropagation(); navigator.clipboard.writeText(card.card_number||''); setCopied(true); toast.success('Скопировано!'); setTimeout(()=>setCopied(false),2000); };
    return (
        <div className="relative w-full" style={{ perspective: '1000px' }}>
            <div className="relative w-full cursor-pointer transition-transform duration-700"
                style={{ transformStyle:'preserve-3d', transform: flipped?'rotateY(180deg)':'rotateY(0deg)', aspectRatio:'1.586/1' }}
                onClick={() => setFlipped(!flipped)}>
                {/* Front */}
                <div className={`absolute inset-0 rounded-3xl p-5 flex flex-col justify-between overflow-hidden shadow-2xl ${color}`}
                    style={{ backfaceVisibility:'hidden', WebkitBackfaceVisibility:'hidden' }}>
                    <div className="absolute inset-0 opacity-20 pointer-events-none"
                        style={{ backgroundImage:'radial-gradient(circle at 85% 15%, #fff 0%, transparent 45%), radial-gradient(circle at 15% 85%, #fff 0%, transparent 40%)' }} />
                    {/* Subtle noise texture */}
                    <svg className="absolute inset-0 w-full h-full opacity-[0.04] pointer-events-none" xmlns="http://www.w3.org/2000/svg"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency="0.75" numOctaves="4" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/></filter><rect width="100%" height="100%" filter="url(#n)"/></svg>
                    <div className="flex justify-between items-start z-10">
                        <div className="text-white font-poppins font-bold text-sm tracking-wider">IOSCO</div>
                        <div className="flex items-center gap-2">
                            {card.is_virtual == 1 && <span className="text-white/70 text-[10px] font-poppins bg-white/10 px-2 py-0.5 rounded-full">VIRTUAL</span>}
                            <ScanLine className="text-white/70" size={16} />
                        </div>
                    </div>
                    <div className="z-10">
                        <div className="flex items-center justify-between mb-3">
                            <SmartphoneNfc className="text-white/70" size={26} />
                            <span className="text-white/60 text-xs font-poppins">{card.currency || 'USD'}</span>
                        </div>
                        <div className="text-white font-mono font-semibold text-sm tracking-widest mb-3">{fmt(card.card_number)}</div>
                        <div className="flex justify-between items-end">
                            <div><div className="text-white/50 text-[10px] font-poppins mb-0.5">ВЛАДЕЛЕЦ</div><div className="text-white font-poppins font-semibold text-xs uppercase tracking-wide">{card.card_holder||'CARD HOLDER'}</div></div>
                            <div className="text-right"><div className="text-white/50 text-[10px] font-poppins mb-0.5">СРОК</div><div className="text-white font-poppins text-xs font-semibold">{card.expiry_date}</div></div>
                        </div>
                    </div>
                    {card.status !== 'active' && (
                        <div className="absolute inset-0 bg-black/60 backdrop-blur-[2px] z-20 flex items-center justify-center rounded-3xl">
                            <span className="bg-red-500/80 text-white px-4 py-2 rounded-full text-sm font-poppins font-semibold flex items-center gap-2"><Lock size={14}/>Заблокирована</span>
                        </div>
                    )}
                    <div className="absolute bottom-2 right-3 text-white/30 text-[10px] font-poppins pointer-events-none">Нажмите для переворота</div>
                </div>
                {/* Back */}
                <div className={`absolute inset-0 rounded-3xl overflow-hidden shadow-2xl ${color}`}
                    style={{ backfaceVisibility:'hidden', WebkitBackfaceVisibility:'hidden', transform:'rotateY(180deg)' }}>
                    <div className="absolute inset-0 opacity-20 pointer-events-none"
                        style={{ backgroundImage:'radial-gradient(circle at 15% 15%, #fff 0%, transparent 45%)' }} />
                    <div className="w-full h-8 bg-black/70 mt-6" />
                    <div className="px-5 mt-3">
                        <div className="bg-white/15 rounded-lg px-4 py-2 mb-2 flex items-center justify-between">
                            <span className="text-white/50 text-xs font-poppins italic flex-1">Подпись</span>
                            <div className="flex items-center gap-2">
                                <span className="text-white font-poppins font-bold text-base tracking-widest">{cvvVisible?(card.cvv||'•••'):'•••'}</span>
                                <button onClick={e=>{e.stopPropagation();setCvvVisible(!cvvVisible);}} className="text-white/70 hover:text-white">{cvvVisible?<EyeOff size={14}/>:<Eye size={14}/>}</button>
                            </div>
                        </div>
                        <div className="text-white/50 text-xs text-center mb-3 font-poppins">CVV / CVC</div>
                        <div className="flex items-center justify-between bg-black/30 rounded-lg px-3 py-1.5">
                            <span className="text-white/60 text-xs font-mono tracking-widest">{fmt(card.card_number)}</span>
                            <button onClick={handleCopy} className="text-white/70 hover:text-white ml-2">{copied?<Check size={12} className="text-green-400"/>:<Copy size={12}/>}</button>
                        </div>
                        <div className="mt-3 flex justify-between">
                            <div><div className="text-white/50 text-[10px] font-poppins">Баланс</div><div className="text-white font-poppins font-semibold text-sm">${parseFloat(card.balance||0).toFixed(2)}</div></div>
                            <div className="text-right"><div className="text-white/50 text-[10px] font-poppins">Тип</div><div className="text-white font-poppins font-semibold text-sm">{card.type==='debit'?'Дебетовая':'Кредитная'}</div></div>
                        </div>
                    </div>
                    <div className="absolute bottom-2 right-3 text-white/30 text-[10px] font-poppins pointer-events-none">Нажмите для переворота</div>
                </div>
            </div>
        </div>
    );
};

const Toggle = ({ checked, onChange }) => (
    <button onClick={onChange} className={`w-12 h-6 rounded-full p-1 transition-colors duration-300 flex items-center ${checked?'bg-secondary':'bg-gray-700'}`}>
        <div className={`w-4 h-4 rounded-full bg-white shadow transition-transform duration-300 ${checked?'translate-x-6':'translate-x-0'}`}/>
    </button>
);

const CardsView = () => {
    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [cardType, setCardType] = useState('debit');
    const [cardCurrency, setCardCurrency] = useState('USD');
    const [isVirtual, setIsVirtual] = useState(false);
    const [isCreating, setIsCreating] = useState(false);
    const [limitModal, setLimitModal] = useState(null);
    const [limitForm, setLimitForm] = useState({ daily: '', monthly: '' });
    const [settings, setSettings] = useState(() => { try { return JSON.parse(localStorage.getItem(CARD_SETTINGS_KEY))||defaultSettings; } catch { return defaultSettings; } });
    const { pushLocal } = useNotifications();

    useEffect(() => { loadCards(); }, []);

    const loadCards = async () => {
        setLoading(true);
        try { const d = await fetchUserData(); setCards(d.cards||[]); }
        catch { toast.error('Ошибка загрузки карт'); }
        finally { setLoading(false); }
    };

    const handleToggle = (key) => {
        const s = { ...settings, [key]: !settings[key] };
        setSettings(s); localStorage.setItem(CARD_SETTINGS_KEY, JSON.stringify(s));
        toast.success(s[key]?'Включено':'Отключено');
    };

    const handleBlockCard = async (card) => {
        const newStatus = card.status === 'active' ? 'blocked' : 'active';
        try {
            await blockCard(card.id, newStatus);
            toast.success(newStatus==='active'?'Карта разблокирована':'Карта заблокирована');
            pushLocal(newStatus==='active'?'Карта разблокирована':'Карта заблокирована', `Карта **** ${card.card_number?.slice(-4)} ${newStatus==='active'?'разблокирована':'заблокирована'}`, newStatus==='active'?'success':'warning');
            loadCards();
        } catch (e) { toast.error(e.message); }
    };

    const handleSaveLimits = async (e) => {
        e.preventDefault();
        try {
            await updateCardLimits(limitModal.id, limitForm.daily||limitModal.daily_limit, limitForm.monthly||limitModal.monthly_limit);
            toast.success('Лимиты обновлены!');
            setLimitModal(null);
            loadCards();
        } catch (e) { toast.error(e.message); }
    };

    const handleCreateCard = async (e) => {
        e.preventDefault();
        setIsCreating(true);
        try {
            const res = await createCard(cardType, cardCurrency, isVirtual);
            toast.success(res.message||'Карта создана!');
            pushLocal('Новая карта', `${isVirtual?'Виртуальная':''} ${cardType==='debit'?'дебетовая':'кредитная'} карта выпущена`, 'success');
            setIsModalOpen(false);
            loadCards();
        } catch (e) { toast.error(e.message||'Ошибка'); }
        finally { setIsCreating(false); }
    };

    const [activeIdx, setActiveIdx] = useState(0);
    const [dropdownOpen, setDropdownOpen] = useState(false);
    const sliderRef = useRef(null);
    const dropdownRef = useRef(null);

    useEffect(() => {
        const handler = (e) => { if (dropdownRef.current && !dropdownRef.current.contains(e.target)) setDropdownOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    const scrollTo = (idx) => {
        setActiveIdx(idx);
        setDropdownOpen(false);
        if (sliderRef.current) {
            const child = sliderRef.current.children[idx];
            if (child) child.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
        }
    };

    const onScroll = () => {
        if (!sliderRef.current) return;
        const { scrollLeft, clientWidth } = sliderRef.current;
        const idx = Math.round(scrollLeft / clientWidth);
        setActiveIdx(Math.max(0, Math.min(idx, cards.length - 1)));
    };

    const CARD_COLORS = [
        'bg-gradient-to-br from-violet-600 via-purple-600 to-indigo-700',
        'bg-gradient-to-br from-slate-800 via-gray-800 to-zinc-900',
        'bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-700',
        'bg-gradient-to-br from-rose-500 via-red-600 to-orange-600',
        'bg-gradient-to-br from-blue-500 via-blue-700 to-indigo-800',
        'bg-gradient-to-br from-amber-500 via-orange-500 to-yellow-600',
    ];
    const getColor = (id, type) => type==='credit' ? CARD_COLORS[1] : CARD_COLORS[id % (CARD_COLORS.length - 1)];

    const CARD_SETTINGS_LIST = [
        { key:'online_payments',  title:'Онлайн-платежи',         desc:'Транзакции в интернете' },
        { key:'atm_withdrawals',  title:'Снятие в банкоматах',    desc:'Наличные через банкоматы' },
        { key:'international',    title:'Международные операции', desc:'Платежи за рубежом' },
        { key:'nfc',              title:'Бесконтактная оплата',   desc:'NFC / Apple Pay' },
    ];

    return (
        <div className="animate-fade-in pb-24">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-1">Мои карты</h2>
                    <p className="text-dimWhite font-poppins text-sm">Нажмите на карту — увидите CVV</p>
                </div>
                <button onClick={() => setIsModalOpen(true)}
                    className="flex items-center gap-2 bg-blue-gradient text-primary px-6 py-3 rounded-2xl font-poppins font-semibold hover:opacity-90 transition-opacity shadow-lg shadow-cyan-500/20">
                    <Plus size={18}/> Выпустить карту
                </button>
            </div>

            {loading ? (
                <div className="flex justify-center py-20"><div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-secondary"></div></div>
            ) : cards.length === 0 ? (
                <div className="bg-black-gradient-2 rounded-3xl p-12 text-center border border-gray-800">
                    <div className="w-16 h-16 rounded-2xl bg-secondary/10 flex items-center justify-center mx-auto mb-4"><CreditCard className="text-secondary" size={30}/></div>
                    <h3 className="text-xl font-poppins text-white mb-2">Карт нет</h3>
                    <p className="text-dimWhite font-poppins mb-6 text-sm">Выпустите дебетовую или кредитную карту</p>
                    <button onClick={() => setIsModalOpen(true)} className="bg-secondary/20 text-secondary hover:bg-secondary/30 px-6 py-2.5 rounded-xl font-poppins font-semibold transition-colors">Создать карту</button>
                </div>
            ) : (
                <>
                    {/* Dropdown selector */}
                    {cards.length > 1 && (
                        <div className="relative mb-4" ref={dropdownRef}>
                            <button onClick={() => setDropdownOpen(v => !v)}
                                className="flex items-center gap-2 bg-black/40 border border-gray-700 hover:border-gray-500 rounded-xl px-4 py-2.5 text-white font-poppins text-sm transition-colors w-full md:w-auto">
                                <div className={`w-3 h-3 rounded-full ${getColor(cards[activeIdx]?.id, cards[activeIdx]?.type).includes('emerald') ? 'bg-emerald-400' : getColor(cards[activeIdx]?.id, cards[activeIdx]?.type).includes('rose') ? 'bg-rose-400' : getColor(cards[activeIdx]?.id, cards[activeIdx]?.type).includes('amber') ? 'bg-amber-400' : 'bg-secondary'}`} />
                                <span className="flex-1 text-left truncate">
                                    **** {cards[activeIdx]?.card_number?.slice(-4)} — {cards[activeIdx]?.type === 'debit' ? 'Дебетовая' : 'Кредитная'} · {cards[activeIdx]?.currency || 'USD'}
                                </span>
                                <ChevronDown size={14} className={`text-dimWhite transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} />
                            </button>
                            {dropdownOpen && (
                                <div className="absolute top-full left-0 mt-1 w-full md:w-80 bg-[#0f0f1a] border border-gray-700/60 rounded-2xl shadow-2xl z-30 overflow-hidden animate-fade-in">
                                    {cards.map((card, i) => (
                                        <button key={card.id} onClick={() => scrollTo(i)}
                                            className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-white/5 ${i === activeIdx ? 'bg-white/5' : ''} ${i < cards.length - 1 ? 'border-b border-gray-800/50' : ''}`}>
                                            <div className={`w-8 h-5 rounded-md ${getColor(card.id, card.type)} flex-shrink-0`} />
                                            <div className="flex-1 min-w-0">
                                                <p className="text-white font-poppins text-sm font-medium">**** {card.card_number?.slice(-4)}</p>
                                                <p className="text-dimWhite font-poppins text-xs">{card.type === 'debit' ? 'Дебетовая' : 'Кредитная'} · {card.currency || 'USD'}</p>
                                            </div>
                                            <span className={`text-[10px] font-poppins px-2 py-0.5 rounded-full ${card.status === 'active' ? 'bg-green-500/15 text-green-400' : 'bg-red-500/15 text-red-400'}`}>
                                                {card.status === 'active' ? 'Активна' : 'Блок'}
                                            </span>
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    )}

                    {/* Horizontal slider */}
                    <div className="relative">
                        <div ref={sliderRef} onScroll={onScroll}
                            className="flex gap-4 overflow-x-auto snap-x snap-mandatory pb-2 scrollbar-hide"
                            style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}>
                            {cards.map((card) => (
                                <div key={card.id} className="flex-shrink-0 w-full md:w-[340px] snap-center flex flex-col gap-3">
                                    <FlipCard card={card} color={getColor(card.id, card.type)}/>
                                    <div className="flex items-center gap-2">
                                        <div className={`flex-1 flex items-center gap-1.5 text-xs font-poppins px-3 py-1.5 rounded-xl ${card.status==='active'?'bg-green-500/10 text-green-400 border border-green-500/20':'bg-red-500/10 text-red-400 border border-red-500/20'}`}>
                                            {card.status==='active'?<Unlock size={11}/>:<Lock size={11}/>}
                                            {card.status==='active'?'Активна':'Заблок.'}
                                        </div>
                                        <button onClick={() => handleBlockCard(card)}
                                            className={`flex items-center gap-1.5 text-xs font-poppins px-3 py-1.5 rounded-xl border transition-all hover:scale-105 ${card.status==='active'?'bg-red-500/10 text-red-400 border-red-500/20 hover:bg-red-500/20':'bg-green-500/10 text-green-400 border-green-500/20 hover:bg-green-500/20'}`}>
                                            {card.status==='active'?<><ShieldOff size={11}/>Блок</>:<><Shield size={11}/>Разблок</>}
                                        </button>
                                        <button onClick={() => { setLimitModal(card); setLimitForm({ daily: card.daily_limit||5000, monthly: card.monthly_limit||50000 }); }}
                                            className="flex items-center gap-1.5 text-xs font-poppins px-3 py-1.5 rounded-xl border border-gray-700 text-dimWhite hover:text-white hover:border-secondary/50 transition-all">
                                            <Settings2 size={11}/>Лимиты
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* Arrow buttons (desktop) */}
                        {cards.length > 1 && (
                            <>
                                <button onClick={() => scrollTo(Math.max(0, activeIdx - 1))}
                                    className={`hidden md:flex absolute left-0 top-[calc(50%-30px)] -translate-x-5 w-9 h-9 rounded-full bg-black/60 border border-gray-700 items-center justify-center text-white hover:border-secondary/50 transition-all z-10 ${activeIdx === 0 ? 'opacity-30 pointer-events-none' : ''}`}>
                                    <ChevronLeft size={16}/>
                                </button>
                                <button onClick={() => scrollTo(Math.min(cards.length - 1, activeIdx + 1))}
                                    className={`hidden md:flex absolute right-0 top-[calc(50%-30px)] translate-x-5 w-9 h-9 rounded-full bg-black/60 border border-gray-700 items-center justify-center text-white hover:border-secondary/50 transition-all z-10 ${activeIdx === cards.length - 1 ? 'opacity-30 pointer-events-none' : ''}`}>
                                    <ChevronRight size={16}/>
                                </button>
                            </>
                        )}
                    </div>

                    {/* Dot indicators */}
                    {cards.length > 1 && (
                        <div className="flex justify-center gap-2 mt-3">
                            {cards.map((_, i) => (
                                <button key={i} onClick={() => scrollTo(i)}
                                    className={`rounded-full transition-all ${i === activeIdx ? 'w-5 h-2 bg-secondary' : 'w-2 h-2 bg-gray-600 hover:bg-gray-400'}`} />
                            ))}
                        </div>
                    )}
                </>
            )}

            {/* Card Settings toggles */}
            <div className="mt-12 bg-black-gradient-2 rounded-3xl p-7 border border-gray-800">
                <h3 className="text-lg font-poppins font-semibold mb-1 flex items-center gap-3"><Settings2 size={18} className="text-secondary"/>Настройки карт</h3>
                <p className="text-dimWhite text-xs font-poppins mb-6">Применяется ко всем вашим картам</p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    {CARD_SETTINGS_LIST.map(item => (
                        <div key={item.key} className="flex items-center justify-between p-4 rounded-2xl bg-white/5 border border-gray-800/60 hover:border-gray-700 transition-colors">
                            <div>
                                <h4 className="text-white font-poppins font-medium text-sm">{item.title}</h4>
                                <p className="text-dimWhite font-poppins text-xs">{item.desc}</p>
                            </div>
                            <Toggle checked={settings[item.key]} onChange={() => handleToggle(item.key)}/>
                        </div>
                    ))}
                </div>
            </div>

            {/* Create Card Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
                    <div className="bg-[#0f0f1a] border border-gray-700/60 w-full max-w-md rounded-3xl p-6 shadow-2xl animate-fade-in relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-secondary via-purple-500 to-pink-500"/>
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="text-xl font-poppins font-bold text-white">Новая карта</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-500 hover:text-white w-8 h-8 rounded-full bg-white/5 flex items-center justify-center"><X size={16}/></button>
                        </div>
                        <form onSubmit={handleCreateCard} className="space-y-4">
                            {/* Type */}
                            <div>
                                <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-2">Тип карты</label>
                                <div className="grid grid-cols-2 gap-3">
                                    {[{val:'debit',t:'Дебетовая',d:'Привязана к балансу'},{val:'credit',t:'Кредитная',d:'Кредитный лимит'}].map(o=>(
                                        <div key={o.val} onClick={() => setCardType(o.val)}
                                            className={`border rounded-2xl p-4 cursor-pointer transition-all ${cardType===o.val?'border-secondary bg-secondary/10':'border-gray-700/60 bg-white/5 hover:border-gray-600'}`}>
                                            <div className="font-poppins font-semibold text-white text-sm mb-0.5">{o.t}</div>
                                            <div className="text-xs text-dimWhite font-poppins">{o.d}</div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                            {/* Currency */}
                            <div>
                                <label className="block text-dimWhite text-xs font-poppins uppercase tracking-wider mb-2">Валюта карты</label>
                                <div className="flex flex-wrap gap-2">
                                    {CURRENCIES.map(c=>(
                                        <button key={c} type="button" onClick={() => setCardCurrency(c)}
                                            className={`px-4 py-2 rounded-xl text-sm font-poppins font-semibold border transition-all ${cardCurrency===c?'bg-secondary/20 text-secondary border-secondary/40':'bg-white/5 text-dimWhite border-gray-700/60 hover:border-gray-600'}`}>
                                            {c}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            {/* Virtual */}
                            <div className="flex items-center justify-between p-4 rounded-2xl bg-white/5 border border-gray-700/60">
                                <div>
                                    <div className="text-white font-poppins font-medium text-sm">Виртуальная карта</div>
                                    <div className="text-dimWhite font-poppins text-xs">Только для онлайн-покупок</div>
                                </div>
                                <Toggle checked={isVirtual} onChange={() => setIsVirtual(!isVirtual)}/>
                            </div>
                            <div className="bg-secondary/5 border border-secondary/20 rounded-2xl p-4 text-xs text-dimWhite font-poppins flex items-start gap-2">
                                <span className="text-secondary mt-0.5">✦</span>
                                Карта выпускается мгновенно. Нажмите на неё чтобы увидеть CVV.
                            </div>
                            <button type="submit" disabled={isCreating}
                                className={`w-full py-3.5 rounded-2xl font-poppins font-bold transition-all text-sm ${isCreating?'bg-gray-700 text-gray-400':'bg-blue-gradient text-primary hover:opacity-90 shadow-lg shadow-cyan-500/20'}`}>
                                {isCreating?'Выпуск...':'Выпустить карту'}
                            </button>
                        </form>
                    </div>
                </div>
            )}

            {/* Limits Modal */}
            {limitModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
                    <div className="bg-[#0f0f1a] border border-gray-700/60 w-full max-w-sm rounded-3xl p-6 shadow-2xl relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-orange-500 to-yellow-500"/>
                        <div className="flex justify-between items-center mb-5">
                            <h3 className="text-lg font-poppins font-bold text-white">Лимиты карты</h3>
                            <button onClick={() => setLimitModal(null)} className="text-gray-500 hover:text-white w-8 h-8 rounded-full bg-white/5 flex items-center justify-center"><X size={16}/></button>
                        </div>
                        <div className="flex items-center gap-2 mb-5 p-3 bg-yellow-500/10 rounded-xl border border-yellow-500/20">
                            <AlertTriangle size={14} className="text-yellow-400 flex-shrink-0"/>
                            <span className="text-yellow-400/80 text-xs font-poppins">Карта **** {limitModal.card_number?.slice(-4)}</span>
                        </div>
                        <form onSubmit={handleSaveLimits} className="space-y-4">
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Дневной лимит ($)</label>
                                <input type="number" value={limitForm.daily} onChange={e => setLimitForm(f=>({...f,daily:e.target.value}))}
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="5000"/>
                            </div>
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Месячный лимит ($)</label>
                                <input type="number" value={limitForm.monthly} onChange={e => setLimitForm(f=>({...f,monthly:e.target.value}))}
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="50000"/>
                            </div>
                            <button type="submit" className="w-full py-3 rounded-2xl font-poppins font-semibold bg-orange-500/20 text-orange-400 hover:bg-orange-500/30 border border-orange-500/30 transition-all">
                                Сохранить лимиты
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default CardsView;
