The computation is deliberately punitive. Any purchase is matched against any sale within six months to produce the maximum recoverable profit, so a sequence of trades can generate a liability even when the insider lost money overall.
Intent is irrelevant and there is no inside-information element. The claim belongs to the issuer, and if it does not act, any shareholder may sue on its behalf, which supports a small industry of plaintiffs' firms scanning form-4 filings.
This is why insiders use scheduled sales, avoid opportunistic round trips, and clear every transaction with counsel. It also explains the awkward six-month gaps you see in insider trading records around option exercises.
Related: section-16-insider, form-4, rule-10b5-1-plan, insider-trading