LAG, and its companion function DIF, are queued functions. That means that when you use Lag inside of an IF, or related conditional code structure, that the "previous value" returned by the function is that the previous time that the IF was true.
So generally the preferred usage is to execute the Lag before any IF so you have the value as needed conditionally and typically drop the lagged variable unless needed later.