Level Restless Dead help

Lots of issues with this code. Two main issues are my character not using chain lightening and after summoning soldiers they fight half the enemies then with my character move to the bottom of the screen. Any help with these specific issues or just general advice on the level is appreciated.

function attack(){
    var enemy = hero.findNearestEnemy();
    if (enemy) 
        while(enemy.health > 0 ) {
        if (hero.distanceTo(enemy) > 10) {
            hero.move(enemy.pos);
        }
         if (hero.isReady('bash')) {
            hero.bash(enemy);
        }
         if(hero.canCast('chain-lightning',enemy)){
           hero.cast('chain-lightning', enemy);
            }
        else {
            hero.attack(enemy);
        }
    }
  }
function collectCoins(){
    var coin = hero.findNearestItem();
    while(coin) {
        hero.moveXY(coin.pos.x, coin.pos.y);
        coin = hero.findNearestItem();
    }
}
function summon(){
    while(hero.gold > hero.costOf("soldier")) {
        hero.summon("soldier");
    }
  }
function command(){
    var troops = hero.findFriends();
    for(var i = 0; i <troops.length;i++){
    var troop = troops[i];
     var enemy = troop.findNearestEnemy();
    if (enemy) {
       hero.command(troop, "attack", enemy); 
    }
  }
}
    hero.moveXY(58, 18);
    attack();
    collectCoins();
    hero.moveXY(19, 40);
    summon();
    while(true) {
       command();
       attack(); 
    }

Can you give a link to the level please?