// Rumbo — Accounts · v3 · Billetera Digital con gradientes y drawer

const { useState: useStA, useEffect: useEffA } = React;

const ACCOUNT_GRADIENTS = {
  cash:       ['#10B981','#059669'],
  bank:       ['#2563EB','#1D4ED8'],
  digital:    ['#7C3AED','#6D28D9'],
  investment: ['#F59E0B','#D97706'],
};
const ACCOUNT_ICONS = { cash:'banknote', bank:'landmark', digital:'smartphone', investment:'trending' };
const ACCOUNT_LABELS = { cash:'Efectivo', bank:'Cuenta bancaria', digital:'Billetera digital', investment:'Inversión' };

/* ── Tarjeta estilo wallet ── */
const WalletCard = ({ account, transactions, selectedMonth, recurringIncomes = [], fixedExpenses = [], debts = [] }) => {
  const [g1, g2] = ACCOUNT_GRADIENTS[account.type] || ['#2563EB','#1D4ED8'];
  const todayKey = `${new Date().getFullYear()}-${String(new Date().getMonth()+1).padStart(2,'0')}`;
  const curMonth = selectedMonth || todayKey;
  const isFutureMonth  = curMonth > todayKey;
  const isCurrentMonth = curMonth === todayKey;

  // Movimientos del mes seleccionado (no globales)
  const monthTxs = transactions.filter(t => t.accountId === account.id && (t.date||'').startsWith(curMonth));
  const monthInc = monthTxs.filter(t => t.type === 'income').reduce((s,t)=>s+t.amount, 0);
  const monthExp = monthTxs.filter(t => t.type === 'expense').reduce((s,t)=>s+t.amount, 0);
  const monthDelta = monthInc - monthExp;

  // Proyección de la cuenta para el mes — solo ingresos recurrentes (tienen accountId).
  // Los gastos fijos / cuotas no tienen accountId en el modelo, así que no los atribuimos por cuenta
  // (mostrarlos repetidos en cada card sería engañoso). Se ven en el hero global.
  const projectedIncomeForAccount = (typeof getDueDatesInMonth === 'function')
    ? recurringIncomes.filter(r => r.active && r.accountId === account.id)
        .reduce((s, r) => s + getDueDatesInMonth(r, curMonth).length * r.amount, 0)
    : 0;

  // Mostramos el saldo actual de la cuenta (no calculamos retroactivo: los balances iniciales
  // del demo no son derivados de las tx, así que el cálculo daría números incoherentes).
  // El "cómo te fue" en el mes lo expresamos por el delta y los stats abajo.
  const displayBalance = account.balance;

  // Recientes del mes seleccionado (no globales)
  const recentTxs = [...monthTxs].sort((a,b) => b.date.localeCompare(a.date)).slice(0, 3);

  const balanceLabel = 'saldo actual';

  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-xl)', overflow:'hidden', boxShadow:'var(--sh-md)' }}>
      {/* Cabecera tipo tarjeta de crédito */}
      <div className="wallet-card" style={{ background:`linear-gradient(135deg, ${g1} 0%, ${g2} 100%)` }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:20 }}>
          <div>
            <div style={{ fontSize:11, fontWeight:700, opacity:0.7, textTransform:'uppercase', letterSpacing:'0.6px', marginBottom:4 }}>
              {ACCOUNT_LABELS[account.type] || account.type}
            </div>
            <div style={{ fontSize:17, fontWeight:800, lineHeight:1.2 }}>{account.name}</div>
          </div>
          <Icon name={ACCOUNT_ICONS[account.type] || 'creditCard'} size={26} color="#fff" strokeWidth={1.6} />
        </div>
        <div style={{ fontSize:32, fontWeight:900, letterSpacing:'-1px', fontVariantNumeric:'tabular-nums', lineHeight:1 }}>
          {fmtFull(displayBalance, account.currency)}
        </div>
        <div style={{ fontSize:12, opacity:0.65, marginTop:5, display:'flex', gap:6, alignItems:'center' }}>
          <span>{account.currency}</span>
          <span>·</span>
          <span>{balanceLabel}</span>
        </div>
        {/* (Antes había un chip flotante con el delta del mes — se sacó porque era ambiguo.
            Los stats "Ingresos del mes / Gastos del mes" abajo ya cubren esa info de forma clara.) */}
      </div>

      {/* Stats — anclados al mes. En futuro: ingresos esperados (atribuidos por accountId);
          los gastos no se atribuyen por cuenta porque fixedExpenses no tienen accountId. */}
      <div style={{ display:'grid', gridTemplateColumns: isFutureMonth ? '1fr' : '1fr 1fr', gap:0, borderBottom:'1px solid var(--border)' }}>
        {isFutureMonth ? (
          <div style={{ padding:'12px 16px' }}>
            <div style={{ fontSize:10, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:5 }}>
              Ingresos esperados acá
            </div>
            <div style={{ fontSize:16, fontWeight:800, color:'var(--success)', fontVariantNumeric:'tabular-nums' }}>
              +{fmtFull(projectedIncomeForAccount, account.currency)}
            </div>
            {projectedIncomeForAccount === 0 && (
              <div style={{ fontSize:10, color:'var(--t5)', marginTop:3, fontStyle:'italic' }}>
                No hay ingresos recurrentes asignados
              </div>
            )}
          </div>
        ) : (
          [
            { l:'Ingresos del mes', v:`+${fmtFull(monthInc, account.currency)}`, c:'var(--success)' },
            { l:'Gastos del mes',   v:`–${fmtFull(monthExp, account.currency)}`,  c:'var(--danger)' },
          ].map(({ l, v, c }, i) => (
            <div key={l} style={{ padding:'12px 16px', borderRight: i===0?'1px solid var(--border)':'none' }}>
              <div style={{ fontSize:10, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:5 }}>{l}</div>
              <div style={{ fontSize:16, fontWeight:800, color:c, fontVariantNumeric:'tabular-nums' }}>{v}</div>
            </div>
          ))
        )}
      </div>

      {/* Movimientos del mes (no globales) */}
      {recentTxs.length > 0 ? (
        <div style={{ padding:'12px 16px' }}>
          <div style={{ fontSize:10, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.5px', marginBottom:8 }}>Movimientos del mes</div>
          {recentTxs.map((t, i) => (
            <div key={t.id} style={{ display:'flex', alignItems:'center', gap:8, padding:'5px 0', borderBottom: i<recentTxs.length-1?'1px solid var(--border)':'none' }}>
              <CategoryIcon category={t.category} size="xs" />
              <span style={{ flex:1, fontSize:12, color:'var(--t3)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{t.description}</span>
              <span style={{ fontSize:12, fontWeight:700, color:t.type==='income'?'var(--success)':'var(--t3)', fontVariantNumeric:'tabular-nums', flexShrink:0 }}>
                {t.type==='income'?'+':'–'}{fmtFull(t.amount, t.currency)}
              </span>
            </div>
          ))}
        </div>
      ) : (
        <div style={{ padding:'14px 16px', textAlign:'center', fontSize:12, color:'var(--t5)', fontStyle:'italic' }}>
          {isFutureMonth ? 'Sin movimientos previstos' : 'Sin movimientos en este mes'}
        </div>
      )}
    </div>
  );
};

/* ── Drawer "Nueva cuenta" — patrón unificado: tira de contexto + wallet preview + decimales ── */
const AddAccountDrawer = ({ onClose, onAdd, data }) => {
  const [form, setF] = useStA({ name:'', type:'bank', balance:'', currency:'ARS' });
  const [showCurrencyPicker, setShowCurrencyPicker] = useStA(false);

  const TYPES = [
    { value:'bank',       label:'Bancaria',  iconName:'landmark'   },
    { value:'digital',    label:'Billetera', iconName:'smartphone' },
    { value:'cash',       label:'Efectivo',  iconName:'banknote'   },
    { value:'investment', label:'Inversión', iconName:'trending'   },
  ];

  // Estilos canónicos
  const secCard  = { background:'var(--surface-2)', border:'1.5px solid var(--border)', borderRadius:'var(--r-lg)', padding:'14px 18px', marginBottom:14 };
  const lbl      = { fontSize:11, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:8 };
  const rawInput = { width:'100%', background:'none', border:'none', outline:'none', color:'var(--t1)', fontSize:15, fontFamily:'var(--font)', fontWeight:500 };
  const noSpin   = { WebkitAppearance:'none', MozAppearance:'textfield' };

  // Helpers — formato de monto con miles + decimal con coma (es-AR)
  const parseAmount = (s) => {
    let v = String(s || '').replace(/[^\d,]/g, '');
    const parts = v.split(',');
    if (parts.length > 2) v = parts[0] + ',' + parts.slice(1).join('');
    const [i, d] = v.split(',');
    return d !== undefined ? `${i},${d.slice(0,2)}` : (i || '');
  };
  const fmtAmount = (raw) => {
    if (raw === '' || raw == null) return '';
    const [i, d] = String(raw).split(',');
    const intNum = Number(i || '0');
    const intFmt = isNaN(intNum) ? '0' : intNum.toLocaleString('es-AR');
    return d !== undefined ? `${intFmt},${d}` : intFmt;
  };
  const toNumber = (raw) => {
    if (raw === '' || raw == null) return 0;
    return parseFloat(String(raw).replace(',', '.')) || 0;
  };

  const selCur  = SUPPORTED_CURRENCIES.find(c => c.code === form.currency) || SUPPORTED_CURRENCIES[0];
  const preview = ACCOUNT_GRADIENTS[form.type] || ['#2563EB','#1D4ED8'];

  // Contexto financiero
  const totalActivosActual = (data?.accounts || []).reduce((s,a) => s + (a.balance||0), 0);
  const nuevoSaldo         = toNumber(form.balance);
  const totalActivosFinal  = totalActivosActual + nuevoSaldo;

  // Frase resumen dinámica
  const summaryPhrase = !form.name
    ? 'Completá el nombre para ver el resumen.'
    : nuevoSaldo > 0
      ? `Vas a crear ${form.name} (${ACCOUNT_LABELS[form.type]?.toLowerCase()}) con un saldo inicial de ${selCur.symbol}${fmtAmount(form.balance)} ${selCur.code}.`
      : `Vas a crear ${form.name} (${ACCOUNT_LABELS[form.type]?.toLowerCase()}) sin saldo inicial.`;

  const submit = () => {
    if (!form.name || !form.balance) { window.showToast('Completá nombre y saldo', 'warning'); return; }
    onAdd({ ...form, balance: nuevoSaldo, id: 'a' + Date.now() });
    onClose();
    window.showToast('Cuenta agregada', 'success');
  };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer">
        <div className="drawer-handle" />

        {/* Header */}
        <div style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 20px 16px', borderBottom:'1px solid var(--border)' }}>
          <button onClick={onClose} style={{ width:34,height:34,borderRadius:'var(--r-md)',background:'var(--surface-2)',border:'1px solid var(--border)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 }}>
            <Icon name="x" size={17} color="var(--t3)" />
          </button>
          <div>
            <div style={{ fontSize:16, fontWeight:800, color:'var(--t1)' }}>Nueva cuenta</div>
            <div style={{ fontSize:12, color:'var(--t4)' }}>Bancaria, efectivo o billetera</div>
          </div>
        </div>

        <div style={{ padding:'18px 20px' }}>

          {/* Tira de contexto financiero */}
          <div style={{
            display:'flex', alignItems:'center', justifyContent:'space-between', gap:12,
            padding:'10px 14px', marginBottom:14,
            background:'var(--surface-2)', border:'1.5px solid var(--border)', borderRadius:'var(--r-lg)',
          }}>
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <div style={{ width:28, height:28, borderRadius:'var(--r-md)', background:'var(--success-bg)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name="trending" size={14} color="var(--success)" />
              </div>
              <div style={{ display:'flex', flexDirection:'column' }}>
                <span style={{ fontSize:10, color:'var(--t5)', fontWeight:700, textTransform:'uppercase', letterSpacing:'0.4px' }}>Activos totales</span>
                <span style={{ fontSize:13, color:'var(--t2)', fontWeight:700, fontVariantNumeric:'tabular-nums' }}>
                  {nuevoSaldo > 0
                    ? <>{fmtFull(totalActivosActual)} → <span style={{ color:'var(--success)' }}>{fmtFull(totalActivosFinal)}</span></>
                    : fmtFull(totalActivosActual)
                  }
                </span>
              </div>
            </div>
            {nuevoSaldo > 0 && (
              <div style={{ fontSize:12, fontWeight:800, color:'var(--success)', fontVariantNumeric:'tabular-nums' }}>
                +{fmtFull(nuevoSaldo)}
              </div>
            )}
          </div>

          {/* Preview wallet en vivo */}
          <div style={{
            background:`linear-gradient(135deg, ${preview[0]} 0%, ${preview[1]} 100%)`,
            borderRadius:'var(--r-xl)', padding:'18px 20px', marginBottom:18, color:'#fff', minHeight:96,
            boxShadow:'var(--sh-fab)', position:'relative', overflow:'hidden',
          }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14 }}>
              <div>
                <div style={{ fontSize:10, fontWeight:700, opacity:0.7, textTransform:'uppercase', letterSpacing:'0.6px', marginBottom:3 }}>
                  {ACCOUNT_LABELS[form.type] || 'Cuenta'}
                </div>
                <div style={{ fontSize:17, fontWeight:800, lineHeight:1.2 }}>{form.name || 'Nombre de la cuenta'}</div>
              </div>
              <Icon name={ACCOUNT_ICONS[form.type] || 'creditCard'} size={22} color="#fff" strokeWidth={1.6} />
            </div>
            <div style={{ fontSize:24, fontWeight:900, letterSpacing:'-0.5px', fontVariantNumeric:'tabular-nums' }}>
              {selCur.symbol}{fmtAmount(form.balance) || '0'}
            </div>
            <div style={{ fontSize:11, opacity:0.65, marginTop:3 }}>{form.currency} · saldo inicial</div>
          </div>

          {/* Nombre */}
          <div style={secCard}>
            <div style={{ ...lbl, display:'flex', justifyContent:'space-between' }}>
              <span>Nombre <span style={{ color:'var(--danger)' }}>*</span></span>
              <span style={{ fontWeight:400, textTransform:'none', letterSpacing:0 }}>{(form.name||'').length}/40</span>
            </div>
            <input type="text" placeholder="Ej. Banco Galicia, Mercado Pago…" value={form.name} maxLength={40}
              onChange={e=>setF(f=>({...f,name:e.target.value}))}
              style={rawInput} />
          </div>

          {/* Tipo — 4 chips visuales */}
          <div style={secCard}>
            <div style={lbl}>Tipo de cuenta</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
              {TYPES.map(t => {
                const active = form.type === t.value;
                const [g1] = ACCOUNT_GRADIENTS[t.value] || ['#2563EB'];
                return (
                  <button key={t.value} type="button" onClick={() => setF(f => ({ ...f, type: t.value }))}
                    style={{
                      display:'flex', alignItems:'center', gap:10,
                      padding:'10px 12px', borderRadius:'var(--r-md)', cursor:'pointer',
                      background: active ? g1 : 'var(--surface)',
                      border: `1.5px solid ${active ? g1 : 'var(--border)'}`,
                      transition:'all 0.15s',
                      boxShadow: active ? `0 4px 14px ${g1}55` : 'none',
                    }}>
                    <Icon name={t.iconName} size={17} color={active ? '#fff' : 'var(--t3)'} strokeWidth={1.7} />
                    <span style={{ fontSize:13, fontWeight:700, color: active ? '#fff' : 'var(--t2)' }}>{t.label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Saldo inicial — estilo monto destacado */}
          <div style={secCard}>
            <div style={lbl}>Saldo inicial <span style={{ color:'var(--danger)' }}>*</span></div>
            <div style={{ display:'flex', alignItems:'center', gap:12 }}>
              <span style={{ fontSize:22, fontWeight:900, color:'var(--success)', lineHeight:1 }}>+</span>
              <input type="text" inputMode="decimal" placeholder="0" value={fmtAmount(form.balance)}
                onChange={e=>setF(f=>({...f,balance:parseAmount(e.target.value)}))}
                style={{ ...rawInput, fontSize:30, fontWeight:900, fontVariantNumeric:'tabular-nums', flex:1 }} />
              {/* Selector de moneda */}
              <button type="button" onClick={() => setShowCurrencyPicker(true)}
                style={{ display:'flex', alignItems:'center', gap:6, background:'var(--surface)', border:'1.5px solid var(--border)', borderRadius:'var(--r-md)', padding:'7px 10px', color:'var(--t2)', fontWeight:700, fontSize:13, flexShrink:0, cursor:'pointer' }}>
                <span style={{ fontSize:18 }}>{selCur.flag}</span>
                <span>{selCur.code}</span>
                <Icon name="chevronDown" size={13} color="var(--t4)" />
              </button>
            </div>
          </div>

          {/* Frase resumen dinámica */}
          <div style={{ background:'var(--surface-2)', border:'1.5px solid var(--border)', borderRadius:'var(--r-lg)', padding:'14px 16px', marginBottom:16, display:'flex', alignItems:'flex-start', gap:10 }}>
            <div style={{ width:32, height:32, borderRadius:'var(--r-md)', background:'var(--accent-muted)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <Icon name="sparkles" size={15} color="var(--accent)" />
            </div>
            <p style={{ fontSize:13, color:'var(--t2)', lineHeight:1.6, margin:0 }}>{summaryPhrase}</p>
          </div>

          {/* Botón */}
          <button onClick={submit} className="btn btn-primary btn-full" style={{ borderRadius:'var(--r-lg)', padding:15, fontSize:15 }}>
            <Icon name="checkCircle" size={18} color="#fff" /> Agregar cuenta
          </button>
        </div>
      </div>

      {/* Currency Picker reutilizado */}
      {showCurrencyPicker && (
        <CurrencyPicker
          value={form.currency}
          onChange={c => setF(f => ({ ...f, currency: c }))}
          onClose={() => setShowCurrencyPicker(false)}
        />
      )}
    </>
  );
};

/* ── Pantalla Cuentas ── */
const Accounts = ({ data, setData, theme, toggleTheme, selectedMonth, setSelectedMonth }) => {
  const [showAdd, setShowAdd] = useStA(false);
  const { accounts, transactions } = data;

  // El FAB central del bottom-nav mobile dispara este evento contextual
  useEffA(() => {
    const handler = (e) => { if (e.detail === 'account') setShowAdd(true); };
    window.addEventListener('rumbo:openAdd', handler);
    return () => window.removeEventListener('rumbo:openAdd', handler);
  }, []);

  const todayKey = `${new Date().getFullYear()}-${String(new Date().getMonth()+1).padStart(2,'0')}`;
  const curMonth = selectedMonth || todayKey;
  const isFutureMonth  = curMonth > todayKey;
  const isCurrentMonth = curMonth === todayKey;

  // Saldo total actual (sin retroactivo — los balances del demo no derivan de las tx)
  const totalBalance = accounts.reduce((s, a) => s + a.balance, 0);
  // Delta del mes seleccionado a nivel global
  const monthTxsAll = transactions.filter(t => (t.date||'').startsWith(curMonth));
  const monthIncTotal = monthTxsAll.filter(t=>t.type==='income').reduce((s,t)=>s+t.amount,0);
  const monthExpTotal = monthTxsAll.filter(t=>t.type==='expense').reduce((s,t)=>s+t.amount,0);
  const monthDeltaTotal = monthIncTotal - monthExpTotal;
  // Proyección del mes (para futuro)
  const projection = (typeof getMonthProjection === 'function') ? getMonthProjection(data, curMonth) : null;

  const handleAdd = a => {
    const updated = { ...data, accounts: [...data.accounts, a] };
    setData(updated); saveData(updated);
  };

  return (
    <div style={{ background:'var(--bg)', minHeight:'100%', paddingBottom:32 }}>

      {/* Header */}
      <div className="screen-header">
        <div>
          <h1 className="screen-title">Mis cuentas</h1>
          <p className="screen-sub">{accounts.length} cuentas activas</p>
        </div>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap', justifyContent:'flex-end' }}>
          {setSelectedMonth && (
            <MonthSwitcher value={curMonth} onChange={setSelectedMonth} transactions={transactions} compact />
          )}
          <button className="theme-toggle" onClick={toggleTheme}>
            <Icon name={theme==='dark'?'sun':'moon'} size={15} color="var(--t3)" />
          </button>
        </div>
      </div>

      <div style={{ padding:'14px 20px 0' }}>
        {/* Hero total activos — anclado al mes seleccionado */}
        <div style={{
          background:'linear-gradient(135deg, var(--accent) 0%, #1D4ED8 100%)',
          borderRadius:'var(--r-xl)', padding:'22px 24px', marginBottom:16,
          color:'#fff', boxShadow:'var(--sh-fab)',
        }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12 }}>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:11, fontWeight:700, opacity:0.7, textTransform:'uppercase', letterSpacing:'0.6px', marginBottom:6 }}>Activos totales (hoy)</div>
              <div style={{ fontSize:38, fontWeight:900, letterSpacing:'-1px', fontVariantNumeric:'tabular-nums', lineHeight:1 }}>{fmtFull(totalBalance)}</div>
            </div>
            {/* Cómo te fue / cómo te va este mes — desglose explícito sin jerga */}
            {!isFutureMonth && (monthIncTotal > 0 || monthExpTotal > 0) && (
              <div style={{ textAlign:'right', flexShrink:0, background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)', borderRadius:'var(--r-md)', padding:'10px 14px', minWidth:200 }}>
                <div style={{ fontSize:10, fontWeight:700, opacity:0.8, textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:6 }}>
                  {isCurrentMonth ? 'Este mes hasta hoy' : 'Resumen del mes'}
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap:3, fontSize:12, fontVariantNumeric:'tabular-nums' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12 }}>
                    <span style={{ opacity:0.85 }}>Entró</span>
                    <span style={{ fontWeight:700 }}>+{fmt(monthIncTotal)}</span>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12 }}>
                    <span style={{ opacity:0.85 }}>Salió</span>
                    <span style={{ fontWeight:700 }}>−{fmt(monthExpTotal)}</span>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12, paddingTop:5, marginTop:3, borderTop:'1px solid rgba(255,255,255,0.2)' }}>
                    <span style={{ fontWeight:700 }}>{monthDeltaTotal >= 0 ? 'Te quedó' : 'Te faltó'}</span>
                    <span style={{ fontWeight:900, fontSize:14 }}>
                      {monthDeltaTotal >= 0 ? '+' : '−'}{fmt(Math.abs(monthDeltaTotal))}
                    </span>
                  </div>
                </div>
              </div>
            )}
            {isFutureMonth && projection && (
              <div style={{ textAlign:'right', flexShrink:0, background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)', borderRadius:'var(--r-md)', padding:'10px 14px', minWidth:200 }}>
                <div style={{ fontSize:10, fontWeight:700, opacity:0.8, textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:6 }}>
                  Proyección del mes
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap:3, fontSize:12, fontVariantNumeric:'tabular-nums' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12 }}>
                    <span style={{ opacity:0.85 }}>Va a entrar</span>
                    <span style={{ fontWeight:700 }}>+{fmt(projection.expected.income)}</span>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12 }}>
                    <span style={{ opacity:0.85 }}>Va a salir</span>
                    <span style={{ fontWeight:700 }}>−{fmt(projection.expected.expense)}</span>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12, paddingTop:5, marginTop:3, borderTop:'1px solid rgba(255,255,255,0.2)' }}>
                    <span style={{ fontWeight:700 }}>{projection.expected.net >= 0 ? 'Vas a quedar' : 'Te va a faltar'}</span>
                    <span style={{ fontWeight:900, fontSize:14 }}>
                      {projection.expected.net >= 0 ? '+' : '−'}{fmt(Math.abs(projection.expected.net))}
                    </span>
                  </div>
                </div>
              </div>
            )}
          </div>
          {/* Barra distribución por cuenta — saldos actuales */}
          <div style={{ height:6, borderRadius:'var(--r-full)', overflow:'hidden', display:'flex', gap:2, marginTop:14, opacity:0.85 }}>
            {accounts.map(a => (
              <div key={a.id} title={a.name}
                style={{ height:'100%', width:`${totalBalance>0?(a.balance/totalBalance)*100:0}%`, background:'rgba(255,255,255,0.7)', transition:'width 0.8s ease', minWidth: a.balance>0?3:0 }} />
            ))}
          </div>
          {/* Leyenda */}
          <div style={{ display:'flex', gap:14, marginTop:10, flexWrap:'wrap' }}>
            {accounts.map(a => (
              <div key={a.id} style={{ display:'flex', alignItems:'center', gap:5 }}>
                <div style={{ width:8, height:8, borderRadius:'50%', background:'rgba(255,255,255,0.8)' }} />
                <span style={{ fontSize:11, opacity:0.75 }}>{a.name}: {fmt(a.balance)}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Cards wallet — cada una anclada al mes */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:16 }}>
          {accounts.map(a => <WalletCard key={a.id} account={a} transactions={transactions} selectedMonth={curMonth}
            recurringIncomes={data.recurringIncomes||[]} fixedExpenses={data.fixedExpenses||[]} debts={data.debts||[]} />)}
        </div>
      </div>

      {/* FAB persistente */}
      <button className="fab fab-fixed" onClick={() => setShowAdd(true)} aria-label="Agregar cuenta">
        <Icon name="plus" size={22} color="#fff" strokeWidth={2} />
      </button>

      {showAdd && <AddAccountDrawer onClose={()=>setShowAdd(false)} onAdd={handleAdd} data={data} />}
    </div>
  );
};

Object.assign(window, { Accounts });
