Problem with Enemy AI?

So I’m trying to get my enemy to chase the character unless it gets too close, in which case the enemy starts attacking, if the player gets too far away, the enemy goes back to its’ waypoint.

What am I doing wrong here?

Why won’t my enemy chase me correctly?

// If the `enemy` is touching the `ground`

if ( isOnFloor ( entity.body ) === true ) {

    // Get the `distance` `from` `player`

    var distFrom = ( player.sprite.width );
    
    // Get the `distance` `to` `enemy`

    var distTo = ( entity.width );

    // Set a `minimum` range

    var minDistRange = (  5 );

    // Set a `maximum` range

    var maxDistRange = (  7 );

    // Get this `distance` between the 
    // `player` & enemy

    var dist = ( distFrom - distTo );

    // Get the `minimum` distance based on `width` of `enemy`
    // plus the `minimum` range of distance

    var minDist = ( ( dist ) + ( minDistRange ) );

    // Get the `maximum` distance based on `width` of `enemy`
    // plus the `maximum` range of distance

    var maxDist = ( ( dist ) + ( maxDistRange ) );

    // Get the non-negative `minimum` distance based on `width` of `enemy`

    var absMinDist = ( Math.abs ( minDist ) );

    // Get the non-negative `maximum` distance based on `width` of `enemy`

    var absMaxDist = ( Math.abs ( maxDist ) );

    // If the `Player` is within range of the `enemy`

    if ( absMinDist > minDistRange && absMaxDist < maxDistRange ) {
        
        // Chase the `Player`

        // Set the `velocity` of the `enemy` dependent on whether 
        // positive or negative & multiply by 
        // `enemy` minimum movespeed

        entity.setVelocityX ( Math.sign ( absMinDist ) * ENEMY_MIN_MOVESPEED );

        // Set `enemy` Animation to `walk`

        PlayAnimation ({
            sprite : entity, 
            animName : 'walk', 
            loopAnim : true, 
        });

    }

    // Otherwise, the `Player` is NOT within the range 
    // of the `enemy`

    else {

        // Stop `enemy` movement

        entity.setVelocity ( 0 );

        // Set `enemy` Animation back to `idle`

        PlayAnimation ({
            sprite : entity, 
            animName : 'idle', 
            loopAnim : true, 
        });

    }

}

ANY & ALL help is GREATLY appreciated!

Thank You! <3

Hello, just an idea here…
calc the distance with the position using x and/or y of the player and enemy, instead of using width?

Wherever enemy or player will be, their width will be the same.
You should verify their coordinates x,y instead.