import React, { useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import PullToRefresh from '@/components/layout/PullToRefresh';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowUpRight, ArrowDownLeft, RefreshCw, Plus, Loader2,
  AlertCircle, Check, ChevronRight, Eye, EyeOff, TrendingUp, TrendingDown,
  Send, Download, ArrowLeftRight, Wallet as WalletIcon
} from 'lucide-react';
import NexusNav from '@/components/dashboard/NexusNav';
import BottomTabBar from '@/components/layout/BottomTabBar';
import TransactionItem from '@/components/crypto/TransactionItem';
import MarketModal from '@/components/wallet/MarketModal';
import SmartConversionModal from '@/components/wallet/SmartConversionModal';
import SwapModal from '@/components/wallet/SwapModal';
import TradeModal from '@/components/crypto/TradeModal';
import SendFundsModal from '@/components/dashboard/SendFundsModal';
import SendSelectorModal from '@/components/wallet/SendSelectorModal';

const COINGECKO_URL = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin,ethereum,tether,solana,binancecoin&sparkline=false&price_change_percentage=24h';

const CRYPTO_COLORS = {
  bitcoin: '#f59e0b', ethereum: '#8b5cf6', tether: '#10b981',
  solana: '#06b6d4', binancecoin: '#facc15',
};

// ── Modal de operación ────────────────────────────────────────────
function ActionModal({ mode, onClose, portfolioItems, userBalance, cryptos, onSuccess }) {
  const queryClient = useQueryClient();
  const [step, setStep] = useState(1); // 1=form, 2=confirm, 3=done
  const [amount, setAmount] = useState('');
  const [address, setAddress] = useState('');
  const [selectedCrypto, setSelectedCrypto] = useState(cryptos[0] ?? null);
  const [method, setMethod] = useState('card');

  const usd = userBalance?.usd_balance ?? 0;
  const holding = portfolioItems.find(p => p.crypto_id === selectedCrypto?.id);
  const price = selectedCrypto?.current_price ?? 0;
  const cryptoBalance = holding?.amount ?? 0;
  const numAmount = parseFloat(amount) || 0;

  const depositMutation = useMutation({
    mutationFn: async () => {
      const newBal = usd + numAmount;
      if (userBalance) await base44.entities.UserBalance.update(userBalance.id, { usd_balance: newBal });
      else await base44.entities.UserBalance.create({ usd_balance: newBal });
    },
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ['userBalance'] });
      const prev = queryClient.getQueryData(['userBalance']);
      queryClient.setQueryData(['userBalance'], (old = []) =>
        old.length ? old.map((b, i) => i === 0 ? { ...b, usd_balance: (b.usd_balance ?? 0) + numAmount } : b)
          : [{ usd_balance: numAmount }]
      );
      return { prev };
    },
    onError: (_err, _vars, ctx) => { if (ctx?.prev) queryClient.setQueryData(['userBalance'], ctx.prev); },
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['userBalance'] }); setStep(3); },
  });

  const withdrawMutation = useMutation({
    mutationFn: async () => {
      const newBal = usd - numAmount;
      await base44.entities.UserBalance.update(userBalance.id, { usd_balance: newBal });
    },
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ['userBalance'] });
      const prev = queryClient.getQueryData(['userBalance']);
      queryClient.setQueryData(['userBalance'], (old = []) =>
        old.map((b, i) => i === 0 ? { ...b, usd_balance: (b.usd_balance ?? 0) - numAmount } : b)
      );
      return { prev };
    },
    onError: (_err, _vars, ctx) => { if (ctx?.prev) queryClient.setQueryData(['userBalance'], ctx.prev); },
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['userBalance'] }); setStep(3); },
  });

  const sendMutation = useMutation({
    mutationFn: async () => {
      const newAmt = cryptoBalance - numAmount;
      if (newAmt <= 0) await base44.entities.Portfolio.delete(holding.id);
      else await base44.entities.Portfolio.update(holding.id, { amount: newAmt });
      await base44.entities.Transaction.create({
        type: 'sell', crypto_id: selectedCrypto.id, crypto_name: selectedCrypto.name,
        amount: numAmount, price_per_unit: price, total_usd: numAmount * price,
      });
    },
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ['portfolio'] });
      const prev = queryClient.getQueryData(['portfolio']);
      queryClient.setQueryData(['portfolio'], (old = []) => {
        const newAmt = cryptoBalance - numAmount;
        if (newAmt <= 0) return old.filter(p => p.crypto_id !== selectedCrypto?.id);
        return old.map(p => p.crypto_id === selectedCrypto?.id ? { ...p, amount: newAmt } : p);
      });
      return { prev };
    },
    onError: (_err, _vars, ctx) => { if (ctx?.prev) queryClient.setQueryData(['portfolio'], ctx.prev); },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portfolio'] });
      queryClient.invalidateQueries({ queryKey: ['transactions'] });
      setStep(3);
    },
  });

  const handleConfirm = () => {
    if (mode === 'deposit') depositMutation.mutate();
    else if (mode === 'withdraw') withdrawMutation.mutate();
    else if (mode === 'send') sendMutation.mutate();
  };

  const isLoading = depositMutation.isPending || withdrawMutation.isPending || sendMutation.isPending;

  const titles = { deposit: 'Depositar', withdraw: 'Retirar', send: 'Enviar Crypto', swap: 'Intercambiar' };
  const icons  = { deposit: Download, withdraw: ArrowUpRight, send: Send, swap: ArrowLeftRight };
  const Icon   = icons[mode];

  return (
    <motion.div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <div className="absolute inset-0 bg-black/80 backdrop-blur-sm" onClick={onClose} />
      <motion.div className="relative w-full max-w-md border border-white/8 z-10"
        style={{ background: 'linear-gradient(135deg, rgba(10,10,10,0.98), rgba(20,20,20,0.98))' }}
        initial={{ y: 60, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 60, opacity: 0 }}>

        {/* Header */}
        <div className="flex items-center gap-3 p-6 border-b border-white/5">
          <div className="w-8 h-8 border border-red-500/30 flex items-center justify-center" style={{ background: 'rgba(220,38,38,0.08)' }}>
            <Icon className="w-4 h-4 text-red-400/70" />
          </div>
          <h3 className="text-white/80 text-sm tracking-widest uppercase">{titles[mode]}</h3>
          <button onClick={onClose} className="ml-auto text-white/20 hover:text-white/60 text-lg leading-none">×</button>
        </div>

        <div className="p-6">
          {step === 3 ? (
            <motion.div className="text-center py-8 space-y-4" initial={{ scale: 0.9 }} animate={{ scale: 1 }}>
              <div className="w-14 h-14 mx-auto border border-emerald-500/30 flex items-center justify-center" style={{ background: 'rgba(16,185,129,0.08)' }}>
                <Check className="w-7 h-7 text-emerald-400" />
              </div>
              <p className="text-emerald-400/80 text-sm tracking-widest uppercase">Operación completada</p>
              <button onClick={() => { onSuccess?.(); onClose(); }}
                className="border border-white/10 text-white/40 text-xs tracking-widest uppercase px-6 py-2 hover:bg-white/5 transition-all">
                Cerrar
              </button>
            </motion.div>
          ) : step === 2 ? (
            <div className="space-y-5">
              <div className="border border-white/5 p-4 space-y-3" style={{ background: 'rgba(255,255,255,0.02)' }}>
                <p className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2">Confirmar operación</p>
                {mode === 'deposit' && <>
                  <Row label="Método" val={method === 'card' ? 'Tarjeta' : 'Transferencia'} />
                  <Row label="Monto" val={`$${numAmount.toFixed(2)} USD`} />
                </>}
                {mode === 'withdraw' && <>
                  <Row label="Monto" val={`$${numAmount.toFixed(2)} USD`} />
                  <Row label="Disponible tras retiro" val={`$${(usd - numAmount).toFixed(2)} USD`} />
                </>}
                {mode === 'send' && <>
                  <Row label="Activo" val={selectedCrypto?.symbol?.toUpperCase()} />
                  <Row label="Cantidad" val={`${numAmount} ${selectedCrypto?.symbol?.toUpperCase()}`} />
                  <Row label="Valor" val={`~$${(numAmount * price).toFixed(2)}`} />
                  <Row label="Destino" val={address ? `${address.slice(0, 8)}...${address.slice(-6)}` : 'N/A'} />
                </>}
              </div>
              <div className="flex gap-3">
                <button onClick={() => setStep(1)} className="flex-1 py-3 border border-white/10 text-white/30 text-xs tracking-widest uppercase hover:bg-white/5 transition-all">
                  Atrás
                </button>
                <button onClick={handleConfirm} disabled={isLoading}
                  className="flex-1 py-3 border border-red-500/40 text-red-400/80 text-xs tracking-widest uppercase hover:bg-red-500/10 transition-all disabled:opacity-30 flex items-center justify-center gap-2">
                  {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Confirmar'}
                </button>
              </div>
            </div>
          ) : (
            /* Step 1 — Form */
            <div className="space-y-5">
              {/* Crypto selector for send */}
              {mode === 'send' && (
                <div>
                  <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">Activo a enviar</label>
                  <div className="flex flex-wrap gap-2">
                    {cryptos.map(c => (
                      <button key={c.id} onClick={() => setSelectedCrypto(c)}
                        className="px-3 py-1.5 border text-[10px] tracking-widest uppercase transition-all"
                        style={{
                          borderColor: selectedCrypto?.id === c.id ? (CRYPTO_COLORS[c.id] || '#ef4444') + '80' : 'rgba(255,255,255,0.08)',
                          color: selectedCrypto?.id === c.id ? (CRYPTO_COLORS[c.id] || '#ef4444') : 'rgba(255,255,255,0.3)',
                          background: selectedCrypto?.id === c.id ? (CRYPTO_COLORS[c.id] || '#ef4444') + '12' : 'transparent',
                        }}>
                        {c.symbol?.toUpperCase()}
                      </button>
                    ))}
                  </div>
                  {selectedCrypto && (
                    <p className="text-white/25 text-[10px] mt-2">
                      Disponible: {cryptoBalance.toFixed(6)} {selectedCrypto.symbol?.toUpperCase()} (≈${(cryptoBalance * price).toFixed(2)})
                    </p>
                  )}
                </div>
              )}

              {/* Method for deposit */}
              {mode === 'deposit' && (
                <div>
                  <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">Método</label>
                  <div className="grid grid-cols-2 gap-2">
                    {[['card', 'Tarjeta'], ['bank', 'Transferencia']].map(([v, l]) => (
                      <button key={v} onClick={() => setMethod(v)}
                        className="py-3 border text-xs tracking-widest uppercase transition-all"
                        style={{
                          borderColor: method === v ? 'rgba(220,38,38,0.5)' : 'rgba(255,255,255,0.08)',
                          color: method === v ? '#ef4444' : 'rgba(255,255,255,0.3)',
                          background: method === v ? 'rgba(220,38,38,0.05)' : 'transparent',
                        }}>
                        {l}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Address for send */}
              {mode === 'send' && (
                <div>
                  <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">Dirección de destino</label>
                  <input type="text" value={address} onChange={e => setAddress(e.target.value)}
                    placeholder="0x... / 1A1z..."
                    className="w-full bg-transparent border border-white/10 text-white h-11 px-4 text-sm font-mono focus:outline-none focus:border-red-500/40 transition-all placeholder:text-white/15"
                  />
                </div>
              )}

              {/* Amount */}
              <div>
                <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">
                  {mode === 'send' ? `Cantidad (${selectedCrypto?.symbol?.toUpperCase()})` : 'Monto (USD)'}
                </label>
                <div className="relative">
                  {mode !== 'send' && <span className="absolute left-4 top-1/2 -translate-y-1/2 text-white/25">$</span>}
                  <input type="number" step={mode === 'send' ? '0.000001' : '0.01'} min="0"
                    value={amount} onChange={e => setAmount(e.target.value)}
                    placeholder="0.00"
                    className={`w-full bg-transparent border border-white/10 text-white h-12 ${mode !== 'send' ? 'pl-8' : 'pl-4'} pr-4 text-lg focus:outline-none focus:border-red-500/40 transition-all placeholder:text-white/15`}
                  />
                </div>
                {mode === 'send' && numAmount > 0 && (
                  <p className="text-white/25 text-[10px] mt-1">≈ ${(numAmount * price).toFixed(2)} USD</p>
                )}
                {/* Quick % */}
                <div className="flex gap-2 mt-2">
                  {[25, 50, 75, 100].map(p => {
                    const max = mode === 'send' ? cryptoBalance : (mode === 'withdraw' ? usd : 0);
                    if (mode === 'deposit') return null;
                    return (
                      <button key={p} type="button"
                        onClick={() => setAmount((max * p / 100).toFixed(mode === 'send' ? 6 : 2))}
                        className="flex-1 py-1.5 border border-white/8 text-white/25 text-[9px] hover:border-red-500/30 hover:text-red-400/60 transition-all">
                        {p}%
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Errors */}
              {mode === 'withdraw' && numAmount > usd && (
                <div className="flex items-center gap-2 border border-red-500/30 p-3" style={{ background: 'rgba(239,68,68,0.05)' }}>
                  <AlertCircle className="w-4 h-4 text-red-400/70" /><p className="text-red-400/70 text-xs">Saldo insuficiente</p>
                </div>
              )}
              {mode === 'send' && numAmount > cryptoBalance && (
                <div className="flex items-center gap-2 border border-red-500/30 p-3" style={{ background: 'rgba(239,68,68,0.05)' }}>
                  <AlertCircle className="w-4 h-4 text-red-400/70" /><p className="text-red-400/70 text-xs">Saldo crypto insuficiente</p>
                </div>
              )}

              <button
                onClick={() => setStep(2)}
                disabled={
                  numAmount <= 0 ||
                  (mode === 'withdraw' && numAmount > usd) ||
                  (mode === 'send' && (numAmount > cryptoBalance || !address))
                }
                className="w-full py-4 border border-red-500/40 text-red-400/80 text-xs tracking-widest uppercase hover:bg-red-500/10 transition-all disabled:opacity-30 disabled:cursor-not-allowed">
                Continuar →
              </button>
            </div>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

function Row({ label, val }) {
  return (
    <div className="flex justify-between text-xs">
      <span className="text-white/30">{label}</span>
      <span className="text-white/70 font-mono">{val}</span>
    </div>
  );
}

// ── Receive modal ─────────────────────────────────────────────────
const WALLET_ADDRS = {
  bitcoin: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
  ethereum: '0x742d35Cc6634C0532925a3b8D4C9D8c2B4e8f3A1',
  tether: 'TN3W4H6rK3eg4bMFHGq7q8fBaD9JwM7QR4',
  solana: '7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV',
  binancecoin: '0x742d35Cc6634C0532925a3b8D4C9D8c2B4e8f3A1',
};

function ReceiveModal({ onClose, cryptos }) {
  const [sel, setSel] = useState(cryptos[0]);
  const [copied, setCopied] = useState(false);
  const addr = WALLET_ADDRS[sel?.id] || '—';
  const copy = () => { navigator.clipboard.writeText(addr); setCopied(true); setTimeout(() => setCopied(false), 2000); };

  return (
    <motion.div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <div className="absolute inset-0 bg-black/80 backdrop-blur-sm" onClick={onClose} />
      <motion.div className="relative w-full max-w-md border border-white/8 z-10"
        style={{ background: 'linear-gradient(135deg, rgba(10,10,10,0.98), rgba(20,20,20,0.98))' }}
        initial={{ y: 60, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 60, opacity: 0 }}>
        <div className="flex items-center gap-3 p-6 border-b border-white/5">
          <div className="w-8 h-8 border border-emerald-500/30 flex items-center justify-center" style={{ background: 'rgba(16,185,129,0.08)' }}>
            <ArrowDownLeft className="w-4 h-4 text-emerald-400/70" />
          </div>
          <h3 className="text-white/80 text-sm tracking-widest uppercase">Recibir Crypto</h3>
          <button onClick={onClose} className="ml-auto text-white/20 hover:text-white/60 text-lg leading-none">×</button>
        </div>
        <div className="p-6 space-y-5">
          <div>
            <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">Seleccionar activo</label>
            <div className="flex flex-wrap gap-2">
              {cryptos.map(c => (
                <button key={c.id} onClick={() => setSel(c)}
                  className="px-3 py-1.5 border text-[10px] tracking-widest uppercase transition-all"
                  style={{
                    borderColor: sel?.id === c.id ? (CRYPTO_COLORS[c.id] || '#ef4444') + '80' : 'rgba(255,255,255,0.08)',
                    color: sel?.id === c.id ? (CRYPTO_COLORS[c.id] || '#ef4444') : 'rgba(255,255,255,0.3)',
                  }}>
                  {c.symbol?.toUpperCase()}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="text-[9px] tracking-[0.4em] uppercase text-white/25 mb-2 block">Tu dirección {sel?.symbol?.toUpperCase()}</label>
            <div className="border border-white/8 p-4 flex items-center gap-3" style={{ background: 'rgba(0,0,0,0.4)' }}>
              <span className="font-mono text-xs text-white/50 flex-1 break-all leading-relaxed">{addr}</span>
              <button onClick={copy} className="shrink-0 flex items-center gap-1.5 text-[9px] tracking-widest uppercase transition-all"
                style={{ color: copied ? '#34d399' : 'rgba(255,255,255,0.3)' }}>
                {copied ? <Check className="w-3.5 h-3.5" /> : null}
                {copied ? 'Copiado' : 'Copiar'}
              </button>
            </div>
          </div>
          <div className="flex items-start gap-2 border border-yellow-500/15 p-3" style={{ background: 'rgba(234,179,8,0.04)' }}>
            <AlertCircle className="w-3.5 h-3.5 text-yellow-500/50 shrink-0 mt-0.5" />
            <p className="text-yellow-500/50 text-[9px] tracking-wide leading-relaxed">
              Envía únicamente {sel?.symbol?.toUpperCase()} a esta dirección.
            </p>
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
}

// ── Main page ─────────────────────────────────────────────────────
export default function Wallet() {
  const [modal, setModal] = useState(null); // null | 'deposit' | 'withdraw' | 'send' | 'receive' | 'swap' | 'market'
  const [hideBalance, setHideBalance] = useState(false);
  const [tradeTarget, setTradeTarget] = useState(null); // crypto selected from MarketModal
  const queryClient = useQueryClient();

  const { data: cryptos = [] } = useQuery({
    queryKey: ['wallet-cryptos'],
    queryFn: async () => {
      const res = await fetch(COINGECKO_URL);
      return res.json();
    },
    refetchInterval: 60000,
    staleTime: 30000,
  });

  const { data: portfolioItems = [] } = useQuery({
    queryKey: ['portfolio'],
    queryFn: () => base44.entities.Portfolio.list(),
  });

  const { data: userBalances = [] } = useQuery({
    queryKey: ['userBalance'],
    queryFn: () => base44.entities.UserBalance.list(),
  });

  const { data: transactions = [] } = useQuery({
    queryKey: ['transactions'],
    queryFn: () => base44.entities.Transaction.list('-created_date', 10),
  });

  const userBalance = userBalances[0];
  const usdCash = userBalance?.usd_balance ?? 0;

  const portfolioValue = portfolioItems.reduce((sum, item) => {
    const crypto = cryptos.find(c => c.id === item.crypto_id);
    return sum + (crypto ? crypto.current_price * item.amount : 0);
  }, 0);

  const totalBalance = usdCash + portfolioValue;

  const totalInvested = portfolioItems.reduce((s, i) => s + i.avg_buy_price * i.amount, 0);
  const pnl = portfolioValue - totalInvested;
  const pnlPositive = pnl >= 0;

  const EUR_RATE = 0.92;
  const eurTotal = totalBalance * EUR_RATE;

  const fmt = (n) => n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const mask = (s) => hideBalance ? '••••••' : s;

  const actions = [
    { id: 'deposit',    label: 'Depositar',    icon: Download,        color: '#10b981' },
    { id: 'sendfunds',  label: 'Enviar',       icon: Send,            color: '#ef4444' },
    { id: 'receive',    label: 'Recibir',      icon: ArrowDownLeft,   color: '#8b5cf6' },
    { id: 'swap',       label: 'Intercambiar', icon: ArrowLeftRight,  color: '#06b6d4' },
  ];

  const navigate = useNavigate();

  const buyMutation = useMutation({
    mutationFn: async ({ crypto, amount, totalUsd }) => {
      const newBalance = usdCash - totalUsd;
      const existing = portfolioItems.find(p => p.crypto_id === crypto.id);
      if (existing) {
        const newAmount = existing.amount + amount;
        const newAvg = (existing.avg_buy_price * existing.amount + crypto.current_price * amount) / newAmount;
        await base44.entities.Portfolio.update(existing.id, { amount: newAmount, avg_buy_price: newAvg });
      } else {
        await base44.entities.Portfolio.create({ crypto_id: crypto.id, crypto_name: crypto.name, amount, avg_buy_price: crypto.current_price });
      }
      if (userBalance) await base44.entities.UserBalance.update(userBalance.id, { usd_balance: newBalance });
      else await base44.entities.UserBalance.create({ usd_balance: newBalance });
      await base44.entities.Transaction.create({ type: 'buy', crypto_id: crypto.id, crypto_name: crypto.name, amount, price_per_unit: crypto.current_price, total_usd: totalUsd });
    },
    onMutate: async ({ crypto, amount, totalUsd }) => {
      await queryClient.cancelQueries({ queryKey: ['portfolio'] });
      await queryClient.cancelQueries({ queryKey: ['userBalance'] });
      const prevPortfolio = queryClient.getQueryData(['portfolio']);
      const prevBalance = queryClient.getQueryData(['userBalance']);
      queryClient.setQueryData(['userBalance'], (old = []) =>
        old.map((b, i) => i === 0 ? { ...b, usd_balance: (b.usd_balance ?? 0) - totalUsd } : b)
      );
      queryClient.setQueryData(['portfolio'], (old = []) => {
        const existing = old.find(p => p.crypto_id === crypto.id);
        if (existing) {
          const newAmount = existing.amount + amount;
          const newAvg = (existing.avg_buy_price * existing.amount + crypto.current_price * amount) / newAmount;
          return old.map(p => p.crypto_id === crypto.id ? { ...p, amount: newAmount, avg_buy_price: newAvg } : p);
        }
        return [...old, { id: `_opt_${Date.now()}`, crypto_id: crypto.id, crypto_name: crypto.name, amount, avg_buy_price: crypto.current_price }];
      });
      return { prevPortfolio, prevBalance };
    },
    onError: (_err, _vars, ctx) => {
      if (ctx?.prevPortfolio) queryClient.setQueryData(['portfolio'], ctx.prevPortfolio);
      if (ctx?.prevBalance) queryClient.setQueryData(['userBalance'], ctx.prevBalance);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portfolio'] });
      queryClient.invalidateQueries({ queryKey: ['userBalance'] });
      queryClient.invalidateQueries({ queryKey: ['transactions'] });
      setTradeTarget(null);
    },
  });

  const sellMutation = useMutation({
    mutationFn: async ({ crypto, amount, totalUsd }) => {
      const existing = portfolioItems.find(p => p.crypto_id === crypto.id);
      if (!existing) return;
      const newAmount = existing.amount - amount;
      if (newAmount <= 0.000001) await base44.entities.Portfolio.delete(existing.id);
      else await base44.entities.Portfolio.update(existing.id, { amount: newAmount });
      await base44.entities.UserBalance.update(userBalance.id, { usd_balance: usdCash + totalUsd });
      await base44.entities.Transaction.create({ type: 'sell', crypto_id: crypto.id, crypto_name: crypto.name, amount, price_per_unit: crypto.current_price, total_usd: totalUsd });
    },
    onMutate: async ({ crypto, amount, totalUsd }) => {
      await queryClient.cancelQueries({ queryKey: ['portfolio'] });
      await queryClient.cancelQueries({ queryKey: ['userBalance'] });
      const prevPortfolio = queryClient.getQueryData(['portfolio']);
      const prevBalance = queryClient.getQueryData(['userBalance']);
      queryClient.setQueryData(['userBalance'], (old = []) =>
        old.map((b, i) => i === 0 ? { ...b, usd_balance: (b.usd_balance ?? 0) + totalUsd } : b)
      );
      queryClient.setQueryData(['portfolio'], (old = []) => {
        const existing = old.find(p => p.crypto_id === crypto.id);
        if (!existing) return old;
        const newAmount = existing.amount - amount;
        if (newAmount <= 0.000001) return old.filter(p => p.crypto_id !== crypto.id);
        return old.map(p => p.crypto_id === crypto.id ? { ...p, amount: newAmount } : p);
      });
      return { prevPortfolio, prevBalance };
    },
    onError: (_err, _vars, ctx) => {
      if (ctx?.prevPortfolio) queryClient.setQueryData(['portfolio'], ctx.prevPortfolio);
      if (ctx?.prevBalance) queryClient.setQueryData(['userBalance'], ctx.prevBalance);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portfolio'] });
      queryClient.invalidateQueries({ queryKey: ['userBalance'] });
      queryClient.invalidateQueries({ queryKey: ['transactions'] });
      setTradeTarget(null);
    },
  });

  const handleRefresh = async () => {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['wallet-cryptos'] }),
      queryClient.invalidateQueries({ queryKey: ['portfolio'] }),
      queryClient.invalidateQueries({ queryKey: ['userBalance'] }),
      queryClient.invalidateQueries({ queryKey: ['transactions'] }),
    ]);
  };

  return (
    <div className="min-h-screen bg-black text-white">
      <PullToRefresh onRefresh={handleRefresh} />
      <NexusNav />

      <div className="pt-4 md:pt-24 max-w-3xl mx-auto px-4 sm:px-6 pb-28 md:pb-24">

        {/* ── Balance Hero Card ── */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
          className="relative border border-white/8 p-8 mb-4 overflow-hidden"
          style={{ background: 'linear-gradient(135deg, rgba(15,15,15,0.95), rgba(25,10,10,0.95))' }}>

          {/* Subtle glow */}
          <div className="absolute top-0 right-0 w-64 h-64 rounded-full opacity-5 pointer-events-none"
            style={{ background: 'radial-gradient(circle, #ef4444, transparent)', transform: 'translate(30%, -30%)' }} />

          <div className="relative">
            <div className="flex items-center justify-between mb-2">
              <p className="text-[9px] tracking-[0.5em] uppercase text-white/30">Balance total</p>
              <button onClick={() => setHideBalance(h => !h)} className="text-white/20 hover:text-white/50 transition-all">
                {hideBalance ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
              </button>
            </div>

            <div className="flex items-end gap-4 mb-1">
              <h1 className="text-4xl sm:text-5xl font-light tracking-tight text-white">
                ${mask(fmt(totalBalance))}
              </h1>
              <div className={`flex items-center gap-1 mb-2 px-2 py-0.5 border text-xs ${pnlPositive ? 'border-emerald-500/25 text-emerald-400/80' : 'border-red-500/25 text-red-400/80'}`}
                style={{ background: pnlPositive ? 'rgba(16,185,129,0.06)' : 'rgba(239,68,68,0.06)' }}>
                {pnlPositive ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
                {pnlPositive ? '+' : ''}{mask(fmt(pnl))}
              </div>
            </div>

            <div className="flex items-center gap-4 text-white/30 text-xs mb-8">
              <span>≈ €{mask(fmt(eurTotal))} EUR</span>
              <span className="w-px h-3 bg-white/10" />
              <span>Efectivo: ${mask(fmt(usdCash))}</span>
              <span className="w-px h-3 bg-white/10" />
              <span>Crypto: ${mask(fmt(portfolioValue))}</span>
            </div>

            {/* Quick Actions */}
            <div className="grid grid-cols-4 gap-3">
              {actions.map(({ id, label, icon: ActionIcon, color }) => (
                <button key={id} onClick={() => setModal(id)}
                  className="flex flex-col items-center gap-2 py-4 border border-white/5 hover:border-white/15 transition-all group"
                  style={{ background: 'rgba(255,255,255,0.02)' }}>
                  <div className="w-8 h-8 border flex items-center justify-center transition-all group-hover:scale-110"
                    style={{ borderColor: color + '30', background: color + '10' }}>
                    <ActionIcon className="w-3.5 h-3.5" style={{ color }} />
                  </div>
                  <span className="text-[9px] tracking-widest uppercase text-white/35 group-hover:text-white/60 transition-all">{label}</span>
                </button>
              ))}
            </div>
          </div>
        </motion.div>

        {/* ── Cash balance pill ── */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="border border-white/5 p-4 mb-8 flex items-center justify-between"
          style={{ background: 'rgba(255,255,255,0.015)' }}>
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 border border-white/10 flex items-center justify-center">
              <WalletIcon className="w-3.5 h-3.5 text-white/30" />
            </div>
            <div>
              <p className="text-white/60 text-sm font-light">USD Cash</p>
              <p className="text-[9px] text-white/25 tracking-wide">Disponible para operar</p>
            </div>
          </div>
          <div className="text-right">
            <p className="text-white/80 text-sm">${mask(fmt(usdCash))}</p>
            <button onClick={() => setModal('deposit')}
              className="text-[9px] tracking-widest uppercase text-red-400/50 hover:text-red-400/80 transition-all mt-0.5">
              + Añadir
            </button>
          </div>
        </motion.div>

        {/* ── Crypto Assets ── */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }} className="mb-8">
          <div className="flex items-center gap-4 mb-4">
            <div className="w-px h-4 bg-red-500/40" />
            <p className="text-[9px] tracking-[0.5em] uppercase text-white/30">Mis activos</p>
            <div className="flex-1 h-px bg-white/4" />
          </div>

          {portfolioItems.length === 0 ? (
            <div className="border border-white/5 p-10 text-center" style={{ background: 'rgba(255,255,255,0.01)' }}>
              <p className="text-white/20 text-xs tracking-widest uppercase mb-3">Sin activos crypto</p>
              <button onClick={() => setModal('market')}
                className="text-[10px] tracking-widest uppercase text-red-400/50 hover:text-red-400/80 transition-all border border-red-500/20 px-4 py-2 hover:border-red-500/40">
                Explorar mercado →
              </button>
            </div>
          ) : (
            <div className="divide-y divide-white/4 border border-white/5" style={{ background: 'rgba(255,255,255,0.01)' }}>
              {portfolioItems.map((item, idx) => {
                const crypto = cryptos.find(c => c.id === item.crypto_id);
                const value = crypto ? crypto.current_price * item.amount : item.avg_buy_price * item.amount;
                const change = crypto?.price_change_percentage_24h ?? 0;
                const color = CRYPTO_COLORS[item.crypto_id] || '#ef4444';
                const pct = totalBalance > 0 ? (value / totalBalance) * 100 : 0;
                return (
                  <motion.div key={item.id} initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: idx * 0.05 }}
                    className="flex items-center gap-4 px-5 py-4 hover:bg-white/2 transition-all group cursor-pointer"
                    onClick={() => navigate('/Dashboard')}>
                    {/* Color dot */}
                    <div className="w-2 h-2 rounded-full shrink-0" style={{ background: color }} />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <p className="text-white/70 text-sm font-light">{item.crypto_name}</p>
                        <p className="text-white/80 text-sm">${mask(fmt(value))}</p>
                      </div>
                      <div className="flex items-center justify-between mt-0.5">
                        <p className="text-white/25 text-[10px]">
                          {mask(item.amount.toFixed(6))} <span className="uppercase">{item.crypto_id.slice(0, 3)}</span>
                          <span className="ml-2 opacity-50">{pct.toFixed(1)}%</span>
                        </p>
                        <span className={`text-[10px] ${change >= 0 ? 'text-emerald-400/70' : 'text-red-400/70'}`}>
                          {change >= 0 ? '+' : ''}{change.toFixed(2)}%
                        </span>
                      </div>
                      {/* Progress bar */}
                      <div className="mt-2 h-px w-full bg-white/5">
                        <div className="h-px transition-all" style={{ width: `${pct}%`, background: color + '80' }} />
                      </div>
                    </div>
                    <ChevronRight className="w-3.5 h-3.5 text-white/10 group-hover:text-white/30 transition-all shrink-0" />
                  </motion.div>
                );
              })}
            </div>
          )}
        </motion.div>

        {/* ── Recent Transactions ── */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
          <div className="flex items-center gap-4 mb-4">
            <div className="w-px h-4 bg-red-500/40" />
            <p className="text-[9px] tracking-[0.5em] uppercase text-white/30">Actividad reciente</p>
            <div className="flex-1 h-px bg-white/4" />
            <button onClick={() => navigate('/History')}
              className="text-[9px] tracking-widest uppercase text-white/20 hover:text-white/50 transition-all">
              Ver todo →
            </button>
          </div>

          {transactions.length === 0 ? (
            <div className="border border-white/5 p-8 text-center" style={{ background: 'rgba(255,255,255,0.01)' }}>
              <p className="text-white/20 text-xs tracking-widest uppercase">Sin transacciones</p>
            </div>
          ) : (
            <div className="space-y-2">
              {transactions.slice(0, 5).map((tx, idx) => (
                <motion.div key={tx.id} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.2 + idx * 0.04 }}>
                  <div className="flex items-center gap-4 px-5 py-3.5 border border-white/5 hover:border-white/10 transition-all"
                    style={{ background: 'rgba(255,255,255,0.01)' }}>
                    <div className={`w-7 h-7 border flex items-center justify-center shrink-0 ${tx.type === 'buy' ? 'border-emerald-500/25' : 'border-red-500/25'}`}
                      style={{ background: tx.type === 'buy' ? 'rgba(16,185,129,0.06)' : 'rgba(239,68,68,0.06)' }}>
                      {tx.type === 'buy'
                        ? <ArrowDownLeft className="w-3.5 h-3.5 text-emerald-400/70" />
                        : <ArrowUpRight className="w-3.5 h-3.5 text-red-400/70" />}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-white/60 text-sm font-light">
                        {tx.type === 'buy' ? 'Compra' : 'Venta'} · {tx.crypto_name}
                      </p>
                      <p className="text-white/20 text-[10px]">
                        {tx.amount?.toFixed(6)} {tx.crypto_id?.slice(0, 3).toUpperCase()}
                      </p>
                    </div>
                    <div className="text-right shrink-0">
                      <p className={`text-sm font-light ${tx.type === 'buy' ? 'text-red-400/70' : 'text-emerald-400/70'}`}>
                        {tx.type === 'buy' ? '-' : '+'}${tx.total_usd?.toFixed(2)}
                      </p>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </motion.div>
      </div>

      <BottomTabBar />

      {/* ── Modals ── */}
      <AnimatePresence>
        {modal === 'sendfunds' && (
          <SendSelectorModal key="sendselector"
            onClose={() => setModal(null)}
            onSelectNexus={() => setModal('nexustransfer')}
            onSelectBlockchain={() => setModal('send')}
          />
        )}
        {modal === 'nexustransfer' && (
          <SendFundsModal key="nexustransfer" onClose={() => setModal(null)} />
        )}
        {modal && modal !== 'receive' && modal !== 'swap' && modal !== 'market' && modal !== 'smart' && modal !== 'sendfunds' && modal !== 'nexustransfer' && (
          <ActionModal key="action" mode={modal} onClose={() => setModal(null)}
            portfolioItems={portfolioItems} userBalance={userBalance}
            cryptos={cryptos} onSuccess={() => {
              queryClient.invalidateQueries({ queryKey: ['portfolio'] });
              queryClient.invalidateQueries({ queryKey: ['userBalance'] });
              queryClient.invalidateQueries({ queryKey: ['transactions'] });
            }} />
        )}
        {modal === 'receive' && (
          <ReceiveModal key="receive" onClose={() => setModal(null)} cryptos={cryptos} />
        )}
        {modal === 'market' && (
          <MarketModal key="market" onClose={() => setModal(null)} onSelectCrypto={(crypto) => {
            setTradeTarget(crypto);
            setModal(null);
          }} />
        )}
        {tradeTarget && (
          <TradeModal
            key="trade"
            isOpen={!!tradeTarget}
            onClose={() => setTradeTarget(null)}
            crypto={tradeTarget}
            userHolding={portfolioItems.find(p => p.crypto_id === tradeTarget.id)}
            usdBalance={usdCash}
            onBuy={(crypto, usdAmt, cryptoAmt) => buyMutation.mutate({ crypto, amount: cryptoAmt, totalUsd: usdAmt })}
            onSell={(crypto, usdAmt, cryptoAmt) => sellMutation.mutate({ crypto, amount: cryptoAmt, totalUsd: usdAmt })}
            isLoading={buyMutation.isPending || sellMutation.isPending}
          />
        )}
        {modal === 'smart' && (
          <SmartConversionModal key="smart" onClose={() => setModal(null)}
            portfolioItems={portfolioItems} cryptos={cryptos} />
        )}
        {modal === 'swap' && (
          <SwapModal key="swap" onClose={() => setModal(null)}
            portfolioItems={portfolioItems} cryptos={cryptos}
            usdBalance={usdCash} userBalance={userBalance} />
        )}
      </AnimatePresence>
    </div>
  );
}