Issues with a Custom Effect using Yanfly BuffsStatesCore

I have a passive state active on a character, and currently, it's effect is that if the user deals a critical strike, their agility is increased by 33% for 2 turns (code as follows):
Spoiler
<Custom Establish Effect>

// Check if the attack is a physical attack that dealt HP damage from a critical hit.

if (this.isPhysical() && target.result().hpDamage > 0 && target.result().critical) {

// Create an AGI buff that lasts 3 turns.

user.addState(997);

}

</Custom Establish Effect>

However, I'd like to modify it to include an if statement, where, if the state which increases agility is already applied, and another critical strike is scored, it will heal the user for 33% of the damage the hit did. Mind you, I have little idea at all what I'm doing with this, the above code was basically copy/pasted from a yanfly tutorial that used it. I did google "js how to write an if statement", and followed the instructions, but it doesn't seem to help much, here is the code I now have (currently, none of it works).
Spoiler
<Custom Establish Effect>

// Check if the attack is a physical attack that dealt HP damage from a critical hit.

if (this.isPhysical() && target.result().hpDamage > 0 && target.result().critical) {

// Create an AGI buff that lasts 3 turns.

if a.State(997) exists

{

user.gainHP (value = user.MaxHP / 5);

}

else

{

user.addState(997);

}

}

</Custom Establish Effect>

If anyone could fix it for me AND go in-depth to explain how and why it needed to be changed, or simply just help explain how I can fix it myself, it would be tremendously appreciated!
This line:

if a.State(997) exists

should be this:

if (user.isStateAffected(997)) {
that fixed it, restoring the part where it adds the state. but the first part, the heal isn't working.
var heal = Math.floor(user.mhp / 5);
user.gainHp(heal);
user.startDamagePopup();
user.clearResult();

Replace the healing line with the above code. This should apply the heal as well as create the number popup. The floor is to make sure you have a round number.
Thank you, it works fine now, but I do have one more question. How would I write it so that it would instead heal for X% of the damage the critical hit did?

for example, if I want it to heal for 50% of the damage done, and the hit was for 50, it would heal you for 25.
var heal = Math.floor(value * 0.5);

In Establish and Respond effects, value is the amount of damage inflicted. In React and Confirm effects, value can be altered to change the amount of damage inflicted, and negative values should heal.

On that subject, target.result().hpDamage > 0 can actually be value > 0.
alright, thank you very much!

Original thread: https://forums.rpgmakerweb.com/threads/issues-with-a-custom-effect-using-yanfly-buffsstatescore.83614/