function Logo({ collapsed }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <svg width="34" height="34" viewBox="0 0 70 70" aria-hidden>
        <circle cx="35" cy="35" r="27" fill="none" stroke="#00c275" strokeWidth="3" />
        <path d="M23 43 L35 27 L47 35" stroke="#00c275" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M41 27 L47 27 L47 33" stroke="#00c275" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      {!collapsed && (
        <div style={{ lineHeight: 1 }}>
          <div style={{ fontFamily: 'Space Grotesk, Inter, sans-serif', fontWeight: 700, fontSize: 17, letterSpacing: -0.5 }}>
            tracker<span style={{ color: '#00c275' }}>pro</span>
          </div>
          <div style={{ fontSize: 9, letterSpacing: 2, color: 'var(--text-faint)', marginTop: 3, fontWeight: 600 }}>BETA</div>
        </div>
      )}
    </div>
  );
}

function Sidebar({ collapsed, onToggle, isMobile, portfolios, activePortfolioId, onSelectPortfolio, onCreatePortfolio, onEditPortfolio, onAddToPortfolio, portfolioTotals, balanceHidden, userEmail, onLogout, isAdmin, onOpenAdmin, adminNewCount = 0 }) {
  const width = collapsed ? 72 : 240;
  return (
    <aside style={{
      width, flexShrink: 0,
      borderRight: collapsed ? 'none' : '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', padding: '18px 14px', gap: 18,
      transition: 'width 0.2s ease, border-color 0.15s', background: 'var(--bg)',
      // En mobile uso 100dvh (dynamic viewport height): se ajusta cuando aparece
      // el teclado o las barras del browser, así la sección de usuario/logout
      // queda siempre dentro del área visible. 100vh no respeta esos cambios y
      // empujaba el logout abajo del teclado.
      height: isMobile ? '100dvh' : 'auto',
      // Scroll de seguridad por si la lista de portafolios crece mucho.
      overflowY: isMobile ? 'auto' : 'visible',
      WebkitOverflowScrolling: 'touch',
    }}>
      {/* header */}
      <div style={{
        display: 'flex',
        justifyContent: isMobile ? 'center' : 'space-between',
        alignItems: 'center', gap: 8,
        position: 'relative',
      }}>
        <Logo collapsed={collapsed} />
        <button
          onClick={onToggle}
          title={isMobile ? 'Cerrar' : (collapsed ? 'Expandir' : 'Colapsar')}
          style={{
            width: 28, height: 28, borderRadius: 8, color: 'var(--text-dim)',
            display: 'grid', placeItems: 'center', transition: 'background 0.15s',
            position: isMobile ? 'absolute' : 'static',
            right: isMobile ? 0 : 'auto',
            top: isMobile ? '50%' : 'auto',
            transform: isMobile ? 'translateY(-50%)' : 'none',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--panel)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >
          {isMobile ? (
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M3 3l10 10M13 3L3 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
            </svg>
          ) : (
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d={collapsed ? "M6 3 L11 8 L6 13" : "M10 3 L5 8 L10 13"} stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
              <path d={collapsed ? "M2 3 L7 8 L2 13" : "M14 3 L9 8 L14 13"} stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          )}
        </button>
      </div>

      {!collapsed && (
        <div style={{ marginTop: 8 }}>
          <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 10, fontWeight: 500 }}>Mis portafolios</div>
          {portfolios.map(p => {
            const isActive = p.id === activePortfolioId;
            const value = portfolioTotals?.[p.id] ?? 0;
            return (
              <div
                key={p.id}
                onClick={() => onSelectPortfolio(p.id)}
                style={{
                  display: 'flex', width: '100%', padding: '12px 14px', borderRadius: 12,
                  background: isActive ? 'var(--panel)' : 'transparent',
                  border: `1px solid ${isActive ? 'var(--border)' : 'transparent'}`,
                  alignItems: 'center', justifyContent: 'space-between', marginBottom: 6,
                  cursor: 'pointer', userSelect: 'none',
                }}
              >
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                    <span style={{
                      fontSize: 13.5, fontWeight: 500,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{p.name}</span>
                    <button
                      onClick={e => { e.stopPropagation(); onEditPortfolio(p); }}
                      title="Editar portafolio"
                      style={{
                        color: 'var(--text-faint)', display: 'grid', placeItems: 'center',
                        borderRadius: 4, padding: 2, flexShrink: 0, lineHeight: 1,
                      }}
                      onMouseEnter={e => e.currentTarget.style.color = 'var(--text-dim)'}
                      onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}
                    >
                      <svg width="11" height="11" viewBox="0 0 16 16" fill="none">
                        <path d="M11.5 2.5l2 2L6 12H4v-2l7.5-7.5z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
                      </svg>
                    </button>
                  </div>
                  <span style={{ fontSize: 12, color: 'var(--text-dim)', fontVariantNumeric: 'tabular-nums' }}>
                    {balanceHidden ? '••••••' : window.formatUSD(value)}
                  </span>
                </div>
                <span
                  aria-hidden
                  style={{
                    width: 14, height: 14, borderRadius: '50%',
                    background: p.color, flexShrink: 0,
                    boxShadow: isActive ? '0 0 0 3px rgba(0, 194, 117, 0.22)' : 'none',
                    transition: 'box-shadow 0.15s',
                  }}
                />
              </div>
            );
          })}

          <button
            onClick={onCreatePortfolio}
            style={{
              padding: '10px 14px', color: 'var(--accent)', fontSize: 13, fontWeight: 500,
              width: '100%', textAlign: 'left',
            }}
          >
            + Crear portafolio
          </button>

          {/* Link de admin solo visible para admin */}
          {isAdmin && (
            <button
              onClick={onOpenAdmin}
              style={{
                marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)',
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '10px 14px', color: 'var(--text-dim)', fontSize: 13, fontWeight: 500,
                textAlign: 'left', borderRadius: 8, position: 'relative',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = 'var(--panel)'; e.currentTarget.style.color = 'var(--text)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-dim)'; }}
            >
              <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                  <path d="M8 1.5l5.5 2.5v4c0 3.5-2.5 5.5-5.5 6.5-3-1-5.5-3-5.5-6.5v-4L8 1.5z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
                  <path d="M5.5 8L7 9.5L10.5 6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                {adminNewCount > 0 && (
                  <span
                    title={`${adminNewCount} feedback${adminNewCount === 1 ? '' : 's'} nuevo${adminNewCount === 1 ? '' : 's'}`}
                    style={{
                      position: 'absolute', top: -3, right: -4,
                      width: 8, height: 8, borderRadius: '50%',
                      background: 'var(--red)',
                      boxShadow: '0 0 0 2px var(--bg)',
                      animation: 'livePulse 1.6s ease-in-out infinite',
                    }}
                  />
                )}
              </span>
              Panel admin
              {adminNewCount > 0 && (
                <span style={{
                  marginLeft: 'auto',
                  background: 'var(--red)', color: '#fff',
                  fontSize: 10, fontWeight: 700,
                  padding: '1px 7px', borderRadius: 999,
                  minWidth: 16, textAlign: 'center', lineHeight: 1.4,
                }}>
                  {adminNewCount > 99 ? '99+' : adminNewCount}
                </span>
              )}
            </button>
          )}
        </div>
      )}

      {/* Sección de usuario al pie */}
      {!collapsed && userEmail && (
        <div style={{
          marginTop: 'auto', paddingTop: 14, borderTop: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
            display: 'grid', placeItems: 'center', color: '#fff',
            fontWeight: 700, fontSize: 11, flexShrink: 0,
          }}>
            {userEmail.slice(0, 2).toUpperCase()}
          </div>
          <div style={{ minWidth: 0, flex: 1, lineHeight: 1.3 }}>
            <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>Conectado como</div>
            <div style={{
              fontSize: 12.5, fontWeight: 500,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{userEmail}</div>
          </div>
          <button
            onClick={onLogout}
            title="Cerrar sesión"
            style={{
              width: 28, height: 28, borderRadius: 8, color: 'var(--text-dim)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'rgba(239,104,104,0.1)'; e.currentTarget.style.color = 'var(--red)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-dim)'; }}
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M6 3H3v10h3M10 5l3 3-3 3M13 8H6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      )}
    </aside>
  );
}

Object.assign(window, { Sidebar });
