this is the final formula
=IF(MATCH("OFF",B:B,0)<MATCH("ON",B:B,0),IF(MATCH(LOOKUP(2,1/(B:B="ON"),A:A),A:A,0)>MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0),SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"Off",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))-SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"On",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))+(E1-LOOKUP(2,1/(B:B="ON"),A:A))+(INDEX(A:A,MATCH("OFF",B:B,0))-D1),SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"Off",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))-SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"On",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))+(INDEX(A:A,MATCH("OFF",B:B,0))-D1)),IF(MATCH(LOOKUP(2,1/(B:B="ON"),A:A),A:A,0)>MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0),SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"Off",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))-SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"On",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))+(E1-LOOKUP(2,1/(B:B="ON"),A:A)),SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"Off",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))-SUMIF(INDEX(B:B,MATCH("ON",B:B,0)):INDEX(B:B,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)),"On",INDEX(A:A,MATCH("ON",B:B,0)):INDEX(A:A,MATCH(LOOKUP(2,1/(B:B="OFF"),A:A),A:A,0)))))
this is the simple version referring to other cells
=IF(D6<D2,IF(D5>D3,SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"Off",INDEX(A:A,D2):INDEX(A:A,D3))-SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"On",INDEX(A:A,D2):INDEX(A:A,D3))+(E1-D4)+(D7-D1),SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"Off",INDEX(A:A,D2):INDEX(A:A,D3))-SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"On",INDEX(A:A,D2):INDEX(A:A,D3))+(D7-D1)),IF(D5>D3,SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"Off",INDEX(A:A,D2):INDEX(A:A,D3))-SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"On",INDEX(A:A,D2):INDEX(A:A,D3))+(E1-D4),SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"Off",INDEX(A:A,D2):INDEX(A:A,D3))-SUMIF(INDEX(B:B,D2):INDEX(B:B,D3),"On",INDEX(A:A,D2):INDEX(A:A,D3))))