File size: 356,748 Bytes
517154b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
"""

browser_session.py

InsightUX research browser.



Flow:

    1. Window opens on real google.com β€” search and click through like a

       normal browser (no scraping, no fake results β€” it's just Google).

    2. Land on whatever page you want to study. Press S to start tracking.

    3. Gaze dot + AOI highlighting (same as run_session.py) kicks in and

       logs sessions/<timestamp>/gaze_log.jsonl + dom_log.jsonl.

    4. Press E to stop. The window auto-navigates to a generated

       analysis_report.html: ranked attention, dwell timeline, heatmap.



Prerequisite:

    calibration.pkl must exist in the working directory (run calibrate.py first).



Run:

    python browser_session.py

"""

import os
import sys

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

from screenshots.gaze_bridge import (
    GazeBridgeProcessor,
    DRAIN_GAZE_BRIDGE_JS,
    INSTALL_GAZE_BRIDGE_JS,
)
from screenshots.chrome_gaze_heatmap_runtime import ChromeHeatmapSession

# A navigation is treated as a short transition, not as part of the page being
# studied. This also gives the WebView2 full-page capture a stable page before
# it changes the viewport height.
PAGE_SETTLE_SECONDS = 2.0

import os
import io
import re
import sys
import csv
import hmac
import json
import time
import math
import base64
import logging
import secrets
import zipfile
import functools
import threading
import subprocess
import queue
from dataclasses import replace
from datetime import datetime
from pathlib import Path
from logging.handlers import RotatingFileHandler

# Windows consoles default to a non-UTF-8 codepage (cp1252) β€” a stray
# unicode character in any print() (ours, or one of calibrate.py/validate.py's
# once relaunched as a subprocess sharing this process's stdout handle) would
# otherwise crash the whole process with UnicodeEncodeError. Confirmed this
# happened for real during a calibration run mid-session.
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

import cv2
from core.camera import (open_camera, read_camera_frame, CameraAccessError,
                         CAMERA_ACCESS_MESSAGE, CAMERA_ERROR_EXIT_CODE)
import numpy as np
import webview
import pyautogui
from PIL import Image

from preprocessing.preprocessing_pipeline import (
    create_face_mesh,
    estimate_camera_matrix,
    estimate_head_pose,
    compute_iris_radius,
    compute_ear,
    step1_normalize,
    step2_illumination,
    LEFT_EYE_INDICES,
    LEFT_EAR_INDICES,
    LEFT_IRIS_INDICES,
    RIGHT_EYE_INDICES,
    RIGHT_EAR_INDICES,
    RIGHT_IRIS_INDICES,
)
from core.inference_pipeline import InsightUXPipeline, GazeAngleSmoother
from calibration.face_check import face_orientation_gate
from core.session_logger import GazeLogger
from screenshots.analysis_microlink import (
    generate_report,
    load_session,
    session_summary,
    summarize_mouse,
    attach_microlink_heatmaps_to_report,
)
try:
    from screenshots.analysis_microlink import refresh_report_if_stale
except ImportError:  # older analysis_microlink.py without the refresh helper
    def refresh_report_if_stale(report_path):
        return False
from core import theme, auth, participants
from ai.drishti_report import report_uri as _drishti_report_uri


# =============================================================================
# CONFIG β€” kept identical to run_session.py so calibration.pkl stays valid
# =============================================================================

# Bundled read-only assets (models/checkpoints) vs. per-user writable data
# (calibration.pkl, sessions/, the generated landing page) need different
# roots once frozen by PyInstaller β€” onedir nests bundled data under
# _internal/, alongside a persistent folder holding InsightUX.exe itself.
if getattr(sys, "frozen", False):
    RESOURCE_DIR = sys._MEIPASS
    DATA_DIR     = os.path.dirname(sys.executable)
else:
    RESOURCE_DIR = PROJECT_ROOT
    DATA_DIR     = RESOURCE_DIR
THEME_PREF_PATH   = os.path.join(DATA_DIR, "theme_pref.json")   # one light/dark choice for every page
FRONTEND_DIR      = os.path.join(DATA_DIR, "frontend")
os.makedirs(FRONTEND_DIR, exist_ok=True)
BASE_DIR         = DATA_DIR   # kept as an alias: subprocess cwd for calibrate/validate relaunches

# =============================================================================
# LOGGING β€” every "[browser_session] ..." diagnostic below goes through
# _log() instead of a bare print(): still prints to the console exactly as
# before (nothing lost for interactive `python browser_session.py` use),
# but is now ALSO durable in DATA_DIR/logs/insightux.log (rotated at 2MB,
# 3 backups kept) so a crash report has something to inspect afterwards
# instead of only whatever was still in a terminal's scrollback.
# =============================================================================
_LOG_DIR = os.path.join(DATA_DIR, "logs")
os.makedirs(_LOG_DIR, exist_ok=True)
_logger = logging.getLogger("insightux")
_logger.setLevel(logging.INFO)
_logger.propagate = False  # this is the only handler we want -- don't also fall through to the root logger's default stderr handler
_log_handler = RotatingFileHandler(
    os.path.join(_LOG_DIR, "insightux.log"), maxBytes=2 * 1024 * 1024, backupCount=3, encoding="utf-8"
)
_log_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
_logger.addHandler(_log_handler)


def _log(msg):
    print(msg)
    try:
        _logger.info(msg)
    except Exception:
        pass  # a full/unwritable disk shouldn't take the console message down with it


# User-action logging can be triggered from pywebview's UI callback thread.
# Keep console and rotating-file I/O off that thread so logging never stalls
# page navigation or other browser interactions.
_ACTION_LOG_QUEUE = queue.SimpleQueue()


def _action_log_worker():
    while True:
        message = _ACTION_LOG_QUEUE.get()
        try:
            _log(message)
        except Exception:
            pass


threading.Thread(target=_action_log_worker, name="insightux-action-log", daemon=True).start()


def _log_user_action(action_name):
    try:
        _ACTION_LOG_QUEUE.put(f"[browser_session] user action: {action_name}")
    except Exception:
        pass


# Bump alongside packaging/installer.iss's AppVersion on every release, and
# update version.json in the same commit β€” see packaging/README.md.
VERSION = "1.0.0"
VERSION_CHECK_URL = "https://huggingface.co/arpitasethiii/insightux/resolve/main/version.json"

ONNX_PATH        = os.path.join(RESOURCE_DIR, "models", "gaze_cnn_v4.onnx")
CALIBRATION_PATH = os.path.join(DATA_DIR, "calibration.pkl")
SCREEN_W, SCREEN_H = pyautogui.size()

PATCH_SOURCE   = "blended"
POSE_SMOOTH    = 0.65
MAX_JUMP       = 220
NO_FACE_RESET  = 15
DOM_EVERY      = 6

EURO_MINCUTOFF = 0.35
EURO_BETA      = 0.12

# Rolling-median window applied to (pitch, yaw) BEFORE the RBF query.
# See GazeAngleSmoother in inference_pipeline.py for why this is essential
# and not merely a nicety. Must match validate.py to stay comparable.
ANGLE_SMOOTH_WINDOW = 10

POSE_NORM_SCALE         = 30.0
HEAD_PITCH_COMPENSATION = 0.0  # reverted β€” 0.35 made accuracy worse, not better
HEAD_YAW_COMPENSATION   = 0.0

SESSIONS_ROOT = os.path.join(DATA_DIR, "sessions")

# WebView2 is an isolated screenshot/heatmap layer. Leave empty to use
# Microlink's public/free request path; set MICROLINK_API_KEY in the
# environment for an authenticated Microlink account.
from screenshots.microlink_gaze_heatmap_runtime import microlink_api_key

MICROLINK_API_KEY = microlink_api_key()

# Every session folder is named by browser_session.py itself in this exact
# shape (see start_tracking()'s datetime.now().strftime("%Y%m%d_%H%M%S")) β€”
# used to validate session ids handed back from JS (rename/open-report calls)
# before joining them onto a filesystem path, since window.pywebview.api is
# reachable from any page's own script, not just our injected chrome.
_SESSION_ID_RE = re.compile(r"^\d{8}_\d{6}$")

# pywebview binds js_api to the whole window, not per-frame -- every page
# the user browses (not just our own landing/report/login pages) gets a
# live window.pywebview.api, so a real website's OWN script could otherwise
# call start_tracking()/delete_my_session()/quit_app()/etc. directly, no
# click of ours involved. A per-origin allowlist isn't possible here (the
# app's whole point is that tracking must work on arbitrary real websites,
# so "which site is loaded" can't be the gate) -- instead every state-
# changing Api method below requires this token as its trailing argument.
# It's baked into CHROME_JS as a closure-local const (see __IUX_TOK__ in
# CHROME_JS below) that's never assigned to `window`, so a hosting page's
# own top-level script has no way to read it back out and forge a call.
# Regenerated fresh every process start; never needs to survive a restart.
_API_TOKEN = secrets.token_hex(24)


def _require_token(fn):
    """Decorates every JS-reachable Api method that mutates state or reads

    otherwise-private data. The token always arrives as the CALLER'S LAST

    positional argument (CHROME_JS appends it to every window.pywebview.api

    call it makes) -- stripped here before the wrapped method ever sees its

    normal argument list, so method bodies below stay unaware this exists.

    login()/create_profile()/list_profiles() are deliberately NOT wrapped:

    they're only ever called from the login page's own self-contained

    script, which (unlike CHROME_JS) never runs alongside third-party page

    content in the first place. log_mouse_data() is also left unwrapped --

    see its own docstring for why that one's a deliberately accepted gap.

    Rejecting returns None, which every existing call site already treats

    as "nothing happened" (`res && res.ok`, `if (ok)`, or no .then() at

    all) -- no call site needed to change to tolerate this."""
    @functools.wraps(fn)
    def wrapper(self, *args):
        token = args[-1] if args else None
        if not isinstance(token, str) or not hmac.compare_digest(token, _API_TOKEN):
            _log(f"[browser_session] rejected {fn.__name__}() -- missing/invalid API token "
                  f"(a page's own script calling window.pywebview.api directly?)")
            return None
        # Log the API action name without arguments: some actions carry private
        # data, and logging parameters could expose it in the console/log file.
        _log_user_action(fn.__name__)
        return fn(self, *args[:-1])
    return wrapper

# =============================================================================
# MULTI-USER PROFILES
#
# CALIBRATION_PATH/SESSIONS_ROOT above were, before profiles existed, the
# one-and-only global data locations β€” and on an install that already has
# data there, they still describe exactly where it lives. _apply_user_paths()
# below repoints these same two names at a per-profile folder the moment
# someone logs in, and every existing call site (gaze_worker(),
# _sessions_json(), the calibration-exists check in start_tracking(),
# the os.makedirs at boot, ...) keeps reading them completely unchanged β€”
# isolation is a side effect of *which folder these constants point to*,
# not a rewrite of the code that uses them.
# =============================================================================
_LEGACY_CALIBRATION_PATH   = CALIBRATION_PATH
_LEGACY_SESSIONS_ROOT      = SESSIONS_ROOT
_LEGACY_BASELINE_POSE_PATH = os.path.join(DATA_DIR, "baseline_pose.pkl")

CURRENT_USER_DIR    = None  # the signed-in owner's own folder; None until login/switch/create
CURRENT_SUBJECT_DIR = None  # the ACTIVE TRACKING SUBJECT's folder β€” owner's own dir in "self"
                             # mode, or users/<owner>/participants/<id>/ when tracking a
                             # participant. SESSIONS_ROOT/CALIBRATION_PATH/_user_onnx_path()
                             # all derive from this one value, never from CURRENT_USER_DIR
                             # directly, so "who owns this account" and "who is being tracked
                             # right now" stay two separately-settable things.


def _user_onnx_path():
    """The active tracking subject's own fine-tuned gaze model if they've

    ever calibrated with fine-tuning on, else the shared bundled default β€”

    mirrors the write side of this in calibrate.py's out_onnx_path. A

    subject (owner or participant) who has never calibrated is correctly

    treated as running on the stock model, never on someone else's."""
    if CURRENT_SUBJECT_DIR:
        candidate = os.path.join(CURRENT_SUBJECT_DIR, "gaze_cnn_v4_finetuned.onnx")
        if os.path.exists(candidate):
            return candidate
    return ONNX_PATH


def _apply_user_paths(user_id):
    """Owner-level redirection only β€” sets CURRENT_USER_DIR to this

    profile's own folder. Session/calibration paths for the ACTIVE

    TRACKING SUBJECT are computed separately by _apply_subject_paths(),

    which the caller (Api._activate_user()) always calls right after this

    (defaulting to self) β€” see that function for why the two are split."""
    global CURRENT_USER_DIR
    CURRENT_USER_DIR = auth.user_dir(DATA_DIR, user_id)
    os.makedirs(CURRENT_USER_DIR, exist_ok=True)


def _apply_subject_paths(participant_record):
    """The one place SESSIONS_ROOT/CALIBRATION_PATH get repointed at the

    active tracking subject's own folder β€” participant_record=None means

    "Myself" (the owner's own folder, exactly the pre-participants

    behavior), a participant dict means their nested

    users/<owner>/participants/<id>/ folder. Every existing call site that

    reads these two names (gaze_worker(), _sessions_json(), the

    calibration-exists check in start_tracking(), ...) needed zero

    changes β€” same reasoning _apply_user_paths() already documents."""
    global SESSIONS_ROOT, CALIBRATION_PATH, CURRENT_SUBJECT_DIR
    if participant_record:
        CURRENT_SUBJECT_DIR = participants.participant_dir(CURRENT_USER_DIR, participant_record["id"])
    else:
        CURRENT_SUBJECT_DIR = CURRENT_USER_DIR
    SESSIONS_ROOT = os.path.join(CURRENT_SUBJECT_DIR, "sessions")
    CALIBRATION_PATH = os.path.join(CURRENT_SUBJECT_DIR, "calibration.pkl")
    os.makedirs(SESSIONS_ROOT, exist_ok=True)


def _migrate_legacy_data(user_id):
    """Runs exactly once, only for the very first profile ever created on

    an install that already had pre-profile global data β€” folds that

    existing calibration/sessions history into the new profile instead of

    silently orphaning it. Never touched again for the 2nd+ profile."""
    import shutil
    dest_dir = auth.user_dir(DATA_DIR, user_id)
    os.makedirs(dest_dir, exist_ok=True)

    if os.path.exists(_LEGACY_CALIBRATION_PATH):
        dest = os.path.join(dest_dir, "calibration.pkl")
        if not os.path.exists(dest):
            shutil.move(_LEGACY_CALIBRATION_PATH, dest)
    if os.path.exists(_LEGACY_BASELINE_POSE_PATH):
        dest = os.path.join(dest_dir, "baseline_pose.pkl")
        if not os.path.exists(dest):
            shutil.move(_LEGACY_BASELINE_POSE_PATH, dest)
    if os.path.isdir(_LEGACY_SESSIONS_ROOT):
        dest_sessions = os.path.join(dest_dir, "sessions")
        os.makedirs(dest_sessions, exist_ok=True)
        for name in os.listdir(_LEGACY_SESSIONS_ROOT):
            src = os.path.join(_LEGACY_SESSIONS_ROOT, name)
            dst = os.path.join(dest_sessions, name)
            if not os.path.exists(dst):
                shutil.move(src, dst)


# The window opens on this local, fully InsightUX-branded page instead of
# raw google.com. What you type here still hits REAL Google β€” no fake
# results, no scraping β€” this page is just the visible skin around that
# one redirect step. Typed URLs go straight there instead.
_LANDING_HTML = r"""<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="insightux-landing" content="true">

<title>InsightUX β€” Eye-Tracking Research Browser</title>

<style>

__THEME_CSS__

  * { box-sizing: border-box; }

  html, body { height: 100%; }

  body {

    margin: 0; display: flex; flex-direction: column;

    align-items: center; justify-content: center; gap: 22px;

    background: var(--iux-page-bg);

    font-family: var(--iux-font); color: var(--iux-text);

    transition: background 0.3s var(--iux-ease), color 0.3s var(--iux-ease);

    overflow: hidden;  /* the page itself never scrolls β€” only .recent-list does */

    padding: 16px 0;

  }

  .brand { text-align: center; }

  .logo-row { display: flex; align-items: center; justify-content: center; gap: 12px; }

  .logo-mark {

    width: 46px; height: 46px; border-radius: 14px; background: var(--iux-accent-grad);

    display: flex; align-items: center; justify-content: center; box-shadow: var(--iux-shadow-glow);

  }

  .logo-mark svg { color: var(--iux-on-accent); }

  .logo {

    font-size: 40px; font-weight: 700; letter-spacing: -0.02em;

    background: var(--iux-accent-grad);

    -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;

  }

  .tagline { color: var(--iux-text-dim); font-size: 14.5px; margin-top: 8px; }

  .desc { color: var(--iux-text-faint); font-size: 12.5px; margin-top: 4px; max-width: 480px; }



  form { width: 560px; max-width: 88vw; position: relative; }

  form .search-icon {

    position: absolute; left: 18px; top: 50%; transform: translateY(-50%); color: var(--iux-text-faint);

    pointer-events: none;

  }

  input {

    width: 100%; padding: 16px 20px 16px 46px; font-size: 15px; border-radius: 28px;

    border: 1.5px solid var(--iux-border); background: var(--iux-surface); color: var(--iux-text);

    outline: none; transition: border-color 0.15s var(--iux-ease), box-shadow 0.15s var(--iux-ease);

    box-shadow: var(--iux-shadow-sm);

  }

  input:focus { border-color: var(--iux-primary-light); box-shadow: var(--iux-shadow-glow); }

  input::placeholder { color: var(--iux-text-faint); }



  .chips { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; max-width: 640px; }

  .chip {

    display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-radius: 999px;

    background: var(--iux-surface); border: 1px solid var(--iux-border); font-size: 12px; color: var(--iux-text-dim);

  }

  .chip kbd {

    background: var(--iux-surface-hi); border: 1px solid var(--iux-border); border-radius: 6px;

    padding: 1px 7px; font: 700 11px var(--iux-font); color: var(--iux-primary-light);

  }



  .hint {

    color: var(--iux-text-faint); text-align: center; line-height: 1.6; font-size: 11.5px; max-width: 520px;

  }

</style>

</head>

<body>

  <div class="brand iux-fade-in">

    <div class="logo-row">

      <div class="logo-mark">__LOGO_ICON__</div>

      <div class="logo">InsightUX</div>

    </div>

    <div class="tagline">AI-Powered Eye &amp; Mouse Tracking Research Browser</div>

    <div class="desc">Browse the real web, then press S to start studying attention β€” gaze, cursor, and clicks, all in one session.</div>

  </div>



  <form id="searchForm" class="iux-fade-in">

    <span class="search-icon">__SEARCH_ICON__</span>

    <input id="searchInput" type="text" autofocus

           placeholder="Search Google, or enter a website address">

  </form>



  <div class="chips iux-fade-in">

    <span class="chip">__PLAY_ICON__ <kbd>S</kbd> Start Tracking</span>

    <span class="chip">__STOP_ICON__ <kbd>E</kbd> Stop Tracking</span>

    <span class="chip">__LAYERS_ICON__ <kbd>H</kbd> Heatmap</span>

    <span class="chip">__CURSOR_ICON__ <kbd>M</kbd> Mouse Panel</span>

  </div>



  <div class="hint">

    Search results and websites open below as normal. Once you land on the page you want

    to study, press <b>S</b> to start eye-tracking, <b>E</b> to stop.

  </div>



<script>

__ICONS_JS__

__THEME_JS__



  document.getElementById('searchForm').addEventListener('submit', function(e){

    e.preventDefault();

    const raw = document.getElementById('searchInput').value.trim();

    if (!raw) return;



    const looksLikeUrl = /^https?:\/\//i.test(raw) ||

                          (/^[\w-]+(\.[\w-]+)+([/?#].*)?$/i.test(raw) && !raw.includes(' '));



    if (looksLikeUrl) {

      window.location.href = raw.startsWith('http') ? raw : ('https://' + raw);

    } else {

      window.location.href = 'https://www.google.com/search?q=' + encodeURIComponent(raw);

    }

  });



</script>

</body>

</html>

"""


def _session_thumbnail_data_uri(session_dir, max_size=(96, 64)):
    """Small base64 data: URI thumbnail from this session's own first

    captured screenshot, if any. A plain file:// <img src> would silently

    fail to load whenever the containing page is a real http(s) website

    (Chromium blocks local-file subresource loads from non-file:// pages)

    β€” the same class of problem Api._open_session_report() already works

    around for "View Report" links, and exactly what analysis.py's own

    _screenshot_data_uri() already sidesteps the same way for the report

    page itself. Resized + JPEG-recompressed and cached as screenshots/

    _thumb.jpg next to the full-resolution PNGs (leading underscore keeps

    it out of the shot_NNNN.png sequence analysis.py reads by exact

    filename, never a directory listing, so this can't confuse it) so a

    session list of many entries only pays the resize cost once, not on

    every single time My Sessions/Persons is opened."""
    screens_dir = os.path.join(session_dir, "screenshots")
    thumb_path = os.path.join(screens_dir, "_thumb.jpg")
    if not os.path.exists(thumb_path):
        if not os.path.isdir(screens_dir):
            return None
        shot_names = sorted(n for n in os.listdir(screens_dir) if n.lower().endswith(".png"))
        if not shot_names:
            return None
        try:
            img = Image.open(os.path.join(screens_dir, shot_names[0]))
            img.thumbnail(max_size)
            img.convert("RGB").save(thumb_path, format="JPEG", quality=60)
        except Exception:
            return None
    try:
        with open(thumb_path, "rb") as f:
            return "data:image/jpeg;base64," + base64.b64encode(f.read()).decode("ascii")
    except Exception:
        return None



def _drishti_sessions_json(root, limit=50, participant_id=None, participant_name=None):
    """Fast, read-only session index for the Drishti picker.



    Do NOT call the normal _sessions_json() here. That function intentionally

    performs report rebuilding, full gaze/DOM loading and screenshot thumbnail

    generation for the richer Profile -> Sessions UI. Doing that work inside a

    pywebview JS-API callback can exceed pywebview's 20-second loaded-event

    guard and makes the callback response fail with ``Main window failed to

    start`` even though the browser window itself is healthy.



    Drishti only needs stable session identity at picker time. Detailed

    evidence is loaded later by drishti_ai.answer() after a session is chosen.

    """
    import datetime as _dt

    entries = []
    if not os.path.isdir(root):
        return entries

    try:
        names = os.listdir(root)
    except Exception:
        return entries

    for name in names:
        full = os.path.join(root, name)
        if not os.path.isdir(full):
            continue
        try:
            ts = _dt.datetime.strptime(name, "%Y%m%d_%H%M%S")
        except ValueError:
            continue

        # Ignore folders that clearly are not completed sessions.
        # A report is preferred, but legacy/partial sessions are still allowed
        # into the picker because Drishti can explain that evidence is missing.
        report_path = os.path.join(full, "analysis_report.html")
        if not os.path.exists(report_path):
            # Keep the picker fast: no report regeneration here.
            continue

        custom_name = None
        stored_participant_id = None
        stored_participant_name = None
        try:
            with open(os.path.join(full, "session_meta.json"), "r", encoding="utf-8") as f:
                meta = json.load(f)
            custom_name = (meta.get("display_name") or "").strip() or None
            stored_participant_id = meta.get("participant_id") or None
            stored_participant_name = meta.get("participant_name") or None
        except Exception:
            pass

        if participant_id is not None and stored_participant_id != participant_id:
            continue

        row = {
            "id": name,
            "label": ts.strftime("%b %d, %Y β€” %I:%M %p").replace(" 0", " "),
            "customName": custom_name,
            "when": ts.strftime("%Y-%m-%d %H:%M"),
            "domain": None,
            "duration": None,
            "samples": None,
            "reportUrl": "file://" + report_path.replace(os.sep, "/"),
            # Same thumbnail My Sessions shows. Cheap: it reuses the cached
            # screenshots/_thumb.jpg, and only resizes one small image the
            # first time a session has none (no report rebuild, no log loading).
            "thumbnail": _session_thumbnail_data_uri(full),
            "participantId": stored_participant_id,
            "subjectName": stored_participant_name or participant_name,
        }
        entries.append((ts, row))

    entries.sort(key=lambda item: item[0], reverse=True)
    return [row for _, row in entries[:max(1, int(limit))]]

def _sessions_json(root, limit=25):
    """Read-only directory listing of sessions/<timestamp> folders under

    an explicitly-given root β€” the shared engine behind Profile -> My

    Sessions and (Three-dot) Persons -> a specific participant's history.

    Taking root as a parameter rather than always reading the global

    SESSIONS_ROOT is what lets both show the *right* folder regardless of

    whoever the Participant panel currently has selected. Never touches

    session contents or tracking state.



    Each entry is matched to its own already-generated analysis_report.html

    (written by generate_report() at session end, under that same session's

    folder β€” the existing session-id -> report mapping already used

    elsewhere) so "View Report" always opens THAT session's report, never

    just the most recent one. Duration/sample-count/domain reuse analysis.py's

    existing load_session()/session_summary() β€” same read-only computation

    the report itself already does, not a new data path."""
    import datetime as _dt
    from urllib.parse import urlparse

    entries = []
    if os.path.isdir(root):
        for name in os.listdir(root):
            full = os.path.join(root, name)
            if not os.path.isdir(full):
                continue
            try:
                ts = _dt.datetime.strptime(name, "%Y%m%d_%H%M%S")
            except ValueError:
                continue
            entries.append((ts, name, full))
    entries.sort(key=lambda triple: triple[0], reverse=True)

    out = []
    for ts, name, full in entries[:limit]:
        report_path = os.path.join(full, "analysis_report.html")
        if not os.path.exists(report_path):
            # A report can fail to build once (e.g. a transient issue right
            # as tracking stopped) even though the underlying session data
            # is completely intact β€” self-heal here instead of leaving that
            # session permanently unreachable. Reuses the exact same
            # generate_report() call gaze_worker() already makes at session
            # end; no new report-building logic.
            try:
                generate_report(full)
            except Exception as e:
                _log(f"[browser_session] could not (re)build report for {name}: {e}")
        report_url = None
        if os.path.exists(report_path):
            report_url = "file://" + report_path.replace(os.sep, "/")

        domain, duration, samples = None, None, None
        try:
            gaze, dom = load_session(full)
            summary = session_summary(gaze, dom)
            duration = summary["duration"] or None
            samples = summary["samples"] or None
            if summary["url"]:
                domain = urlparse(summary["url"]).netloc or summary["url"]
        except Exception:
            pass  # malformed/partial session folder β€” still list it, just without stats

        custom_name = None
        try:
            with open(os.path.join(full, "session_meta.json"), "r", encoding="utf-8") as f:
                custom_name = (json.load(f).get("display_name") or "").strip() or None
        except Exception:
            pass  # no session_meta.json (legacy session) or unreadable β€” no custom name

        thumbnail = _session_thumbnail_data_uri(full)

        out.append({
            "id": name,  # stable session identifier (its own timestamp folder name) β€” used to key rename/report calls, never shown directly
            "label": ts.strftime("%b %d, %Y β€” %I:%M %p").replace(" 0", " "),
            "customName": custom_name,
            "when": ts.strftime("%Y-%m-%d %H:%M"),
            "domain": domain,
            "duration": duration,
            "samples": samples,
            "reportUrl": report_url,
            "thumbnail": thumbnail,
        })
    return out


def _write_landing_page():
    path = os.path.join(FRONTEND_DIR, "insightux_landing.html")
    html = _LANDING_HTML
    html = html.replace("__THEME_CSS__", theme.THEME_CSS)
    html = html.replace("__THEME_JS__", theme.THEME_TOGGLE_JS)
    html = html.replace("__ICONS_JS__", theme.ICONS_JS)
    html = html.replace("__LOGO_ICON__", theme.icon("eye", 24))
    html = html.replace("__SEARCH_ICON__", theme.icon("search", 18))
    html = html.replace("__PLAY_ICON__", theme.icon("play", 13))
    html = html.replace("__STOP_ICON__", theme.icon("stop", 13))
    html = html.replace("__LAYERS_ICON__", theme.icon("layers", 13))
    html = html.replace("__CURSOR_ICON__", theme.icon("cursor", 13))
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    return "file://" + path.replace(os.sep, "/")


LANDING_URL = _write_landing_page()


# =============================================================================
# LOGIN / PROFILE PICKER β€” the window opens HERE, not on LANDING_URL, so a
# password is always required before any profile's data can be reached.
# No login state is persisted across app restarts.
# =============================================================================
_LOGIN_HTML = r"""<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="insightux-login" content="true">

<title>InsightUX β€” Sign in</title>

<style>

__THEME_CSS__

  * { box-sizing: border-box; }

  html, body { height: 100%; }

  body {

    margin: 0; display: flex; flex-direction: column;

    align-items: center; justify-content: center; gap: 20px;

    background: var(--iux-page-bg);

    font-family: var(--iux-font); color: var(--iux-text);

    transition: background 0.3s var(--iux-ease), color 0.3s var(--iux-ease);

    overflow: hidden;

    padding: 16px 0;

  }

  .theme-toggle { position: fixed; top: 20px; right: 22px; width: 38px; height: 38px; padding: 0; }

  .brand { text-align: center; }

  .logo-row { display: flex; align-items: center; justify-content: center; gap: 12px; }

  .logo-mark {

    width: 42px; height: 42px; border-radius: 13px; background: var(--iux-accent-grad);

    display: flex; align-items: center; justify-content: center; box-shadow: var(--iux-shadow-glow);

  }

  .logo-mark svg { color: var(--iux-on-accent); }

  .logo {

    font-size: 32px; font-weight: 700; letter-spacing: -0.02em;

    background: var(--iux-accent-grad);

    -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;

  }

  .tagline { color: var(--iux-text-dim); font-size: 13px; margin-top: 6px; }



  .auth-card { width: 380px; max-width: 90vw; padding: 22px; display: flex; flex-direction: column; gap: 14px; }

  .auth-tabs { display: flex; gap: 6px; background: var(--iux-surface-hi); padding: 3px; border-radius: 999px; }

  .auth-tab {

    flex: 1 1 auto; border: none; background: transparent; padding: 8px; border-radius: 999px;

    color: var(--iux-text-dim); font: 600 12.5px var(--iux-font); cursor: pointer;

  }

  .auth-tab.on { background: var(--iux-accent-grad); color: var(--iux-on-accent); }



  .profile-list { display: flex; flex-direction: column; gap: 6px; max-height: 260px; overflow-y: auto; }

  .profile-row {

    display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-radius: 10px;

    border: 1px solid var(--iux-border); cursor: pointer; transition: background .12s ease;

  }

  .profile-row:hover { background: var(--iux-surface-hi); }

  .profile-row .avatar {

    width: 32px; height: 32px; border-radius: 50%; flex-shrink: 0;

    background: var(--iux-accent-grad); color: var(--iux-on-accent);

    display: flex; align-items: center; justify-content: center; font: 700 13px var(--iux-font);

  }

  .profile-row .who { min-width: 0; flex: 1 1 auto; }

  .profile-row .name {

    font: 600 12.5px var(--iux-font); color: var(--iux-text);

    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;

  }

  .profile-row .email {

    font-size: 11px; color: var(--iux-text-faint);

    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;

  }



  .field { display: flex; flex-direction: column; gap: 5px; }

  .field label { font-size: 11px; color: var(--iux-text-faint); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }

  .field input {

    padding: 10px 12px; font-size: 13.5px; border-radius: 10px;

    border: 1.5px solid var(--iux-border); background: var(--iux-surface); color: var(--iux-text);

    outline: none; transition: border-color .15s var(--iux-ease), box-shadow .15s var(--iux-ease);

  }

  .field input:focus { border-color: var(--iux-primary-light); box-shadow: var(--iux-shadow-glow); }



  .auth-error {

    display: none; font-size: 12px; color: var(--iux-danger); background: rgba(251,113,133,0.1);

    border: 1px solid rgba(251,113,133,0.3); border-radius: 8px; padding: 8px 10px;

  }

  .auth-error.on { display: block; }



  .auth-submit {

    padding: 11px; border-radius: 10px; border: none; background: var(--iux-accent-grad);

    color: var(--iux-on-accent); font: 700 13px var(--iux-font); cursor: pointer;

    transition: transform .15s var(--iux-ease), box-shadow .15s var(--iux-ease);

  }

  .auth-submit:hover { box-shadow: var(--iux-shadow-glow); }

  .auth-submit:disabled { opacity: .6; cursor: default; }



  .auth-back { background: transparent; border: none; color: var(--iux-text-faint); font-size: 11.5px; cursor: pointer; text-align: left; padding: 0; }

  .auth-back:hover { color: var(--iux-text); }



  .auth-empty { font-size: 12px; color: var(--iux-text-faint); text-align: center; padding: 18px 0; }

  .auth-notice { max-width:90vw; padding:10px 14px; border:1px solid rgba(52,211,153,.4); border-radius:10px; background:rgba(52,211,153,.12); color:var(--iux-success); font:600 12px var(--iux-font); text-align:center; }

  .auth-hint { color: var(--iux-text-faint); font-size: 11px; text-align: center; max-width: 380px; }

</style>

</head>

<body>

  <button type="button" class="theme-toggle iux-btn" id="themeToggle" title="Toggle theme"></button>



  <div class="brand iux-fade-in">

    <div class="logo-row">

      <div class="logo-mark">__LOGO_ICON__</div>

      <div class="logo">InsightUX</div>

    </div>

    <div class="tagline">Sign in to your profile to continue</div>

  </div>



  <div class="auth-notice" id="authNotice" role="status" style="__PROFILE_NOTICE_STYLE__">Your profile and its associated data have been deleted.</div>



  <div class="auth-card iux-card iux-fade-in">

    <div class="auth-tabs">

      <button type="button" class="auth-tab on" id="tabLogin">Log in</button>

      <button type="button" class="auth-tab" id="tabCreate">Create profile</button>

    </div>



    <div id="loginPane">

      <div id="profileListWrap">

        <div class="profile-list" id="profileList"></div>

      </div>

      <div id="passwordWrap" style="display:none; flex-direction:column; gap:14px;">

        <button type="button" class="auth-back" id="backToList">&larr; Back to profiles</button>

        <div class="field">

          <label id="passwordForLabel">Password</label>

          <input id="loginPassword" type="password" autocomplete="current-password" placeholder="Enter your password">

        </div>

        <div class="auth-error" id="loginError"></div>

        <button type="button" class="auth-submit" id="loginSubmit">Log in</button>

      </div>

    </div>



    <div id="createPane" style="display:none; flex-direction:column; gap:14px;">

      <div class="field"><label>Name</label><input id="createName" type="text" autocomplete="name" placeholder="Your name"></div>

      <div class="field"><label>Email</label><input id="createEmail" type="email" autocomplete="email" placeholder="you@example.com"></div>

      <div class="field"><label>Password</label><input id="createPassword" type="password" autocomplete="new-password" placeholder="At least 6 characters"></div>

      <div class="auth-error" id="createError"></div>

      <button type="button" class="auth-submit" id="createSubmit">Create profile</button>

    </div>

  </div>



  <div class="auth-hint">Each profile's sessions, calibration, and reports are private to that profile β€” no other profile on this device can see them.</div>



<script>

__ICONS_JS__

__THEME_JS__



  document.getElementById('themeToggle').innerHTML = iuxIcon(window.insightuxGetTheme() === 'light' ? 'moon' : 'sun', 18);

  document.getElementById('themeToggle').addEventListener('click', function(){

    const next = window.insightuxToggleTheme();

    this.innerHTML = iuxIcon(next === 'light' ? 'moon' : 'sun', 18);

  });



  // profile name/email are free text from create_profile() β€” escape before

  // innerHTML so a crafted profile name can't run script on this page.

  function escapeHtml(str){

    return String(str).replace(/[&<>"']/g, function(c){

      return { '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c];

    });

  }



  const PROFILES = __PROFILES_JSON__;

  let selectedProfile = null;



  function renderProfiles(){

    const list = document.getElementById('profileList');

    if (!PROFILES.length) {

      list.innerHTML = '<div class="auth-empty">No profiles yet on this device β€” create one to get started.</div>';

      return;

    }

    list.innerHTML = PROFILES.map(function(p, i){

      return '<div class="profile-row" data-idx="' + i + '">' +

        '<span class="avatar">' + escapeHtml(p.avatar) + '</span>' +

        '<div class="who"><div class="name">' + escapeHtml(p.name) + '</div><div class="email">' + escapeHtml(p.email) + '</div></div>' +

      '</div>';

    }).join('');

    Array.from(list.children).forEach(function(row, i){

      row.addEventListener('click', function(){ selectProfile(PROFILES[i]); });

    });

  }

  renderProfiles();



  function selectProfile(p){

    selectedProfile = p;

    document.getElementById('profileListWrap').style.display = 'none';

    document.getElementById('passwordWrap').style.display = 'flex';

    document.getElementById('passwordForLabel').textContent = 'Password for ' + p.name;

    const pwInput = document.getElementById('loginPassword');

    pwInput.value = '';

    document.getElementById('loginError').classList.remove('on');

    pwInput.focus();

  }

  document.getElementById('backToList').addEventListener('click', function(){

    document.getElementById('passwordWrap').style.display = 'none';

    document.getElementById('profileListWrap').style.display = 'block';

    selectedProfile = null;

  });



  function showError(id, msg){

    const el = document.getElementById(id);

    el.textContent = msg;

    el.classList.add('on');

  }



  function doLogin(){

    if (!selectedProfile || !window.pywebview) return;

    const pw = document.getElementById('loginPassword').value;

    const btn = document.getElementById('loginSubmit');

    btn.disabled = true; btn.textContent = 'Signing in...';

    window.pywebview.api.login(selectedProfile.id, pw).then(function(res){

      if (!res || !res.ok) {

        btn.disabled = false; btn.textContent = 'Log in';

        showError('loginError', (res && res.error) || 'Could not sign in.');

      }

      // On success Python itself navigates the window -- nothing else to do here.

    });

  }

  document.getElementById('loginSubmit').addEventListener('click', doLogin);

  document.getElementById('loginPassword').addEventListener('keydown', function(e){ if (e.key === 'Enter') doLogin(); });



  function doCreate(){

    if (!window.pywebview) return;

    const name = document.getElementById('createName').value.trim();

    const email = document.getElementById('createEmail').value.trim();

    const pw = document.getElementById('createPassword').value;

    const btn = document.getElementById('createSubmit');

    btn.disabled = true; btn.textContent = 'Creating...';

    window.pywebview.api.create_profile(name, email, pw).then(function(res){

      if (!res || !res.ok) {

        btn.disabled = false; btn.textContent = 'Create profile';

        showError('createError', (res && res.error) || 'Could not create profile.');

      }

    });

  }

  document.getElementById('createSubmit').addEventListener('click', doCreate);



  function showTab(which){

    const login = which === 'login';

    document.getElementById('tabLogin').classList.toggle('on', login);

    document.getElementById('tabCreate').classList.toggle('on', !login);

    document.getElementById('loginPane').style.display = login ? 'block' : 'none';

    document.getElementById('createPane').style.display = login ? 'none' : 'flex';

  }

  document.getElementById('tabLogin').addEventListener('click', function(){ showTab('login'); });

  document.getElementById('tabCreate').addEventListener('click', function(){ showTab('create'); });

  if (!PROFILES.length) showTab('create');

</script>

</body>

</html>

"""


def _write_login_page(profile_deleted=False):
    path = os.path.join(FRONTEND_DIR, "insightux_login.html")
    html = _LOGIN_HTML
    html = html.replace("__THEME_CSS__", theme.THEME_CSS)
    html = html.replace("__THEME_JS__", theme.THEME_TOGGLE_JS)
    html = html.replace("__ICONS_JS__", theme.ICONS_JS)
    html = html.replace("__LOGO_ICON__", theme.icon("eye", 20))
    html = html.replace("__PROFILES_JSON__", json.dumps(auth.list_profiles(DATA_DIR)))
    html = html.replace(
        "__PROFILE_NOTICE_STYLE__",
        "display:block;" if profile_deleted else "display:none;",
    )
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    return "file://" + path.replace(os.sep, "/")


LOGIN_URL = _write_login_page()


def normalize_pose(pitch_deg, yaw_deg, roll_deg):
    return np.array([
        pitch_deg / POSE_NORM_SCALE,
        yaw_deg   / POSE_NORM_SCALE,
        roll_deg  / POSE_NORM_SCALE,
    ], dtype=np.float32)

def compensate_pitch(raw_pitch, head_pitch_deg):
    return raw_pitch - np.radians(head_pitch_deg) * HEAD_PITCH_COMPENSATION

def compensate_yaw(raw_yaw, head_yaw_deg):
    return raw_yaw - np.radians(head_yaw_deg) * HEAD_YAW_COMPENSATION


# =============================================================================
# ONE EURO FILTER (display smoothing only)
# =============================================================================

class OneEuroFilter:
    def __init__(self, mincutoff=0.8, beta=0.4, dcutoff=1.0):
        self.mincutoff = mincutoff
        self.beta = beta
        self.dcutoff = dcutoff
        self.x_prev = None
        self.dx_prev = 0.0
        self.t_prev = None

    @staticmethod
    def _alpha(cutoff, dt):
        tau = 1.0 / (2 * math.pi * cutoff)
        return 1.0 / (1.0 + tau / dt)

    def __call__(self, x, t):
        if self.x_prev is None:
            self.x_prev, self.t_prev = x, t
            return x
        dt = t - self.t_prev
        if dt <= 0:
            dt = 1e-3
        self.t_prev = t
        dx = (x - self.x_prev) / dt
        a_d = self._alpha(self.dcutoff, dt)
        dx_hat = a_d * dx + (1 - a_d) * self.dx_prev
        cutoff = self.mincutoff + self.beta * abs(dx_hat)
        a = self._alpha(cutoff, dt)
        x_hat = a * x + (1 - a) * self.x_prev
        self.x_prev, self.dx_prev = x_hat, dx_hat
        return x_hat

    def reset(self):
        self.x_prev = None
        self.dx_prev = 0.0
        self.t_prev = None


# =============================================================================
# JS: browser chrome (always present) β€” top toolbar (back/forward/reload/
# home/address bar) + left sidebar (Calibrate/Validate/Start Session), so the
# window reads as a normal browser instead of a bare content pane. Purely an
# HTML/CSS/JS overlay drawn on top of whatever page is loaded β€” pywebview
# 4.4.1 has no native toolbar API, so this is the only way to add persistent
# chrome without switching GUI frameworks.
#
# The page itself is pushed down/right by exactly the toolbar height and
# sidebar width (via forced <body> padding, not just floating the chrome on
# top of it) so real page content is never hidden underneath β€” the chrome
# and the website occupy clearly separate regions instead of overlapping.
# overflow-x is force-hidden as a safety net against the small width
# reduction ever introducing a horizontal scrollbar. The one edge case this
# can't fully solve: a small minority of sites use position:fixed elements
# of their own pinned to the true viewport edges (independent of body
# padding) β€” those can still end up visually behind our chrome.
# =============================================================================

CHROME_JS = r"""

(function(){

  if (window.__insightuxControl) { return; }

  window.__insightuxControl = true;



  // Required as the trailing argument on every state-changing/private

  // window.pywebview.api call below (see _require_token in browser_session.py

  // for the full reasoning). A plain closure-local const, deliberately never

  // assigned to `window` β€” pywebview exposes window.pywebview.api to every

  // page's own script, not just this injected one, so a hostile website

  // could otherwise call start_tracking()/delete_my_session()/quit_app()

  // etc. directly. Because this is a normal JS closure variable, a page's

  // own top-level script has no way to read it back out β€” only code that

  // was actually part of THIS script (baked in by Python at injection

  // time) can produce a valid call.

  const __IUX_TOK__ = "__API_TOKEN__";



  // S/E (start/stop tracking) only make sense on an actual website β€” not on

  // the InsightUX landing/search page and not on a generated insights

  // report page. The toolbar/sidebar, and X (quit), always work everywhere

  // except the login page, which has no user/session context yet.

  const isLanding   = !!document.querySelector('meta[name="insightux-landing"]');

  const __reportPathMatch = decodeURIComponent(location.pathname || '').match(/(\d{8}_\d{6})[\\/]analysis_report\.html$/);

  const isReport    = !!document.querySelector('meta[name="insightux-report"]') || !!__reportPathMatch ||

                      /analysis_report\.html$/i.test(decodeURIComponent(location.pathname || ''));

  const isLogin     = !!document.querySelector('meta[name="insightux-login"]');

  const isTrackable = !isLanding && !isReport && !isLogin;

  let isTrackingNow = false;



__ICONS_JS__

__THEME_JS__



  // ---------------------------------------------------------------------------

  // Drishti shared helpers (used by BOTH the in-page Drishti modal and the

  // report-page "Ask Drishti AI" overlay): Markdown rendering for answers and

  // image attachment (button / paste / drag-drop).

  //

  // Answers used to be inserted with textContent, so raw "### " and "**" showed

  // up, and in the report overlay newlines collapsed. They are now rendered

  // from Markdown identically whether the answer is live or reloaded from the

  // saved conversation.

  // ---------------------------------------------------------------------------

  (function(){

    if (document.getElementById('__iux_md_css')) return;

    const st = document.createElement('style');

    st.id = '__iux_md_css';

    st.textContent = [

      '.iux-md{white-space:normal !important;word-wrap:break-word;overflow-wrap:anywhere;line-height:1.62;}',

      '.iux-md>*:first-child{margin-top:0 !important;}.iux-md>*:last-child{margin-bottom:0 !important;}',

      '.iux-md p{margin:0 0 8px;}',

      '.iux-md h4.iux-md-h{margin:13px 0 6px;font-size:13.5px;font-weight:800;letter-spacing:-.005em;line-height:1.35;}',

      '.iux-md ul,.iux-md ol{margin:4px 0 9px;padding-left:20px;}',

      '.iux-md li{margin:3px 0;padding-left:2px;}',

      '.iux-md li>ul,.iux-md li>ol{margin:3px 0 3px;}',

      '.iux-md hr{border:0;border-top:1px solid rgba(128,128,128,.30);margin:11px 0;}',

      '.iux-md strong{font-weight:700;}',

      '.iux-md code{font:11.5px ui-monospace,Consolas,monospace;background:rgba(128,128,128,.16);padding:1px 5px;border-radius:5px;}',

      '.iux-md pre{background:rgba(128,128,128,.14);padding:9px 11px;border-radius:9px;overflow:auto;margin:7px 0;}',

      '.iux-md pre code{background:none;padding:0;}',

      '.iux-md table{border-collapse:collapse;margin:7px 0;font-size:12px;display:block;overflow:auto;max-width:100%;}',

      '.iux-md th,.iux-md td{border:1px solid rgba(128,128,128,.32);padding:5px 8px;text-align:left;vertical-align:top;}',

      '.iux-md th{background:rgba(128,128,128,.12);font-weight:700;}',

      '.iux-md blockquote{margin:7px 0;padding:2px 11px;border-left:3px solid rgba(128,128,128,.42);opacity:.92;}',

      '.iux-md-regions{margin-top:10px;padding-top:7px;border-top:1px dashed rgba(128,128,128,.32);font-size:11px;opacity:.78;}',

      '.iux-msg-img{display:block;max-width:240px;max-height:170px;border-radius:9px;margin:0 0 7px;border:1px solid rgba(128,128,128,.35);background:#fff;object-fit:contain;}',

      '.iux-msg-imgs{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 7px;}',

      '.iux-msg-imgs .iux-msg-img{margin:0;max-width:190px;max-height:130px;}',

      '.iux-att-btn{width:44px;height:44px;padding:0;border:1px solid rgba(128,128,128,.38);border-radius:11px;background:transparent;color:inherit;cursor:pointer;display:grid;place-items:center;flex-shrink:0;}',

      '.iux-att-btn:hover{background:rgba(128,128,128,.14);}.iux-att-btn:disabled{opacity:.5;cursor:default;}',

      '.iux-att-preview{display:none;align-items:center;flex-wrap:wrap;gap:8px 10px;padding:8px 12px;border-top:1px solid rgba(128,128,128,.25);font-size:11.5px;max-height:122px;overflow:auto;}',

      '.iux-att-chip{position:relative;display:inline-block;flex:0 0 auto;}',

      '.iux-att-chip img{display:block;height:52px;max-width:120px;object-fit:cover;border-radius:7px;border:1px solid rgba(128,128,128,.4);background:#fff;}',

      '.iux-att-chip .iux-att-x{position:absolute;top:-6px;right:-6px;width:18px;height:18px;border-radius:50%;border:1px solid rgba(128,128,128,.55);background:#2b2723;color:#fff;cursor:pointer;padding:0;display:grid;place-items:center;line-height:1;}',

      '.iux-att-preview .iux-att-name{flex:1;min-width:120px;opacity:.85;}',

      '.iux-att-drop{outline:2px dashed rgba(233,173,0,.9);outline-offset:-6px;}'

    ].join('\n');

    (document.head || document.documentElement).appendChild(st);

  })();



  function iuxMdEsc(v){

    return String(v == null ? '' : v).replace(/[&<>"']/g, function(c){

      return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];

    });

  }

  function iuxMdInline(raw){

    let s = iuxMdEsc(raw);

    s = s.replace(/`([^`]+)`/g, '<code>$1</code>');

    s = s.replace(/\*\*([^*]+?)\*\*/g, '<strong>$1</strong>');

    s = s.replace(/__([^_]+?)__/g, '<strong>$1</strong>');

    s = s.replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?![*\w])/g, '$1<em>$2</em>');

    return s;

  }

  function iuxMd(text){

    let t = String(text == null ? '' : text).replace(/\r\n?/g, '\n');

    // Some answers arrive flattened onto one line ("### A * **x** --- ### B").

    // Re-break the obvious markers so they render as structure, not as noise.

    if (t.split('\n').length < 3 && t.length > 120) {

      t = t.replace(/([^\n#])\s+(#{2,4}\s)/g, '$1\n\n$2')

           .replace(/\s+---\s+/g, '\n\n---\n\n')

           .replace(/(#{2,4}\s[^\n*]*?)\s+\*\s+(?=\*\*)/g, '$1\n* ')

           .replace(/\s+\*\s+(?=\*\*)/g, '\n* ')

           .replace(/\s+(\d{1,2})\.\s+(?=\*\*)/g, '\n$1. ')

           .replace(/(#{2,4}\s(?:Measured Facts|Facts|Interpretation|Recommendations?|Summary|Diagnosis|Evidence|Verdict|Next Steps|How to Verify))\s+(?=\S)/gi, '$1\n\n');

    }

    const lines = t.split('\n');

    const html = [];

    let para = [], inCode = false, code = [];

    const stack = [];                       // open lists: {type, indent}

    function flushPara(){

      if (para.length) { html.push('<p>' + para.map(iuxMdInline).join('<br>') + '</p>'); para = []; }

    }

    function closeLists(toIndent){

      while (stack.length && stack[stack.length - 1].indent >= toIndent) {

        html.push('</li></' + stack.pop().type + '>');

      }

    }

    function splitRow(line){

      return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(function(c){ return c.trim(); });

    }

    for (let i = 0; i < lines.length; i++) {

      const line = lines[i];

      if (/^\s*```/.test(line)) {

        if (inCode) { html.push('<pre><code>' + iuxMdEsc(code.join('\n')) + '</code></pre>'); code = []; inCode = false; }

        else { flushPara(); closeLists(0); inCode = true; }

        continue;

      }

      if (inCode) { code.push(line); continue; }

      if (!line.trim()) { flushPara(); continue; }



      let m = line.match(/^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/);

      if (m) { flushPara(); closeLists(0); html.push('<h4 class="iux-md-h">' + iuxMdInline(m[2]) + '</h4>'); continue; }

      if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) { flushPara(); closeLists(0); html.push('<hr>'); continue; }



      if (line.indexOf('|') !== -1 && i + 1 < lines.length &&

          /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(lines[i + 1])) {

        flushPara(); closeLists(0);

        const head = splitRow(line);

        let j = i + 2, rows = [];

        while (j < lines.length && lines[j].indexOf('|') !== -1 && lines[j].trim()) { rows.push(splitRow(lines[j])); j++; }

        html.push('<table><thead><tr>' + head.map(function(c){ return '<th>' + iuxMdInline(c) + '</th>'; }).join('') +

          '</tr></thead><tbody>' + rows.map(function(r){

            return '<tr>' + r.map(function(c){ return '<td>' + iuxMdInline(c) + '</td>'; }).join('') + '</tr>';

          }).join('') + '</tbody></table>');

        i = j - 1;

        continue;

      }

      m = line.match(/^\s*>\s?(.*)$/);

      if (m) { flushPara(); closeLists(0); html.push('<blockquote>' + iuxMdInline(m[1]) + '</blockquote>'); continue; }



      m = line.match(/^(\s*)([-*\u2022]|\d{1,3}[.)])\s+(.*)$/);

      if (m) {

        flushPara();

        const indent = m[1].replace(/\t/g, '    ').length;

        const type = /\d/.test(m[2]) ? 'ol' : 'ul';

        const top = stack[stack.length - 1];

        if (!top || indent > top.indent) {

          const start = (type === 'ol' && parseInt(m[2], 10) > 1) ? ' start="' + parseInt(m[2], 10) + '"' : '';

          html.push('<' + type + start + '><li>');

          stack.push({ type: type, indent: indent });

        } else {

          while (stack.length && stack[stack.length - 1].indent > indent) html.push('</li></' + stack.pop().type + '>');

          const cur = stack[stack.length - 1];

          if (cur && cur.type !== type) {

            html.push('</li></' + stack.pop().type + '>');

            html.push('<' + type + '><li>'); stack.push({ type: type, indent: indent });

          } else if (cur) {

            html.push('</li><li>');

          } else {

            html.push('<' + type + '><li>'); stack.push({ type: type, indent: indent });

          }

        }

        html.push(iuxMdInline(m[3]));

        continue;

      }

      // continuation line of a list item (indented prose) stays inside the item

      if (stack.length && /^\s{2,}\S/.test(line)) { html.push('<br>' + iuxMdInline(line.trim())); continue; }

      closeLists(0);

      para.push(line.trim());

    }

    if (inCode) html.push('<pre><code>' + iuxMdEsc(code.join('\n')) + '</code></pre>');

    flushPara(); closeLists(0);

    return html.join('');

  }

  function iuxRegionCaption(msg){

    if (!msg || !msg.regions || !msg.regions.length) return '';

    const how = msg.region_source === 'image' ? 'matched from your picture'

              : msg.region_source === 'both' ? 'matched from your text and picture' : 'matched from your text';

    return '<div class="iux-md-regions">Region analysed: <strong>' +

      msg.regions.map(iuxMdEsc).join(', ') + '</strong> \u00b7 ' + how + '</div>';

  }



  // Read a picked/pasted/dropped image, shrink it, return a data: URL.

  function iuxReadImage(file){

    return new Promise(function(resolve, reject){

      const okType = /^image\/(png|jpe?g|webp)$/i.test(file.type || '');

      if (!okType) { reject(new Error('Attach a PNG, JPEG or WebP image.')); return; }

      if (file.size > 12 * 1024 * 1024) { reject(new Error('That image is larger than 12 MB.')); return; }

      const fr = new FileReader();

      fr.onerror = function(){ reject(new Error('The image could not be read.')); };

      fr.onload = function(){

        const img = new Image();

        img.onerror = function(){ reject(new Error('The image could not be opened.')); };

        img.onload = function(){

          const MAX = 1600;

          const k = Math.min(1, MAX / Math.max(img.naturalWidth, img.naturalHeight));

          const w = Math.max(1, Math.round(img.naturalWidth * k)), h = Math.max(1, Math.round(img.naturalHeight * k));

          const cv = document.createElement('canvas'); cv.width = w; cv.height = h;

          const cx = cv.getContext('2d'); cx.fillStyle = '#fff'; cx.fillRect(0, 0, w, h); cx.drawImage(img, 0, 0, w, h);

          let out = cv.toDataURL('image/png');

          if (out.length > 4000000) out = cv.toDataURL('image/jpeg', 0.9);

          resolve(out);

        };

        img.src = fr.result;

      };

      fr.readAsDataURL(file);

    });

  }

  // Adds an attach button + preview chips + paste + drag/drop to a chat composer.

  // Holds SEVERAL pictures (up to IUX_MAX_ATTACH). A picture stays here until the

  // researcher removes it or sends the message; sending clears them at once.

  const IUX_MAX_ATTACH = 6;

  function iuxAttachInit(o){

    const state = { items: [] };            // [{dataUrl, name}]

    const fileIn = document.createElement('input');

    fileIn.type = 'file'; fileIn.accept = 'image/png,image/jpeg,image/webp'; fileIn.multiple = true; fileIn.style.display = 'none';

    const btn = document.createElement('button');

    btn.type = 'button'; btn.className = 'iux-att-btn';

    btn.title = 'Attach pictures of the regions you want analysed (you can also paste or drop several)';

    btn.innerHTML = iuxIcon('image', 16);

    o.composeRow.insertBefore(btn, o.composeRow.firstChild);

    o.composeRow.appendChild(fileIn);

    function render(quiet){

      const host = o.previewHost;

      host.innerHTML = '';

      if (!quiet && o.onChange) { try { o.onChange(); } catch (_) {} }

      if (!state.items.length) { host.style.display = 'none'; return; }

      host.style.display = 'flex';

      state.items.forEach(function(it, idx){

        const chip = document.createElement('span'); chip.className = 'iux-att-chip';

        const im = document.createElement('img'); im.src = it.dataUrl; im.alt = ''; im.title = it.name || 'Attached picture';

        const rm = document.createElement('button'); rm.type = 'button'; rm.className = 'iux-att-x'; rm.title = 'Remove this picture'; rm.innerHTML = iuxIcon('x', 9);

        rm.onclick = function(){ state.items.splice(idx, 1); render(); };

        chip.appendChild(im); chip.appendChild(rm); host.appendChild(chip);

      });

      const nm = document.createElement('span'); nm.className = 'iux-att-name';

      nm.textContent = state.items.length === 1 ? 'Drishti will analyse this region' : state.items.length + ' pictures \u2014 Drishti will analyse each region';

      host.appendChild(nm);

    }

    function addFiles(files){

      const list = Array.prototype.slice.call(files || []).filter(function(f){ return f && /^image\//.test(f.type || ''); });

      if (!list.length) return;

      const room = IUX_MAX_ATTACH - state.items.length;

      if (room <= 0) { if (o.onError) o.onError('You can attach up to ' + IUX_MAX_ATTACH + ' pictures per message.'); return; }

      if (list.length > room && o.onError) o.onError('Only ' + IUX_MAX_ATTACH + ' pictures can be attached per message; the extra ones were skipped.');

      Promise.all(list.slice(0, room).map(function(f){

        return iuxReadImage(f).then(function(du){ return { dataUrl: du, name: f.name || 'Pasted picture' }; })

          .catch(function(e){ if (o.onError) o.onError(e.message || 'Could not attach that image.'); return null; });

      })).then(function(got){

        got.forEach(function(it){ if (it && state.items.length < IUX_MAX_ATTACH) state.items.push(it); });

        render();

      });

    }

    btn.onclick = function(){ fileIn.click(); };

    fileIn.onchange = function(){ addFiles(fileIn.files); fileIn.value = ''; };

    o.textarea.addEventListener('paste', function(e){

      const items = (e.clipboardData && e.clipboardData.items) || [];

      const files = [];

      for (let i = 0; i < items.length; i++) {

        if (items[i].kind === 'file' && /^image\//.test(items[i].type)) { const f = items[i].getAsFile(); if (f) files.push(f); }

      }

      if (files.length) { e.preventDefault(); addFiles(files); }

    });

    const dz = o.dropTarget || o.composeRow;

    dz.addEventListener('dragover', function(e){ e.preventDefault(); dz.classList.add('iux-att-drop'); });

    dz.addEventListener('dragleave', function(){ dz.classList.remove('iux-att-drop'); });

    dz.addEventListener('drop', function(e){

      e.preventDefault(); dz.classList.remove('iux-att-drop');

      if (e.dataTransfer && e.dataTransfer.files) addFiles(e.dataTransfer.files);

    });

    return {

      // array of data: URLs (empty array when nothing is attached)

      get: function(){ return state.items.map(function(it){ return it.dataUrl; }); },

      getState: function(){ return { items: state.items.map(function(it){ return { dataUrl: it.dataUrl, name: it.name }; }) }; },

      // accepts {items:[...]} or the legacy single {dataUrl,name}

      setState: function(st){

        let items = [];

        if (st && Array.isArray(st.items)) items = st.items.filter(function(it){ return it && it.dataUrl; });

        else if (st && st.dataUrl) items = [{ dataUrl: st.dataUrl, name: st.name || '' }];

        state.items = items.slice(0, IUX_MAX_ATTACH).map(function(it){ return { dataUrl: it.dataUrl, name: it.name || '' }; });

        render(true);

      },

      clear: function(){ state.items = []; render(); },

      setDisabled: function(b){ btn.disabled = !!b; }

    };

  }

  // Thumbnails of one chat message, whether it came from a live send ({attachments})

  // or from a saved conversation (attachments[], or the older single attachment).

  function iuxMsgThumbs(meta){

    if (!meta) return [];

    if (Array.isArray(meta.attachments)) return meta.attachments.map(function(a){ return a && a.thumb; }).filter(Boolean);

    if (meta.attachment && meta.attachment.thumb) return [meta.attachment.thumb];

    return [];

  }

  function iuxThumbsEl(meta){

    const th = iuxMsgThumbs(meta);

    if (!th.length) return null;

    const box = document.createElement('div'); box.className = 'iux-msg-imgs';

    th.forEach(function(u){ const im = document.createElement('img'); im.className = 'iux-msg-img'; im.src = u; im.alt = 'Attached region'; box.appendChild(im); });

    return box;

  }

  // live-send helper: array of data URLs -> message meta

  function iuxLiveMeta(urls){ return (urls && urls.length) ? { attachments: urls.map(function(u){ return { thumb: u }; }) } : null; }



  // ---- Drishti drafts: whatever the researcher has typed (and any attached

  // picture) stays put until they send it or delete it themselves. The text

  // is mirrored to memory on every keystroke (instant, survives closing the

  // chat or switching session) and to the conversation file shortly after

  // (survives navigating to another page or restarting the app). ----

  const iuxDraftMem = {};

  let iuxActiveDraft = null;

  // ---- Drishti in-flight requests. A question stays visible (and its answer

  // still lands) even if the chat window is closed, re-opened or switched to

  // another session while Drishti is still thinking. Keyed by conversation id.

  //   rec = { status:'pending'|'failed', text, shownText, att, baseCount, firstTurn, ui, error }

  // `ui` is the CURRENTLY displayed view of that conversation (or null); it is

  // swapped every time a view is (re)built, so a closed/rebuilt view never

  // receives the result. With no live view, a success needs no UI at all (the

  // answer is already saved server-side and loads on next open) and a failure

  // is kept so the next open can show it and give the text back.

  const iuxInflight = {};

  function iuxAnyInflight(){ return Object.keys(iuxInflight).some(function(k){ return iuxInflight[k].status === 'pending'; }); }

  function iuxInflightSettle(convId, rec, ok, payload){

    if (iuxInflight[convId] !== rec) return;

    const live = !!(rec.ui && rec.ui.live && rec.ui.live());

    if (ok) {

      delete iuxInflight[convId];

      delete iuxDraftMem[convId];

      if (live) rec.ui.onDone(payload);

      return;

    }

    // failed: the message was never saved, so hand the text (and picture) back as a draft

    iuxDraftMem[convId] = { text: rec.text, goal: undefined, att: (rec.att && rec.att.length) ? { items: rec.att.map(function(u){ return { dataUrl: u, name: '' }; }) } : null };

    if (live) { delete iuxInflight[convId]; rec.ui.onFail(payload); }

    else { rec.status = 'failed'; rec.error = payload; rec.ui = null; }

  }

  function iuxDraftBinder(o){

    let timer = null;

    function ctx(){ return o.getCtx(); }

    function remember(){

      const c = ctx(); if (!c || !c.conv) return null;

      const entry = { text: o.input.value, goal: o.goalInput ? o.goalInput.value : '', att: o.att ? o.att.getState() : null };

      iuxDraftMem[c.conv.conversation_id] = entry;

      return { c: c, entry: entry };

    }

    function persist(){

      const r = remember(); if (!r) return;

      try {

        window.pywebview.api.set_drishti_draft(r.c.sessionId, r.c.participantId || null, r.c.conv.conversation_id, r.entry.text, r.entry.goal, __IUX_TOK__);

      } catch (_) {}

    }

    function touch(){ remember(); clearTimeout(timer); timer = setTimeout(persist, 400); }

    o.input.addEventListener('input', touch);

    if (o.goalInput) o.goalInput.addEventListener('input', touch);

    const binder = {

      touch: touch,

      cancel: function(){ clearTimeout(timer); },

      flush: function(){ clearTimeout(timer); persist(); },

      // Called once the message really went out: the draft is no longer a draft.

      discard: function(){ clearTimeout(timer); const c = ctx(); if (c && c.conv) delete iuxDraftMem[c.conv.conversation_id]; },

      restore: function(){

        const c = ctx(); if (!c || !c.conv) return;

        const mem = iuxDraftMem[c.conv.conversation_id];

        const disk = c.conv.draft;

        const d = mem || (disk ? { text: disk.text || '', goal: disk.goal, att: null } : null);

        if (!d) return;

        o.input.value = d.text || '';

        if (o.goalInput && typeof d.goal === 'string' && (d.text || d.goal)) o.goalInput.value = d.goal;

        if (o.att && d.att && ((d.att.items && d.att.items.length) || d.att.dataUrl)) o.att.setState(d.att);

      }

    };

    iuxActiveDraft = binder;

    return binder;

  }

  window.addEventListener('pagehide', function(){ try { if (iuxActiveDraft) iuxActiveDraft.flush(); } catch (_) {} });

  window.addEventListener('beforeunload', function(){ try { if (iuxActiveDraft) iuxActiveDraft.flush(); } catch (_) {} });



  // The report page (isReport) and the login page (isLogin) get none of

  // this injected chrome β€” no toolbar, no sidebar, no reserved body

  // padding β€” so each has the full window to itself. Only X-quit (further

  // down, outside this guard) still works there, same as before.

  if (!isReport && !isLogin) {



  const style = document.createElement('style');

  style.textContent = `

__THEME_CSS__

    html { overflow-x: hidden !important; }

    body {

      box-sizing: border-box !important;

      width: 100vw !important;

      margin: 0 !important;

      padding-top: 54px !important;

      padding-left: 78px !important;

      overflow-x: hidden !important;

    }

    #__insightux_toolbar.chrome-hidden { transform: translateY(-130%); }

    #__insightux_sidebar.chrome-hidden { transform: translateX(-130%); }

    #__insightux_toolbar {

      position:fixed; top:0; left:0; right:0; height:54px; z-index:2147483647;

      display:flex; align-items:center; gap:8px; padding:0 14px; box-sizing:border-box;

      font:12px var(--iux-font); color:var(--iux-text);

      border-bottom:1px solid var(--iux-border);

      transition: transform .25s var(--iux-ease);

    }

    #__insightux_toolbar .iux-navbtn {

      flex:0 0 auto; width:32px; height:32px; border-radius:10px; padding:0;

    }

    /* Tracking mode: shrink the toolbar down to status pills + a small

       "reveal" handle so the tracked page gets the screen back, without

       ever removing the controls β€” __iux_reveal_toggle brings them back. */

    #__insightux_toolbar.tracking-compact { height:38px; gap:6px; padding:0 10px; }

    #__insightux_toolbar.tracking-compact .iux-navbtn,

    #__insightux_toolbar.tracking-compact #__iux_addr_wrap,

    #__insightux_toolbar.tracking-compact #__insightux_update,

    #__insightux_toolbar.tracking-compact #__insightux_status { display:none; }

    #__insightux_toolbar.tracking-compact #__iux_reveal_toggle { display:flex !important; }

    body.iux-tracking-compact { padding-top:38px !important; }

    #__iux_addr_wrap {

      flex:1 1 auto; min-width:0; position:relative; display:flex; align-items:center;

    }

    #__iux_addr_wrap .lead-icon { position:absolute; left:12px; color:var(--iux-text-faint); pointer-events:none; display:flex; }

    #__iux_addr_form { flex:1 1 auto; min-width:0; }

    #__iux_addr {

      width:100%; box-sizing:border-box; padding:8px 14px 8px 36px; border-radius:999px;

      border:1.5px solid var(--iux-border); background:var(--iux-surface); color:var(--iux-text); outline:none;

      font-size:12.5px; transition:border-color .15s var(--iux-ease), box-shadow .15s var(--iux-ease);

    }

    #__iux_addr:focus { border-color:var(--iux-primary-light); box-shadow:var(--iux-shadow-glow); }

    #__iux_loadbar {

      position:fixed; top:0; left:0; height:2px; width:0; z-index:2147483647;

      background:var(--iux-accent-grad); transition:width .5s var(--iux-ease), opacity .3s ease .25s; opacity:0;

    }

    #__insightux_indicators { display:flex; align-items:center; gap:6px; flex:0 0 auto; }

    #__insightux_status.iux-pill { max-width:26vw; }

    #__insightux_status .txt { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

    #__iux_microlink_usage { flex:0 0 auto; white-space:nowrap; }

    #__iux_microlink_usage .txt { white-space:nowrap; }

    #__iux_theme_toggle { flex:0 0 auto; }



    #__insightux_sidebar {

      position:fixed; top:66px; left:12px; bottom:12px; width:66px; z-index:2147483647;

      display:flex; flex-direction:column; align-items:stretch; gap:8px; padding:12px 8px;

      box-sizing:border-box; font:11px var(--iux-font);

      border-radius:var(--iux-radius-lg);

      transition:width .2s var(--iux-ease), transform .25s var(--iux-ease);

    }

    #__insightux_sidebar.collapsed { width:56px; }

    #__insightux_sidebar .side-btn {

      position:relative; flex-direction:column; gap:4px; padding:11px 4px; line-height:1.35;

      font-size:10.5px; width:100%;

    }

    #__insightux_sidebar .side-btn.active {

      background:var(--iux-accent-grad); border-color:transparent; color:var(--iux-on-accent); box-shadow:var(--iux-shadow-glow);

    }

    #__insightux_sidebar.collapsed .side-btn .lbl { display:none; }

    #__insightux_sidebar .side-btn .tip {

      position:absolute; left:100%; top:50%; transform:translateY(-50%) translateX(8px);

      background:var(--iux-surface-hi); color:var(--iux-text); border:1px solid var(--iux-border);

      padding:5px 10px; border-radius:8px; font-size:11px; white-space:nowrap; pointer-events:none;

      opacity:0; transition:opacity .15s ease; box-shadow:var(--iux-shadow-sm);

    }

    #__insightux_sidebar.collapsed .side-btn:hover .tip { opacity:1; }

    #__insightux_sidebar .spacer { margin-top:auto; }

    #__insightux_sidebar .hints {

      color:var(--iux-text-faint); font-size:9px; line-height:1.7; text-align:center; padding:2px 0;

    }

    #__insightux_sidebar.collapsed .hints { display:none; }

    #__iux_collapse_btn { width:100%; }



    #__iux_settings_pop {

      position:absolute; left:100%; bottom:0; margin-left:10px; width:220px; padding:14px;

      display:none; z-index:2147483647; border-radius:var(--iux-radius);

    }

    #__iux_settings_pop.open { display:block; }

    #__iux_settings_pop h4 { margin:0 0 10px; font-size:12px; color:var(--iux-text); }

    #__iux_settings_pop .row { display:flex; align-items:center; justify-content:space-between; margin-bottom:8px; font-size:11.5px; color:var(--iux-text-dim); }

    #__iux_settings_pop .kbd-row { display:flex; justify-content:space-between; font-size:11px; color:var(--iux-text-faint); padding:3px 0; }

    #__iux_settings_pop .ver { margin-top:8px; font-size:10px; color:var(--iux-text-faint); text-align:center; }



    #__iux_participant_pop {

      position:absolute; left:100%; bottom:0; margin-left:10px; width:250px; padding:14px;

      display:none; z-index:2147483647; border-radius:var(--iux-radius);

      max-height:min(420px, 80vh); overflow-y:auto;

    }

    #__iux_participant_pop.open { display:block; }

    #__iux_participant_pop h4 { margin:0 0 8px; font-size:12px; color:var(--iux-text); }

    .iux-subject-list { display:flex; flex-direction:column; gap:2px; margin-bottom:2px; }

    .iux-subject-row {

      display:flex; align-items:center; gap:9px; padding:7px 8px; border-radius:8px; cursor:pointer;

      font-size:12px; color:var(--iux-text-dim); transition:background .12s ease, color .12s ease;

    }

    .iux-subject-row:hover { background:var(--iux-surface-hi); }

    .iux-subject-row.on { color:var(--iux-text); font-weight:600; }

    .iux-subject-radio {

      width:14px; height:14px; border-radius:50%; border:1.5px solid var(--iux-border);

      flex-shrink:0; position:relative;

    }

    .iux-subject-row.on .iux-subject-radio { border-color:var(--iux-primary-light); }

    .iux-subject-row.on .iux-subject-radio::after {

      content:''; position:absolute; inset:2.5px; border-radius:50%; background:var(--iux-primary-light);

    }

    .iux-subject-name { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

    .iux-participant-label {

      font-size:9.5px; text-transform:uppercase; letter-spacing:.06em; color:var(--iux-text-faint);

      font-weight:700; margin:8px 2px 4px;

    }

    .iux-participant-empty { font-size:11px; color:var(--iux-text-faint); padding:6px 8px; }

    .iux-participant-back {

      display:flex; align-items:center; gap:6px; background:transparent; border:none;

      color:var(--iux-text-faint); font-size:11.5px; cursor:pointer; padding:0; margin-bottom:12px;

    }

    .iux-participant-back:hover { color:var(--iux-text); }

    .iux-participant-error {

      display:none; font-size:11px; color:var(--iux-danger); background:rgba(251,113,133,0.1);

      border:1px solid rgba(251,113,133,0.3); border-radius:8px; padding:7px 9px; margin-bottom:10px;

    }

    .iux-participant-error.on { display:block; }

    .iux-field { display:flex; flex-direction:column; gap:4px; margin-bottom:10px; }

    .iux-field label {

      font-size:10px; color:var(--iux-text-faint); font-weight:600;

      text-transform:uppercase; letter-spacing:.04em;

    }

    .iux-field input {

      padding:8px 10px; font-size:12.5px; border-radius:8px; border:1.5px solid var(--iux-border);

      background:var(--iux-surface); color:var(--iux-text); outline:none;

      transition:border-color .15s var(--iux-ease), box-shadow .15s var(--iux-ease);

    }

    .iux-field input:focus { border-color:var(--iux-primary-light); box-shadow:var(--iux-shadow-glow); }

    .iux-form-row { display:flex; gap:8px; margin-top:4px; }

    .iux-form-row .iux-btn { flex:1 1 auto; justify-content:center; padding:8px; font-size:11.5px; }

    .iux-form-row .iux-btn.primary { background:var(--iux-accent-grad); color:var(--iux-on-accent); border-color:transparent; }



    #__insightux_update {

      display:none; cursor:pointer; flex:0 0 auto; white-space:nowrap;

      padding:6px 13px; border-radius:999px; font-weight:600; font-size:11px;

      background:var(--iux-accent-grad); color:var(--iux-on-accent); align-items:center; gap:6px;

    }

    #__insightux_update:hover { transform:translateY(-1px); }



    /* -- profile avatar + three-dot menu: right end of the toolbar -- */

    #__iux_profile_btn {

      width:32px; height:32px; padding:0; border-radius:50%; flex-shrink:0;

      background:var(--iux-accent-grad); color:var(--iux-on-accent);

      font:700 12.5px var(--iux-font); border-color:transparent;

    }

    .iux-toolbar-pop {

      position:absolute; top:calc(100% + 8px); right:0; z-index:2147483647;

      min-width:230px; padding:8px; border-radius:var(--iux-radius);

      display:none; flex-direction:column; gap:2px;

    }

    .iux-toolbar-pop.open { display:flex; }

    .iux-profile-head { display:flex; align-items:center; gap:10px; padding:8px 10px 10px; }

    .iux-profile-avatar {

      width:34px; height:34px; border-radius:50%; flex-shrink:0;

      background:var(--iux-accent-grad); color:var(--iux-on-accent);

      display:flex; align-items:center; justify-content:center; font:700 13px var(--iux-font);

    }

    .iux-profile-name { font-size:12.5px; font-weight:600; color:var(--iux-text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

    .iux-profile-email { font-size:11px; color:var(--iux-text-faint); margin-top:1px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

    .iux-profile-active {

      display:flex; align-items:center; gap:6px; padding:0 10px 8px;

      font-size:10.5px; color:var(--iux-success); font-weight:600;

    }

    .iux-menu-sep { height:1px; background:var(--iux-border); margin:4px 6px; }

    .iux-menu-item {

      display:flex; align-items:center; gap:8px; width:100%; text-align:left;

      padding:8px 10px; border-radius:8px; border:none; background:transparent;

      color:var(--iux-text-dim); font-size:12px; font-family:var(--iux-font);

      cursor:pointer; transition:background .12s ease, color .12s ease;

    }

    .iux-menu-item:hover { background:var(--iux-surface-hi); color:var(--iux-text); }



    #__iux_info_modal {

      position:fixed; inset:0; z-index:2147483647; display:none;

      align-items:center; justify-content:center; background:rgba(0,0,0,0.35);

    }

    #__iux_info_modal.open { display:flex; }

    #__iux_info_modal .box {

      width:420px; max-width:88vw; padding:20px; border-radius:var(--iux-radius);

    }

    #__iux_info_modal h4 { margin:0 0 8px; font-size:14px; color:var(--iux-text); display:flex; align-items:center; gap:8px; }

    #__iux_info_modal p { margin:0; font-size:12.5px; line-height:1.6; color:var(--iux-text-dim); white-space:pre-line; }

    #__iux_info_actions { display:flex; gap:9px; margin-top:16px; }

    #__iux_info_actions .iux-btn { margin-top:0; flex:1; justify-content:center; }



    #__iux_cal_quality_modal { position:fixed; inset:0; z-index:2147483646; display:none; align-items:center; justify-content:center; padding:24px; font:14px var(--iux-font); color:var(--iux-text); }

    #__iux_cal_quality_modal.open { display:flex; }

    #__iux_cal_quality_modal .backdrop { position:absolute; inset:0; background:rgba(10,8,7,.72); backdrop-filter:blur(7px); }

    #__iux_cal_quality_modal .card { position:relative; width:min(540px,calc(100vw - 40px)); padding:30px; border:1px solid var(--iux-border); border-radius:22px; background:var(--iux-surface); box-shadow:0 28px 90px rgba(0,0,0,.45); }

    #__iux_cal_quality_modal .close { position:absolute; top:14px; right:14px; width:34px; height:34px; display:grid; place-items:center; border:1px solid var(--iux-border); border-radius:10px; background:var(--iux-surface-hi); color:var(--iux-text-dim); font:22px/1 var(--iux-font); cursor:pointer; }

    #__iux_cal_quality_modal .close:hover { color:var(--iux-text); background:var(--iux-surface); }

    #__iux_cal_quality_modal .icon { width:44px; height:44px; display:grid; place-items:center; border-radius:13px; margin-bottom:16px; }

    #__iux_cal_quality_modal .kicker { font-size:10px; font-weight:800; letter-spacing:.15em; color:var(--iux-text-faint); }

    #__iux_cal_quality_modal h2 { margin:8px 0 10px; font-size:24px; line-height:1.2; }

    #__iux_cal_quality_modal p { margin:0; color:var(--iux-text-dim); line-height:1.6; white-space:pre-line; }

    #__iux_cal_quality_modal .progress { margin-top:18px; }

    #__iux_cal_quality_modal .progress-head { display:flex; justify-content:space-between; gap:12px; margin-bottom:7px; color:var(--iux-text-faint); font-size:11px; }

    #__iux_cal_quality_modal .progress-track { height:6px; overflow:hidden; border-radius:99px; background:var(--iux-border); }

    #__iux_cal_quality_modal .progress-fill { width:0; height:100%; border-radius:inherit; background:var(--iux-accent-grad); transition:width .25s ease; }

    #__iux_cal_quality_modal .progress-track.indeterminate .progress-fill { width:36%; animation:iux-cal-progress 1.5s ease-in-out infinite; }

    #__iux_cal_quality_modal .metrics { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:9px; margin-top:20px; }

    #__iux_cal_quality_modal .metric { padding:12px 13px; border:1px solid var(--iux-border); border-radius:12px; background:var(--iux-surface-hi); }

    #__iux_cal_quality_modal .metric .label { font-size:10px; color:var(--iux-text-faint); font-weight:700; text-transform:uppercase; letter-spacing:.05em; }

    #__iux_cal_quality_modal .metric .value { margin-top:4px; font-size:15px; font-weight:700; color:var(--iux-text); }

    #__iux_cal_quality_modal .actions { display:flex; justify-content:flex-end; gap:9px; margin-top:22px; }

    #__iux_cal_quality_modal .actions .iux-btn { min-width:130px; padding:10px 14px; justify-content:center; }

    #__iux_cal_quality_modal .quality-good { color:var(--iux-success); }

    #__iux_cal_quality_modal .quality-warning { color:var(--iux-warning); }

    #__iux_cal_quality_modal .quality-poor { color:var(--iux-danger); }

    @keyframes iux-cal-progress{0%{transform:translateX(-110%)}100%{transform:translateX(320%)}}

    @media(prefers-reduced-motion:reduce){#__iux_cal_quality_modal .progress-fill{animation:none!important}}

    @media(max-width:520px){#__iux_cal_quality_modal .card{padding:22px}#__iux_cal_quality_modal .metrics{grid-template-columns:1fr}#__iux_cal_quality_modal .actions{flex-direction:column-reverse}#__iux_cal_quality_modal .actions .iux-btn{width:100%}}



    /* -- session history: Profile > My Sessions / Three-dot > Persons -- */

    #__iux_sessions_modal {

      position:fixed; inset:0; z-index:2147483647; display:none;

      align-items:center; justify-content:center; background:rgba(0,0,0,0.35);

    }

    #__iux_sessions_modal.open { display:flex; }

    #__iux_sessions_modal .box {

      width:440px; max-width:90vw; max-height:78vh; padding:18px;

      border-radius:var(--iux-radius); display:flex; flex-direction:column; gap:12px;

    }

    .iux-sessions-head { display:flex; align-items:center; gap:8px; flex-shrink:0; }

    .iux-sessions-head h4 { margin:0; font-size:13.5px; color:var(--iux-text); }

    .iux-sessions-back {

      width:26px; height:26px; border-radius:8px; border:1px solid var(--iux-border);

      background:var(--iux-surface); color:var(--iux-text-dim); cursor:pointer;

      display:flex; align-items:center; justify-content:center; flex-shrink:0; padding:0;

    }

    .iux-sessions-back:hover { background:var(--iux-surface-hi); color:var(--iux-text); }

    #__iux_sessions_search_wrap {

      display:none; align-items:center; gap:8px; padding:7px 11px; border-radius:9px;

      border:1px solid var(--iux-border); background:var(--iux-surface); flex-shrink:0;

    }

    #__iux_sessions_search_wrap.on { display:flex; }

    #__iux_sessions_search_wrap svg { color:var(--iux-text-faint); flex-shrink:0; }

    #__iux_sessions_search_input {

      flex:1 1 auto; min-width:0; border:none; outline:none; background:transparent;

      font-size:12.5px; color:var(--iux-text); font-family:var(--iux-font);

    }

    #__iux_sessions_search_input::placeholder { color:var(--iux-text-faint); }

    #__iux_sessions_body { overflow-y:auto; display:flex; flex-direction:column; gap:8px; min-height:60px; }

    .iux-session-card, .iux-person-card {

      display:flex; align-items:center; gap:12px; padding:12px 14px; border-radius:10px;

      border:1px solid var(--iux-border); background:var(--iux-surface-hi);

      cursor:pointer; transition:background .12s ease, transform .12s ease; flex-shrink:0;

    }

    .iux-session-card:hover, .iux-person-card:hover { background:var(--iux-surface); transform:translateY(-1px); }

    .iux-session-card .info, .iux-person-card .info { flex:1 1 auto; min-width:0; }

    .iux-session-card .when, .iux-person-card .when { font-size:12px; font-weight:600; color:var(--iux-text); }

    .iux-session-card .meta, .iux-person-card .meta {

      font-size:11px; color:var(--iux-text-faint); margin-top:3px;

      overflow:hidden; text-overflow:ellipsis; white-space:nowrap;

    }

    .iux-session-card .go, .iux-person-card .go {

      flex-shrink:0; font-size:11px; font-weight:600; color:var(--iux-primary-light);

      white-space:nowrap; display:flex; align-items:center; gap:4px;

    }

    .iux-person-card .avatar {

      width:32px; height:32px; border-radius:50%; flex-shrink:0;

      background:var(--iux-accent-grad); color:var(--iux-on-accent);

      display:flex; align-items:center; justify-content:center; font:700 13px var(--iux-font);

    }

    .iux-sessions-empty { font-size:12px; color:var(--iux-text-faint); text-align:center; padding:24px 0; }



    .iux-session-label-row { display:flex; align-items:center; gap:6px; }

    .iux-session-edit-btn {

      flex-shrink:0; width:20px; height:20px; border-radius:6px; display:flex; align-items:center;

      justify-content:center; color:var(--iux-text-faint); opacity:0; transition:opacity .12s ease, color .12s ease;

    }

    .iux-session-card:hover .iux-session-edit-btn, .iux-person-card:hover .iux-session-edit-btn { opacity:1; }

    .iux-session-edit-btn:hover { color:var(--iux-primary-light); background:var(--iux-surface); }

    .iux-session-name-edit { display:flex; align-items:center; gap:6px; width:100%; }

    .iux-session-name-input {

      flex:1 1 auto; min-width:0; padding:5px 9px; font-size:12px; border-radius:7px;

      border:1.5px solid var(--iux-primary-light); background:var(--iux-surface); color:var(--iux-text); outline:none;

    }

    .iux-session-name-edit .iux-btn { flex-shrink:0; width:22px; height:22px; padding:0; }

    .iux-person-edit { display:flex; flex-direction:column; gap:6px; width:100%; }

    .iux-person-edit .iux-session-name-input { width:100%; }

    .iux-person-edit-actions { display:flex; align-items:center; gap:6px; justify-content:flex-end; }

    .iux-person-edit-actions .iux-btn { flex-shrink:0; width:22px; height:22px; padding:0; }

    .iux-session-thumb {

      flex-shrink:0; width:52px; height:36px; border-radius:7px; object-fit:cover;

      background:var(--iux-surface); border:1px solid var(--iux-border);

    }

    .iux-session-thumb-empty {

      display:flex; align-items:center; justify-content:center; color:var(--iux-text-faint);

    }

  #__iux_drishti_btn { color:var(--iux-text-dim); }

  #__iux_drishti_btn:hover { color:var(--iux-text); }

  #__iux_drishti_btn svg { color:var(--iux-primary-light); }

  #__iux_drishti_modal { position:fixed; inset:0; z-index:2147483647; display:none; align-items:center; justify-content:center; background:rgba(12,10,9,.48); backdrop-filter:blur(7px); }

  #__iux_drishti_modal.open { display:flex; }

  #__iux_drishti_modal .dr-panel { width:min(900px,calc(100vw - 44px)); height:min(720px,calc(100vh - 44px)); border:1px solid var(--iux-border); border-radius:22px; background:var(--iux-page-bg); color:var(--iux-text); box-shadow:0 28px 100px rgba(0,0,0,.38); display:flex; flex-direction:column; overflow:hidden; }

  .dr-head { padding:16px 18px; border-bottom:1px solid var(--iux-border); display:flex; align-items:center; gap:12px; background:var(--iux-surface); }

  .dr-brand { width:38px; height:38px; border-radius:12px; display:grid; place-items:center; background:var(--iux-accent-grad); color:var(--iux-on-accent); flex-shrink:0; }

  .dr-title { font-size:14px; font-weight:800; }

  .dr-sub { margin-top:3px; font-size:11px; color:var(--iux-text-faint); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

  .dr-head-actions { margin-left:auto; display:flex; gap:7px; }

  .dr-head-actions button { width:30px; height:30px; padding:0; }

  .dr-body { flex:1; min-height:0; display:flex; flex-direction:column; }

  .dr-picker { padding:22px; overflow:auto; }

  .dr-picker h2 { margin:0 0 6px; font-size:21px; letter-spacing:-.02em; }

  .dr-picker p { margin:0 0 18px; color:var(--iux-text-dim); font-size:12.5px; line-height:1.55; }

  .dr-session-list { display:grid; gap:9px; }

  .dr-session { display:flex; align-items:center; gap:12px; padding:13px 14px; border:1px solid var(--iux-border); border-radius:12px; background:var(--iux-surface); cursor:pointer; text-align:left; color:var(--iux-text); font:inherit; }

  .dr-session:hover { border-color:var(--iux-primary-light); transform:translateY(-1px); }

  .dr-session-thumb { width:58px; height:40px; border-radius:8px; object-fit:cover; background:var(--iux-surface-hi); border:1px solid var(--iux-border); flex-shrink:0; }

  .dr-session-info { min-width:0; flex:1; }

  .dr-session-title { display:block; font-size:12.5px; font-weight:700; color:var(--iux-text); }

  .dr-session-meta { display:block; margin-top:3px; font-size:10.5px; color:var(--iux-text-faint); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

  .dr-chat { display:flex; flex-direction:column; min-height:0; height:100%; }

  .dr-chatbar { padding:10px 16px; border-bottom:1px solid var(--iux-border); display:flex; gap:8px; align-items:center; }

  .dr-goal { flex:1; min-width:0; padding:7px 10px; border:1px solid var(--iux-border); border-radius:9px; background:var(--iux-surface); color:var(--iux-text); outline:none; font:11.5px var(--iux-font); }

  .dr-goal::placeholder { color:var(--iux-text-faint); }

  .dr-messages { flex:1; min-height:0; overflow:auto; padding:18px; display:flex; flex-direction:column; gap:12px; }

  .dr-msg { max-width:82%; padding:11px 13px; border-radius:14px; font-size:12.5px; line-height:1.62; white-space:pre-wrap; }

  .dr-msg.user { align-self:flex-end; background:var(--iux-accent-grad); color:var(--iux-on-accent); border-bottom-right-radius:5px; }

  .dr-msg.user.failed { opacity:.68; outline:1px dashed var(--iux-danger, #d66); }

  .dr-msg.assistant { align-self:flex-start; background:var(--iux-surface); border:1px solid var(--iux-border); color:var(--iux-text); border-bottom-left-radius:5px; }

  .dr-msg .dr-idea { margin-top:10px; padding:9px 10px; border-radius:9px; background:var(--iux-surface-hi); border:1px solid var(--iux-border); }

  .dr-msg .dr-idea strong { display:block; margin-bottom:3px; }

  .dr-compose { border-top:1px solid var(--iux-border); padding:11px; display:flex; gap:8px; background:var(--iux-surface); }

  .dr-input { flex:1; min-height:44px; max-height:120px; resize:vertical; padding:10px 12px; border:1px solid var(--iux-border); border-radius:11px; background:var(--iux-page-bg); color:var(--iux-text); outline:none; font:12.5px var(--iux-font); }

  .dr-send { width:44px; height:44px; padding:0; border:0; border-radius:11px; background:var(--iux-accent-grad); color:var(--iux-on-accent); cursor:pointer; }

  .dr-empty { text-align:center; color:var(--iux-text-faint); padding:30px; font-size:12px; }

  `;

  document.head.appendChild(style);



  const loadbar = document.createElement('div');

  loadbar.id = '__iux_loadbar';

  document.documentElement.appendChild(loadbar);

  requestAnimationFrame(function(){

    loadbar.style.opacity = '1'; loadbar.style.width = '70%';

    setTimeout(function(){ loadbar.style.width = '100%'; }, 160);

    setTimeout(function(){ loadbar.style.opacity = '0'; }, 550);

  });



  const toolbar = document.createElement('div');

  toolbar.id = '__insightux_toolbar';

  toolbar.className = 'iux-glass';

  toolbar.innerHTML = `

    <button type="button" class="iux-btn iux-navbtn" id="__iux_back" title="Back">${iuxIcon('arrow-left',15)}</button>

    <button type="button" class="iux-btn iux-navbtn" id="__iux_fwd" title="Forward">${iuxIcon('arrow-right',15)}</button>

    <button type="button" class="iux-btn iux-navbtn" id="__iux_reload" title="Reload">${iuxIcon('refresh',15)}</button>

    <button type="button" class="iux-btn iux-navbtn" id="__iux_home" title="Home">${iuxIcon('home',15)}</button>

    <div id="__iux_addr_wrap">

      <span class="lead-icon" id="__iux_security_icon"></span>

      <form id="__iux_addr_form"><input id="__iux_addr" type="text" autocomplete="off"

        placeholder="Search or enter address"></form>

    </div>

    <div id="__insightux_indicators" style="display:none;">

      <span class="iux-pill" id="__iux_pill_eye"><span class="dot"></span>Eye Tracking</span>

      <span class="iux-pill" id="__iux_pill_mouse"><span class="dot"></span>Mouse Tracking</span>

      <span class="iux-pill" id="__iux_pill_time" style="display:none;">${iuxIcon('clock',11)}<span class="txt">00:00</span></span>

    </div>

    <span id="__insightux_update" title="Click to open the download page"></span>

    <span id="__insightux_status" class="iux-pill" style="display:none;"><span class="txt">Press S to start &middot; H heatmap &middot; M panel &middot; X quit</span></span>

    <button type="button" class="iux-btn" id="__iux_reveal_toggle" title="Show controls" style="width:32px;height:32px;display:none;">${iuxIcon('menu',15)}</button>

    <button type="button" class="iux-btn" id="__iux_theme_toggle" title="Toggle theme" style="width:32px;height:32px;"></button>

    <div style="position:relative;">

      <button type="button" class="iux-btn" id="__iux_profile_btn" title="Profile"></button>

      <div class="iux-toolbar-pop iux-glass" id="__iux_profile_pop">

        <div class="iux-profile-head">

          <div class="iux-profile-avatar" id="__iux_profile_avatar"></div>

          <div style="min-width:0;">

            <div class="iux-profile-name" id="__iux_profile_name"></div>

            <div class="iux-profile-email" id="__iux_profile_email"></div>

          </div>

        </div>

        <div class="iux-profile-active">${iuxIcon('check',12)} Active profile</div>

        <div class="iux-menu-sep"></div>

        <button type="button" class="iux-menu-item" id="__iux_my_sessions_btn">${iuxIcon('clock',14)} My Sessions</button>

        <div class="iux-menu-sep"></div>

        <button type="button" class="iux-menu-item" id="__iux_switch_profile">${iuxIcon('users',14)} Switch profile</button>

        <button type="button" class="iux-menu-item" id="__iux_logout">${iuxIcon('log-out',14)} Log out</button>

        <button type="button" class="iux-menu-item" id="__iux_delete_profile" style="color:#fb7185;">${iuxIcon('trash',14)} Delete Profile</button>

      </div>

    </div>

    <div style="position:relative;">

      <button type="button" class="iux-btn iux-navbtn" id="__iux_more_btn" title="More">${iuxIcon('more-vertical',15)}</button>

      <div class="iux-toolbar-pop iux-glass" id="__iux_more_pop">

        <button type="button" class="iux-menu-item" id="__iux_persons_btn">${iuxIcon('users',14)} Persons</button>

        <div class="iux-menu-sep"></div>

        <button type="button" class="iux-menu-item" id="__iux_more_help">${iuxIcon('info',14)} Help</button>

        <button type="button" class="iux-menu-item" id="__iux_more_about">${iuxIcon('eye',14)} About InsightUX</button>

      </div>

    </div>

  `;

  document.documentElement.appendChild(toolbar);



  const deleteDialog = document.createElement('dialog');

  deleteDialog.id = '__iux_delete_profile_dialog';

  deleteDialog.style.cssText = 'width:min(440px,calc(100vw - 32px));padding:0;border:1px solid rgba(198,188,178,.2);border-radius:18px;background:#221f1d;color:#f9f8f3;box-shadow:0 24px 80px rgba(0,0,0,.55);font:14px -apple-system,BlinkMacSystemFont,Segoe UI,Arial,sans-serif;';

  deleteDialog.innerHTML = '<div style="padding:24px 24px 20px;"><div style="width:40px;height:40px;display:grid;place-items:center;border-radius:12px;background:rgba(251,113,133,.12);color:#fb7185;margin-bottom:16px;">' + iuxIcon('trash',19) + '</div><h2 style="margin:0 0 8px;font-size:18px;">Delete your profile?</h2><p style="margin:0;color:#c6bcb2;line-height:1.55;">This will permanently remove your InsightUX profile and associated account data. This action cannot be undone.</p><p id="__iux_delete_profile_error" role="alert" style="display:none;color:#fb7185;font-size:12px;margin:12px 0 0;"></p><div style="display:flex;justify-content:flex-end;gap:8px;margin-top:22px;"><button type="button" id="__iux_delete_cancel" style="padding:9px 14px;border:1px solid rgba(198,188,178,.2);border-radius:9px;background:#292522;color:#f9f8f3;cursor:pointer;">Cancel</button><button type="button" id="__iux_delete_confirm" style="padding:9px 14px;border:0;border-radius:9px;background:#be354f;color:#fff;font-weight:700;cursor:pointer;">Delete Profile</button></div></div>';

  deleteDialog.addEventListener('click', function(e){ if (e.target === deleteDialog) deleteDialog.close(); });

  document.body.appendChild(deleteDialog);

  const deleteBackdropStyle = document.createElement('style');

  deleteBackdropStyle.textContent = '#__iux_delete_profile_dialog::backdrop{background:rgba(12,10,9,.72);backdrop-filter:blur(5px)} @media(prefers-color-scheme:light){#__iux_delete_profile_dialog{background:#fbf7e7;color:#312f2e}}';

  document.head.appendChild(deleteBackdropStyle);



  const sidebar = document.createElement('div');

  sidebar.id = '__insightux_sidebar';

  sidebar.className = 'iux-glass';

  sidebar.innerHTML = `

    <button type="button" class="iux-btn side-btn" id="__iux_calibrate">${iuxIcon('eye',18)}<span class="lbl">Calibrate</span><span class="tip">Calibrate</span></button>

    <button type="button" class="iux-btn side-btn" id="__iux_validate">${iuxIcon('target',18)}<span class="lbl">Validate</span><span class="tip">Validate</span></button>

    <button type="button" class="iux-btn side-btn" id="__iux_session">${iuxIcon('play',18)}<span class="lbl">Start<br>Session</span><span class="tip">Start Session</span></button>

    <button type="button" class="iux-btn side-btn iux-drishti-side" id="__iux_drishti_btn">${iuxIcon('eye',18)}<span class="lbl">Drishti<br>AI</span><span class="tip">Drishti AI</span></button>

    <div class="spacer"></div>

    <div style="position:relative;">

      <button type="button" class="iux-btn side-btn" id="__iux_participant_btn">${iuxIcon('users',18)}<span class="lbl">Participant</span><span class="tip">Participant</span></button>

      <div id="__iux_participant_pop" class="iux-glass iux-fade-in">

        <div id="__iux_participant_main">

          <h4>Tracking Subject</h4>

          <div class="iux-subject-list" id="__iux_subject_list"></div>

          <div class="iux-menu-sep"></div>

          <div class="iux-participant-label">Participants</div>

          <div class="iux-subject-list" id="__iux_participant_list"></div>

          <button type="button" class="iux-menu-item" id="__iux_add_participant_btn">${iuxIcon('plus',14)} Add Participant</button>

        </div>

        <div id="__iux_participant_addform" style="display:none;">

          <button type="button" class="iux-participant-back" id="__iux_add_participant_back">${iuxIcon('arrow-left',12)} Back</button>

          <div class="iux-field"><label>Name</label><input id="__iux_add_participant_name" type="text" placeholder="Participant name"></div>

          <div class="iux-field"><label>Notes (optional)</label><input id="__iux_add_participant_notes" type="text" placeholder="Optional notes"></div>

          <div class="iux-participant-error" id="__iux_add_participant_error"></div>

          <div class="iux-form-row">

            <button type="button" class="iux-btn" id="__iux_add_participant_cancel">Cancel</button>

            <button type="button" class="iux-btn primary" id="__iux_add_participant_submit">Add Participant</button>

          </div>

        </div>

      </div>

    </div>

    <div style="position:relative;">

      <button type="button" class="iux-btn side-btn" id="__iux_settings_btn">${iuxIcon('settings',18)}<span class="lbl">Settings</span><span class="tip">Settings</span></button>

      <div id="__iux_settings_pop" class="iux-glass iux-fade-in">

        <h4>Shortcuts</h4>

        <div class="kbd-row"><span>Start / Stop tracking</span><b>S / E</b></div>

        <div class="kbd-row"><span>Toggle heatmap</span><b>H</b></div>

        <div class="kbd-row"><span>Mouse panel</span><b>M</b></div>

        <div class="kbd-row"><span>Quit</span><b>X</b></div>

        <div class="ver">InsightUX v__INSIGHTUX_VERSION__</div>

      </div>

    </div>

    <button type="button" class="iux-btn" id="__iux_collapse_btn" title="Collapse sidebar">${iuxIcon('chevron-left',14)}</button>

    <div class="hints">S/E &middot; H &middot; M &middot; X</div>

  `;

  document.documentElement.appendChild(sidebar);



  // -- Drishti AI workspace --

  const drishtiModal = document.createElement('div');

  drishtiModal.id = '__iux_drishti_modal';

  drishtiModal.innerHTML = `

    <div class="dr-panel">

      <div class="dr-head">

        <div class="dr-brand">${iuxIcon('eye',19)}</div>

        <div style="min-width:0;"><div class="dr-title">Drishti AI</div><div class="dr-sub" id="__iux_dr_sub">AI UX Analyst</div></div>

        <div class="dr-head-actions"><button type="button" class="iux-btn" id="__iux_dr_change" title="Change session">${iuxIcon('layers',13)}</button><button type="button" class="iux-btn" id="__iux_dr_close">${iuxIcon('x',13)}</button></div>

      </div>

      <div class="dr-body" id="__iux_dr_body"></div>

    </div>`;

  document.documentElement.appendChild(drishtiModal);



  let drishtiSession = null;

  let drishtiConversation = null;

  let drishtiBusy = false;

  let drAtt = null;

  let drDraft = null;

  const drBody = document.getElementById('__iux_dr_body');

  const drSub = document.getElementById('__iux_dr_sub');

  function drEsc(v){ return String(v == null ? '' : v).replace(/[&<>"']/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]; }); }

  function drSetOpen(on){ if(!on&&drDraft)drDraft.flush(); drishtiModal.classList.toggle('open', !!on); }

  function drSessionTitle(s){ return s.customName || s.domain || s.label || s.id; }

  function drAppendMessage(role, content, idea, meta){

    const box=document.getElementById('__iux_dr_messages'); if(!box)return;

    const el=document.createElement('div'); el.className='dr-msg '+(role==='user'?'user':'assistant');

    if(role==='user'){

      const thumbs=iuxThumbsEl(meta);if(thumbs)el.appendChild(thumbs);

      const tx=document.createElement('div');tx.textContent=content||'';el.appendChild(tx);

    } else {

      // Same Markdown rendering for live answers and reopened chats.

      el.classList.add('iux-md');el.innerHTML=iuxMd(content||'')+iuxRegionCaption(meta);

    }

    if(idea&&idea.title){const card=document.createElement('div');card.className='dr-idea';card.innerHTML='<strong>New idea: '+drEsc(idea.title)+'</strong>'+drEsc(idea.summary||'');el.appendChild(card);}

    box.appendChild(el); box.scrollTop=box.scrollHeight; return el;

  }

  function drRenderPicker(sessions){

    drSub.textContent='Choose a captured session';

    drBody.innerHTML='<div class="dr-picker"><h2>Which session should Drishti analyze?</h2><p>Choose one captured session. The conversation stays scoped to that session so unrelated research is never mixed.</p><div class="dr-session-list" id="__iux_dr_sessions"></div></div>';

    const list=document.getElementById('__iux_dr_sessions');

    if(!sessions||!sessions.length){list.innerHTML='<div class="dr-empty">No completed sessions are available yet.</div>';return;}

    sessions.forEach(function(s){

      const el=document.createElement('button');el.type='button';el.className='dr-session';

      const thumb=s.thumbnail?'<img class="dr-session-thumb" src="'+s.thumbnail+'" alt="">':'<span class="dr-session-thumb"></span>';

      const meta=[s.domain,s.duration!=null?s.duration+'s':'',s.samples!=null?s.samples+' gaze samples':'',s.subjectName?'Participant: '+s.subjectName:''].filter(Boolean).join(' Β· ');

      el.innerHTML=thumb+'<span class="dr-session-info"><span class="dr-session-title">'+drEsc(drSessionTitle(s))+'</span><span class="dr-session-meta">'+drEsc(s.label||'')+' Β· '+drEsc(meta)+'</span></span>'+iuxIcon('chevron-right',13);

      el.addEventListener('click',function(){drOpenSession(s);});list.appendChild(el);

    });

  }

  function drRenderChat(){

    const c=drishtiConversation||{messages:[]},s=drishtiSession||{};

    drSub.textContent='Session: '+(s.domain||s.label||s.session_id||s.id||'Current session');

    drBody.innerHTML='<div class="dr-chat"><div class="dr-chatbar"><input id="__iux_dr_goal" class="dr-goal" placeholder="Optional UX goal, e.g. increase Apply Now clicks" maxlength="500"></div><div class="dr-messages" id="__iux_dr_messages"></div><div class="iux-att-preview" id="__iux_dr_att_prev"></div><div class="dr-compose" id="__iux_dr_compose"><textarea id="__iux_dr_input" class="dr-input" placeholder="Ask about this session, name a region (e.g. the CONNECT section), or attach a picture of one…"></textarea><button type="button" class="dr-send" id="__iux_dr_send">'+iuxIcon('arrow-right',16)+'</button></div></div>';

    document.getElementById('__iux_dr_goal').value=c.ux_goal||'';

    (c.messages||[]).forEach(function(m){drAppendMessage(m.role,m.content,null,m);});

    if(!(c.messages||[]).length)drAppendMessage('assistant','I’m ready to analyze this session. Ask me about attention, gaze behavior, interactions, screenshots, or what you could improve.');

    const input=document.getElementById('__iux_dr_input');input.addEventListener('keydown',function(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();drSend();}});document.getElementById('__iux_dr_send').addEventListener('click',drSend);

    drAtt=iuxAttachInit({textarea:input,composeRow:document.getElementById('__iux_dr_compose'),previewHost:document.getElementById('__iux_dr_att_prev'),dropTarget:drBody,onError:function(m){drAppendMessage('assistant',m);},onChange:function(){if(drDraft)drDraft.touch();}});

    drDraft=iuxDraftBinder({getCtx:function(){return(drishtiSession&&drishtiConversation)?{sessionId:drishtiSession.id,participantId:drishtiSession.participantId||null,conv:drishtiConversation}:null;},input:input,goalInput:document.getElementById('__iux_dr_goal'),att:drAtt});

    drDraft.restore();

    drShowInflight(c);

  }

  function drSetBusyUI(busy){

    drishtiBusy=!!busy;

    const i=document.getElementById('__iux_dr_input'),sb=document.getElementById('__iux_dr_send');

    if(i)i.disabled=!!busy;if(sb)sb.disabled=!!busy;if(drAtt)drAtt.setDisabled(!!busy);

  }

  // Wire a request record to the bubbles currently on screen.

  function drBindInflight(convId,rec,userBubble,pendingEl){

    rec.ui={

      live:function(){return !!(pendingEl&&pendingEl.isConnected);},

      onDone:function(res){

        if(drishtiConversation&&drishtiConversation.conversation_id===convId)drishtiConversation=res.conversation;

        pendingEl.remove();

        drAppendMessage('assistant',res.answer,res.idea,{regions:res.regions,region_source:res.region_source});

        drSetBusyUI(iuxAnyInflight());

      },

      onFail:function(msg){

        if(userBubble&&userBubble.isConnected)userBubble.classList.add('failed');

        pendingEl.textContent='Message not sent. '+(msg||'Unknown error');

        const input=document.getElementById('__iux_dr_input');

        if(input&&drishtiConversation&&drishtiConversation.conversation_id===convId){input.value=rec.text;if(drAtt&&rec.att&&rec.att.length)drAtt.setState({items:rec.att.map(function(u){return{dataUrl:u,name:''};})});if(drDraft)drDraft.touch();}

        drSetBusyUI(iuxAnyInflight());

      }

    };

  }

  // Re-open while Drishti is still thinking (or after it failed while closed):

  // show the question again and keep waiting for the same answer.

  function drShowInflight(c){

    const rec=iuxInflight[c.conversation_id];

    if(!rec||(c.messages||[]).length>rec.baseCount){drSetBusyUI(iuxAnyInflight());return;}

    const userBubble=drAppendMessage('user',rec.shownText,null,iuxLiveMeta(rec.att));

    if(rec.status==='failed'){

      userBubble.classList.add('failed');

      const note=drAppendMessage('assistant','');note.textContent='Message not sent. '+(rec.error||'Unknown error');

      delete iuxInflight[c.conversation_id];

      drSetBusyUI(iuxAnyInflight());return;

    }

    const pend=drAppendMessage('assistant',rec.firstTurn?'Preparing your research session…':'Drishti is answering…');

    drBindInflight(c.conversation_id,rec,userBubble,pend);

    drSetBusyUI(true);

  }

  async function drOpenSession(s){

    drishtiSession=s;drBody.innerHTML='<div class="dr-empty">Loading this session…</div>';drSub.textContent='Loading saved conversation';

    try{const res=await window.pywebview.api.get_drishti_conversation(s.id,s.participantId||null,__IUX_TOK__);if(!res||!res.ok)throw new Error((res&&res.error)||'Could not open session');drishtiConversation=res.conversation;drishtiSession=Object.assign({},s,res.session||{});drRenderChat();}catch(e){drBody.innerHTML='<div class="dr-empty">'+drEsc(e.message||'Could not open this session.')+'</div>';}

  }

  async function drOpenPicker(){

    if(drDraft)drDraft.flush();

    drSetOpen(true);drBody.innerHTML='<div class="dr-empty">Loading sessions…</div>';drSub.textContent='Your captured sessions';

    try{const res=await window.pywebview.api.list_drishti_sessions(50,__IUX_TOK__);if(!res||!res.ok)throw new Error((res&&res.error)||'Could not load sessions');drRenderPicker(res.sessions);}catch(e){drBody.innerHTML='<div class="dr-empty">'+drEsc(e.message||'Could not load sessions.')+'</div>';}

  }

  async function drSend(){

    const input=document.getElementById('__iux_dr_input');if(drishtiBusy||!input||!drishtiSession||!drishtiConversation)return;

    const attached=drAtt?drAtt.get():[];const msg=input.value.trim();if(!msg&&!attached.length)return;

    if(drDraft)drDraft.cancel();

    const convId=drishtiConversation.conversation_id,sess=drishtiSession;

    const shown=msg||(attached.length>1?'Analyze each attached region and suggest how to increase attention on them.':'Analyze the attached region and suggest how to increase attention on it.');

    const rec={status:'pending',text:msg,shownText:shown,att:attached.length?attached:null,baseCount:(drishtiConversation.messages||[]).length,firstTurn:!drishtiConversation.gemini_interaction_id,ui:null,error:null};

    iuxInflight[convId]=rec;input.value='';

    // The message is on its way: the pictures leave the composer NOW (they are

    // handed back automatically if Drishti fails). Unsent pictures stay until removed.

    if(drAtt)drAtt.clear();

    const userBubble=drAppendMessage('user',shown,null,iuxLiveMeta(attached));

    const pending=drAppendMessage('assistant',rec.firstTurn?'Preparing your research session…':'Drishti is answering…');

    drBindInflight(convId,rec,userBubble,pending);drSetBusyUI(true);

    const goal=(document.getElementById('__iux_dr_goal')||{}).value||'';

    try{

      const res=await window.pywebview.api.send_drishti_message(sess.id,sess.participantId||null,convId,msg,goal,attached.length?attached:null,__IUX_TOK__);

      if(!res||!res.ok)throw new Error((res&&res.error)||'Drishti could not answer');

      iuxInflightSettle(convId,rec,true,res);

    }catch(e){iuxInflightSettle(convId,rec,false,(e&&e.message)||'Unknown error');}

  }

  document.getElementById('__iux_drishti_btn').addEventListener('click',function(){closeAllPops();drOpenPicker();});

  document.getElementById('__iux_dr_close').addEventListener('click',function(){drSetOpen(false);});

  document.getElementById('__iux_dr_change').addEventListener('click',function(){drOpenPicker();});

  drishtiModal.addEventListener('click',function(e){if(e.target===drishtiModal)drSetOpen(false);});



  setInterval(function(){

    if (!document.documentElement.contains(toolbar)) document.documentElement.appendChild(toolbar);

    if (!document.documentElement.contains(sidebar)) document.documentElement.appendChild(sidebar);

  }, 1000);



  // -- theme toggle --

  const themeBtn = document.getElementById('__iux_theme_toggle');

  function paintThemeBtn(){

    themeBtn.innerHTML = iuxIcon(window.insightuxGetTheme() === 'light' ? 'moon' : 'sun', 15);

  }

  paintThemeBtn();

  themeBtn.addEventListener('click', function(){ window.insightuxToggleTheme(); paintThemeBtn(); });



  // -- sidebar collapse (persisted like theme) --

  const collapseBtn = document.getElementById('__iux_collapse_btn');

  function applyCollapsed(collapsed){

    sidebar.classList.toggle('collapsed', collapsed);

    collapseBtn.innerHTML = iuxIcon(collapsed ? 'chevron-right' : 'chevron-left', 14);

  }

  applyCollapsed(window.insightuxGetPrefs().sidebarCollapsed === true);

  collapseBtn.addEventListener('click', function(){

    const collapsed = !sidebar.classList.contains('collapsed');

    applyCollapsed(collapsed);

    window.insightuxSetPref('sidebarCollapsed', collapsed);

  });



  // -- tracking-mode compact chrome: sidebar + toolbar shrink automatically

  // once a session starts, so the tracked page gets maximum space, without

  // ever removing the controls β€” __iux_reveal_toggle (only shown while

  // tracking) brings the full toolbar/sidebar back temporarily. --

  const revealToggle = document.getElementById('__iux_reveal_toggle');

  let controlsRevealed = false;

  function applyTrackingChrome(){

    const compact = isTrackingNow && !controlsRevealed;

    toolbar.classList.toggle('tracking-compact', compact);

    document.body.classList.toggle('iux-tracking-compact', compact);

    if (isTrackingNow) {

      sidebar.classList.toggle('collapsed', !controlsRevealed);

    } else {

      applyCollapsed(window.insightuxGetPrefs().sidebarCollapsed === true);

    }

    revealToggle.innerHTML = iuxIcon(controlsRevealed ? 'x' : 'menu', 15);

    revealToggle.title = controlsRevealed ? 'Hide controls' : 'Show controls';

  }

  revealToggle.addEventListener('click', function(){

    controlsRevealed = !controlsRevealed;

    applyTrackingChrome();

  });



  // -- settings popover --

  const settingsBtn = document.getElementById('__iux_settings_btn');

  const settingsPop = document.getElementById('__iux_settings_pop');

  settingsBtn.addEventListener('click', function(e){

    e.stopPropagation();

    participantPop.classList.remove('open');

    settingsPop.classList.toggle('open');

  });

  document.addEventListener('click', function(){

    settingsPop.classList.remove('open');

    participantPop.classList.remove('open');

  });



  // -- participant panel ------------------------------------------------

  // Tracking subject (Myself vs. a participant) and the participant list

  // itself both live only in Python (participants.py) β€” this panel is a

  // thin view over list_participants()/add_participant()/

  // set_tracking_subject(), the same call-Python-then-repaint pattern the

  // profile popover already uses.

  const participantBtn      = document.getElementById('__iux_participant_btn');

  const participantPop      = document.getElementById('__iux_participant_pop');

  const participantMain     = document.getElementById('__iux_participant_main');

  const participantAddForm  = document.getElementById('__iux_participant_addform');

  let PARTICIPANTS_CACHE = [];

  let ACTIVE_SUBJECT_ID  = '';  // '' = Myself



  participantPop.addEventListener('click', function(e){ e.stopPropagation(); });



  participantBtn.addEventListener('click', function(e){

    e.stopPropagation();

    settingsPop.classList.remove('open');

    const wasOpen = participantPop.classList.contains('open');

    participantPop.classList.remove('open');

    if (!wasOpen) {

      participantPop.classList.add('open');

      showParticipantMain();

      refreshParticipantList();

    }

  });



  function showParticipantMain(){

    participantAddForm.style.display = 'none';

    participantMain.style.display = 'block';

  }



  function refreshParticipantList(){

    if (!window.pywebview) return;

    window.pywebview.api.list_participants(__IUX_TOK__).then(function(list){

      PARTICIPANTS_CACHE = list || [];

      renderSubjectList();

    });

  }



  function renderSubjectList(){

    const wrap = document.getElementById('__iux_subject_list');

    wrap.innerHTML = '<div class="iux-subject-row' + (ACTIVE_SUBJECT_ID === '' ? ' on' : '') + '" data-id="">' +

      '<span class="iux-subject-radio"></span><span class="iux-subject-name">Myself</span></div>';



    const plist = document.getElementById('__iux_participant_list');

    if (!PARTICIPANTS_CACHE.length) {

      plist.innerHTML = '<div class="iux-participant-empty">No participants yet.</div>';

    } else {

      plist.innerHTML = PARTICIPANTS_CACHE.map(function(p){

        return '<div class="iux-subject-row' + (ACTIVE_SUBJECT_ID === p.id ? ' on' : '') + '" data-id="' + p.id + '">' +

          '<span class="iux-subject-radio"></span><span class="iux-subject-name">' + escapeHtml(p.name) + '</span></div>';

      }).join('');

    }



    Array.from(wrap.children).concat(Array.from(plist.children)).forEach(function(row){

      if (!row.dataset || row.dataset.id === undefined) return;

      row.addEventListener('click', function(){

        const id = row.getAttribute('data-id');

        if (id === ACTIVE_SUBJECT_ID || !window.pywebview) return;

        window.pywebview.api.set_tracking_subject(id || null, __IUX_TOK__).then(function(ok){

          if (ok) { ACTIVE_SUBJECT_ID = id; renderSubjectList(); }

        });

      });

    });

  }



  window.insightuxSetSubject = function(subject){

    ACTIVE_SUBJECT_ID = (subject && subject.id) || '';

    if (participantPop.classList.contains('open')) renderSubjectList();

  };



  document.getElementById('__iux_add_participant_btn').addEventListener('click', function(e){

    e.stopPropagation();

    participantMain.style.display = 'none';

    participantAddForm.style.display = 'block';

    document.getElementById('__iux_add_participant_error').classList.remove('on');

    document.getElementById('__iux_add_participant_name').value = '';

    document.getElementById('__iux_add_participant_notes').value = '';

    document.getElementById('__iux_add_participant_name').focus();

  });

  document.getElementById('__iux_add_participant_back').addEventListener('click', function(e){

    e.stopPropagation();

    showParticipantMain();

  });

  document.getElementById('__iux_add_participant_cancel').addEventListener('click', function(e){

    e.stopPropagation();

    showParticipantMain();

  });

  document.getElementById('__iux_add_participant_submit').addEventListener('click', function(e){

    e.stopPropagation();

    if (!window.pywebview) return;

    const name = document.getElementById('__iux_add_participant_name').value.trim();

    const notes = document.getElementById('__iux_add_participant_notes').value.trim();

    const errEl = document.getElementById('__iux_add_participant_error');

    errEl.classList.remove('on');

    if (!name) { errEl.textContent = 'Name is required.'; errEl.classList.add('on'); return; }

    const btn = e.currentTarget;

    btn.disabled = true;

    window.pywebview.api.add_participant(name, notes, __IUX_TOK__).then(function(res){

      btn.disabled = false;

      if (res && res.ok) {

        showParticipantMain();

        refreshParticipantList();

      } else {

        errEl.textContent = (res && res.error) || 'Could not add participant.';

        errEl.classList.add('on');

      }

    });

  });



  // -- profile popover + three-dot menu --------------------------------

  // Same call-a-Python-method-then-let-it-navigate pattern as every other

  // sidebar action (__iux_calibrate/__iux_validate/__iux_session above) β€”

  // no new plumbing, just two more buttons feeding the existing callApi().

  const profileBtn  = document.getElementById('__iux_profile_btn');

  const profilePop  = document.getElementById('__iux_profile_pop');

  const moreBtn     = document.getElementById('__iux_more_btn');

  const morePop     = document.getElementById('__iux_more_pop');



  function closeAllPops(){

    settingsPop.classList.remove('open');

    profilePop.classList.remove('open');

    morePop.classList.remove('open');

  }

  profileBtn.addEventListener('click', function(e){

    e.stopPropagation();

    const wasOpen = profilePop.classList.contains('open');

    closeAllPops();

    if (!wasOpen) profilePop.classList.add('open');

  });

  moreBtn.addEventListener('click', function(e){

    e.stopPropagation();

    const wasOpen = morePop.classList.contains('open');

    closeAllPops();

    if (!wasOpen) morePop.classList.add('open');

  });

  document.addEventListener('click', closeAllPops);



  window.insightuxSetProfile = function(profile){

    if (!profile || !profile.name) return;

    profileBtn.textContent = profile.avatar || profile.name.charAt(0).toUpperCase();

    document.getElementById('__iux_profile_avatar').textContent = profile.avatar || profile.name.charAt(0).toUpperCase();

    document.getElementById('__iux_profile_name').textContent = profile.name;

    document.getElementById('__iux_profile_email').textContent = profile.email || '';

  };



  const deleteProfileBtn = document.getElementById('__iux_delete_profile');

  const deleteConfirmBtn = deleteDialog.querySelector('#__iux_delete_confirm');

  const deleteCancelBtn = deleteDialog.querySelector('#__iux_delete_cancel');

  const deleteError = deleteDialog.querySelector('#__iux_delete_profile_error');

  deleteProfileBtn.addEventListener('click', function(){

    closeAllPops();

    deleteError.style.display = 'none';

    deleteDialog.showModal();

  });

  deleteCancelBtn.addEventListener('click', function(){ deleteDialog.close(); });

  deleteConfirmBtn.addEventListener('click', function(){

    if (!window.pywebview || !window.pywebview.api) {

      deleteError.textContent = 'Profile deletion is unavailable right now. Please try again.';

      deleteError.style.display = 'block';

      return;

    }

    deleteConfirmBtn.disabled = true;

    deleteConfirmBtn.textContent = 'Deleting…';

    window.pywebview.api.delete_profile(__IUX_TOK__).then(function(res){

      if (res && res.ok) return;

      deleteConfirmBtn.disabled = false;

      deleteConfirmBtn.textContent = 'Delete Profile';

      deleteError.textContent = (res && res.error) || 'Your profile could not be deleted. Please try again.';

      deleteError.style.display = 'block';

    }).catch(function(){

      deleteConfirmBtn.disabled = false;

      deleteConfirmBtn.textContent = 'Delete Profile';

      deleteError.textContent = 'Your profile could not be deleted. Please try again.';

      deleteError.style.display = 'block';

    });

  });



  document.getElementById('__iux_switch_profile').addEventListener('click', function(){

    closeAllPops();

    callApi('switch_profile_screen');

  });

  document.getElementById('__iux_logout').addEventListener('click', function(){

    closeAllPops();

    callApi('logout');

  });

  document.getElementById('__iux_my_sessions_btn').addEventListener('click', function(){

    closeAllPops();

    openMySessions();

  });



  // -- Persons (three-dot menu) --

  document.getElementById('__iux_persons_btn').addEventListener('click', function(){

    closeAllPops();

    openPersonsList();

  });



  // -- session history modal: Profile > My Sessions / Three-dot > Persons

  // > a specific participant's history. One shared overlay, reused for

  // all three views (renderSessionList for a flat session list,

  // renderPersonList for the participant picker) so there's a single

  // place that knows how to render a session card / a "View Report" link.

  const sessionsModal = document.createElement('div');

  sessionsModal.id = '__iux_sessions_modal';

  sessionsModal.innerHTML = `

    <div class="box iux-glass iux-fade-in">

      <div class="iux-sessions-head">

        <button type="button" class="iux-sessions-back" id="__iux_sessions_back" style="display:none;">${iuxIcon('arrow-left',13)}</button>

        <h4 id="__iux_sessions_title"></h4>

        <button type="button" class="iux-btn" id="__iux_sessions_close" style="width:28px;height:28px;padding:0;margin-left:auto;">${iuxIcon('x',13)}</button>

      </div>

      <div id="__iux_sessions_search_wrap">

        ${iuxIcon('search',13)}

        <input type="text" id="__iux_sessions_search_input" placeholder="Search sessions by name or site" maxlength="100">

      </div>

      <div id="__iux_sessions_body"></div>

    </div>

  `;

  document.documentElement.appendChild(sessionsModal);

  document.getElementById('__iux_sessions_close').addEventListener('click', function(){ sessionsModal.classList.remove('open'); });

  sessionsModal.addEventListener('click', function(e){ if (e.target === sessionsModal) sessionsModal.classList.remove('open'); });



  // Client-side only -- the full list for whatever session view is

  // currently open is already in memory (fetched once by load() in

  // openMySessions()/openPersonDetails()), so filtering as the user types

  // needs no round trip to Python. Re-applied after every reload() too

  // (rename/delete), so the filter text survives an in-place refresh.

  let __iuxAllSessions = [];

  let __iuxSessionsCtx = null;

  const sessionsSearchInput = document.getElementById('__iux_sessions_search_input');

  sessionsSearchInput.addEventListener('click', function(e){ e.stopPropagation(); });

  sessionsSearchInput.addEventListener('keydown', function(e){ e.stopPropagation(); });

  sessionsSearchInput.addEventListener('input', applySessionFilter);



  function applySessionFilter(){

    const q = sessionsSearchInput.value.trim().toLowerCase();

    const filtered = !q ? __iuxAllSessions : __iuxAllSessions.filter(function(s){

      return (s.customName && s.customName.toLowerCase().includes(q)) ||

             (s.label && s.label.toLowerCase().includes(q)) ||

             (s.domain && s.domain.toLowerCase().includes(q));

    });

    const emptyMessage = (q && __iuxAllSessions.length)

      ? 'No sessions match β€œ' + escapeHtml(sessionsSearchInput.value.trim()) + '”.'

      : undefined;

    renderSessionList(filtered, __iuxSessionsCtx, emptyMessage);

  }



  function openSessionsModal(title, onBack, searchable){

    document.getElementById('__iux_sessions_title').textContent = title;

    const backBtn = document.getElementById('__iux_sessions_back');

    backBtn.style.display = onBack ? 'flex' : 'none';

    backBtn.onclick = onBack || null;

    document.getElementById('__iux_sessions_body').innerHTML = '<div class="iux-sessions-empty">Loading…</div>';

    sessionsSearchInput.value = '';

    document.getElementById('__iux_sessions_search_wrap').classList.toggle('on', !!searchable);

    __iuxAllSessions = [];

    __iuxSessionsCtx = null;

    sessionsModal.classList.add('open');

  }



  // Session rename text is user-typed and, unlike the auto timestamp label,

  // now persists to disk and is re-rendered on every future visit to this

  // list β€” escape it before it goes into innerHTML so a rename can't smuggle

  // in markup that runs in this window's own script context.

  function escapeHtml(str){

    return String(str).replace(/[&<>"']/g, function(c){

      return { '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c];

    });

  }



  function sessionCardHtml(s, i){

    const stats = [];

    if (s.domain) stats.push(escapeHtml(s.domain));  // domain comes from the tracked page's own URL, not typed by anyone in this app

    if (s.duration != null) stats.push(s.duration + 's');

    if (s.samples != null) stats.push(s.samples + ' gaze samples');

    const displayName = escapeHtml(s.customName || s.label);

    const metaLine = (s.customName ? [escapeHtml(s.label)].concat(stats) : stats).join(' &middot; ');

    // s.thumbnail is a data: URI built server-side from base64-encoded

    // image bytes (see _session_thumbnail_data_uri()) -- never user text,

    // safe to drop straight into the src attribute unescaped.

    const thumbHtml = s.thumbnail

      ? '<img class="iux-session-thumb" src="' + s.thumbnail + '" alt="">'

      : '<span class="iux-session-thumb iux-session-thumb-empty">' + iuxIcon('image', 14) + '</span>';

    return '<div class="iux-session-card"' + (s.reportUrl ? '' : ' style="cursor:default;"') + '>' +

      thumbHtml +

      '<div class="info">' +

        '<div class="iux-session-label-row" id="__iux_sess_row' + i + '">' +

          '<span class="when" id="__iux_sess_label' + i + '">' + displayName + '</span>' +

          '<button type="button" class="iux-session-edit-btn" id="__iux_sess_edit' + i + '" title="Rename session">' + iuxIcon('type', 11) + '</button>' +

          '<button type="button" class="iux-session-edit-btn" id="__iux_sess_export' + i + '" title="Download report as PDF">' + iuxIcon('download', 11) + '</button>' +

          '<button type="button" class="iux-session-edit-btn" id="__iux_sess_delete' + i + '" title="Delete session">' + iuxIcon('trash', 11) + '</button>' +

        '</div>' +

        (metaLine ? '<div class="meta">' + metaLine + '</div>' : '') +

      '</div>' +

      (s.reportUrl ? '<span class="go">View Report ' + iuxIcon('arrow-right', 12) + '</span>' : '') +

    '</div>';

  }



  // Reused for both My Sessions and a specific participant's history β€” the

  // `ctx` (openReport/rename/remove/reload) is what differs between the

  // two, so this one function knows how to render a session card, open its

  // report natively (avoids the http(s)->file:// script-navigation block β€”

  // see Api._open_session_report()'s own comment), rename it in place, and

  // delete it.

  function renderSessionList(sessions, ctx, emptyMessage){

    const body = document.getElementById('__iux_sessions_body');

    if (!sessions.length) {

      body.innerHTML = '<div class="iux-sessions-empty">' + (emptyMessage || 'No sessions yet.') + '</div>';

      return;

    }

    body.innerHTML = sessions.map(function(s, i){ return sessionCardHtml(s, i); }).join('');

    Array.from(body.children).forEach(function(card, i){

      const s = sessions[i];

      if (s.reportUrl) card.addEventListener('click', function(){ ctx.openReport(s.id); });

      const editBtn = document.getElementById('__iux_sess_edit' + i);

      if (editBtn) {

        editBtn.addEventListener('click', function(e){ e.stopPropagation(); startEditingSessionName(sessions, i, ctx); });

      }

      const exportBtn = document.getElementById('__iux_sess_export' + i);

      if (exportBtn) {

        exportBtn.addEventListener('click', function(e){

          e.stopPropagation();

          exportBtn.style.pointerEvents = 'none';

          ctx.export(s.id).then(function(ok){

            exportBtn.style.pointerEvents = '';

            if (ok) window.insightuxSetStatus && window.insightuxSetStatus('Creating PDF report...');

          });

        });

      }

      const delBtn = document.getElementById('__iux_sess_delete' + i);

      if (delBtn) {

        delBtn.addEventListener('click', function(e){

          e.stopPropagation();

          if (!confirm('Delete this session and its report? This cannot be undone.')) return;

          ctx.remove(s.id).then(function(ok){ if (ok) ctx.reload(); });

        });

      }

    });

  }



  function startEditingSessionName(sessions, i, ctx){

    const s = sessions[i];

    const row = document.getElementById('__iux_sess_row' + i);

    row.innerHTML =

      '<div class="iux-session-name-edit">' +

        '<input type="text" class="iux-session-name-input" id="__iux_sess_name_input' + i + '" value="' +

          escapeHtml(s.customName || '') + '" placeholder="' + escapeHtml(s.label) + '" maxlength="80">' +

        '<button type="button" class="iux-btn" id="__iux_sess_name_save' + i + '" title="Save">' + iuxIcon('check', 12) + '</button>' +

        '<button type="button" class="iux-btn" id="__iux_sess_name_cancel' + i + '" title="Cancel">' + iuxIcon('x', 12) + '</button>' +

      '</div>';

    const input = document.getElementById('__iux_sess_name_input' + i);

    input.addEventListener('click', function(e){ e.stopPropagation(); });

    input.focus();

    input.select();



    function commit(){ ctx.rename(s.id, input.value).then(function(){ ctx.reload(); }); }

    function cancel(){ ctx.reload(); }



    document.getElementById('__iux_sess_name_save' + i).addEventListener('click', function(e){ e.stopPropagation(); commit(); });

    document.getElementById('__iux_sess_name_cancel' + i).addEventListener('click', function(e){ e.stopPropagation(); cancel(); });

    input.addEventListener('keydown', function(e){

      e.stopPropagation();

      if (e.key === 'Enter') { e.preventDefault(); commit(); }

      else if (e.key === 'Escape') { e.preventDefault(); cancel(); }

    });

  }



  function personCardHtml(p, i){

    const last = p.last_session_at

      ? new Date(p.last_session_at).toLocaleDateString(undefined, {month:'short', day:'numeric', year:'numeric'})

      : 'never';

    const count = p.session_count || 0;

    return '<div class="iux-person-card" data-id="' + p.id + '">' +

      '<span class="avatar">' + (p.name ? escapeHtml(p.name.charAt(0).toUpperCase()) : '?') + '</span>' +

      '<div class="info">' +

        '<div class="iux-session-label-row" id="__iux_person_row' + i + '">' +

          '<span class="when" id="__iux_person_label' + i + '">' + escapeHtml(p.name) + '</span>' +

          '<button type="button" class="iux-session-edit-btn" id="__iux_person_edit' + i + '" title="Edit participant">' + iuxIcon('type', 11) + '</button>' +

          '<button type="button" class="iux-session-edit-btn" id="__iux_person_delete' + i + '" title="Delete participant">' + iuxIcon('trash', 11) + '</button>' +

        '</div>' +

        '<div class="meta">' + count + ' tracking session' + (count === 1 ? '' : 's') + ' &middot; Last tracked: ' + last + '</div>' +

      '</div>' +

      '<span class="go">' + iuxIcon('arrow-right', 12) + '</span>' +

    '</div>';

  }



  function renderPersonList(list){

    const body = document.getElementById('__iux_sessions_body');

    if (!list.length) {

      body.innerHTML = '<div class="iux-sessions-empty">No participants yet β€” add one from the Participant panel.</div>';

      return;

    }

    body.innerHTML = list.map(function(p, i){ return personCardHtml(p, i); }).join('');

    Array.from(body.children).forEach(function(card, i){

      const p = list[i];

      card.addEventListener('click', function(){ openPersonDetails(p); });

      const editBtn = document.getElementById('__iux_person_edit' + i);

      if (editBtn) {

        editBtn.addEventListener('click', function(e){ e.stopPropagation(); startEditingPerson(list, i); });

      }

      const delBtn = document.getElementById('__iux_person_delete' + i);

      if (delBtn) {

        delBtn.addEventListener('click', function(e){

          e.stopPropagation();

          if (!confirm('Delete ' + p.name + ' and all ' + (p.session_count || 0) + ' of their sessions? This cannot be undone.')) return;

          window.pywebview.api.delete_participant(p.id, __IUX_TOK__).then(function(res){

            if (!(res && res.ok) && res && res.error) window.insightuxSetStatus && window.insightuxSetStatus(res.error);

            openPersonsList();

          });

        });

      }

    });

  }



  function startEditingPerson(list, i){

    const p = list[i];

    const row = document.getElementById('__iux_person_row' + i);

    row.className = 'iux-person-edit';

    row.innerHTML =

      '<input type="text" class="iux-session-name-input" id="__iux_person_name_input' + i + '" value="' +

        escapeHtml(p.name) + '" placeholder="Name" maxlength="60">' +

      '<input type="text" class="iux-session-name-input" id="__iux_person_notes_input' + i + '" value="' +

        escapeHtml(p.notes || '') + '" placeholder="Notes (optional)" maxlength="200">' +

      '<div class="iux-person-edit-actions">' +

        '<button type="button" class="iux-btn" id="__iux_person_save' + i + '" title="Save">' + iuxIcon('check', 12) + '</button>' +

        '<button type="button" class="iux-btn" id="__iux_person_cancel' + i + '" title="Cancel">' + iuxIcon('x', 12) + '</button>' +

      '</div>';

    const nameInput = document.getElementById('__iux_person_name_input' + i);

    const notesInput = document.getElementById('__iux_person_notes_input' + i);

    [nameInput, notesInput].forEach(function(el){ el.addEventListener('click', function(e){ e.stopPropagation(); }); });

    nameInput.focus();

    nameInput.select();



    function commit(){

      const name = nameInput.value.trim();

      if (!name) { nameInput.focus(); return; }

      window.pywebview.api.update_participant(p.id, name, notesInput.value, __IUX_TOK__).then(function(res){

        if (!(res && res.ok) && res && res.error) window.insightuxSetStatus && window.insightuxSetStatus(res.error);

        openPersonsList();

      });

    }

    function cancel(){ openPersonsList(); }



    document.getElementById('__iux_person_save' + i).addEventListener('click', function(e){ e.stopPropagation(); commit(); });

    document.getElementById('__iux_person_cancel' + i).addEventListener('click', function(e){ e.stopPropagation(); cancel(); });

    [nameInput, notesInput].forEach(function(el){

      el.addEventListener('keydown', function(e){

        e.stopPropagation();

        if (e.key === 'Enter') { e.preventDefault(); commit(); }

        else if (e.key === 'Escape') { e.preventDefault(); cancel(); }

      });

    });

  }



  function openPersonDetails(person){

    openSessionsModal(person.name, function(){ openPersonsList(); }, true);

    if (!window.pywebview) return;

    const ctx = {

      openReport: function(id){ window.pywebview.api.open_participant_session_report(person.id, id, sessionHistoryReturnUrl('participant', person.id), __IUX_TOK__); },

      rename: function(id, name){ return window.pywebview.api.rename_participant_session(person.id, id, name, __IUX_TOK__); },

      remove: function(id){ return window.pywebview.api.delete_participant_session(person.id, id, __IUX_TOK__); },

      export: function(id){ return window.pywebview.api.export_participant_session(person.id, id, sessionHistoryReturnUrl('participant', person.id), __IUX_TOK__); },

      reload: function(){ load(); }

    };

    function load(){

      window.pywebview.api.list_participant_sessions(person.id, __IUX_TOK__).then(function(sessions){

        __iuxAllSessions = sessions || [];

        __iuxSessionsCtx = ctx;

        applySessionFilter();

      });

    }

    load();

  }



  function openPersonsList(){

    openSessionsModal('Persons', null, false);

    if (!window.pywebview) return;

    window.pywebview.api.list_participants(__IUX_TOK__).then(function(list){

      renderPersonList(list || []);

    });

  }



  function sessionHistoryReturnUrl(kind, participantId){

    const base = window.location.href.split('#')[0];

    const params = new URLSearchParams();

    params.set('insightux_sessions', kind);

    if (participantId) params.set('participant', participantId);

    return base + '#' + params.toString();

  }



  function openMySessions(){

    openSessionsModal('My Sessions', null, true);

    if (!window.pywebview) return;

    const ctx = {

      openReport: function(id){ window.pywebview.api.open_my_session_report(id, sessionHistoryReturnUrl('my'), __IUX_TOK__); },

      rename: function(id, name){ return window.pywebview.api.rename_my_session(id, name, __IUX_TOK__); },

      remove: function(id){ return window.pywebview.api.delete_my_session(id, __IUX_TOK__); },

      export: function(id){ return window.pywebview.api.export_my_session(id, sessionHistoryReturnUrl('my'), __IUX_TOK__); },

      reload: function(){ load(); }

    };

    function load(){

      window.pywebview.api.list_my_sessions(__IUX_TOK__).then(function(sessions){

        __iuxAllSessions = sessions || [];

        __iuxSessionsCtx = ctx;

        applySessionFilter();

      });

    }

    load();

  }



  const sessionReturnState = new URLSearchParams(window.location.hash.slice(1));

  const sessionReturnKind = sessionReturnState.get('insightux_sessions');

  if (sessionReturnKind === 'my') {

    const restoreMySessions = setInterval(function(){

      if (!window.pywebview || !window.pywebview.api) return;

      clearInterval(restoreMySessions);

      openMySessions();

    }, 100);

  } else if (sessionReturnKind === 'participant' && sessionReturnState.get('participant')) {

    const participantId = sessionReturnState.get('participant');

    const restoreParticipantSessions = setInterval(function(){

      if (!window.pywebview || !window.pywebview.api) return;

      clearInterval(restoreParticipantSessions);

      window.pywebview.api.list_participants(__IUX_TOK__).then(function(list){

        const person = (list || []).find(function(item){ return item.id === participantId; });

        if (person) openPersonDetails(person);

        else openPersonsList();

      });

    }, 100);

  }



  const infoModal = document.createElement('div');

  infoModal.id = '__iux_info_modal';

  infoModal.innerHTML = `

    <div class="box iux-glass iux-fade-in">

      <h4 id="__iux_info_title"></h4>

      <p id="__iux_info_body"></p>

      <div id="__iux_info_actions"><button type="button" class="iux-btn" id="__iux_info_close">Close</button></div>

    </div>

  `;

  document.documentElement.appendChild(infoModal);

  infoModal.addEventListener('click', function(e){ if (e.target === infoModal) infoModal.classList.remove('open'); });



  const calQualityModal = document.createElement('div');

  calQualityModal.id = '__iux_cal_quality_modal';

  calQualityModal.innerHTML = `

    <div class="backdrop"></div>

    <div class="card iux-fade-in" role="dialog" aria-modal="true" aria-labelledby="__iux_cal_quality_title">

      <button type="button" class="close" id="__iux_cal_quality_close" aria-label="Close calibration and validation dialog" title="Close">Γ—</button>

      <div class="icon" id="__iux_cal_quality_icon"></div>

      <div class="kicker" id="__iux_cal_quality_kicker"></div>

      <h2 id="__iux_cal_quality_title"></h2>

      <p id="__iux_cal_quality_body"></p>

      <div class="progress" id="__iux_cal_quality_progress" style="display:none;">

        <div class="progress-head"><span id="__iux_cal_quality_progress_label"></span><span id="__iux_cal_quality_progress_pct"></span></div>

        <div class="progress-track" id="__iux_cal_quality_progress_track"><div class="progress-fill" id="__iux_cal_quality_progress_fill"></div></div>

      </div>

      <div class="metrics" id="__iux_cal_quality_metrics"></div>

      <div class="actions" id="__iux_cal_quality_actions"></div>

    </div>`;

  document.documentElement.appendChild(calQualityModal);

  function calQualityOpen(state){ calQualityModal.dataset.state = state || 'result'; calQualityModal.classList.add('open'); }

  function calQualityClose(){ calQualityModal.dataset.state = 'closed'; calQualityModal.classList.remove('open'); }

  function calQualityDismiss(){

    const wasRunning = calQualityModal.dataset.state === 'running';

    const wasCalibrating = calQualityModal.dataset.state === 'calibrating';

    calQualityClose();

    if (wasRunning && window.pywebview && window.pywebview.api && window.pywebview.api.cancel_validation) {

      window.pywebview.api.cancel_validation(__IUX_TOK__);

    }

    if (wasCalibrating && window.pywebview && window.pywebview.api && window.pywebview.api.cancel_calibration) {

      window.pywebview.api.cancel_calibration(__IUX_TOK__);

    }

  }

  // While calibration or validation is running, ONLY the x button cancels it.

  // Clicking the dimmed area must never abort a run; once a result is showing

  // (nothing left to cancel) it still closes the card as before.

  calQualityModal.querySelector('.backdrop').addEventListener('click', function(e){

    const st = calQualityModal.dataset.state;

    if (st === 'running' || st === 'calibrating') { e.stopPropagation(); return; }

    calQualityClose();

  });

  document.getElementById('__iux_cal_quality_close').addEventListener('click', calQualityDismiss);

  function calQualityMetric(label, value){

    return '<div class="metric"><div class="label">'+label+'</div><div class="value">'+value+'</div></div>';

  }

  function calQualityButton(id, label, primary){

    return '<button type="button" class="iux-btn'+(primary?' primary':'')+'" id="'+id+'">'+label+'</button>';

  }

  function calQualityShowProgress(stage, message, label, progress){

    calQualityModal.dataset.state = 'calibrating';

    document.getElementById('__iux_cal_quality_icon').innerHTML = iuxIcon('eye', 22);

    document.getElementById('__iux_cal_quality_icon').style.background = 'rgba(56,189,248,.12)';

    document.getElementById('__iux_cal_quality_icon').style.color = 'var(--iux-info)';

    document.getElementById('__iux_cal_quality_kicker').textContent = stage || 'CALIBRATION IN PROGRESS';

    document.getElementById('__iux_cal_quality_title').textContent = 'Preparing your gaze calibration';

    document.getElementById('__iux_cal_quality_body').textContent = message || 'InsightUX is collecting and processing calibration data.';

    document.getElementById('__iux_cal_quality_metrics').innerHTML = '';

    document.getElementById('__iux_cal_quality_actions').innerHTML = '';

    document.getElementById('__iux_cal_quality_progress').style.display = 'block';

    document.getElementById('__iux_cal_quality_progress_label').textContent = label || '';

    const track = document.getElementById('__iux_cal_quality_progress_track');

    const fill = document.getElementById('__iux_cal_quality_progress_fill');

    const pct = document.getElementById('__iux_cal_quality_progress_pct');

    if (progress !== null && progress !== undefined && Number.isFinite(Number(progress))) {

      const bounded = Math.max(0, Math.min(100, Number(progress)));

      track.classList.remove('indeterminate');

      fill.style.width = bounded+'%';

      pct.textContent = Math.round(bounded)+'%';

    } else {

      track.classList.add('indeterminate');

      fill.style.width = '';

      pct.textContent = '';

    }

    calQualityOpen('calibrating');

  }



  window.insightuxShowCameraError = function(message){

    window.insightuxSetSessionUI(false, 0, false, false);

    showInfo('eye', 'Camera access required', message);

  };



  function showInfo(icon, title, body){

    document.getElementById('__iux_info_title').innerHTML = iuxIcon(icon, 16) + ' ' + title;

    document.getElementById('__iux_info_body').textContent = body;

    document.getElementById('__iux_info_actions').innerHTML = '<button type="button" class="iux-btn" id="__iux_info_close">Close</button>';

    document.getElementById('__iux_info_close').addEventListener('click', function(){ infoModal.classList.remove('open'); });

    infoModal.classList.add('open');

  }

  window.insightuxShowValidationResult = function(result){

    if (!result) return;

    const grade = String(result.grade || 'NO_BASELINE');

    const good = grade === 'GOOD';

    const moderate = grade === 'MODERATE';

    const cls = good ? 'quality-good' : (moderate ? 'quality-warning' : 'quality-poor');

    const title = result.title || (good ? 'CALIBRATION LOOKS GOOD' : (moderate ? 'CALIBRATION IS MODERATE' : (grade === 'NO_BASELINE' ? 'VALIDATION COMPLETE' : 'CALIBRATION QUALITY IS POOR')));

    const icon = document.getElementById('__iux_cal_quality_icon');

    icon.style.display = 'grid';

    icon.innerHTML = iuxIcon(good ? 'check' : 'target', 22);

    icon.style.background = good ? 'rgba(52,211,153,.12)' : (moderate ? 'rgba(245,158,11,.12)' : 'rgba(251,113,133,.12)');

    icon.style.color = good ? 'var(--iux-success)' : (moderate ? 'var(--iux-warning)' : 'var(--iux-danger)');

    document.getElementById('__iux_cal_quality_kicker').textContent = 'VALIDATION VS SAVED BEST';

    document.getElementById('__iux_cal_quality_title').innerHTML = '<span class="'+cls+'">'+title+'</span>';

    document.getElementById('__iux_cal_quality_body').textContent = result.message || 'Validation completed. Review the measured result against the saved best.';

    document.getElementById('__iux_cal_quality_progress').style.display = 'none';

    const currentZonePct = Number(result.targets) > 0 ? 100 * Number(result.zone_hits) / Number(result.targets) : 0;

    let metrics =

      calQualityMetric('Mean Gaze Error', Math.round(Number(result.mean_error_px))+' px') +

      calQualityMetric('Mean Error', Number(result.mean_error_pct).toFixed(1)+'% of screen diagonal') +

      calQualityMetric('Median Gaze Error', Math.round(Number(result.median_error_px))+' px') +

      calQualityMetric('3Γ—3 Zone Accuracy', result.zone_hits+'/'+result.targets+' ('+currentZonePct.toFixed(0)+'%)');

    if (result.baseline_error_pct != null) {

      const delta = Number(result.delta_percentage_points);

      const difference = Math.abs(delta) < 0.05 ? 'Same as saved best' : Math.abs(delta).toFixed(1)+' percentage points '+(delta > 0 ? 'worse' : 'better');

      metrics += calQualityMetric('Saved Best Error', Number(result.baseline_error_pct).toFixed(1)+'% of screen diagonal') +

        calQualityMetric('Difference from Best', difference) +

        (result.baseline_error_px != null ? calQualityMetric('Saved Best Mean Error', Math.round(Number(result.baseline_error_px))+' px') : '') +

        (result.baseline_zone_hit_rate != null ? calQualityMetric('Saved Best Zone Accuracy', Math.round(Number(result.baseline_zone_hit_rate))+'%') : '');

    } else {

      metrics += calQualityMetric('Saved Best Comparison', 'Unavailable');

    }

    document.getElementById('__iux_cal_quality_metrics').innerHTML = metrics;

    document.getElementById('__iux_cal_quality_actions').innerHTML =

      calQualityButton('__iux_cal_quality_recalibrate', 'Recalibrate', false) +

      calQualityButton('__iux_cal_quality_continue', 'Proceed without recalibrating', true);

    document.getElementById('__iux_cal_quality_continue').onclick = calQualityClose;

    document.getElementById('__iux_cal_quality_recalibrate').onclick = function(){

      calQualityClose();

      if (window.pywebview && window.pywebview.api && window.pywebview.api.start_calibration) window.pywebview.api.start_calibration(__IUX_TOK__);

    };

    calQualityOpen('result');

  };

  window.insightuxShowCalibrationComplete = function(){

    const icon = document.getElementById('__iux_cal_quality_icon');

    icon.style.display = 'grid';

    icon.innerHTML = iuxIcon('check', 22);

    icon.style.background = 'rgba(52,211,153,.12)';

    icon.style.color = 'var(--iux-success)';

    document.getElementById('__iux_cal_quality_kicker').textContent = 'CALIBRATION COMPLETE';

    document.getElementById('__iux_cal_quality_title').textContent = 'Measure this calibration';

    document.getElementById('__iux_cal_quality_body').textContent = 'Calibration created a gaze mapping. Run the independent 9-point validation to compare its measured accuracy with the saved best result.';

    document.getElementById('__iux_cal_quality_progress').style.display = 'none';

    document.getElementById('__iux_cal_quality_metrics').innerHTML = '';

    document.getElementById('__iux_cal_quality_actions').innerHTML =

      calQualityButton('__iux_cal_quality_validate', 'Run validation', true) +

      calQualityButton('__iux_cal_quality_continue', 'Proceed without validation', false);

    document.getElementById('__iux_cal_quality_validate').onclick = function(){

      calQualityClose();

      if (window.pywebview && window.pywebview.api && window.pywebview.api.run_validation) window.pywebview.api.run_validation(__IUX_TOK__);

    };

    document.getElementById('__iux_cal_quality_continue').onclick = calQualityClose;

    calQualityOpen('prompt');

  };

  window.insightuxShowCalibrationRunning = function(){

    calQualityShowProgress('CALIBRATION STARTED', 'Follow the targets in the calibration window and keep your head steady. InsightUX will process the captured samples after the targets are collected.', 'Waiting for calibration to start', 0);

  };

  window.insightuxUpdateCalibrationProgress = function(stage, message, label, progress){

    calQualityShowProgress(stage, message, label, progress);

  };

  window.insightuxShowValidationRunning = function(){

    const icon = document.getElementById('__iux_cal_quality_icon');

    icon.style.display = 'grid';

    icon.innerHTML = iuxIcon('target', 22);

    icon.style.background = 'rgba(56,189,248,.12)';

    icon.style.color = 'var(--iux-info)';

    document.getElementById('__iux_cal_quality_kicker').textContent = 'INDEPENDENT VALIDATION';

    document.getElementById('__iux_cal_quality_title').textContent = 'Measuring calibration accuracy';

    document.getElementById('__iux_cal_quality_body').textContent = 'Look at each of the nine targets until the test finishes. InsightUX is measuring how closely your predicted gaze lands on each target.';

    document.getElementById('__iux_cal_quality_progress').style.display = 'none';

    document.getElementById('__iux_cal_quality_metrics').innerHTML = '';

    document.getElementById('__iux_cal_quality_actions').innerHTML = '';

    calQualityOpen('running');

  };

  window.insightuxShowValidationError = function(message){

    const icon = document.getElementById('__iux_cal_quality_icon');

    icon.style.display = 'grid';

    icon.innerHTML = iuxIcon('info', 22);

    icon.style.background = 'rgba(245,158,11,.12)';

    icon.style.color = 'var(--iux-warning)';

    document.getElementById('__iux_cal_quality_kicker').textContent = 'VALIDATION NOT COMPLETED';

    document.getElementById('__iux_cal_quality_title').textContent = 'We could not measure calibration accuracy';

    document.getElementById('__iux_cal_quality_body').textContent = message || 'The independent test did not measure all nine targets. Please retry validation or continue without it.';

    document.getElementById('__iux_cal_quality_progress').style.display = 'none';

    document.getElementById('__iux_cal_quality_metrics').innerHTML = '';

    document.getElementById('__iux_cal_quality_actions').innerHTML =

      calQualityButton('__iux_cal_quality_retry', 'Retry validation', true) +

      calQualityButton('__iux_cal_quality_error_close', 'Proceed without validation', false);

    document.getElementById('__iux_cal_quality_retry').onclick = function(){

      calQualityClose();

      if (window.pywebview && window.pywebview.api && window.pywebview.api.run_validation) window.pywebview.api.run_validation(__IUX_TOK__);

    };

    document.getElementById('__iux_cal_quality_error_close').onclick = calQualityClose;

    calQualityOpen('error');

  };

  window.insightuxShowCalibrationError = function(message){

    const icon = document.getElementById('__iux_cal_quality_icon');

    icon.style.display = 'grid';

    icon.innerHTML = iuxIcon('info', 22);

    icon.style.background = 'rgba(245,158,11,.12)';

    icon.style.color = 'var(--iux-warning)';

    document.getElementById('__iux_cal_quality_kicker').textContent = 'CALIBRATION NOT COMPLETED';

    document.getElementById('__iux_cal_quality_title').textContent = 'Calibration stopped before it finished';

    document.getElementById('__iux_cal_quality_body').textContent = message || 'Calibration did not complete. Please try again or continue without recalibrating.';

    document.getElementById('__iux_cal_quality_progress').style.display = 'none';

    document.getElementById('__iux_cal_quality_metrics').innerHTML = '';

    document.getElementById('__iux_cal_quality_actions').innerHTML =

      calQualityButton('__iux_cal_quality_retry_calibration', 'Try calibration again', true) +

      calQualityButton('__iux_cal_quality_calibration_error_close', 'Close', false);

    document.getElementById('__iux_cal_quality_retry_calibration').onclick = function(){

      calQualityClose();

      if (window.pywebview && window.pywebview.api && window.pywebview.api.start_calibration) window.pywebview.api.start_calibration(__IUX_TOK__);

    };

    document.getElementById('__iux_cal_quality_calibration_error_close').onclick = calQualityClose;

    calQualityOpen('error');

  };

  document.getElementById('__iux_more_help').addEventListener('click', function(){

    closeAllPops();

    showInfo('info', 'Help', 'Press S to start tracking on any website, E to stop. H toggles the attention heatmap, M opens the mouse panel, and X quits InsightUX. Calibrate and Validate live in the left sidebar.');

  });

  document.getElementById('__iux_more_about').addEventListener('click', function(){

    closeAllPops();

    showInfo('eye', 'About InsightUX', 'InsightUX v__INSIGHTUX_VERSION__ β€” AI-powered eye and mouse tracking research browser. Each profile is private: sessions, calibration, and reports are stored separately per profile and never shared with other profiles on this device. Switching profiles or logging out clears the active profile from memory β€” the next person has to sign in with their own password before any of that data is reachable again.');

  });



  // -- security icon (padlock for https, globe otherwise) --

  document.getElementById('__iux_security_icon').innerHTML =

    iuxIcon(location.protocol === 'https:' ? 'lock' : 'globe', 14);



  // -- status text / pills, driven by the same Python calls as before --

  const statusEl = () => document.querySelector('#__insightux_status .txt');

  window.insightuxSetStatus = function(text){

    const el = statusEl();

    if (el) el.textContent = text;

    // Only ever a real event (calibration/validation launch+finish, tracking

    // start, "wrapping up", or an error) reaches this function β€” the default

    // idle hint baked into the HTML never does β€” so showing the pill here

    // and nowhere else keeps it hidden during plain idle browsing without

    // touching any of the calls themselves.

    const wrap = document.getElementById('__insightux_status');

    if (wrap) wrap.style.display = text ? 'inline-flex' : 'none';

  };



  let sessionElapsedBaseMs = 0, sessionRunStartedAt = null, timerInterval = null;

  function showReportLoading(){

    if (document.getElementById('__iux_report_loading')) return;

    const screen = document.createElement('div');

    screen.id = '__iux_report_loading';

    screen.setAttribute('role', 'status');

    screen.setAttribute('aria-live', 'polite');

    screen.innerHTML = `<div class="iux-report-glow iux-report-glow-a"></div><div class="iux-report-glow iux-report-glow-b"></div><main class="iux-report-card"><div class="iux-report-brand"><span class="iux-report-mark">${iuxIcon('eye',22)}</span><span>InsightUX</span></div><div class="iux-report-kicker">SESSION COMPLETE</div><h1>Your report is taking shape</h1><p class="iux-report-copy">We’re analyzing your session and preparing your personalized UX insights. This may take a little while.</p><div class="iux-report-progress"><div class="iux-report-progress-track"><span></span></div><div class="iux-report-progress-label">Preparing your report</div></div><ol class="iux-report-steps"><li class="done"><span class="step-mark">${iuxIcon('check',13)}</span><span>Session captured</span></li><li class="active"><span class="step-mark"><i></i></span><span>Analyzing gaze and interactions</span></li><li><span class="step-mark"></span><span>Building report visualizations</span></li><li><span class="step-mark"></span><span>Opening your report</span></li></ol><div class="iux-report-foot">You can stay on this screen. Your report will open automatically when it’s ready.</div></main>`;

    const style = document.createElement('style');

    style.id = '__iux_report_loading_style';

    style.textContent = `#__iux_report_loading{position:fixed;inset:0;z-index:2147483647;display:grid;place-items:center;overflow:auto;padding:28px 18px;background:radial-gradient(ellipse at 50% 0%,#302b25 0%,#1b1918 54%,#171513 100%);color:#f9f8f3;font:14px -apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif}#__iux_report_loading *{box-sizing:border-box}#__iux_report_loading .iux-report-glow{position:absolute;width:240px;height:240px;border-radius:50%;filter:blur(80px);opacity:.12;pointer-events:none;background:#ffe9a8}#__iux_report_loading .iux-report-glow-a{top:8%;left:12%}#__iux_report_loading .iux-report-glow-b{right:10%;bottom:8%;background:#7fe0c8;opacity:.08}#__iux_report_loading .iux-report-card{position:relative;width:min(560px,100%);padding:clamp(24px,5vw,42px);border:1px solid rgba(255,255,255,.11);border-radius:24px;background:rgba(35,32,29,.82);box-shadow:0 28px 90px rgba(0,0,0,.35);backdrop-filter:blur(18px)}#__iux_report_loading .iux-report-brand{display:flex;align-items:center;gap:10px;font-size:14px;font-weight:700;letter-spacing:.01em}#__iux_report_loading .iux-report-mark{display:grid;place-items:center;width:36px;height:36px;border-radius:11px;background:#ffe9a8;color:#312f2e}#__iux_report_loading .iux-report-kicker{margin-top:34px;color:#c5ae68;font-size:10px;font-weight:800;letter-spacing:.16em}#__iux_report_loading h1{margin:9px 0 10px;font-size:clamp(27px,5vw,36px);line-height:1.12;letter-spacing:-.035em}#__iux_report_loading .iux-report-copy{max-width:440px;margin:0;color:#c6bcb2;line-height:1.65;font-size:14px}#__iux_report_loading .iux-report-progress{margin-top:28px}#__iux_report_loading .iux-report-progress-track{height:4px;overflow:hidden;border-radius:99px;background:rgba(255,255,255,.1)}#__iux_report_loading .iux-report-progress-track span{display:block;width:38%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#ffe9a8,#7fe0c8);animation:iux-report-progress 2.4s ease-in-out infinite}#__iux_report_loading .iux-report-progress-label{margin-top:9px;color:#f2dda0;font-size:11px;font-weight:700}#__iux_report_loading .iux-report-steps{display:grid;gap:13px;list-style:none;margin:24px 0 0;padding:0}#__iux_report_loading .iux-report-steps li{display:flex;align-items:center;gap:11px;color:#817b74;font-size:12px}#__iux_report_loading .iux-report-steps li.done{color:#c6bcaa}#__iux_report_loading .iux-report-steps li.active{color:#f9f8f3;font-weight:700}#__iux_report_loading .step-mark{display:grid;place-items:center;width:20px;height:20px;border:1px solid rgba(255,255,255,.16);border-radius:50%;color:#7fe0c8}#__iux_report_loading li.done .step-mark{border-color:rgba(127,224,200,.35);background:rgba(127,224,200,.1)}#__iux_report_loading li.active .step-mark{border-color:#ffe9a8}#__iux_report_loading li.active .step-mark i{width:6px;height:6px;border-radius:50%;background:#ffe9a8;animation:iux-report-pulse 1.6s ease-in-out infinite}#__iux_report_loading .iux-report-foot{margin-top:26px;padding-top:18px;border-top:1px solid rgba(255,255,255,.09);color:#8e8e92;font-size:11px;line-height:1.5}@keyframes iux-report-progress{0%{transform:translateX(-115%)}100%{transform:translateX(350%)}}@keyframes iux-report-pulse{50%{opacity:.35;transform:scale(.75)}}@media(prefers-reduced-motion:reduce){#__iux_report_loading .iux-report-progress-track span,#__iux_report_loading li.active .step-mark i{animation:none}}`;

    document.head.appendChild(style);

    (document.body || document.documentElement).appendChild(screen);

    document.body.setAttribute('aria-busy', 'true');

  }



  function hideReportLoading(){

    ['__iux_report_loading', '__iux_report_loading_style'].forEach(function(id){

      const el = document.getElementById(id);

      if (el) el.remove();

    });

    if (document.body) document.body.removeAttribute('aria-busy');

  }



  function tickTimer(){

    const pill = document.getElementById('__iux_pill_time');

    if (sessionRunStartedAt === null && sessionElapsedBaseMs <= 0) {

      pill.style.display = 'none'; return;

    }

    const runningMs = sessionRunStartedAt === null ? 0 : (Date.now() - sessionRunStartedAt);

    const diff = Math.max(0, Math.floor((sessionElapsedBaseMs + runningMs) / 1000));

    const m = String(Math.floor(diff / 60)).padStart(2, '0');

    const s = String(diff % 60).padStart(2, '0');

    pill.querySelector('.txt').textContent = m + ':' + s;

    pill.style.display = 'inline-flex';

  }

  // The timer is based on ACTIVE recording time, not wall-clock time.

  // Navigation/render/capture transitions explicitly pause it, and a fresh

  // CHROME_JS injection receives the accumulated active milliseconds from

  // Python so the visible timer never counts time the user could not see/use

  // the new page.

  window.insightuxSetSessionUI = function(isTracking, activeElapsedMs, isPaused, reportPending){

    const btn = document.getElementById('__iux_session');

    if (btn) {

      btn.innerHTML = isTracking

        ? iuxIcon('stop',18) + '<span class="lbl">Stop<br>Session</span><span class="tip">Stop Session</span>'

        : iuxIcon('play',18) + '<span class="lbl">Start<br>Session</span><span class="tip">Start Session</span>';

      btn.classList.toggle('active', isTracking);

    }

    document.getElementById('__iux_pill_eye').classList.toggle('on', isTracking);

    document.getElementById('__iux_pill_mouse').classList.toggle('on', isTracking);

    const indicators = document.getElementById('__insightux_indicators');

    if (indicators) indicators.style.display = isTracking ? 'flex' : 'none';

    isTrackingNow = isTracking;

    controlsRevealed = false;

    applyTrackingChrome();

    if (isTracking) {

      sessionElapsedBaseMs = Math.max(0, Number(activeElapsedMs) || 0);

      sessionRunStartedAt = isPaused ? null : Date.now();

      if (timerInterval) clearInterval(timerInterval);

      timerInterval = setInterval(tickTimer, 250);

      tickTimer();

    } else {

      sessionElapsedBaseMs = 0;

      sessionRunStartedAt = null;

      if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }

      tickTimer();

    }

    // Stopping/cancelling alone does not mean a report is being generated.

    if (!isTracking && reportPending && isTrackable) showReportLoading();

    else hideReportLoading();

  };

  window.insightuxShowUpdate = function(version, url){

    const el = document.getElementById('__insightux_update');

    if (!el) return;

    el.innerHTML = iuxIcon('download', 12) + '<span>Update available (v' + version + ')</span>';

    el.style.display = 'inline-flex';

    el.onclick = function(){

      if (window.pywebview && window.pywebview.api && window.pywebview.api.open_update_page) {

        window.pywebview.api.open_update_page(url, __IUX_TOK__);

      }

    };

  };



  // -- address bar / navigation (pure DOM history/location, no Python round-trip) --

  const addrInput = document.getElementById('__iux_addr');

  addrInput.value = isLanding ? '' : location.href;

  document.getElementById('__iux_addr_form').addEventListener('submit', function(e){

    e.preventDefault();

    const raw = addrInput.value.trim();

    if (!raw) return;

    const looksLikeUrl = /^https?:\/\//i.test(raw) ||

                          (/^[\w-]+(\.[\w-]+)+([/?#].*)?$/i.test(raw) && !raw.includes(' '));

    if (looksLikeUrl) {

      location.href = raw.startsWith('http') ? raw : ('https://' + raw);

    } else {

      location.href = 'https://www.google.com/search?q=' + encodeURIComponent(raw);

    }

  });

  document.getElementById('__iux_back').addEventListener('click', function(){ history.back(); });

  document.getElementById('__iux_fwd').addEventListener('click', function(){ history.forward(); });

  document.getElementById('__iux_reload').addEventListener('click', function(){ location.reload(); });



  // -- keep ALL website navigation inside the InsightUX WebView ---------

  // Some real websites use target=\"_blank\", named targets, or

  // window.open() for normal navigation. WebView2/pywebview can hand those

  // requests to the Windows default browser, which breaks the InsightUX

  // browsing/tracking flow. Force those navigations back into this same

  // WebView instead. Normal same-tab links are left completely untouched.

  // This runs again after every page load because CHROME_JS is re-injected

  // into each newly loaded website.

  if (isTrackable) {

    document.addEventListener('click', function(e){

      if (e.defaultPrevented || e.button !== 0) return;

      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;



      const anchor = e.target && e.target.closest

        ? e.target.closest('a[href]')

        : null;

      if (!anchor) return;



      const target = (anchor.getAttribute('target') || '').trim().toLowerCase();

      if (!target || target === '_self') return;



      const href = anchor.href;

      if (!href || href.startsWith('javascript:') || href.startsWith('#')) return;



      e.preventDefault();

      e.stopImmediatePropagation();

      location.href = href;

    }, true);



    // A few sites use forms with target=\"_blank\" instead of anchors.

    document.addEventListener('submit', function(e){

      if (e.defaultPrevented) return;

      const form = e.target;

      if (!form || !form.getAttribute) return;



      const target = (form.getAttribute('target') || '').trim().toLowerCase();

      if (!target || target === '_self') return;



      const action = form.action || location.href;

      if (!action || action.startsWith('javascript:')) return;



      // Let the normal form submission happen, but rewrite the target so

      // WebView2 does not create/send a separate external window.

      form.setAttribute('target', '_self');

    }, true);



    // Catch JavaScript-driven popups such as window.open(url, '_blank').

    // Returning the current window also lets code that does

    // popup.location = ... continue to navigate inside InsightUX.

    const __iuxNativeWindowOpen = window.open;

    window.open = function(url, target, features) {

      try {

        if (url && String(url) !== 'about:blank') {

          const resolved = new URL(String(url), location.href).href;

          location.href = resolved;

        }

      } catch (_) {

        if (url) location.href = String(url);

      }

      return window;

    };

  }



  // -- sidebar actions (Python decides validity β€” camera/session conflicts,

  // wrong page β€” and reports back through the status text) --

  function callApi(method){

    if (window.pywebview && window.pywebview.api && window.pywebview.api[method]) {

      window.pywebview.api[method](__IUX_TOK__);

    }

  }

  // A page loaded over http(s) can't script-navigate itself to a file://

  // URL β€” the browser silently blocks it, no exception, no navigation β€”

  // so this has to go through the native window.load_url() call in

  // Api.go_home() instead of a plain location.href assignment.

  document.getElementById('__iux_home').addEventListener('click', function(){ callApi('go_home'); });

  document.getElementById('__iux_calibrate').addEventListener('click', function(){ callApi('start_calibration'); });

  document.getElementById('__iux_validate').addEventListener('click', function(){ callApi('run_validation'); });

  document.getElementById('__iux_session').addEventListener('click', function(){ callApi('toggle_session'); });



  // -- adaptive visibility while browsing a real website: hide on scroll

  // down, reveal on scroll up or near the top. Landing page keeps chrome

  // permanently visible (no listener attached there); report page never

  // reaches this code at all (whole block is skipped when isReport).

  if (isTrackable) {

    let lastScrollY = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;

    const REVEAL_ZONE = 80, HIDE_DELTA = 24;

    window.addEventListener('scroll', function(){

      const y = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;

      const goingDown = y > lastScrollY + HIDE_DELTA;

      const goingUp = y < lastScrollY - HIDE_DELTA;

      if (y < REVEAL_ZONE) {

        toolbar.classList.remove('chrome-hidden');

        sidebar.classList.remove('chrome-hidden');

      } else if (goingDown) {

        toolbar.classList.add('chrome-hidden');

        sidebar.classList.add('chrome-hidden');

        lastScrollY = y;

      } else if (goingUp) {

        toolbar.classList.remove('chrome-hidden');

        sidebar.classList.remove('chrome-hidden');

        lastScrollY = y;

      }

    }, { passive: true });

  }



  }  // end if (!isReport && !isLogin)



  // Every session report can reopen its session-scoped Drishti chat. The

  // pywebview bridge is injected asynchronously, so a one-shot check at script

  // start can miss it on some navigations (that is what hid the button on some

  // reports). Wait for it instead of giving up.

  function iuxWhenApiReady(fn){

    let done = false;

    function go(){ if (done) return; if (window.pywebview && window.pywebview.api) { done = true; fn(); } }

    go(); if (done) return;

    window.addEventListener('pywebviewready', go);

    let tries = 0;

    const iv = setInterval(function(){ go(); if (done || ++tries > 100) clearInterval(iv); }, 200);

  }

  // Runtime fix for "Back to Browser". Reports are static HTML files written when a

  // session ends, so edits to the report template never reach sessions recorded

  // earlier. This listener runs from the browser chrome on every report load instead,

  // in the capture phase so it wins over whatever handler the stored report has

  // (the old one calls history.back(), which reloads the home screen).

  if (isReport) {

    (function(){

      function returnUrl(){

        try {

          const h = new URLSearchParams(location.hash.slice(1)).get('insightux_return');

          if (h) return h;

        } catch (_) {}

        try { return new URLSearchParams(location.search).get('insightux_return') || ''; } catch (_) { return ''; }

      }

      document.addEventListener('click', function(e){

        const t = e.target && e.target.closest ? e.target.closest('#backNav') : null;

        if (!t) return;

        const ret = returnUrl();

        if (!ret || ret.indexOf('insightux_sessions=') === -1) return;  // opened right after a session: normal Back

        e.preventDefault();

        e.stopImmediatePropagation();

        location.replace(ret);

      }, true);

    })();

  }



  if (isReport) iuxWhenApiReady(function(){

    const participantMeta = document.querySelector('meta[name="insightux-participant-id"]');

    const reportQuery = new URLSearchParams(location.search);

    const participantId = (participantMeta && participantMeta.getAttribute('content')) ||

      new URLSearchParams(location.hash.slice(1)).get('insightux_participant') ||

      reportQuery.get('insightux_participant') || participantFromPath_() || null;

    function participantFromPath_(){

      return (decodeURIComponent(location.pathname).match(/[\\/]participants?[\\/]([^\\/]+)[\\/]sessions[\\/]\d{8}_\d{6}[\\/]/) || [])[1] || null;

    }

    // Session id: the timestamp folder name when it matches, otherwise the report's

    // own folder name, a meta tag, or any timestamp in the URL. Never skip the

    // button just because a report was opened through an unusual path.

    const m = __reportPathMatch ||

      (function(){

        const dec = decodeURIComponent(location.pathname || '');

        const metaSid = document.querySelector('meta[name="insightux-session-id"]');

        const cand = (metaSid && metaSid.getAttribute('content')) ||

          (dec.match(/[\\/]([^\\/]+)[\\/][^\\/]*\.html$/) || [])[1] ||

          ((dec + ' ' + location.search + ' ' + location.hash).match(/(\d{8}_\d{6})/) || [])[1] || null;

        return cand ? [cand, cand] : null;

      })();

    if (m) {

        // The Drishti button lives INSIDE the report's own control rows instead of

        // floating over the page, so it can never cover Export / chart-type /

        // close buttons: one in the page header, one in the full-screen chart

        // bar (immediately left of the chart-type button) and one in the

        // screenshot viewer bar.

        const aiStyle = document.createElement('style');

        aiStyle.textContent = '.iux-ai-btn{display:inline-flex;align-items:center;gap:7px;flex:0 0 auto;white-space:nowrap;padding:8px 13px;border:1px solid rgba(0,0,0,.12);border-radius:10px;background:linear-gradient(135deg,#f6c928,#e6a900);color:#241f14;font:700 12px -apple-system,BlinkMacSystemFont,Segoe UI,Arial,sans-serif;cursor:pointer;box-shadow:0 4px 14px rgba(0,0,0,.14);}.iux-ai-btn:hover{filter:brightness(1.05);}.iux-ai-btn:disabled{opacity:.7;cursor:default;}@media print{.iux-ai-btn{display:none!important;}}';

        document.head.appendChild(aiStyle);

        const reportBtns = [];

        function makeReportBtn(){

          const b = document.createElement('button');

          b.type = 'button'; b.className = 'iux-ai-btn'; b.title = 'Ask Drishti AI about this session';

          b.innerHTML = iuxIcon('eye',15) + '<span>Ask Drishti AI</span>';

          b.addEventListener('click', function(ev){ ev.stopPropagation(); openReportDrishti(); });

          reportBtns.push(b);

          return b;

        }

        function placeReportBtns(){

          // 1) page header

          const actions = document.querySelector('.topbar .actions');

          if (actions && !actions.querySelector('.iux-ai-btn')) actions.insertBefore(makeReportBtn(), actions.firstChild);

          // 2) full-screen element chart bar: left of the chart-type button

          const fsBar = document.getElementById('elemFullscreenBar');

          if (fsBar) {

            let b = fsBar.querySelector(':scope > .iux-ai-btn');

            if (!b) { b = makeReportBtn(); fsBar.appendChild(b); }

            const controls = document.getElementById('elemChartControls');

            if (controls && controls.parentNode === fsBar) { if (b.nextSibling !== controls) fsBar.insertBefore(b, controls); }

          }

          // 2b) Attention Heatmaps panel toolbar (next to its Fullscreen / Download buttons)

          const hmDl = document.getElementById('hmDownload');

          if (hmDl && hmDl.parentNode && !hmDl.parentNode.querySelector('.iux-ai-btn')) {

            const hb = makeReportBtn(); hb.style.padding = '7px 11px'; hb.style.fontSize = '11.5px'; hb.style.marginLeft = '6px';

            hmDl.parentNode.insertBefore(hb, hmDl.nextSibling);

          }

          // 3) screenshot / heatmap viewer bar: left of the right-hand tools

          const ivBar = document.querySelector('#iuxViewer .iv-topbar');

          if (ivBar && !ivBar.querySelector('.iux-ai-btn')) {

            const anchor = document.getElementById('ivFullscreen') || document.getElementById('ivDownload') || document.getElementById('ivClose');

            const b = makeReportBtn();

            if (anchor && anchor.parentNode === ivBar) ivBar.insertBefore(b, anchor); else ivBar.appendChild(b);

          }

          // 3b) the full-page heatmap lightbox (#iuxLightbox) built by analysis_microlink.py.

          // Its own tools sit at the right edge, so the button goes just left of the close button.

          const lbx = document.getElementById('iuxLightbox');

          if (lbx && !lbx.querySelector('.iux-ai-btn')) {

            const lb = makeReportBtn();

            lb.style.cssText += ';position:absolute;top:18px;right:74px;z-index:3;height:42px;padding:0 13px;';

            lbx.appendChild(lb);

          }

          // 4) Any other full-screen image/canvas viewer (for example the one added to the

          // report together with the full-page heatmap, which has different element ids).

          // It gets a small button centred at the top so it never covers the viewer's own tools.

          const SKIP = { iuxViewer:1, elemFullscreen:1, printReport:1, __insightux_toolbar:1, __insightux_sidebar:1, __iux_report_loading:1 };

          Array.from(document.body.children).forEach(function(el){

            if (SKIP[el.id] || el.querySelector('#__dr_report_body') || el.querySelector('.iux-ai-btn')) return;

            let cs; try { cs = getComputedStyle(el); } catch (_) { return; }

            if (cs.position !== 'fixed' || cs.display === 'none' || cs.visibility === 'hidden') return;

            const r = el.getBoundingClientRect();

            if (r.width < window.innerWidth * 0.85 || r.height < window.innerHeight * 0.85) return;

            if (!el.querySelector('img,canvas,svg')) return;

            const b = makeReportBtn();

            b.style.cssText += ';position:absolute;top:12px;left:50%;transform:translateX(-50%);z-index:2147483647;';

            el.appendChild(b);

          });

        }

        placeReportBtns();

        try {

          new MutationObserver(placeReportBtns).observe(document.body || document.documentElement, { childList: true, subtree: true });

        } catch (_) {}

        let reportDrishtiWrap = null;

        document.addEventListener('fullscreenchange', function(){

          if (reportDrishtiWrap && reportDrishtiWrap.isConnected) {

            (document.fullscreenElement || document.documentElement).appendChild(reportDrishtiWrap);

          }

        });

        function setReportBtns(disabled, label){

          reportBtns.forEach(function(b){ b.disabled = !!disabled; b.innerHTML = iuxIcon('eye',15) + '<span>' + label + '</span>'; });

        }

        function resetReportButton(){ setReportBtns(false, 'Ask Drishti AI'); }



        async function openReportDrishti(){

          if (reportDrishtiWrap && reportDrishtiWrap.isConnected) {

            const existingInput = reportDrishtiWrap.querySelector('#__dr_r_input');

            if (existingInput) existingInput.focus();

            return;

          }

          setReportBtns(true, 'Opening Drishti…');

          try {

            const res = await window.pywebview.api.get_drishti_conversation(m[1], participantId, __IUX_TOK__);

            if (!res || !res.ok) throw new Error((res && res.error) || 'Could not open this session');

            const wrap = document.createElement('div');

            wrap.style.cssText = 'position:fixed;inset:0;z-index:2147483646;display:flex;align-items:center;justify-content:center;background:rgba(12,10,9,.48);backdrop-filter:blur(7px);';

            wrap.innerHTML = '<div style="width:min(900px,calc(100vw - 44px));height:min(720px,calc(100vh - 44px));background:#faf7ee;border:1px solid rgba(90,80,60,.18);border-radius:22px;box-shadow:0 28px 100px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Arial,sans-serif;">' +

              '<div style="padding:16px 18px;border-bottom:1px solid #e4ddd2;display:flex;align-items:center;gap:10px;"><div style="width:38px;height:38px;border-radius:12px;background:#e9ad00;display:grid;place-items:center;">' + iuxIcon('eye',19) + '</div><div><div style="font-weight:800;font-size:14px;color:#2d2924;">Drishti AI</div><div style="font-size:11px;color:#77706a;">Analyzing this session</div></div><button id="__dr_report_close" style="margin-left:auto;width:30px;height:30px;border:1px solid #ddd4c7;border-radius:8px;background:#fff;color:#5f5850;cursor:pointer;">' + iuxIcon('x',13) + '</button></div>' +

              '<div id="__dr_report_body" style="flex:1;min-height:0;display:flex;flex-direction:column;"></div></div>';

            // In real browser fullscreen (screenshot/heatmap viewer) only the fullscreen

            // element's subtree is visible, so the window must live inside it.

            (document.fullscreenElement || document.documentElement).appendChild(wrap);

            reportDrishtiWrap = wrap;

            const body = wrap.querySelector('#__dr_report_body');

            body.innerHTML = '<div style="padding:22px;display:flex;flex-direction:column;height:100%;"><div style="color:#302c28;font-weight:700;margin-bottom:12px;">Ask anything about this session</div><div id="__dr_r_msgs" style="flex:1;overflow:auto;display:flex;flex-direction:column;gap:10px;padding:8px 0;"></div><div id="__dr_r_att_prev" class="iux-att-preview" style="color:#302c28;"></div><div id="__dr_r_compose" style="display:flex;gap:8px;border-top:1px solid #e4ddd2;padding-top:12px;color:#302c28;"><textarea id="__dr_r_input" placeholder="Ask about this session, name a region (e.g. CONNECT), or attach a picture of one…" style="flex:1;min-height:46px;resize:vertical;border:1px solid #d8d0c4;border-radius:10px;padding:10px;font:12.5px Arial;color:#302c28;"></textarea><button id="__dr_r_send" style="width:46px;border:0;border-radius:10px;background:#e9ad00;color:#2d2924;cursor:pointer;">' + iuxIcon('arrow-right',16) + '</button></div></div>';

            const msgs = body.querySelector('#__dr_r_msgs');

            function bubbleCss(role){

              return 'max-width:82%;align-self:'+(role==='user'?'flex-end':'flex-start')+';background:'+(role==='user'?'#e9ad00':'#fff')+';color:#302c28;padding:10px 12px;border-radius:12px;font:12.5px/1.6 Arial;white-space:pre-wrap;border:1px solid #e0d8cc;';

            }

            // One renderer for live and saved messages so they always look the same.

            function fillBubble(d, role, content, meta){

              d.style.cssText = bubbleCss(role);

              d.textContent = '';

              if (role === 'user') {

                const thumbs = iuxThumbsEl(meta); if (thumbs) d.appendChild(thumbs);

                const tx=document.createElement('div'); tx.textContent=content||''; d.appendChild(tx);

              } else {

                d.classList.add('iux-md'); d.innerHTML = iuxMd(content||'') + iuxRegionCaption(meta);

              }

            }

            function addMsg(role, content, meta){

              const d=document.createElement('div'); fillBubble(d, role, content, meta); msgs.appendChild(d); msgs.scrollTop=msgs.scrollHeight; return d;

            }

            const savedMessages = res.conversation.messages || [];

            savedMessages.forEach(function(x){ addMsg(x.role, x.content, x); });

            if (!savedMessages.length) {

              addMsg('assistant', 'I’m ready to analyze this session. Ask me about attention, gaze behavior, interactions, screenshots, or possible improvements. You can also name a region (e.g. β€œthe CONNECT section”) or attach a picture of one and I’ll tell you how to increase its attention.');

            }

            let conv = res.conversation;

            let reportSending = false;

            const reportAtt = iuxAttachInit({

              textarea: body.querySelector('#__dr_r_input'),

              composeRow: body.querySelector('#__dr_r_compose'),

              previewHost: body.querySelector('#__dr_r_att_prev'),

              dropTarget: body,

              onError: function(m){ addMsg('assistant', m); },

              onChange: function(){ if (reportDraft) reportDraft.touch(); }

            });

            const reportDraft = iuxDraftBinder({

              getCtx: function(){ return { sessionId: m[1], participantId: participantId, conv: conv }; },

              input: body.querySelector('#__dr_r_input'), goalInput: null, att: reportAtt

            });

            reportDraft.restore();

            function setReportBusy(b){

              reportSending = !!b;

              const sb=body.querySelector('#__dr_r_send'), ip=body.querySelector('#__dr_r_input');

              if(sb)sb.disabled=!!b; if(ip)ip.disabled=!!b; reportAtt.setDisabled(!!b);

            }

            function makePending(first){

              const pending=document.createElement('div'); pending.textContent=first?'Preparing your research session…':'Drishti is answering…'; pending.style.cssText='max-width:82%;align-self:flex-start;background:#fff;color:#777;padding:10px 12px;border-radius:12px;font:12.5px/1.6 Arial;'; msgs.appendChild(pending); msgs.scrollTop=msgs.scrollHeight; return pending;

            }

            function bindReportInflight(convId, rec, userBubble, pending){

              rec.ui = {

                live: function(){ return !!(pending && pending.isConnected); },

                onDone: function(r){

                  conv = r.conversation;

                  fillBubble(pending, 'assistant', r.answer, {regions:r.regions, region_source:r.region_source});

                  msgs.scrollTop = msgs.scrollHeight; setReportBusy(iuxAnyInflight());

                },

                onFail: function(msg){

                  if(userBubble) userBubble.style.opacity='.6';

                  pending.textContent = 'Message not sent. ' + (msg || 'Unknown error');

                  const ip=body.querySelector('#__dr_r_input'); if(ip){ ip.value = rec.text; if(rec.att&&rec.att.length)reportAtt.setState({items:rec.att.map(function(u){return{dataUrl:u,name:''};})}); reportDraft.touch(); }

                  setReportBusy(iuxAnyInflight());

                }

              };

            }

            // Re-opened while Drishti is still thinking (or it failed while the window was closed).

            (function(){

              const rec = iuxInflight[conv.conversation_id];

              if (!rec || (conv.messages || []).length > rec.baseCount) { setReportBusy(iuxAnyInflight()); return; }

              const ub = addMsg('user', rec.shownText, iuxLiveMeta(rec.att));

              if (rec.status === 'failed') {

                ub.style.opacity = '.6';

                const note = makePending(false); note.textContent = 'Message not sent. ' + (rec.error || 'Unknown error');

                delete iuxInflight[conv.conversation_id]; setReportBusy(iuxAnyInflight()); return;

              }

              const pend = makePending(rec.firstTurn);

              bindReportInflight(conv.conversation_id, rec, ub, pend); setReportBusy(true);

            })();

            function send(){

              if (reportSending) return;

              const inp=body.querySelector('#__dr_r_input'); const text=(inp.value||'').trim(); const attached=reportAtt.get();

              if(!text && !attached.length)return; reportDraft.cancel();

              const convId = conv.conversation_id;

              const shown = text || (attached.length>1 ? 'Analyze each attached region and suggest how to increase attention on them.' : 'Analyze the attached region and suggest how to increase attention on it.');

              const rec = { status:'pending', text:text, shownText:shown, att:attached.length?attached:null, baseCount:(conv.messages||[]).length, firstTurn:!conv.gemini_interaction_id, ui:null, error:null };

              iuxInflight[convId] = rec; inp.value='';

              // Sent: the pictures leave the composer now (handed back if Drishti fails).

              reportAtt.clear();

              const userBubble = addMsg('user', shown, iuxLiveMeta(attached));

              const pending = makePending(rec.firstTurn);

              bindReportInflight(convId, rec, userBubble, pending); setReportBusy(true);

              window.pywebview.api.send_drishti_message(m[1],participantId,convId,text,'',attached.length?attached:null,__IUX_TOK__).then(function(r){

                if(!r||!r.ok) throw new Error((r&&r.error)||'Drishti could not answer');

                iuxInflightSettle(convId, rec, true, r);

              }).catch(function(e){ iuxInflightSettle(convId, rec, false, (e&&e.message)||'Unknown error'); });

            }

            body.querySelector('#__dr_r_send').onclick=send;

            body.querySelector('#__dr_r_input').addEventListener('keydown',function(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send();}});

            wrap.querySelector('#__dr_report_close').onclick=function(){reportDraft.flush();wrap.remove();reportDrishtiWrap=null;resetReportButton();};

            resetReportButton();

          } catch(e) {

            resetReportButton();

            alert(e.message || 'Could not open Drishti.');

          }

        }

    }

  });



  function isTypingTarget(el){

    if (!el) return false;

    const tag = el.tagName ? el.tagName.toLowerCase() : '';

    return tag === 'input' || tag === 'textarea' || tag === 'select' ||

           el.isContentEditable === true;

  }



  // Tell Python as soon as the current document is leaving. The next

  // document will call on_page_loaded(), which starts the settle timer.

  // This closes the gap between the user's click and the new page rendering.

  window.addEventListener('beforeunload', function(){

    try {

      if (window.pywebview && window.pywebview.api && window.pywebview.api.page_navigation_started) {

        window.pywebview.api.page_navigation_started(__IUX_TOK__);

      }

    } catch (_) {}

  }, { capture: true });



  window.addEventListener('keydown', function(e){

    const key = (e.key || '').toLowerCase();

    const startKey = key === 's' || e.code === 'KeyS';

    const stopKey = key === 'e' || e.code === 'KeyE';

    const quitKey = key === 'x' || e.code === 'KeyX';

    if (!startKey && !stopKey && !quitKey) return;

    if (e.repeat || e.ctrlKey || e.altKey || e.metaKey) return;



    const typingBlocked = isTypingTarget(e.target) || isTypingTarget(document.activeElement);

    const apiReady = !!(window.pywebview && window.pywebview.api);

    console.log('[insightux] key=' + key, 'typingBlocked=' + typingBlocked, 'apiReady=' + apiReady, 'focusedEl=' + (document.activeElement && document.activeElement.tagName));



    if (!apiReady) return;

    if (typingBlocked) {

      if (startKey || stopKey) window.insightuxSetStatus("Click somewhere on the page (not a text field) before pressing S/E");

      return;

    }

    if (quitKey) {

      e.preventDefault();

      e.stopPropagation();

      window.pywebview.api.quit_app(__IUX_TOK__);

      return;

    }

    if (!isTrackable) return;  // S/E do nothing on the landing page or a report page



    // Route keyboard shortcuts through the same button handler as a click,

    // so keyboard and sidebar actions share one authenticated API path.

    const shouldToggle = (startKey && !isTrackingNow) || (stopKey && isTrackingNow);

    if (!shouldToggle) return;

    e.preventDefault();

    e.stopPropagation();

    const sessionButton = document.getElementById('__iux_session');

    if (sessionButton) sessionButton.click();

  }, true);  // capture phase β€” fires before page scripts can intercept/stop the event

})();

"""
CHROME_JS = CHROME_JS.replace("__ICONS_JS__", theme.ICONS_JS)
CHROME_JS = CHROME_JS.replace("__THEME_JS__", theme.THEME_TOGGLE_JS)
CHROME_JS = CHROME_JS.replace("__THEME_CSS__", theme.THEME_CSS)
CHROME_JS = CHROME_JS.replace("__INSIGHTUX_VERSION__", VERSION)
CHROME_JS = CHROME_JS.replace("__API_TOKEN__", _API_TOKEN)

# JS: tracking overlay (gaze dot + AOI highlighting) β€” injected only once
# tracking actually starts. Ported directly from run_session.py's JS_SETUP.
TRACKING_JS = r"""

(function(){

  if (window.__insightux) { return; }

  const OWN_UI_IDS = new Set(['__insightux_toolbar', '__insightux_sidebar', '__insightux_pill', '__insightux_canvas', '__insightux_mouse_panel', '__iux_report_loading']);

  const OWN_UI_SELECTOR = '#__insightux_toolbar, #__insightux_sidebar, #__insightux_pill, #__insightux_canvas, #__insightux_mouse_panel, #__iux_report_loading';

  const state = { aois: [] };

  const dwell = { pendLabel: null, pendSince: 0, activeLabel: null, emptySince: 0 };

  const DWELL_MS = 420;

  const RELEASE_MS = 1200;



  let activeBox = null;

  const target  = { fx: 0.5, fy: 0.5 };

  const dot     = { x: null, y: null };

  const DOT_LERP = 0.07;



  const cv = document.createElement('canvas');

  cv.id = '__insightux_canvas';

  cv.style.cssText = 'position:fixed;left:0;top:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483646;';

  (document.body || document.documentElement).appendChild(cv);

  const ctx = cv.getContext('2d');

  function resize(){ cv.width = window.innerWidth; cv.height = window.innerHeight; }

  resize();

  window.addEventListener('resize', resize, {passive:true});

  setInterval(function(){

    if (!document.body.contains(cv)) document.body.appendChild(cv);

  }, 1000);



  // Momentarily hides InsightUX's own injected UI (toolbar, sidebar, this

  // gaze/AOI canvas, the mouse HUD panel) so pyautogui's full-screen grab in

  // maybe_capture_screenshot() captures only the tracked page underneath β€”

  // called from Python right before/after each screenshot, never during

  // normal tracking.

  window.__insightuxSetCaptureMode = function(hidden){

    const vis = hidden ? 'hidden' : '';

    cv.style.visibility = vis;

    ['__insightux_toolbar', '__insightux_sidebar', '__insightux_mouse_panel', '__iux_report_loading'].forEach(function(id){

      const el = document.getElementById(id);

      if (el) el.style.visibility = vis;

    });

  };



  function roundRectPath(c, x, y, w, h, r){

    c.beginPath();

    c.moveTo(x + r, y);

    c.arcTo(x + w, y, x + w, y + h, r);

    c.arcTo(x + w, y + h, x, y + h, r);

    c.arcTo(x, y + h, x, y, r);

    c.arcTo(x, y, x + w, y, r);

    c.closePath();

  }



  const MIN_W=40, MIN_H=24, MAX_AOIS=90, MAX_SCAN=2500;

  const PAD_PX = 90;

  const TALL_WRAPPER_H = 220;



  const ALWAYS_SELECTOR = "nav, header, footer, img, video, iframe, h1, h2, h3, button, figure, [class*='hero'], [class*='banner'], [class*='card']";

  const TEXT_CONTAINER_SELECTOR = "div, span, section, article, main, aside, p, li";



  function hasOwnText(el){

    for (const node of el.childNodes){

      if (node.nodeType === 3 && node.textContent.trim().length > 2) return true;

    }

    return false;

  }



  function labelFor(el){

    if (el.dataset && el.dataset.aoi) return el.dataset.aoi.slice(0,40);

    const tag = el.tagName.toLowerCase();

    if (tag==='nav') return 'navbar';

    if (tag==='header') return 'header';

    if (tag==='footer') return 'footer';

    if (tag==='img'){

      const alt=(el.getAttribute('alt')||'').trim();

      if (alt) return 'img: '+alt.slice(0,30);

      const src=el.getAttribute('src')||'';

      const name=src.split('/').pop().split('?')[0];

      return 'img: '+(name||'image').slice(0,30);

    }

    if (tag==='video') return 'video';

    if (tag==='iframe') return 'embed';

    if (tag==='h1'||tag==='h2'){

      const t=(el.innerText||'').trim().replace(/\s+/g,' ');

      if (t) return tag+': '+t.slice(0,30);

    }

    const id=el.id?('#'+el.id):'';

    let cls='';

    if (el.className && typeof el.className==='string'){

      const f=el.className.trim().split(/\s+/)[0];

      if (f) cls='.'+f;

    }

    const txt=(el.innerText||'').trim().replace(/\s+/g,' ').slice(0,24);

    const base=id||cls||tag;

    return txt?(base+' ('+txt+')'):base;

  }



  function refresh(){

    const vh = window.innerHeight;

    const raw = [];

    const seen = new Set();

    let full = false;



    function consider(el){

      if (full) return;

      // Never track InsightUX's own injected UI (toolbar, sidebar, the

      // gaze-dot canvas, the mouse tracker panel) as if it were page content.

      if (OWN_UI_IDS.has(el.id)) return;

      if (el.closest && el.closest(OWN_UI_SELECTOR)) return;

      const tag = el.tagName.toLowerCase();

      const explicit = !!(el.dataset && el.dataset.aoi);

      if (!explicit){

        const isAlways = (tag==='nav'||tag==='header'||tag==='footer'||tag==='img'||

                           tag==='video'||tag==='iframe'||

                           tag==='h1'||tag==='h2'||tag==='h3'||tag==='button'||tag==='figure') ||

                          (el.className && typeof el.className==='string' &&

                           /hero|banner|card/i.test(el.className));

        if (!isAlways && !hasOwnText(el)) return;

      }

      const r = el.getBoundingClientRect();

      if (r.width<MIN_W || r.height<MIN_H) return;

      if (r.bottom<0 || r.top>vh) return;

      const label = labelFor(el);

      if (!label) return;

      const key = label+'@'+Math.round(r.left)+','+Math.round(r.top);

      if (seen.has(key)) return;

      seen.add(key);

      const pos = getComputedStyle(el).position;

      raw.push({el:el, label:label, x:Math.round(r.left), y:Math.round(r.top),

                w:Math.round(r.width), h:Math.round(r.height),

                sticky:(pos==='sticky'||pos==='fixed')});

      if (raw.length >= MAX_AOIS*2) full = true;

    }



    document.querySelectorAll('[data-aoi]').forEach(consider);

    document.querySelectorAll(ALWAYS_SELECTOR).forEach(consider);



    const candidates = document.querySelectorAll(TEXT_CONTAINER_SELECTOR);

    for (let i=0; i<candidates.length && i<MAX_SCAN && !full; i++){

      consider(candidates[i]);

    }



    const filtered = raw.filter(o => {

      const isTallWrapper = o.h > TALL_WRAPPER_H &&

                             raw.some(o2 => o2 !== o && o.el.contains(o2.el));

      return !isTallWrapper;

    });



    state.aois = filtered.slice(0, MAX_AOIS).map(o => ({

      label:o.label, x:o.x, y:o.y, w:o.w, h:o.h, sticky:o.sticky

    }));

  }

  refresh();

  window.addEventListener('scroll', refresh, {passive:true});

  setInterval(refresh, 400);



  // window.scrollY/document.documentElement.scrollHeight assume <html> is

  // the element that actually scrolls. Some real-world pages instead put

  // overflow/height on <body> (or trigger the browser's legacy quirks-mode

  // scrolling element), which leaves window.scrollY pinned at 0 forever

  // even while the page visibly scrolls -- the classic documentElement-vs-

  // body split. Falling back to document.body's own scroll metrics

  // whenever the documentElement ones read exactly 0 costs nothing on

  // pages where documentElement was already correct (body's would-be

  // fallback value only gets used when the primary is falsy) and fixes it

  // on pages where it wasn't.

  function scrollPos(){

    const sx = window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft || 0;

    const sy = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;

    return { x: sx, y: sy };

  }

  function pageSize(){

    return {

      w: Math.max(document.documentElement.scrollWidth, document.body.scrollWidth),

      h: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight),

    };

  }



  // Elements with position:fixed/sticky stay pinned to the same spot in

  // every viewport-sized screenshot regardless of scroll depth (a "Brochure"

  // side tab, a floating CTA, a persistent nav) β€” the report's full-page

  // stitcher (analysis.py/buildFullPageStitch) needs to know about them so

  // it can paste each one only once instead of once per screenshot it was

  // captured in. AOI candidates (state.aois above) don't cover this: that

  // list only includes elements matching the attention-worthy-content

  // heuristics (headings, images, text blocks, ...), so a plain nav tab

  // never becomes an AOI candidate and its stickiness is never even

  // evaluated. This is a separate, purpose-built scan, capped by the same

  // MAX_SCAN budget as the AOI scan above and capped again on result count

  // since fixed/sticky elements are rare on a normal page.

  const MAX_STICKY = 20;

  function stickyRects(){

    const vw = window.innerWidth, vh = window.innerHeight;

    const all = document.querySelectorAll('*');

    const out = [];

    for (let i = 0; i < all.length && i < MAX_SCAN && out.length < MAX_STICKY; i++){

      const el = all[i];

      if (OWN_UI_IDS.has(el.id) || (el.closest && el.closest(OWN_UI_SELECTOR))) continue;

      const pos = getComputedStyle(el).position;

      if (pos !== 'fixed' && pos !== 'sticky') continue;

      const r = el.getBoundingClientRect();

      if (r.width < MIN_W || r.height < MIN_H) continue;

      if (r.bottom <= 0 || r.top >= vh || r.right <= 0 || r.left >= vw) continue;

      out.push({

        x: Math.round(Math.max(0, r.left)), y: Math.round(Math.max(0, r.top)),

        w: Math.round(Math.min(vw, r.right) - Math.max(0, r.left)),

        h: Math.round(Math.min(vh, r.bottom) - Math.max(0, r.top)),

      });

    }

    return out;

  }



  window.insightuxAOIs = function(){

    const pos = scrollPos();

    const size = pageSize();

    return JSON.stringify({

      url: location.href,

      title: document.title || '',

      scrollX: Math.round(pos.x),

      scrollY: Math.round(pos.y),

      viewport:{w:window.innerWidth,h:window.innerHeight},

      page:{w:size.w,h:size.h},

      aois: state.aois,

      stickyRects: stickyRects()

    });

  };



  window.insightuxUpdate = function(fx, fy){

    target.fx = fx;

    target.fy = fy;

  };



  function renderLoop(){

    const w = window.innerWidth, h = window.innerHeight;

    const tx = target.fx * w, ty = target.fy * h;

    if (dot.x === null){ dot.x = tx; dot.y = ty; }

    dot.x += (tx - dot.x) * DOT_LERP;

    dot.y += (ty - dot.y) * DOT_LERP;



    const now = performance.now();

    const px = dot.x, py = dot.y;



    let cand = null;

    for (const a of state.aois){

      if (px>=a.x-PAD_PX && px<=a.x+a.w+PAD_PX && py>=a.y-PAD_PX && py<=a.y+a.h+PAD_PX){

        if (!cand || (a.w*a.h)<(cand.w*cand.h)) cand = a;

      }

    }



    const candLabel = cand ? cand.label : null;

    if (candLabel !== dwell.pendLabel){ dwell.pendLabel = candLabel; dwell.pendSince = now; }

    if (cand){

      dwell.emptySince = 0;

      if (dwell.activeLabel !== cand.label && (now - dwell.pendSince) >= DWELL_MS){

        dwell.activeLabel = cand.label;

      }

    } else {

      if (dwell.emptySince === 0) dwell.emptySince = now;

      if (dwell.activeLabel && (now - dwell.emptySince) >= RELEASE_MS){

        dwell.activeLabel = null;

      }

    }



    let active = null;

    if (dwell.activeLabel){

      for (const a of state.aois){ if (a.label === dwell.activeLabel){ active = a; break; } }

      if (!active) dwell.activeLabel = null;

    }

    activeBox = active;



    ctx.clearRect(0,0,cv.width,cv.height);



    if (activeBox){

      ctx.save();

      ctx.fillStyle = 'rgba(255,233,168,0.14)';

      ctx.strokeStyle = '#FFE9A8'; ctx.lineWidth = 2.5;

      roundRectPath(ctx, activeBox.x, activeBox.y, activeBox.w, activeBox.h, 8);

      ctx.fill();

      ctx.stroke();

      ctx.restore();



      const label = activeBox.label;

      ctx.font = '600 12px -apple-system, "Segoe UI", Arial';

      const tw = ctx.measureText(label).width + 20;

      const ly = Math.max(0, activeBox.y - 26);

      ctx.save();

      ctx.fillStyle = '#FFE9A8';

      roundRectPath(ctx, activeBox.x, ly, tw, 22, 11);

      ctx.fill();

      ctx.fillStyle = '#312F2E';

      ctx.fillText(label, activeBox.x + 10, ly + 15);

      ctx.restore();

    }



    // soft pulsing ring around the dot, on a slow independent cycle

    const pulse = (Math.sin(now / 420) + 1) / 2;

    ctx.beginPath();

    ctx.arc(dot.x, dot.y, 15 + pulse * 5, 0, 2*Math.PI);

    ctx.strokeStyle = 'rgba(255,233,168,' + (0.35 - pulse * 0.2) + ')';

    ctx.lineWidth = 1.5;

    ctx.stroke();



    ctx.beginPath();

    ctx.arc(dot.x, dot.y, 12, 0, 2*Math.PI);

    ctx.fillStyle = 'rgba(255,255,255,0.92)';

    ctx.fill();



    ctx.beginPath();

    ctx.arc(dot.x, dot.y, 8, 0, 2*Math.PI);

    ctx.fillStyle = '#FFE9A8';

    ctx.fill();

    ctx.lineWidth = 1.5;

    ctx.strokeStyle = 'rgba(27,25,24,0.55)';

    ctx.stroke();



    requestAnimationFrame(renderLoop);

  }

  requestAnimationFrame(renderLoop);



  window.__insightux = true;

})();

"""


# JS: mouse tracking overlay β€” ported feature-for-feature from the
# "Mouse Tracker & Heatmap" Chrome extension (Mouse/content.js + background.js
# + popup.js), adapted to run as a single injected script instead of a
# content-script/background/popup trio (pywebview has no extension host).
# Same trail/heatmap/dwell sampling loop, same click interest labeling, same
# heatmap render, plus an in-page panel that replaces the extension's popup
# (Start/Stop/Clear/Toggle Heatmap/View Logs, timer, "Most Viewed Element").
# =============================================================================

MOUSE_JS = r"""

(function(){

  if (window.__insightuxMouse) { return; }

  window.__insightuxMouse = true;



  let isTracking = true;

  let canvas = null;

  let panelOpen = false;

  let logsOpen = false;



  // Per-sync buffers (flushed to Python every 2s for on-disk persistence)

  let trailBuffer = [];

  let heatmapBuffer = [];

  let clickBuffer = [];

  let dwellBuffer = [];



  // Cumulative in-page state (mirrors the extension's background.js state)

  let allTrail = [];

  let allHeatmap = [];

  let allClicks = [];

  let dwellTotals = {};



  let sessionStart = Date.now();

  let sessionStop = null;



  let lastClientX = 0, lastClientY = 0;

  let lastPageX = 0, lastPageY = 0;

  let lastSampleTime = 0;

  const sampleRate = 50;

  const DWELL_THRESHOLD = 5000;

  let stationaryStart = 0;

  let isStationary = false;



  window.insightuxMouseSetTracking = function(on){

    isTracking = !!on;

    if (isTracking) {

      sessionStart = Date.now();

      sessionStop = null;

    } else {

      sessionStop = Date.now();

      flushDwell();

    }

    updatePanel();

  };



  // ---- sampling loop (trail while moving, heatmap dwell points while still) ----

  setInterval(function(){

    if (!isTracking) return;

    // Same documentElement-vs-body fallback as TRACKING_JS's scrollPos()

    // (see its comment) β€” this loop reconstructs page-absolute coordinates

    // manually (clientX/Y + scroll offset) instead of using the browser's

    // own event.pageX/Y (which the click/hover handlers below use and

    // don't need this), so it needs the same defensive read.

    const currentScrollX = window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft || 0;

    const currentScrollY = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;

    if (lastPageX === 0 && lastPageY === 0 && lastClientX !== 0) {

      lastPageX = lastClientX + currentScrollX;

      lastPageY = lastClientY + currentScrollY;

    }

    const currentPageX = (lastClientX !== 0) ? (lastClientX + currentScrollX) : lastPageX;

    const currentPageY = (lastClientY !== 0) ? (lastClientY + currentScrollY) : lastPageY;

    if (currentPageX === 0 && currentPageY === 0) return;



    const now = Date.now();

    const dt = now - lastSampleTime;

    if (dt > 1000) { lastSampleTime = now; return; }



    const dx = currentPageX - lastPageX, dy = currentPageY - lastPageY;

    const distance = Math.sqrt(dx * dx + dy * dy);



    if (distance > 2) {

      const pt = { x: currentPageX, y: currentPageY };

      trailBuffer.push(pt); allTrail.push(pt);

      lastPageX = currentPageX; lastPageY = currentPageY;

      isStationary = false; stationaryStart = 0;

    } else {

      if (!isStationary) { isStationary = true; stationaryStart = now; }

      else {

        const dwellDuration = now - stationaryStart;

        if (dwellDuration > DWELL_THRESHOLD) {

          const pt = { x: currentPageX, y: currentPageY };

          heatmapBuffer.push(pt); allHeatmap.push(pt);

        }

      }

    }

    lastSampleTime = now;

  }, sampleRate);



  // ---- dwell / element-interest tracking ----

  let currentHoverLabel = null, currentHoverStartTime = 0;

  function handleHoverChange(newLabel){

    if (!isTracking) return;

    if (newLabel !== currentHoverLabel) {

      const now = Date.now();

      if (currentHoverLabel && currentHoverStartTime > 0) {

        const duration = now - currentHoverStartTime;

        if (duration > 10) recordDwell(currentHoverLabel, duration);

      }

      currentHoverLabel = newLabel;

      currentHoverStartTime = newLabel ? now : 0;

    }

  }

  function recordDwell(element, duration){

    dwellBuffer.push({ element: element, duration: duration });

    dwellTotals[element] = (dwellTotals[element] || 0) + duration;

  }

  function flushDwell(){

    if (currentHoverLabel && currentHoverStartTime > 0) {

      const now = Date.now();

      const duration = now - currentHoverStartTime;

      if (duration > 50) recordDwell(currentHoverLabel, duration);

      currentHoverStartTime = now;

    }

  }



  // ---- sync to Python -> mouse_log.jsonl in the session folder ----

  // Named so the click handler below can call it directly instead of

  // waiting for the next tick: a click that opens a link navigates

  // immediately, which tears down this page's JS (and whatever's still

  // sitting in clickBuffer) before a 2s-only interval would ever get to

  // send it β€” the click simply never reaches mouse_log.jsonl. Calling

  // this right after a click is captured, in addition to the periodic

  // tick for everything else (trail/heatmap/dwell), closes that race.

  function syncMouseBatch(){

    flushDwell();

    if (trailBuffer.length || heatmapBuffer.length || clickBuffer.length || dwellBuffer.length) {

      const payload = {

        trail: trailBuffer.length ? trailBuffer : null,

        heatmap: heatmapBuffer.length ? heatmapBuffer : null,

        click: clickBuffer.length ? clickBuffer : null,

        dwell: dwellBuffer.length ? dwellBuffer : null,

      };

      trailBuffer = []; heatmapBuffer = []; clickBuffer = []; dwellBuffer = [];

      if (window.pywebview && window.pywebview.api && window.pywebview.api.log_mouse_data) {

        try { window.pywebview.api.log_mouse_data(payload).catch(function(){}); } catch (e) {}

      }

    }

    updatePanel();

  }

  setInterval(syncMouseBatch, 2000);



  // ---- exclude InsightUX's own injected UI from every measurement ----

  // (the toolbar, sidebar, mouse-tracker panel, heatmap canvas) β€” only

  // real website elements should ever show up in trail/heatmap/dwell/clicks.

  const OWN_UI_IDS = new Set(['__insightux_toolbar', '__insightux_sidebar', '__insightux_pill', '__insightux_canvas', '__insightux_mouse_panel', '__iux_report_loading']);

  const OWN_UI_SELECTOR = '#__insightux_toolbar, #__insightux_sidebar, #__insightux_pill, #__insightux_canvas, #__insightux_mouse_panel, #__iux_report_loading';

  function isOwnUI(el){

    if (!el) return false;

    if (OWN_UI_IDS.has(el.id)) return true;

    return !!(el.closest && el.closest(OWN_UI_SELECTOR));

  }



  // ---- mouse position + hover tracking ----

  function updateMousePos(e){

    if (isOwnUI(e.target)) return;

    lastClientX = e.clientX; lastClientY = e.clientY;

    if (lastPageX === 0) lastPageX = e.pageX;

    if (lastPageY === 0) lastPageY = e.pageY;

    if (isTracking) handleHoverChange(getSmartLabel(e.target));

  }

  document.addEventListener('mousemove', updateMousePos, true);

  document.addEventListener('mouseenter', updateMousePos, true);

  document.addEventListener('mouseover', updateMousePos, true);

  document.addEventListener('click', updateMousePos, true);

  document.addEventListener('mouseleave', function(){

    lastClientX = 0; lastClientY = 0;

    handleHoverChange(null);

  }, true);



  document.addEventListener('click', function(e){

    if (!isTracking) return;

    if (e.target === canvas) return;

    if (isOwnUI(e.target)) return;

    if (!isInteractable(e.target)) return;



    const x = e.pageX, y = e.pageY;

    const label = getSmartLabel(e.target) || e.target.tagName;

    if (['BODY', 'HTML', 'DIV', 'SPAN'].includes(label) && !e.target.innerText.trim()) return;



    const logEntry = {

      timestamp: new Date().toLocaleTimeString(),

      x: x, y: y, element: label,

      text: e.target.innerText ? e.target.innerText.substring(0, 30).replace(/(\r\n|\n|\r)/gm, ' ').trim() : '',

      url: window.location.href

    };

    clickBuffer.push(logEntry); allClicks.push(logEntry);

    if (canvas) drawClick(x, y);

    syncMouseBatch();  // send immediately β€” this click may trigger a navigation right after it returns

  }, true);



  function isInteractable(el){

    if (!el) return false;

    const tag = el.tagName.toLowerCase();

    if (['a', 'button', 'input', 'select', 'textarea', 'details', 'summary', 'label'].includes(tag)) return true;

    const role = el.getAttribute('role');

    if (role === 'button' || role === 'link' || role === 'menuitem' || role === 'tab') return true;

    try { if (window.getComputedStyle(el).cursor === 'pointer') return true; } catch (e) {}

    let parent = el.parentElement, depth = 0;

    while (parent && depth < 3) {

      const pTag = parent.tagName.toLowerCase();

      if (['a', 'button'].includes(pTag)) return true;

      if (parent.getAttribute('role') === 'button') return true;

      parent = parent.parentElement; depth++;

    }

    if (tag === 'code' || tag === 'pre' || el.classList.contains('code') || el.closest('pre')) return true;

    return false;

  }



  function getSmartLabel(el){

    if (!el) return null;

    const tag = el.tagName.toLowerCase();

    if (['body', 'html', 'main', 'div', 'span', 'section', 'article'].includes(tag)) {

      if (el.id && (el.id.includes('logo') || el.id.includes('wrapper') || el.id.includes('container'))) return null;

      if (el.className && typeof el.className === 'string' &&

          (el.className.toLowerCase().includes('logo') || el.className.toLowerCase().includes('brand'))) return null;

      const aria = el.getAttribute('aria-label');

      if (aria) return 'Element: ' + aria;

      if (el.children.length === 0) {

        const txt = el.innerText.trim();

        if (txt.length > 2 && txt.length < 50 && /[a-zA-Z0-9]/.test(txt)) return 'Element: ' + txt;

      }

      return null;

    }

    if (tag === 'a') return 'Link: ' + (el.innerText.trim().substring(0, 30) || 'Link');

    if (tag === 'button') return 'Button: ' + (el.innerText.trim().substring(0, 30) || 'Button');

    if (tag === 'input') return 'Input: ' + (el.placeholder || el.name || el.id || 'Input');

    if (tag === 'textarea') return 'Input: Text Area';

    if (tag === 'img') return 'Image: ' + (el.alt || 'Image');

    if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)) return tag.toUpperCase() + ': ' + el.innerText.trim().substring(0, 40);

    if (tag === 'code' || tag === 'pre') return 'Code: ' + el.innerText.trim().substring(0, 30);

    const text = el.innerText.trim();

    if (text && text.length > 2) {

      if (el.classList.contains('code') || el.closest('pre')) return 'Code: ' + text.substring(0, 30);

      if (text.toLowerCase().includes('no message found')) return null;

      const isHex = /^#[0-9A-F]{6}$/i.test(text) || /^#[0-9A-F]{3}$/i.test(text);

      const isColorName = ['red', 'blue', 'green', 'yellow', 'black', 'white', 'orange', 'purple', 'gray', 'grey', 'pink', 'brown', 'cyan', 'magenta'].includes(text.toLowerCase());

      if (isHex || isColorName) return null;

      if (text.length > 50) return 'Text: ' + text.substring(0, 47) + '...';

      return 'Text: ' + text;

    }

    return null;

  }



  // ---- heatmap overlay canvas (ported 1:1 from the extension) ----

  let heatOpacity = 0.85, heatIntensity = 0.05;

  window.insightuxMouseToggleHeatmap = function(){

    if (canvas) { document.body.removeChild(canvas); canvas = null; return; }

    canvas = document.createElement('canvas');

    canvas.style.position = 'absolute';

    canvas.style.top = '0'; canvas.style.left = '0';

    canvas.style.zIndex = '2147483645';

    canvas.style.pointerEvents = 'none';

    canvas.style.opacity = heatOpacity;

    canvas.style.transition = 'opacity .15s ease';

    canvas.width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, document.documentElement.offsetWidth);

    canvas.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.offsetHeight);

    document.body.appendChild(canvas);

    drawHeatmapHighQuality(allHeatmap, allTrail, allClicks);

  };

  window.insightuxMouseSetHeatStyle = function(opacity, intensity){

    if (opacity != null) { heatOpacity = opacity; if (canvas) canvas.style.opacity = heatOpacity; }

    if (intensity != null) { heatIntensity = intensity; if (canvas) drawHeatmapHighQuality(allHeatmap, allTrail, allClicks); }

  };



  function drawClick(x, y){

    if (!canvas) return;

    const ctx = canvas.getContext('2d');

    ctx.save();

    ctx.beginPath();

    ctx.strokeStyle = '#00FF00'; ctx.lineWidth = 3;

    ctx.shadowColor = 'black'; ctx.shadowBlur = 2;

    const size = 10;

    ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size);

    ctx.moveTo(x + size, y - size); ctx.lineTo(x - size, y + size);

    ctx.stroke();

    ctx.beginPath(); ctx.arc(x, y, size + 5, 0, Math.PI * 2); ctx.stroke();

    ctx.restore();

  }



  function drawHeatmapHighQuality(heatmapData, trailData, clickData){

    if (!canvas) return;

    const ctx = canvas.getContext('2d');

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    let allHeatPoints = [];

    if (heatmapData && heatmapData.length) allHeatPoints = allHeatPoints.concat(heatmapData);

    if (trailData && trailData.length) allHeatPoints = allHeatPoints.concat(trailData);

    if (clickData && clickData.length) {

      clickData.forEach(function(c){ for (let i = 0; i < 5; i++) allHeatPoints.push({ x: c.x, y: c.y }); });

    }

    if (!allHeatPoints.length) return;

    const radius = 24;  // smaller, more precise spots (was 60)

    const brushCanvas = document.createElement('canvas');

    brushCanvas.width = radius * 2; brushCanvas.height = radius * 2;

    const brushCtx = brushCanvas.getContext('2d');

    const g = brushCtx.createRadialGradient(radius, radius, 0, radius, radius, radius);

    g.addColorStop(0, 'rgba(0, 0, 0, ' + heatIntensity + ')'); g.addColorStop(1, 'rgba(0, 0, 0, 0)');

    brushCtx.fillStyle = g; brushCtx.fillRect(0, 0, radius * 2, radius * 2);

    allHeatPoints.forEach(function(point){ ctx.drawImage(brushCanvas, point.x - radius, point.y - radius); });

    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    const data = imageData.data;

    const gradientMap = createGradientMap();

    for (let i = 0; i < data.length; i += 4) {

      const alpha = data[i + 3];

      if (alpha > 0) {

        let mapIndex = Math.floor(alpha * 1.5);

        if (mapIndex > 255) mapIndex = 255;

        const cIndex = mapIndex * 4;

        data[i] = gradientMap[cIndex]; data[i + 1] = gradientMap[cIndex + 1]; data[i + 2] = gradientMap[cIndex + 2];

        data[i + 3] = Math.min(255, 150 + alpha);

      }

    }

    ctx.putImageData(imageData, 0, 0);

  }



  function createGradientMap(){

    const c = document.createElement('canvas'); c.width = 256; c.height = 1;

    const ctx = c.getContext('2d');

    const g = ctx.createLinearGradient(0, 0, 256, 0);

    g.addColorStop(0.0, 'rgba(0, 0, 255, 0)');

    g.addColorStop(0.1, 'rgba(0, 0, 255, 1)');

    g.addColorStop(0.4, 'rgba(0, 255, 255, 1)');

    g.addColorStop(0.6, 'rgba(0, 255, 0, 1)');

    g.addColorStop(0.8, 'rgba(255, 255, 0, 1)');

    g.addColorStop(1.0, 'rgba(255, 0, 0, 1)');

    ctx.fillStyle = g; ctx.fillRect(0, 0, 256, 1);

    return ctx.getImageData(0, 0, 256, 1).data;

  }



  window.addEventListener('resize', function(){

    if (canvas) {

      canvas.width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, document.documentElement.offsetWidth);

      canvas.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.offsetHeight);

    }

  });



  // ---- insights panel: in-page port of the extension's popup.html/popup.js ----

__ICONS_JS__

  const style = document.createElement('style');

  style.textContent = `

__THEME_CSS__

    #__insightux_mouse_panel {

      position: fixed; top: 66px; right: 16px; width: 268px; z-index: 2147483647;

      border-radius: var(--iux-radius); box-shadow: var(--iux-shadow);

      font: 12px var(--iux-font); color: var(--iux-text); padding: 14px;

      pointer-events: auto; display: none;

      transform: translateY(-8px); opacity: 0; transition: transform .2s var(--iux-ease), opacity .2s var(--iux-ease);

    }

    #__insightux_mouse_panel.open { display: block; }

    #__insightux_mouse_panel.show { transform: translateY(0); opacity: 1; }

    #__insightux_mouse_panel h3 { margin: 0 0 10px 0; font-size: 12.5px; color: var(--iux-text); font-weight: 600;

      display:flex; align-items:center; gap:6px; }

    #__insightux_mouse_panel .muted { color: var(--iux-text-faint); font-size: 11px; }

    #__insightux_mouse_panel .row { display: flex; gap: 6px; margin-bottom: 10px; flex-wrap: wrap; }

    #__insightux_mouse_panel .row .iux-btn {

      flex: 1 1 auto; padding: 7px 6px; font-size: 10.5px; gap: 4px;

    }

    #__insightux_mouse_panel .row .iux-btn.active { background: var(--iux-accent-grad); border-color: transparent; color: var(--iux-on-accent); }

    #__insightux_mouse_panel .timer { font-weight: 600; margin-bottom: 10px; display:flex; align-items:center; gap:6px; color: var(--iux-text-dim); }

    #__insightux_mouse_panel .hero {

      background: linear-gradient(135deg, color-mix(in srgb, var(--iux-primary) 16%, transparent), color-mix(in srgb, var(--iux-indigo) 10%, transparent));

      border: 1px solid var(--iux-border); border-radius: var(--iux-radius-sm);

      padding: 10px; text-align: center; margin-bottom: 10px;

    }

    #__insightux_mouse_panel .hero .lbl { font-size: 9px; text-transform: uppercase; color: var(--iux-text-faint); letter-spacing: 0.06em; }

    #__insightux_mouse_panel .hero .el { font-weight: 700; margin: 4px 0; color: var(--iux-primary-light); }

    #__insightux_mouse_panel .interest-item, #__insightux_mouse_panel .log-item {

      background: var(--iux-surface-hi); border-radius: 8px; padding: 6px 8px; margin-bottom: 5px; font-size: 11px;

    }

    #__insightux_mouse_panel .list { max-height: 160px; overflow-y: auto; }

    #__insightux_mouse_panel .sliders { display: none; margin-bottom: 10px; }

    #__insightux_mouse_panel .sliders.open { display: block; }

    #__insightux_mouse_panel .slider-row { display:flex; align-items:center; gap:8px; margin-bottom:6px; font-size: 10.5px; color: var(--iux-text-dim); }

    #__insightux_mouse_panel .slider-row span { flex: 0 0 52px; }

    #__insightux_mouse_panel input[type=range] { flex: 1 1 auto; accent-color: var(--iux-primary-light); }

  `;

  document.head.appendChild(style);



  const panel = document.createElement('div');

  panel.id = '__insightux_mouse_panel';

  panel.className = 'iux-glass';

  panel.innerHTML = `

    <h3>${iuxIcon('cursor', 14)} Mouse Tracker <span class="muted" id="__mt_status" style="margin-left:auto;">idle</span></h3>

    <div class="timer">${iuxIcon('clock', 13)} <span id="__mt_timer">00:00</span></div>

    <div class="row">

      <button class="iux-btn" id="__mt_clear" title="Clear collected data">${iuxIcon('trash', 13)} Clear</button>

      <button class="iux-btn" id="__mt_heatmap" title="Toggle heatmap overlay (H)">${iuxIcon('layers', 13)} Heatmap</button>

      <button class="iux-btn" id="__mt_logs" title="View click log">${iuxIcon('type', 13)} Logs</button>

    </div>

    <div class="sliders" id="__mt_sliders">

      <div class="slider-row"><span>Opacity</span><input type="range" id="__mt_opacity" min="20" max="100" value="85"></div>

      <div class="slider-row"><span>Intensity</span><input type="range" id="__mt_intensity" min="2" max="12" value="5"></div>

    </div>

    <div id="__mt_hero" class="hero" style="display:none;">

      <div class="lbl">Most Viewed Element</div>

      <div class="el" id="__mt_hero_el">-</div>

      <div id="__mt_hero_time">0s</div>

    </div>

    <div id="__mt_interests" class="list"></div>

    <div id="__mt_logs_list" class="list" style="display:none;"></div>

  `;

  document.documentElement.appendChild(panel);

  requestAnimationFrame(function(){ panel.classList.add('show'); });



  document.getElementById('__mt_clear').addEventListener('click', function(){

    trailBuffer = []; heatmapBuffer = []; clickBuffer = []; dwellBuffer = [];

    allTrail = []; allHeatmap = []; allClicks = []; dwellTotals = {};

    sessionStart = Date.now(); sessionStop = null;

    if (canvas) { document.body.removeChild(canvas); canvas = null; }

    updatePanel();

  });

  const heatmapBtn = document.getElementById('__mt_heatmap');

  const slidersEl = document.getElementById('__mt_sliders');

  heatmapBtn.addEventListener('click', function(){

    window.insightuxMouseToggleHeatmap();

    heatmapBtn.classList.toggle('active', !!canvas);

    slidersEl.classList.toggle('open', !!canvas);

  });

  document.getElementById('__mt_opacity').addEventListener('input', function(e){

    window.insightuxMouseSetHeatStyle(e.target.value / 100, null);

  });

  document.getElementById('__mt_intensity').addEventListener('input', function(e){

    window.insightuxMouseSetHeatStyle(null, e.target.value / 100);

  });

  document.getElementById('__mt_logs').addEventListener('click', function(){

    logsOpen = !logsOpen;

    document.getElementById('__mt_logs').classList.toggle('active', logsOpen);

    document.getElementById('__mt_logs_list').style.display = logsOpen ? 'block' : 'none';

    document.getElementById('__mt_interests').style.display = logsOpen ? 'none' : 'block';

    updatePanel();

  });



  window.insightuxMouseTogglePanel = function(){

    panelOpen = !panelOpen;

    panel.classList.toggle('open', panelOpen);

    if (panelOpen) updatePanel();

  };



  function formatTime(ms){ return Math.round(ms / 1000) + 's'; }



  function updatePanel(){

    if (!panelOpen) return;

    document.getElementById('__mt_status').textContent = isTracking ? 'tracking' : 'stopped';

    const startTs = sessionStart;

    const diff = isTracking ? Math.floor((Date.now() - startTs) / 1000)

                             : (sessionStop ? Math.floor((sessionStop - startTs) / 1000) : 0);

    const mins = Math.floor(diff / 60).toString().padStart(2, '0');

    const secs = (diff % 60).toString().padStart(2, '0');

    document.getElementById('__mt_timer').textContent = 'Session Time: ' + mins + ':' + secs;



    const interests = Object.entries(dwellTotals).map(function(e){ return { element: e[0], duration: e[1] }; })

      .sort(function(a, b){ return b.duration - a.duration; }).slice(0, 6);



    const hero = document.getElementById('__mt_hero');

    if (interests.length) {

      hero.style.display = 'block';

      document.getElementById('__mt_hero_el').textContent = interests[0].element;

      document.getElementById('__mt_hero_time').textContent = formatTime(interests[0].duration);

    } else {

      hero.style.display = 'none';

    }



    const interestsEl = document.getElementById('__mt_interests');

    if (!logsOpen) {

      if (interests.length > 1) {

        interestsEl.innerHTML = interests.slice(1).map(function(it, i){

          return '<div class="interest-item">' + (i + 2) + '. <b>' + it.element + '</b> β€” ' + formatTime(it.duration) + '</div>';

        }).join('');

      } else {

        interestsEl.innerHTML = '<div class="muted">No other interests yet.</div>';

      }

    }



    const logsEl = document.getElementById('__mt_logs_list');

    if (logsOpen) {

      if (allClicks.length) {

        logsEl.innerHTML = allClicks.slice().reverse().slice(0, 20).map(function(l){

          return '<div class="log-item"><span class="muted">' + l.timestamp + '</span><br><b>' + l.element + '</b><br>"' + l.text + '"</div>';

        }).join('');

      } else {

        logsEl.innerHTML = '<div class="muted">No clicks recorded.</div>';

      }

    }

  }

  setInterval(updatePanel, 1000);



  // ---- hotkeys: H = toggle heatmap, M = toggle insights panel ----

  function isTypingTarget(el){

    if (!el) return false;

    const tag = el.tagName ? el.tagName.toLowerCase() : '';

    return tag === 'input' || tag === 'textarea' || tag === 'select' || el.isContentEditable === true;

  }

  document.addEventListener('keydown', function(e){

    const typingBlocked = isTypingTarget(e.target) || isTypingTarget(document.activeElement);

    if (typingBlocked) return;

    if (e.key === 'h' || e.key === 'H') window.insightuxMouseToggleHeatmap();

    else if (e.key === 'm' || e.key === 'M') window.insightuxMouseTogglePanel();

  }, true);



  updatePanel();

})();

"""
MOUSE_JS = MOUSE_JS.replace("__ICONS_JS__", theme.ICONS_JS)
MOUSE_JS = MOUSE_JS.replace("__THEME_CSS__", theme.THEME_CSS)


# =============================================================================
# API exposed to JS β€” start/stop/quit are the entry points
# =============================================================================

# Pages tracking must never start on, checked against window.get_current_url()
# as a Python-side backstop to CHROME_JS's isTrackable check (belt and
# suspenders β€” the JS guard can't run before the JS bridge is up).
_NON_TRACKABLE_URL_MARKERS = ("insightux_landing.html", "analysis_report.html", "insightux_login.html")


def _relaunch_args(mode):
    """Command to spawn calibrate.py/validate.py's logic in a fresh process.

    Frozen (PyInstaller) builds have no bundled interpreter to hand a .py

    file to, and sys.executable IS the frozen exe itself β€” so a frozen build

    relaunches itself with --mode instead. Unpackaged/dev mode still runs

    from the venv exactly as before."""
    if getattr(sys, "frozen", False):
        return [sys.executable, "--mode", mode]
    return [sys.executable, os.path.abspath(__file__), "--mode", mode]


class Api:
    def __init__(self):
        self.window = None
        self.tracking = False
        # Microlink capture is explicitly enabled only for the active tracking session.
        # This stays false during the stop/report-wrap-up window, so navigation after E
        # can never trigger a new screenshot request.
        self.microlink_capture_enabled = False
        self.session_started_at = None
        self.current_session_dir = None  # the folder gaze_worker() is actively writing into right now, else None β€” the one session delete_*_session() must refuse to touch
        self.stop_event = threading.Event()
        self.thread = None
        self.mouse_log_f = None
        self.mouse_close_timer = None
        self.calib_proc = None
        self.calibration_cancel_event = None
        self.validate_proc = None
        self.validation_cancel_event = None
        self.update_info = None
        # Phase 3 gaze bridge: observes the existing window.insightuxUpdate
        # callback without changing the gaze-estimation worker.
        self.gaze_bridge_processor = GazeBridgeProcessor()
        self.gaze_bridge_stop = threading.Event()
        self.gaze_bridge_thread = None
        # URL-scoped Microlink sessions. These consume existing Phase-3
        # GazeSample objects only; gaze_worker() is not changed.
        self.microlink_sessions = {}
        # Screenshot acquisition happens when a page becomes stable; heatmap
        # rendering is serialized through this queue so expensive image work
        # never piles up in the navigation/gaze path.
        self.chrome_heatmap_queue = queue.Queue()
        self.page_heatmap_queued = set()
        self.chrome_heatmap_worker_thread = threading.Thread(
            target=self._chrome_heatmap_worker,
            name="chrome-heatmap-worker",
            daemon=True,
        )
        self.chrome_heatmap_worker_thread.start()
        self.page_transitioning = False
        self.page_transition_serial = 0
        self.page_resume_timer = None
        # Session clock counts only active recording time. Page navigation and
        # render/capture transitions are deliberately excluded.
        self.session_active_elapsed = 0.0
        self.session_active_started_at = None
        self.microlink_finalize_thread = None
        self.current_user = None  # None until login()/create_profile() succeeds
        self.active_tracking_subject = None  # None = tracking "Myself"; else a participant dict
        # One-shot context for the report that was just generated by the
        # current tracking run. Historical reports must not show an AI button.

    def _notify_update(self, version, url):
        try:
            self.window.evaluate_js(
                f"window.insightuxShowUpdate && window.insightuxShowUpdate("
                f"{json.dumps(version)}, {json.dumps(url)})"
            )
        except Exception:
            pass

    @_require_token
    def open_update_page(self, url):
        _log(f"[browser_session] open_update_page() called from JS: {url}")
        import webbrowser
        try:
            webbrowser.open(url)
        except Exception as e:
            _log(f"[browser_session] failed to open update url: {e}")
        return True

    # -- profiles -------------------------------------------------------
    # InsightUX has no server/database β€” auth.py's users.json *is* the
    # backend here. The frontend never supplies a user id as proof of
    # anything: list_profiles() only ever returns public fields (never a
    # password hash), and login()/create_profile() are the only two ways
    # self.current_user gets set, both gated on auth.verify_login()/
    # auth.create_user() actually succeeding server-side (i.e. in this
    # Python process). Every other per-user read/write in the app goes
    # through SESSIONS_ROOT/CALIBRATION_PATH/_user_onnx_path(), which only
    # _apply_user_paths() (called from here) is allowed to repoint.

    def list_profiles(self):
        return auth.list_profiles(DATA_DIR)

    def login(self, user_id, password):
        _log(f"[browser_session] login() called from JS for user_id={user_id}")
        try:
            profile = auth.verify_login(DATA_DIR, user_id, password)
        except auth.AuthError as e:
            _log(f"[browser_session]   login failed: {e}")
            return {"ok": False, "error": str(e)}
        self._activate_user(profile)
        return {"ok": True}

    def create_profile(self, name, email, password):
        _log(f"[browser_session] create_profile() called from JS for email={email}")
        was_first_ever = not auth.load_users(DATA_DIR)
        try:
            profile = auth.create_user(DATA_DIR, name, email, password)
        except auth.AuthError as e:
            _log(f"[browser_session]   create_profile failed: {e}")
            return {"ok": False, "error": str(e)}
        if was_first_ever:
            try:
                _migrate_legacy_data(profile["id"])
            except Exception as e:
                _log(f"[browser_session]   legacy data migration failed (non-fatal): {e}")
        self._activate_user(profile)
        return {"ok": True}

    @_require_token
    def delete_profile(self):
        """Delete the active profile, then clear its authenticated session."""
        if not self.current_user:
            _log("[browser_session] profile deletion rejected: no active profile")
            return {"ok": False, "error": "Sign in before deleting a profile."}
        if self.tracking:
            _log("[browser_session] profile deletion rejected: session is still active")
            return {"ok": False, "error": "Stop the active session before deleting your profile."}
        try:
            auth.delete_user(DATA_DIR, self.current_user["id"])
        except auth.AuthError as exc:
            _log(f"[browser_session] profile deletion failed: {exc}")
            return {"ok": False, "error": str(exc)}
        except Exception as exc:
            _log(f"[browser_session] profile deletion failed: {type(exc).__name__}: {exc}")
            return {"ok": False, "error": "Your profile could not be deleted. Please try again."}

        _log("[browser_session] profile deletion succeeded; clearing session and returning to login")
        self.current_user = None
        self.active_tracking_subject = None
        self._clear_user_paths()
        try:
            self.window.load_url(_write_login_page(profile_deleted=True))
        except Exception as exc:
            _log(f"[browser_session] profile deleted but login navigation failed: {type(exc).__name__}: {exc}")
        return {"ok": True}

    def _activate_user(self, profile):
        """The one place 'current user' and every per-user path flip

        together, atomically β€” used by both login() and create_profile()

        so there's never a window where the paths point at one profile

        while current_user says another. Every login/switch starts back

        in "Myself" mode β€” the previous session's tracking subject (if

        any) never carries over to a different signed-in owner."""
        self.current_user = profile
        self.active_tracking_subject = None
        _apply_user_paths(profile["id"])
        _apply_subject_paths(None)
        self._set_profile_ui()
        self._set_subject_ui()
        try:
            fresh_url = _write_landing_page()
            self.window.load_url(fresh_url)
        except Exception as e:
            _log(f"[browser_session] navigating to landing page after login failed: {e}")

    @_require_token
    def switch_profile_screen(self):
        """'Switch profile' in the profile popover. Waits for any active

        tracking session to fully finish (report included, same as

        letting it stop on its own) before showing the picker, so the

        session Log out/Switch never races the auto-navigate-to-report

        step already built into gaze_worker()."""
        _log("[browser_session] switch_profile_screen() called from JS")
        self._stop_tracking_and_wait()
        try:
            fresh_url = _write_login_page()
            self.window.load_url(fresh_url)
        except Exception as e:
            _log(f"[browser_session] switch_profile_screen navigation failed: {e}")
        return True

    @_require_token
    def logout(self):
        _log("[browser_session] logout() called from JS")
        self._stop_tracking_and_wait()
        self.current_user = None
        self.active_tracking_subject = None
        self._clear_user_paths()
        try:
            fresh_url = _write_login_page()
            self.window.load_url(fresh_url)
        except Exception as e:
            _log(f"[browser_session] logout navigation failed: {e}")
        return True

    def _stop_tracking_and_wait(self):
        """Shared by logout()/switch_profile_screen(): stop_tracking()

        itself only signals the tracking thread and returns immediately

        (same as pressing E) β€” join it here so the thread's own

        report-generation + window navigation (see gaze_worker()) has

        already happened before we navigate to the login page ourselves,

        instead of the two racing for the last word on where the window

        ends up. A bounded timeout keeps logout/switch from ever hanging

        indefinitely if report generation is unusually slow."""
        if not self.tracking:
            return
        self.stop_tracking.__wrapped__(self)
        if self.thread and self.thread.is_alive():
            self.thread.join(timeout=8)

    def _clear_user_paths(self):
        """Repoints the per-user constants at a location that's

        guaranteed never to exist, so that if anything were ever read

        through them while logged out it fails safe (finds nothing)

        instead of silently reading whichever profile was active last."""
        global SESSIONS_ROOT, CALIBRATION_PATH, CURRENT_USER_DIR, CURRENT_SUBJECT_DIR
        CURRENT_USER_DIR = None
        CURRENT_SUBJECT_DIR = None
        SESSIONS_ROOT = os.path.join(DATA_DIR, "_no_active_profile", "sessions")
        CALIBRATION_PATH = os.path.join(DATA_DIR, "_no_active_profile", "calibration.pkl")

    def _set_profile_ui(self):
        try:
            payload = self.current_user or {}
            self.window.evaluate_js(
                f"window.insightuxSetProfile && window.insightuxSetProfile({json.dumps(payload)})"
            )
        except Exception:
            pass

    # -- participants ----------------------------------------------------
    # A participant is a tracking SUBJECT, not an InsightUX login β€” they
    # never authenticate. Isolation instead comes from where their data
    # physically lives: participants.participant_dir() only ever resolves
    # to users/<CURRENT_USER_DIR>/participants/<id>/, so a participant of
    # one owner can never be reached while a different owner is signed in
    # (there is no cross-owner participant_id lookup β€” the folder simply
    # doesn't exist under the wrong owner).

    @_require_token
    def list_participants(self):
        if not CURRENT_USER_DIR:
            return []
        return participants.list_participants(CURRENT_USER_DIR)

    @_require_token
    def add_participant(self, name, notes=""):
        if not CURRENT_USER_DIR:
            return {"ok": False, "error": "Sign in first."}
        try:
            record = participants.create_participant(CURRENT_USER_DIR, name, notes)
        except participants.ParticipantError as e:
            return {"ok": False, "error": str(e)}
        return {"ok": True, "participant": record}

    @_require_token
    def update_participant(self, participant_id, name, notes=""):
        if not CURRENT_USER_DIR:
            return {"ok": False, "error": "Sign in first."}
        try:
            record = participants.update_participant(CURRENT_USER_DIR, participant_id, name=name, notes=notes)
        except participants.ParticipantError as e:
            return {"ok": False, "error": str(e)}
        # Keep the in-memory "who's actively selected" copy (name shown in
        # the sidebar's Participant panel / status line) in sync β€” without
        # this a rename wouldn't show up there until a Myself<->them
        # round trip re-read it from disk.
        if self.active_tracking_subject and self.active_tracking_subject.get("id") == participant_id:
            self.active_tracking_subject = record
            self._set_subject_ui()
        return {"ok": True, "participant": record}

    @_require_token
    def delete_participant(self, participant_id):
        if not CURRENT_USER_DIR:
            return {"ok": False, "error": "Sign in first."}
        if self.tracking and self.active_tracking_subject and self.active_tracking_subject.get("id") == participant_id:
            return {"ok": False, "error": "Stop the current session (E) before deleting this participant."}
        try:
            participants.delete_participant(CURRENT_USER_DIR, participant_id)
        except participants.ParticipantError as e:
            return {"ok": False, "error": str(e)}
        if self.active_tracking_subject and self.active_tracking_subject.get("id") == participant_id:
            # Deleted while merely selected (not mid-session) -- fall back
            # to "Myself" rather than leaving SESSIONS_ROOT/CALIBRATION_PATH
            # pointed at a folder that no longer has a participant record
            # behind it.
            self.active_tracking_subject = None
            _apply_subject_paths(None)
            self._set_subject_ui()
        return {"ok": True}

    @_require_token
    def set_tracking_subject(self, participant_id):
        """participant_id falsy -> "Myself". Refuses mid-session, same

        guard as calibration β€” switching subjects under a live session

        would otherwise silently split one session's data across two

        people's folders."""
        _log(f"[browser_session] set_tracking_subject() called from JS: {participant_id!r}")
        if self.tracking:
            self._set_status("Stop the current session (E) before changing the tracking subject.")
            return False
        if not participant_id:
            self.active_tracking_subject = None
        else:
            record = participants.get_participant(CURRENT_USER_DIR, participant_id) if CURRENT_USER_DIR else None
            if not record:
                self._set_status("That participant no longer exists.")
                return False
            self.active_tracking_subject = record
        _apply_subject_paths(self.active_tracking_subject)
        self._set_subject_ui()
        who = self.active_tracking_subject["name"] if self.active_tracking_subject else "Myself"
        self._set_status(f"Now tracking: {who}")
        return True

    def _set_subject_ui(self):
        try:
            payload = self.active_tracking_subject  # None serializes to JS null -- "Myself"
            self.window.evaluate_js(
                f"window.insightuxSetSubject && window.insightuxSetSubject({json.dumps(payload)})"
            )
        except Exception:
            pass

    # -- Drishti AI --
    @_require_token
    def list_drishti_sessions(self, limit=50):
        if not CURRENT_USER_DIR:
            return {"ok": False, "error": "No active profile."}
        try:
            rows=[]
            rows.extend(_drishti_sessions_json(
                os.path.join(CURRENT_USER_DIR,"sessions"),
                limit,
                participant_id=None,
                participant_name=None,
            ))
            for person in participants.list_participants(CURRENT_USER_DIR):
                root=os.path.join(participants.participant_dir(CURRENT_USER_DIR,person["id"]),"sessions")
                rows.extend(_drishti_sessions_json(
                    root,
                    limit,
                    participant_id=person["id"],
                    participant_name=person.get("name"),
                ))
            rows.sort(key=lambda x:x.get("when") or "", reverse=True)
            return {"ok":True,"sessions":rows[:max(1,int(limit))]}
        except Exception as e:
            _log(f"[drishti] list sessions failed: {e}")
            return {"ok":False,"error":"Could not load sessions."}

    def _drishti_session_dir(self, session_id, participant_id=None):
        if not CURRENT_USER_DIR: return None
        if participant_id:
            person=participants.get_participant(CURRENT_USER_DIR,participant_id)
            if not person: return None
            root=os.path.join(participants.participant_dir(CURRENT_USER_DIR,participant_id),"sessions")
        else:
            root=os.path.join(CURRENT_USER_DIR,"sessions")
        return self._resolve_session_dir(root,session_id)

    @_require_token
    def get_drishti_conversation(self, session_id, participant_id=None):
        if not CURRENT_USER_DIR: return {"ok":False,"error":"No active profile."}
        try:
            session_dir=self._drishti_session_dir(session_id,participant_id)
            if not session_dir: return {"ok":False,"error":"Session not found."}
            from ai.drishti_ai import load_conversation,new_conversation,_session_identity,conversation_matches_session
            identity=_session_identity(session_dir);identity["participant_id"]=participant_id or identity.get("participant_id")
            person=participants.get_participant(CURRENT_USER_DIR,participant_id) if participant_id else None
            identity["participant_name"]=identity.get("participant_name") or (person.get("name") if person else None)
            key=f"{identity['session_id']}:{identity.get('participant_id') or 'self'}"
            root=os.path.join(CURRENT_USER_DIR,"drishti","session_index");os.makedirs(root,exist_ok=True)
            index_path=os.path.join(root,re.sub(r"[^A-Za-z0-9_.-]","_",key)+".json")
            idx=None
            try:
                with open(index_path,"r",encoding="utf-8") as f: idx=json.load(f)
            except Exception: pass
            conv=load_conversation(CURRENT_USER_DIR,idx.get("conversation_id")) if idx else None
            if not conv or not conversation_matches_session(conv,session_dir,identity.get("participant_id")):
                conv=new_conversation(CURRENT_USER_DIR,identity)
                with open(index_path,"w",encoding="utf-8") as f: json.dump({"conversation_id":conv["conversation_id"]},f,indent=2)
                _log(f"[drishti] created conversation session_id={identity['session_id']} participant_id={identity.get('participant_id') or 'self'} conversation_id={conv['conversation_id']}")
            else:
                _log(f"[drishti] opened conversation session_id={identity['session_id']} participant_id={identity.get('participant_id') or 'self'} conversation_id={conv['conversation_id']}")
            return {"ok":True,"session":identity,"conversation":conv}
        except Exception as e:
            _log(f"[drishti] open conversation failed: {e}")
            return {"ok":False,"error":"Could not open Drishti conversation."}

    @_require_token
    def send_drishti_message(self, session_id, participant_id, conversation_id, message, ux_goal="", attachment=None):
        if not CURRENT_USER_DIR: return {"ok":False,"error":"No active profile."}
        message=(message or "").strip()
        # An attached region picture may be sent with no text ("analyze this").
        if isinstance(attachment,str): attachment=[attachment]
        if attachment is not None and not isinstance(attachment,(list,tuple)):
            return {"ok":False,"error":"The attached images are invalid."}
        attachment=[a for a in (attachment or []) if a]
        if not message and not attachment: return {"ok":False,"error":"Message cannot be empty."}
        if len(attachment)>6: return {"ok":False,"error":"You can attach up to 6 pictures per message."}
        if any((not isinstance(a,str) or len(a)>14_000_000) for a in attachment) or sum(len(a) for a in attachment)>40_000_000:
            return {"ok":False,"error":"An attached image is invalid or too large."}
        try:
            session_dir=self._drishti_session_dir(session_id,participant_id)
            if not session_dir: return {"ok":False,"error":"Session not found."}
            from ai.drishti_ai import answer,load_conversation,conversation_matches_session
            conv=load_conversation(CURRENT_USER_DIR,conversation_id)
            if not conv: return {"ok":False,"error":"Conversation not found."}
            if not conversation_matches_session(conv,session_dir,participant_id):
                return {"ok":False,"error":"Conversation/session mismatch."}
            is_first_turn=not conv.get("gemini_interaction_id")
            _log(f"[drishti] {'initializing context' if is_first_turn else 'continuing interaction'} session_id={session_id} participant_id={participant_id or 'self'} conversation_id={conversation_id}")
            # The typed text is being sent, so it stops being a draft. This only touches
            # the in-memory copy: if answer() fails nothing is saved and the draft on
            # disk survives, so the researcher can retry.
            conv.pop("draft",None)
            result=answer(CURRENT_USER_DIR,session_dir,conv,message,ux_goal,attachment=attachment or None)
            _log(f"[drishti] interaction complete session_id={session_id} conversation_id={conversation_id} interaction_id={result['conversation'].get('gemini_interaction_id')}")
            return {"ok":True,"answer":result["answer"],"idea":result.get("idea"),"conversation":result["conversation"],"regions":result.get("regions") or [],"region_source":result.get("region_source")}
        except Exception as e:
            _log(f"[drishti] message failed: {type(e).__name__}: {str(e)[:300]}")
            return {"ok":False,"error":str(e)[:500]}

    @_require_token
    def set_drishti_draft(self, session_id, participant_id, conversation_id, text, goal=""):
        """Keep an unsent chat message (and UX-goal edit) with its conversation so it is

        still there when the researcher reopens Drishti, switches pages or restarts the

        app. Removed when sent (send_drishti_message) or when the box is emptied."""
        if not CURRENT_USER_DIR: return {"ok":False}
        try:
            session_dir=self._drishti_session_dir(session_id,participant_id)
            if not session_dir: return {"ok":False}
            from ai.drishti_ai import load_conversation,save_conversation,conversation_matches_session
            conv=load_conversation(CURRENT_USER_DIR,conversation_id)
            if not conv or not conversation_matches_session(conv,session_dir,participant_id): return {"ok":False}
            text=str(text or "")[:8000]; goal=str(goal or "")[:500]
            if text.strip() or (goal.strip() and goal.strip()!=str(conv.get("ux_goal") or "").strip()):
                conv["draft"]={"text":text,"goal":goal}
            else:
                if "draft" not in conv: return {"ok":True}
                conv.pop("draft",None)
            save_conversation(CURRENT_USER_DIR,conv)
            return {"ok":True}
        except Exception as e:
            _log(f"[drishti] draft save failed: {type(e).__name__}: {str(e)[:200]}")
            return {"ok":False}

    # -- session history: Profile -> My Sessions / (Three-dot) Persons ---
    # Both always resolve an EXPLICIT folder, never the currently-active
    # SESSIONS_ROOT β€” so "My Sessions" keeps showing the owner's own
    # sessions and "Persons -> Rahul" keeps showing Rahul's, no matter who
    # the Participant panel currently has selected. Each call does a fresh
    # directory listing (_sessions_json()), so simply opening either panel
    # is the "live refresh" β€” no separate polling/push needed.

    @_require_token
    def list_my_sessions(self, limit=25):
        if not CURRENT_USER_DIR:
            return []
        return _sessions_json(os.path.join(CURRENT_USER_DIR, "sessions"), limit)

    @_require_token
    def list_participant_sessions(self, participant_id, limit=25):
        if not CURRENT_USER_DIR or not participant_id:
            return []
        pdir = participants.participant_dir(CURRENT_USER_DIR, participant_id)
        return _sessions_json(os.path.join(pdir, "sessions"), limit)

    def _resolve_session_dir(self, sessions_root, session_id):
        """session_id round-trips through JS on every rename/open-report

        call, and window.pywebview.api is reachable from ANY loaded page's

        own script (not just our injected chrome) β€” reject anything that

        doesn't look like a folder name we ourselves generated before it

        ever touches os.path.join, instead of trusting it as a path

        component."""
        if not session_id or not _SESSION_ID_RE.match(session_id):
            return None
        session_dir = os.path.join(sessions_root, session_id)
        if not os.path.isdir(session_dir):
            return None
        return session_dir

    def _report_uri_for(self, report_path, participant_id=None, return_url=None, autoprint=False):
        """report_uri() lives in drishti_report.py. Depending on which version of that

        file is installed it may not accept `return_url`; a TypeError there used to make

        every "View Report" click fail silently. Try the newest call first, then older

        signatures, then a plain file URI, so a report always opens."""
        for args in ((report_path, participant_id, return_url), (report_path, participant_id), (report_path,)):
            try:
                return self._with_autoprint(_drishti_report_uri(*args), autoprint)
            except TypeError:
                continue
            except Exception as e:
                _log(f"[browser_session] report_uri failed: {type(e).__name__}: {e}")
                break
        uri = Path(report_path).resolve().as_uri()
        if participant_id:
            from urllib.parse import quote
            uri += "#insightux_participant=" + quote(str(participant_id), safe="")
        if return_url:
            from urllib.parse import quote
            uri += ("&" if "#" in uri else "#") + "insightux_return=" + quote(str(return_url), safe="")
        return self._with_autoprint(uri, autoprint)

    @staticmethod
    def _with_autoprint(uri, autoprint):
        """Adds insightux_autoprint=1 to the #fragment (never the ?query --

        the webview can't open a file:// path that carries a query string)

        so the report page runs its own Export as soon as it is ready."""
        if not autoprint:
            return uri
        return uri + ("&" if "#" in uri else "#") + "insightux_autoprint=1"

    def _open_session_report(self, sessions_root, session_id, participant_id=None, return_url=None, autoprint=False):
        """Native window.load_url() call, not page script β€” mirrors

        go_home() above: a page loaded over http(s) can't script-navigate

        itself to a file:// URL (Chromium/WebView2 silently blocks it), so

        "View Report" from My Sessions/Persons has to come in through here

        to work while browsing a real website, not just from the landing

        or report pages (which happen to already be file:// and were

        masking this)."""
        session_dir = self._resolve_session_dir(sessions_root, session_id)
        if not session_dir:
            return False
        report_path = os.path.join(session_dir, "analysis_report.html")
        if not os.path.exists(report_path):
            return False
        try:
            # Reports are static files written when a session ended, so an old one still
            # has the old chart/template. Rebuild it once from the session's raw data
            # (keeping its heatmap images) before showing it.
            if refresh_report_if_stale(report_path):
                _log(f"[browser_session] refreshed stale report -> {report_path}")
        except Exception as e:
            _log(f"[browser_session] report refresh skipped: {type(e).__name__}: {e}")
        try:
            self.window.load_url(self._report_uri_for(report_path, participant_id, return_url, autoprint))
        except Exception as e:
            import traceback
            _log(f"[browser_session] open session report failed: {type(e).__name__}: {e}\n{traceback.format_exc()}")
            return False
        return True

    @_require_token
    def open_my_session_report(self, session_id, return_url=None):
        if not CURRENT_USER_DIR:
            return False
        return self._open_session_report(os.path.join(CURRENT_USER_DIR, "sessions"), session_id, return_url=return_url)

    @_require_token
    def open_participant_session_report(self, participant_id, session_id, return_url=None):
        if not CURRENT_USER_DIR or not participant_id:
            return False
        pdir = participants.participant_dir(CURRENT_USER_DIR, participant_id)
        return self._open_session_report(os.path.join(pdir, "sessions"), session_id, participant_id, return_url)

    def _export_session(self, sessions_root, session_id):
        """Bundles a JSON summary + a CSV of raw gaze samples into a single

        .zip (one native Save dialog, one resulting file, rather than

        making the researcher pick a destination twice or hunt for two

        loose files afterwards) and writes it wherever the user chooses.

        Read-only against the session itself -- never touches session_dir."""
        session_dir = self._resolve_session_dir(sessions_root, session_id)
        if not session_dir:
            return False
        try:
            gaze, dom = load_session(session_dir)
            summary = session_summary(gaze, dom)
            mouse = summarize_mouse(session_dir)
        except Exception as e:
            _log(f"[browser_session] export: could not load session data: {e}")
            return False

        meta = {}
        meta_path = os.path.join(session_dir, "session_meta.json")
        if os.path.exists(meta_path):
            try:
                with open(meta_path, "r", encoding="utf-8") as f:
                    meta = json.load(f)
            except Exception:
                meta = {}

        summary_json = {
            "session_id": session_id,
            "display_name": meta.get("display_name"),
            "started_at": meta.get("started_at"),
            "tracking_mode": meta.get("tracking_mode", "self"),
            "participant_name": meta.get("participant_name"),
            "url": summary["url"],
            "duration_seconds": summary["duration"],
            "gaze_samples": summary["samples"],
            "mouse_clicks": mouse["click_count"],
            "mouse_trail_points": mouse["trail_points"],
            "mouse_heatmap_points": mouse["heatmap_points"],
            "top_dwell_elements": mouse["interests"],
        }

        try:
            # webview.FileDialog.SAVE doesn't exist in the pinned pywebview
            # 4.4.1 (added in a later release) -- SAVE_DIALOG is the name
            # that actually exists here, deprecated or not.
            result = self.window.create_file_dialog(
                webview.SAVE_DIALOG, directory="",
                save_filename=f"insightux_session_{session_id}.zip",
                file_types=("Zip files (*.zip)",),
            )
        except Exception as e:
            _log(f"[browser_session] export: save dialog failed: {e}")
            return False
        if not result:
            return False  # user cancelled the dialog
        # window.create_file_dialog()'s own type hint promises Sequence[str]
        # -- but the pinned pywebview 4.4.1's WinForms backend returns a
        # plain str for SAVE_DIALOG specifically (dialog.FileName directly,
        # unlike OPEN_DIALOG/FOLDER_DIALOG which do wrap their result in a
        # tuple). Trusting the type hint here silently wrote to a mangled
        # one-character path (result[0] on a string is just its first
        # character) instead of anywhere the user actually chose.
        dest_path = result if isinstance(result, str) else result[0]
        if not dest_path.lower().endswith(".zip"):
            dest_path += ".zip"

        try:
            with zipfile.ZipFile(dest_path, "w", zipfile.ZIP_DEFLATED) as zf:
                zf.writestr("session_summary.json", json.dumps(summary_json, indent=2))
                csv_buf = io.StringIO()
                writer = csv.writer(csv_buf)
                writer.writerow(["timestamp_seconds", "screen_x", "screen_y"])
                for g in gaze:
                    writer.writerow([g.get("t"), g.get("sx"), g.get("sy")])
                zf.writestr("gaze_samples.csv", csv_buf.getvalue())
        except Exception as e:
            _log(f"[browser_session] export: failed to write {dest_path}: {e}")
            return False

        _log(f"[browser_session] exported session {session_id} -> {dest_path}")
        return True

    # The session-list Download button writes the same PDF the report's own
    # Export button produces, WITHOUT navigating away from the sessions list:
    # ask where to save, then render that session's analysis_report.html to PDF
    # with headless Edge/Chrome (print stylesheet = the report's PDF layout) in
    # a background thread. _export_session() above (JSON+CSV zip) is unused now.
    @staticmethod
    def _find_headless_browser():
        import shutil
        names = [("Google", "Chrome", "Application", "chrome.exe"),
                 ("Microsoft", "Edge", "Application", "msedge.exe")]
        for env in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):
            base = os.environ.get(env)
            if not base:
                continue
            for parts in names:
                p = os.path.join(base, *parts)
                if os.path.exists(p):
                    return p
        for exe in ("chrome", "msedge", "google-chrome", "chromium"):
            p = shutil.which(exe)
            if p:
                return p
        return None

    def _render_report_pdf(self, browser, report_path, dest_path):
        import tempfile, shutil
        tmp = tempfile.mkdtemp(prefix="iux_pdf_")
        out = os.path.join(tmp, "report.pdf")
        cmd = [
            browser, "--headless=new", "--disable-gpu", "--no-first-run",
            "--no-default-browser-check",
            f"--user-data-dir={os.path.join(tmp, 'profile')}",
            "--no-pdf-header-footer", "--print-to-pdf-no-header",
            "--run-all-compositor-stages-before-draw",
            "--virtual-time-budget=20000",   # lets the report's async print-page build finish
            f"--print-to-pdf={out}",
            Path(report_path).resolve().as_uri(),
        ]
        try:
            subprocess.run(cmd, timeout=120, stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL,
                           creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
            if os.path.exists(out) and os.path.getsize(out) > 0:
                shutil.move(out, dest_path)
                _log(f"[browser_session] exported PDF report -> {dest_path}")
                self._set_status("PDF report saved: " + os.path.basename(dest_path))
            else:
                _log("[browser_session] PDF export: browser produced no file")
                self._set_status("Could not create the PDF report. Open the report and use Export instead.")
        except Exception as e:
            _log(f"[browser_session] PDF export failed: {type(e).__name__}: {e}")
            self._set_status("Could not create the PDF report. Open the report and use Export instead.")
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def _export_session_pdf(self, sessions_root, session_id):
        session_dir = self._resolve_session_dir(sessions_root, session_id)
        if not session_dir:
            return False
        report_path = os.path.join(session_dir, "analysis_report.html")
        if not os.path.exists(report_path):
            self._set_status("This session has no report to export.")
            return False
        browser = self._find_headless_browser()
        if not browser:
            self._set_status("Chrome or Edge is needed to save the PDF. Open the report and use Export instead.")
            return False
        try:
            if refresh_report_if_stale(report_path):
                _log(f"[browser_session] refreshed stale report -> {report_path}")
        except Exception as e:
            _log(f"[browser_session] report refresh skipped: {type(e).__name__}: {e}")
        try:
            result = self.window.create_file_dialog(
                webview.SAVE_DIALOG, directory="",
                save_filename=f"insightux_report_{session_id}.pdf",
                file_types=("PDF files (*.pdf)",),
            )
        except Exception as e:
            _log(f"[browser_session] PDF export: save dialog failed: {e}")
            return False
        if not result:
            return False  # cancelled
        dest_path = result if isinstance(result, str) else result[0]
        if not dest_path.lower().endswith(".pdf"):
            dest_path += ".pdf"
        self._set_status("Creating PDF report...")
        threading.Thread(target=self._render_report_pdf,
                         args=(browser, report_path, dest_path),
                         name="report-pdf-export", daemon=True).start()
        return True

    @_require_token
    def export_my_session(self, session_id, return_url=None):
        if not CURRENT_USER_DIR:
            return False
        return self._export_session_pdf(os.path.join(CURRENT_USER_DIR, "sessions"), session_id)

    @_require_token
    def export_participant_session(self, participant_id, session_id, return_url=None):
        if not CURRENT_USER_DIR or not participant_id:
            return False
        pdir = participants.participant_dir(CURRENT_USER_DIR, participant_id)
        return self._export_session_pdf(os.path.join(pdir, "sessions"), session_id)

    # -- theme: one saved choice for every page ---------------------------
    # localStorage is per web origin, so the theme picked on the landing page
    # (file://) was invisible to the report (another file://) and to every
    # website the chrome is injected into. The choice is stored here instead
    # and pushed into each page by THEME_SYNC_JS (see on_page_loaded()).
    # Deliberately NOT token-gated: the login and report pages' own scripts
    # have no token, and the only thing a caller can do is set "light"/"dark".
    def get_theme(self):
        try:
            with open(THEME_PREF_PATH, "r", encoding="utf-8") as f:
                value = json.load(f).get("theme")
            return value if value in ("light", "dark") else None
        except Exception:
            return None

    def set_theme(self, theme_name):
        if theme_name not in ("light", "dark"):
            return False
        try:
            os.makedirs(os.path.dirname(THEME_PREF_PATH), exist_ok=True)
            tmp = THEME_PREF_PATH + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump({"theme": theme_name}, f)
            os.replace(tmp, THEME_PREF_PATH)
            return True
        except Exception as e:
            _log(f"[browser_session] could not save theme preference: {e}")
            return False

    def _set_session_display_name(self, sessions_root, session_id, name):
        """Persisted to that session's own session_meta.json (as

        display_name) instead of browser localStorage β€” localStorage is

        scoped per web origin, so a name saved while looking at one

        website would never show up while looking at another, or from the

        file:// landing page. A file next to the session's own data is the

        one place every view of it (My Sessions, Persons, the report

        itself) can agree on. Sessions from before session_meta.json

        existed just get a fresh one with only this field."""
        session_dir = self._resolve_session_dir(sessions_root, session_id)
        if not session_dir:
            return False
        meta_path = os.path.join(session_dir, "session_meta.json")
        meta = {}
        if os.path.exists(meta_path):
            try:
                with open(meta_path, "r", encoding="utf-8") as f:
                    meta = json.load(f)
            except Exception:
                meta = {}
        trimmed = (name or "").strip()
        if trimmed:
            meta["display_name"] = trimmed
        else:
            meta.pop("display_name", None)
        try:
            with open(meta_path, "w", encoding="utf-8") as f:
                json.dump(meta, f, indent=2)
        except Exception as e:
            _log(f"[browser_session] could not save session display name: {e}")
            return False
        return True

    @_require_token
    def rename_my_session(self, session_id, name):
        if not CURRENT_USER_DIR:
            return False
        return self._set_session_display_name(os.path.join(CURRENT_USER_DIR, "sessions"), session_id, name)

    @_require_token
    def rename_participant_session(self, participant_id, session_id, name):
        if not CURRENT_USER_DIR or not participant_id:
            return False
        pdir = participants.participant_dir(CURRENT_USER_DIR, participant_id)
        return self._set_session_display_name(os.path.join(pdir, "sessions"), session_id, name)

    def _delete_session(self, sessions_root, session_id):
        """Irreversible; the caller is expected to have already confirmed

        with the user. Refuses the one folder gaze_worker() might still

        have file handles open on (self.current_session_dir) β€” rmtree'ing

        a session mid-recording would race its own logger/screenshot

        writes instead of just deleting old, already-closed data."""
        session_dir = self._resolve_session_dir(sessions_root, session_id)
        if not session_dir:
            return False
        if self.current_session_dir and os.path.normcase(os.path.normpath(session_dir)) == \
                os.path.normcase(os.path.normpath(self.current_session_dir)):
            return False
        import shutil
        try:
            shutil.rmtree(session_dir)
        except Exception as e:
            _log(f"[browser_session] could not delete session: {e}")
            return False
        return True

    @_require_token
    def delete_my_session(self, session_id):
        if not CURRENT_USER_DIR:
            return False
        return self._delete_session(os.path.join(CURRENT_USER_DIR, "sessions"), session_id)

    @_require_token
    def delete_participant_session(self, participant_id, session_id):
        if not CURRENT_USER_DIR or not participant_id:
            return False
        pdir = participants.participant_dir(CURRENT_USER_DIR, participant_id)
        return self._delete_session(os.path.join(pdir, "sessions"), session_id)

    @_require_token
    def toggle_session(self):
        """Single entry point for the sidebar's Start/Stop Session button β€”

        lets the JS button stay dumb (always call the same thing) while

        Python decides which action makes sense from current state.

        Calls start_tracking()/stop_tracking() via .__wrapped__ (the

        original undecorated function functools.wraps preserves) rather

        than through self.start_tracking()/self.stop_tracking() directly β€”

        those are themselves @_require_token, which expects the token as

        the caller's last positional arg. This internal call passes none,

        so going through the normal bound method would always be rejected

        by that same decorator, silently no-op'ing the button."""
        return self.stop_tracking.__wrapped__(self) if self.tracking else self.start_tracking.__wrapped__(self)

    def _active_elapsed_seconds(self):
        elapsed = float(self.session_active_elapsed or 0.0)
        if self.session_active_started_at is not None:
            elapsed += max(0.0, time.time() - self.session_active_started_at)
        return elapsed

    def _pause_session_clock(self):
        if self.session_active_started_at is not None:
            self.session_active_elapsed = self._active_elapsed_seconds()
            self.session_active_started_at = None

    def _resume_session_clock(self):
        if self.session_active_started_at is None and self.tracking and not self.page_transitioning:
            self.session_active_started_at = time.time()

    def _chrome_heatmap_worker(self):
        """Serialize expensive heatmap rendering after page capture.



        Screenshot capture itself is tied to the live WebView2 page and is

        started as soon as a stable page is confirmed. Only the CPU-heavy

        gaze-to-PNG overlay is queued, so multiple visited pages cannot make

        the browser navigation path wait on image rendering.

        """
        while True:
            session = self.chrome_heatmap_queue.get()
            try:
                # A queued capture must be allowed to finish after recording stops.
                # The real-Chrome capture service has its own navigation timeout and
                # reports failures, so this wait does not hang on a normal network/
                # server failure.
                session.finalize(wait_seconds=None)
            except Exception as exc:
                _log(f"[browser_session] queued Chrome heatmap processing failed for {session.url}: {exc}")
            finally:
                self.chrome_heatmap_queue.task_done()

    def _queue_page_heatmap(self, url):
        """Queue one stable URL for heatmap rendering, at most once."""
        url = str(url or "").strip()
        if not url or url in self.page_heatmap_queued:
            return
        session = self.microlink_sessions.get(url)
        if session is None:
            return
        self.page_heatmap_queued.add(url)
        self.chrome_heatmap_queue.put(session)
        _log(f"[browser_session] queued heatmap processing for {url}")

    @_require_token
    def page_navigation_started(self, token=None):
        """Called by the old document just before a real navigation starts.



        Recording remains alive, but gaze/mouse/DOM samples are paused until

        the new document has loaded and settled. This keeps page-transition

        frames out of the session and prevents accidental fast clicks from

        becoming screenshot/heatmap pages.

        """
        if not self.tracking:
            return False
        # The old page has now ended. If it survived the stable-page gate,
        # finalize its gaze/image pairing asynchronously before navigation
        # continues. This happens only while recording is ON.
        try:
            old_url = self.window.get_current_url() or ""
        except Exception:
            old_url = ""
        if not self.page_transitioning:
            self._queue_page_heatmap(old_url)
        self.page_transition_serial += 1
        self._pause_session_clock()
        self.page_transitioning = True
        if self.page_resume_timer:
            try:
                self.page_resume_timer.cancel()
            except Exception:
                pass
            self.page_resume_timer = None
        self._set_mouse_tracking(False)
        self._set_session_ui(True)
        self._set_status("Page changing β€” recording paused until the new page is ready...")
        _log("[browser_session] page navigation started -> recording paused")
        return True

    def _schedule_page_ready(self, expected_url):
        """Resume recording and queue the screenshot after a stable-page delay."""
        if not self.tracking or not self.microlink_capture_enabled:
            return
        self.page_transition_serial += 1
        serial = self.page_transition_serial
        self.page_transitioning = True
        if self.page_resume_timer:
            try:
                self.page_resume_timer.cancel()
            except Exception:
                pass

        def finish_transition():
            if serial != self.page_transition_serial:
                return
            if not self.tracking or not self.microlink_capture_enabled:
                return
            try:
                current = self.window.get_current_url() or ""
            except Exception:
                current = ""
            if current != str(expected_url or ""):
                _log(f"[browser_session] page changed again during settle window; ignoring {expected_url}")
                return
            self.page_transitioning = False
            self._resume_session_clock()
            self._inject_tracking_overlay()
            self._inject_gaze_bridge()
            self._inject_mouse_overlay()
            self._set_mouse_tracking(True)
            self._set_session_ui(True)
            self._set_status("Recording β€” gaze + mouse... Press E to stop, H for heatmap, M for mouse panel")
            # The page has crossed the 2-second stability threshold. Create
            # exactly one URL-scoped session and start Chromium's full-size
            # screenshot now, while this URL is still the live WebView page.
            # The session carries this navigation serial as a final stale-job
            # guard, so a queued/blocked capture can never accidentally start
            # against a later page.
            self._ensure_microlink_session(current, capture_serial=serial)
            _log(f"[browser_session] page ready -> recording resumed for {current}")

        self.page_resume_timer = threading.Timer(PAGE_SETTLE_SECONDS, finish_transition)
        self.page_resume_timer.daemon = True
        self.page_resume_timer.start()

    def _ensure_microlink_session(self, url, capture_serial=None):
        """Create/start one Microlink screenshot session per exact page URL.



        This is deliberately guarded by the active tracking-session flag.

        Microlink must never be contacted merely because the browser opens,

        navigates, reloads, or sits on a page while tracking is OFF.

        """
        if not self.tracking or not self.microlink_capture_enabled:
            return None
        # Never create a screenshot session while the browser is between pages.
        # A fast accidental navigation therefore does not consume a capture or
        # create a misleading heatmap.
        if self.page_transitioning:
            return None
        url = str(url or "").strip()
        if not url or not url.startswith(("http://", "https://")):
            return None
        existing = self.microlink_sessions.get(url)
        if existing is not None:
            return existing
        if not self.current_session_dir:
            return None
        try:
            # IMPORTANT: once a stable page has crossed the 2-second gate and
            # its screenshot request is queued, that request belongs to this
            # recording session and must NOT be invalidated by a later browser
            # navigation or by pressing E. Real Chrome opens this exact URL in
            # its own capture context, so it does not depend on the live
            # WebView2 being on the same page anymore.
            session = ChromeHeatmapSession(
                self.current_session_dir,
                url,
                self.window,
                capture_guard=None,
            )
            self.microlink_sessions[url] = session
            session.start_capture()
            _log(f"[browser_session] Chrome full-page screenshot queued for {url}")
            self._set_microlink_usage_ui()
            return session
        except Exception as e:
            _log(f"[browser_session] Chrome screenshot session setup failed for {url}: {e}")
            return None

    def _finalize_microlink_sessions(self, report_path=None):
        """Finish Microlink, embed every completed heatmap into the report,

        verify the final report exists, and navigate to it exactly once.



        IMPORTANT: this method is called only after gaze_worker() has finished

        generating the base analysis_report.html. That ordering prevents

        WebView2 from opening a stale/base report before the Microlink image

        has been embedded.

        """
        sessions = list(self.microlink_sessions.values())
        if report_path is None:
            for session in sessions:
                candidate = Path(session.session_dir) / "analysis_report.html"
                if candidate.exists():
                    report_path = candidate
                    break

        if report_path is None:
            _log("[browser_session] final report path is unavailable; report navigation skipped")
            return False

        report_path = Path(report_path).resolve()
        if not report_path.exists():
            _log(f"[browser_session] final report does not exist yet: {report_path}")
            return False

        # Let the background heatmap queue finish the pages that have already
        # been captured. finalize() below is idempotent and only waits for any
        # capture/render that is still outstanding.
        try:
            self.chrome_heatmap_queue.join()
        except Exception:
            pass

        completed_heatmaps = []
        failed_heatmaps = []

        # First finish every URL-scoped Microlink session. We intentionally
        # collect all completed images before touching the report, because a
        # single tracking session may visit many different webpages.
        for session in sessions:
            try:
                # Every session that crossed the stable-page gate remains a
                # real queued request until it finishes, even after E/Stop.
                # A capture failure is recorded but must never block the
                # successful pages from appearing in the report.
                ok = session.finalize(wait_seconds=None)
                if not ok:
                    failed_heatmaps.append({
                        "url": session.url,
                        "error": session.capture_error or "unknown capture failure",
                    })
                    _log(
                        f"[browser_session] Chrome heatmap unavailable for "
                        f"{session.url}: {session.capture_error}"
                    )
                    continue

                completed_heatmaps.append({
                    "url": session.url,
                    "composite_path": str(session.final_path),
                })
                _log(
                    f"[browser_session] Chrome full-page heatmap ready for "
                    f"{session.url}"
                )
                self._set_microlink_usage_ui()
            except Exception as e:
                failed_heatmaps.append({
                    "url": session.url,
                    "error": repr(e),
                })
                _log(
                    f"[browser_session] Chrome heatmap finalize failed "
                    f"for {session.url}: {e}"
                )

        # Embed every successfully generated image. Failed URLs are simply
        # omitted; the report must still be usable and must never contain blank
        # placeholder images for pages whose capture failed.
        if completed_heatmaps:
            try:
                attached = attach_microlink_heatmaps_to_report(
                    report_path, completed_heatmaps
                )
                if not attached:
                    _log(
                        "[browser_session] successful Chrome heatmaps could not be "
                        "embedded into the final report"
                    )
                else:
                    _log(
                        f"[browser_session] embedded {len(completed_heatmaps)} "
                        f"successful Chrome webpage heatmap(s) into report -> {report_path}"
                    )
            except Exception as e:
                _log(f"[browser_session] successful Chrome report embedding failed: {e}")
        else:
            _log("[browser_session] no Chrome heatmaps were generated; opening the base report without blank image placeholders")

        if failed_heatmaps:
            _log(
                f"[browser_session] {len(failed_heatmaps)} Chrome page capture(s) failed; "
                f"report will contain only successfully generated images"
            )

        # The report is still valid when one or more capture requests fail.
        # Only successful images are embedded; never withhold the whole report
        # because a single webpage was unreachable or otherwise failed.

        try:
            # A native file URI is the same navigation mechanism used by
            # Previous Sessions, which reliably loads the already-finalized
            # HTML and its embedded base64 PNG.
            participant_id = None
            try:
                with open(report_path.parent / "session_meta.json", "r", encoding="utf-8") as f:
                    participant_id = json.load(f).get("participant_id") or None
            except Exception:
                pass
            report_uri = _drishti_report_uri(report_path, participant_id)
            self.window.load_url(report_uri)
            _log(f"[browser_session] final report loaded with Chrome full-page heatmap -> {report_uri}")
            return True
        except Exception as load_exc:
            _log(f"[browser_session] final report navigation failed: {load_exc}")
            return False

    def _start_microlink_finalize_thread(self):
        if self.microlink_finalize_thread and self.microlink_finalize_thread.is_alive():
            return
        self.microlink_finalize_thread = threading.Thread(
            target=self._finalize_microlink_sessions,
            name="microlink-heatmap-finalize",
            daemon=True,
        )
        self.microlink_finalize_thread.start()

    def _abort_camera_session(self):
        """Return to idle if camera access is lost during a live check/session."""
        self._pause_session_clock()
        self.tracking = False
        self.microlink_capture_enabled = False
        self.page_transitioning = False
        self.session_started_at = None
        self.current_session_dir = None
        self.stop_event.set()
        self.gaze_bridge_stop.set()
        if self.page_resume_timer:
            self.page_resume_timer.cancel()
            self.page_resume_timer = None
        self._set_mouse_tracking(False)
        self._set_session_ui(False)
        self._close_mouse_log()
        self._set_status(CAMERA_ACCESS_MESSAGE)
        try:
            self.window.evaluate_js(
                "window.insightuxShowCameraError && window.insightuxShowCameraError("
                + json.dumps(CAMERA_ACCESS_MESSAGE) + ")")
        except Exception:
            pass

    def _open_session_camera(self):
        """Verify camera access before creating a session; keep it for the worker."""
        try:
            return open_camera(cv2)
        except CameraAccessError:
            pass
        message = CAMERA_ACCESS_MESSAGE
        self._set_status(message)
        try:
            self.window.evaluate_js(
                "window.insightuxShowCameraError && window.insightuxShowCameraError("
                + json.dumps(message) + ")")
        except Exception:
            pass
        return None

    @_require_token
    def start_tracking(self):
        _log("[browser_session] start_tracking() called from JS")
        if self.tracking:
            _log("[browser_session]   already tracking, ignoring")
            return False
        if self.current_user is None:
            _log("[browser_session]   refusing to start, no profile signed in")
            self._set_status("Sign in to a profile before starting a session.")
            return False
        try:
            current_url = self.window.get_current_url() or ""
        except Exception:
            current_url = ""
        if any(marker in current_url for marker in _NON_TRACKABLE_URL_MARKERS):
            _log(f"[browser_session]   refusing to start on non-website page: {current_url}")
            self._set_status("Start tracking only works on a website β€” search or open a page first.")
            return False
        if self._external_proc_running():
            _log("[browser_session]   refusing to start, calibration/validation still running")
            self._set_status("Wait for calibration/validation to finish before starting a session.")
            return False
        if not os.path.exists(CALIBRATION_PATH):
            _log(f"[browser_session]   no {CALIBRATION_PATH} found β€” run calibrate.py first")
            self._set_status("No calibration.pkl found β€” run calibrate.py first.")
            return False

        # pywebview API calls run off the UI thread. Do not create session
        # files, timers, overlays or participant statistics until access succeeds.
        if getattr(self, "_camera_starting", False):
            return False
        self._camera_starting = True
        try:
            cap = self._open_session_camera()
        finally:
            self._camera_starting = False
        if cap is None:
            return False

        self.tracking = True
        self.microlink_capture_enabled = True
        self.session_started_at = time.time()
        self.stop_event.clear()
        self.page_transitioning = True
        self.page_transition_serial += 1
        self.session_active_elapsed = 0.0
        self.session_active_started_at = None
        session_dir = os.path.join(SESSIONS_ROOT, datetime.now().strftime("%Y%m%d_%H%M%S"))
        os.makedirs(session_dir, exist_ok=True)
        self.current_session_dir = session_dir
        self.microlink_sessions = {}
        self.page_heatmap_queued = set()
        self.microlink_finalize_thread = None
        _log(f"[browser_session]   starting tracking thread -> {session_dir}")
        self._write_session_meta(session_dir)
        # Do not capture immediately. Give the current page the same short
        # settle window used after navigation, so the screenshot is taken only
        # after the page is stable.
        self._schedule_page_ready(current_url)

        self._inject_tracking_overlay()
        self._inject_gaze_bridge()
        self._inject_mouse_overlay()
        self._open_mouse_log(session_dir)
        # Initial page preparation is part of the transition pause. The camera
        # thread may already be alive, but no gaze/mouse samples or active time
        # are recorded until _schedule_page_ready() confirms a stable page.
        self._set_mouse_tracking(False)
        self._set_session_ui(True)
        who = self.active_tracking_subject["name"] if self.active_tracking_subject else "yourself"
        self._set_status(f"Preparing page for {who} β€” recording paused until the page is ready...")

        self.thread = threading.Thread(
            target=gaze_worker, args=(self.window, self.stop_event, session_dir, self, cap),
            daemon=True
        )
        self.thread.start()
        self.gaze_bridge_stop.clear()
        self.gaze_bridge_thread = threading.Thread(
            target=self._gaze_bridge_loop, daemon=True
        )
        self.gaze_bridge_thread.start()
        return True

    def _write_session_meta(self, session_dir):
        """Ownership is recorded up front, at the moment session_dir is

        created β€” never reconstructed after the fact from which folder a

        session happens to be found under. website_url/duration are

        deliberately NOT duplicated here: analysis.py already derives

        those from gaze_log.jsonl/dom_log.jsonl, and this file only holds

        what isn't already derivable β€” who owns the session and who was

        being tracked."""
        subject = self.active_tracking_subject
        meta = {
            "owner_id": self.current_user["id"],
            "tracking_mode": "participant" if subject else "self",
            "participant_id": subject["id"] if subject else None,
            "participant_name": subject["name"] if subject else None,
            "started_at": datetime.now().isoformat(),
        }
        try:
            with open(os.path.join(session_dir, "session_meta.json"), "w", encoding="utf-8") as f:
                json.dump(meta, f, indent=2)
        except Exception as e:
            _log(f"[browser_session] could not write session_meta.json: {e}")
        if subject:
            try:
                participants.touch_session_stats(CURRENT_USER_DIR, subject["id"])
            except Exception as e:
                _log(f"[browser_session] could not update participant stats: {e}")

    @_require_token
    def stop_tracking(self):
        _log("[browser_session] stop_tracking() called from JS")
        if not self.tracking:
            _log("[browser_session]   not currently tracking, ignoring")
            return False
        self._set_status("Wrapping up your session...")
        self._pause_session_clock()
        # Finalize the currently stable page before recording is disabled.
        # This is the last point at which its gaze stream belongs to this
        # recording session.
        if not self.page_transitioning:
            try:
                current_url = self.window.get_current_url() or ""
            except Exception:
                current_url = ""
            self._queue_page_heatmap(current_url)
        # Stop accepting new Microlink capture work immediately. The gaze/report
        # thread may still be finishing existing URL sessions, but a navigation
        # after E must never create another screenshot request.
        self.microlink_capture_enabled = False
        self.page_transitioning = False
        if self.page_resume_timer:
            try:
                self.page_resume_timer.cancel()
            except Exception:
                pass
            self.page_resume_timer = None
        self._set_mouse_tracking(False)
        self._set_session_ui(False, report_pending=True)
        self.session_started_at = None
        self.stop_event.set()
        self.gaze_bridge_stop.set()
        # Do NOT finalize Microlink here. The gaze worker still has to close
        # its logs and generate analysis_report.html first. Finalization is
        # deliberately triggered by gaze_worker() after report generation so
        # the user can never see the unfinished/base report.

        # Give the page a moment to flush its last batch of mouse data over
        # log_mouse_data() before the file handle is closed.
        if self.mouse_close_timer:
            self.mouse_close_timer.cancel()
        self.mouse_close_timer = threading.Timer(2.5, self._close_mouse_log)
        self.mouse_close_timer.daemon = True
        self.mouse_close_timer.start()
        return True

    @_require_token
    def quit_app(self):
        # X is an emergency kill switch, not a graceful shutdown β€” the user
        # wants the terminal process gone immediately, camera/threads and all.
        _log("[browser_session] quit_app() called from JS -- terminating process")
        os._exit(0)

    @_require_token
    def go_home(self):
        # A page loaded over http(s) can't script-navigate itself to a
        # file:// URL β€” Chromium/WebView2 silently blocks it (no exception,
        # no navigation), which is what made the toolbar's Home button a
        # no-op via location.href. window.load_url() is a native host call,
        # not page script, so it isn't subject to that restriction β€” same
        # mechanism the report page's own navigation already relies on.
        _log("[browser_session] go_home() called from JS")
        try:
            # _write_landing_page() writes to the same fixed path every
            # time and returns the same URL β€” but LANDING_URL itself was
            # only ever computed once, at app startup, so the "Recent
            # Sessions" list it baked in went stale after the first session
            # of the run. Rebuild it fresh right before navigating so Home
            # always reflects whatever sessions exist right now.
            fresh_url = _write_landing_page()
            self.window.load_url(fresh_url)
        except Exception as e:
            _log(f"[browser_session] go_home failed: {e}")
        return True

    # -- calibration / validation ------------------------------------------
    # calibrate.py and validate.py are unmodified, standalone OpenCV/pyautogui
    # scripts (their own fullscreen window, their own event loop) β€” they were
    # never meant to share a process with pywebview's GUI loop. Launching them
    # as a subprocess reuses them exactly as-is instead of rewriting their
    # display logic into the browser.

    def _external_proc_running(self):
        running = lambda p: p is not None and p.poll() is None
        return running(self.calib_proc) or running(self.validate_proc)

    def _subprocess_user_env(self):
        """calibrate.py/validate.py run as separate processes and compute

        their own DATA_DIR independently (see their own module docstrings)

        β€” this env var is the only channel that tells them which subject's

        folder to read/write, and which per-subject path fine-tuning

        should save its adapted model to instead of overwriting the

        shared bundled ONNX everyone's inference loads. Deliberately

        CURRENT_SUBJECT_DIR, not CURRENT_USER_DIR: calibrating while

        "Rahul" is the active tracking subject must calibrate Rahul, not

        the signed-in owner. Absent (dev/standalone `python calibrate.py`),

        both scripts fall back to today's exact behavior β€” see their own

        INSIGHTUX_USER_DATA_DIR checks."""
        env = dict(os.environ)
        if CURRENT_SUBJECT_DIR:
            env["INSIGHTUX_USER_DATA_DIR"] = CURRENT_SUBJECT_DIR
            env["INSIGHTUX_USER_ONNX_OUT"] = os.path.join(CURRENT_SUBJECT_DIR, "gaze_cnn_v4_finetuned.onnx")
        return env

    @_require_token
    def start_calibration(self):
        _log("[browser_session] start_calibration() called from JS")
        if self.current_user is None:
            self._set_status("Sign in to a profile before calibrating.")
            return False
        if self.tracking:
            self._set_status("Stop the current session (E) before calibrating.")
            return False
        if self._external_proc_running():
            self._set_status("Calibration/validation is already running in another window.")
            return False
        try:
            calibration_cancel_event = threading.Event()
            calibration_env = self._subprocess_user_env()
            calibration_env["PYTHONUNBUFFERED"] = "1"
            self.calib_proc = subprocess.Popen(
                _relaunch_args("calibrate"), cwd=BASE_DIR, env=calibration_env,
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                text=True, encoding="utf-8", errors="replace", bufsize=1
            )
            self.calibration_cancel_event = calibration_cancel_event
        except Exception as e:
            _log(f"[browser_session] failed to launch calibrate.py: {e}")
            self._set_status("Could not launch calibration β€” see terminal for details.")
            return False
        self._set_status("Calibration started β€” follow the targets and keep your head steady.")
        try:
            self.window.evaluate_js("window.insightuxShowCalibrationRunning && window.insightuxShowCalibrationRunning()")
        except Exception:
            pass
        threading.Thread(
            target=self._watch_external_proc, args=(self.calib_proc, "Calibration", calibration_cancel_event), daemon=True
        ).start()
        return True

    @_require_token
    def cancel_calibration(self):
        """Cancel calibration when the user closes its progress dialog."""
        proc = self.calib_proc
        cancel_event = self.calibration_cancel_event
        if proc is None or cancel_event is None:
            return False
        cancel_event.set()
        try:
            if proc.poll() is None:
                proc.terminate()
        except OSError as exc:
            if proc.poll() is None:
                cancel_event.clear()
                _log(f"[browser_session] calibration cancel failed: {type(exc).__name__}: {exc}")
                return False
        self._set_status("Calibration cancelled.")
        return True

    def _update_calibration_progress_from_line(self, line):
        stage = message = label = None
        progress = None
        point = re.search(r"Point\s+(\d+)\s*/\s*(\d+)\s*\|", line)
        fine_tune_step = re.search(r"Step\s+(\d+)\s*/\s*(\d+)\s*\|", line)
        total_points = re.search(r"Calibration started\s*-\s*(\d+)\s+points", line)
        if "Checking face setup before calibration" in line:
            stage = "CHECKING CAMERA AND FACE"
            message = "Checking that your face is centered and visible before collecting calibration targets."
            label = "Camera and face check"
        elif total_points:
            total = int(total_points.group(1))
            stage = "COLLECTING CALIBRATION TARGETS"
            message = "Look directly at each dot and keep your head steady until the dot moves."
            label = f"0 of {total} targets captured"
            progress = 0
        elif point:
            current, total = int(point.group(1)), int(point.group(2))
            stage = "COLLECTING CALIBRATION TARGETS"
            message = "Calibration targets are being recorded. Keep following each dot with your eyes."
            label = f"{current} of {total} targets captured"
            progress = 100.0 * current / max(total, 1)
        elif "[Reliability filter]" in line:
            stage = "PROCESSING CALIBRATION DATA"
            message = "All available target samples are collected. InsightUX is checking sample quality before fitting your gaze mapping."
            label = "Preparing captured samples"
        elif "Fine-tuning CNN on your eyes" in line or "[Fine-tune]" in line and "steps on" in line:
            stage = "PERSONALIZING THE GAZE MODEL"
            message = "InsightUX is adapting the gaze model to the eye images captured during calibration."
            label = "Preparing model update"
            progress = 0
        elif fine_tune_step:
            current, total = int(fine_tune_step.group(1)), int(fine_tune_step.group(2))
            stage = "PERSONALIZING THE GAZE MODEL"
            message = "Processing your captured eye samples to personalize gaze tracking."
            label = f"Model update step {current} of {total}"
            progress = 100.0 * current / max(total, 1)
        elif "Fine-tuning SKIPPED" in line:
            stage = "FITTING THE SCREEN MAPPING"
            message = "The base gaze model is ready. InsightUX is fitting the mapping from gaze estimates to your screen."
            label = "Building gaze-to-screen mapping"
        elif "Adapted ONNX saved" in line:
            stage = "FITTING THE SCREEN MAPPING"
            message = "Model processing is complete. InsightUX is fitting the personalized gaze-to-screen mapping."
            label = "Building gaze-to-screen mapping"
        elif "Fitting RBF calibration" in line:
            stage = "FITTING THE SCREEN MAPPING"
            message = "Mapping the captured eye and head-pose samples to screen positions. This can take a few moments."
            label = "Building gaze-to-screen mapping"
        elif "Saved baseline_pose.pkl" in line:
            stage = "SAVING CALIBRATION"
            message = "The screen mapping is fitted. Saving your calibration and head-pose baseline."
            label = "Saving calibration files"
        elif "Calibration complete!" in line:
            stage = "FINALIZING CALIBRATION"
            message = "Calibration processing is complete. Preparing the quality summary."
            label = "Preparing calibration summary"
        if stage is None:
            return
        self._set_status(f"Calibration: {stage.lower()}.")
        try:
            args = (stage, message, label, progress)
            self.window.evaluate_js(
                "window.insightuxUpdateCalibrationProgress && window.insightuxUpdateCalibrationProgress("
                + ",".join(json.dumps(value, ensure_ascii=False) for value in args) + ")"
            )
        except Exception as exc:
            _log(f"[browser_session] calibration progress display failed: {type(exc).__name__}: {exc}")

    @_require_token
    def run_validation(self):
        _log("[browser_session] run_validation() called from JS")
        if self.current_user is None:
            self._set_status("Sign in to a profile before validating.")
            return False
        if self.tracking:
            self._set_status("Stop the current session (E) before validating.")
            return False
        if self._external_proc_running():
            self._set_status("Calibration/validation is already running in another window.")
            return False
        if not os.path.exists(CALIBRATION_PATH):
            self._set_status("No calibration.pkl found β€” run Calibrate first.")
            return False
        try:
            cancel_event = threading.Event()
            self.validate_proc = subprocess.Popen(
                _relaunch_args("validate"), cwd=BASE_DIR, env=self._subprocess_user_env(),
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                text=True, encoding="utf-8", errors="replace"
            )
            self.validation_cancel_event = cancel_event
        except Exception as e:
            _log(f"[browser_session] failed to launch validate.py: {e}")
            self._set_status("Could not launch validation β€” see terminal for details.")
            return False
        self._set_status("Validation launched in a separate window β€” look at each dot.")
        try:
            self.window.evaluate_js("window.insightuxShowValidationRunning && window.insightuxShowValidationRunning()")
        except Exception:
            pass
        threading.Thread(
            target=self._watch_external_proc, args=(self.validate_proc, "Validation", cancel_event), daemon=True
        ).start()
        return True

    @_require_token
    def cancel_validation(self):
        """Cancel the active validation when the user closes its progress dialog."""
        proc = self.validate_proc
        cancel_event = self.validation_cancel_event
        if proc is None or cancel_event is None:
            return False
        cancel_event.set()
        try:
            if proc.poll() is None:
                proc.terminate()
        except OSError as exc:
            if proc.poll() is None:
                cancel_event.clear()
                _log(f"[browser_session] validation cancel failed: {type(exc).__name__}: {exc}")
                return False
        self._set_status("Validation cancelled.")
        return True

    @staticmethod
    def _parse_validation_output(output):
        """Extract the independent validation metrics from validate.py output."""
        measured = re.search(r"Targets measured\s*:\s*(\d+)\s*/\s*(\d+)", output or "")
        mean_px = re.search(r"Mean pixel error\s*:\s*([0-9.]+)", output or "")
        median_px = re.search(r"Median pixel error\s*:\s*([0-9.]+)", output or "")
        mean_pct = re.search(r"Mean error vs screen\s*:\s*([0-9.]+)%", output or "")
        zone = re.search(r"Zone hit rate \(3x3\)\s*:\s*(\d+)\s*/\s*(\d+)", output or "")
        if not (measured and mean_px and median_px and mean_pct and zone):
            return None
        targets, expected = int(measured.group(1)), int(measured.group(2))
        zone_hits, zone_targets = int(zone.group(1)), int(zone.group(2))
        if targets != 9 or expected != 9 or zone_targets != targets:
            return None
        try:
            values = {
                "mean_error_px": float(mean_px.group(1)),
                "median_error_px": float(median_px.group(1)),
                "mean_error_pct": float(mean_pct.group(1)),
            }
        except ValueError:
            return None
        if any(not math.isfinite(value) or value < 0 for value in values.values()):
            return None
        if zone_hits < 0 or zone_hits > targets:
            return None
        return {**values, "zone_hits": zone_hits, "targets": targets}

    @staticmethod
    def _load_validation_baseline():
        """Read the best validation result from user data or bundled resources.



        User-specific history takes precedence. A packaged build keeps the

        developer baseline beside its read-only resources, while calibration

        history created during normal use belongs in the writable data folder.

        """
        history_paths = [Path(DATA_DIR) / "calibration_quality_history.json"]
        resource_history = Path(RESOURCE_DIR) / "calibration_quality_history.json"
        if resource_history not in history_paths:
            history_paths.append(resource_history)

        for history_path in history_paths:
            try:
                history = json.loads(history_path.read_text(encoding="utf-8"))
                if not isinstance(history, dict):
                    continue
                optimal = history.get("optimal") or {}
                if not isinstance(optimal, dict):
                    continue
                mean_pct = float(optimal["validation_error_pct"])
                if not math.isfinite(mean_pct) or mean_pct < 0:
                    continue
                baseline = {"mean_error_pct": mean_pct}
                for source_key, target_key in (
                    ("validation_error_px", "mean_error_px"),
                    ("zone_hit_rate", "zone_hit_rate"),
                ):
                    try:
                        value = float(optimal[source_key])
                        if math.isfinite(value) and value >= 0:
                            baseline[target_key] = value
                    except (KeyError, TypeError, ValueError):
                        pass
                return baseline
            except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError):
                continue
        return None

    @staticmethod
    def _compare_validation_result(metrics, baseline):
        """Grade by normalized mean error relative to the saved best result."""
        if baseline is None:
            return {"grade": "NO_BASELINE", "title": "Validation complete"}
        delta = float(metrics["mean_error_pct"]) - float(baseline["mean_error_pct"])
        if delta <= 1.0:
            grade, title = "GOOD", "Calibration looks good"
        elif delta <= 5.0:
            grade, title = "MODERATE", "Recalibration is recommended"
        else:
            grade, title = "BAD", "Calibration quality is poor"
        return {
            "grade": grade,
            "title": title,
            "baseline_error_pct": float(baseline["mean_error_pct"]),
            "baseline_error_px": baseline.get("mean_error_px"),
            "baseline_zone_hit_rate": baseline.get("zone_hit_rate"),
            "delta_percentage_points": round(delta, 1),
        }

    @staticmethod
    def _format_validation_result(metrics, baseline, comparison):
        lines = [
            f"Mean gaze error: {metrics['mean_error_px']:.0f} px ({metrics['mean_error_pct']:.1f}% of screen diagonal)",
            f"Median gaze error: {metrics['median_error_px']:.0f} px",
            f"3Γ—3 zone accuracy: {metrics['zone_hits']}/{metrics['targets']} targets",
        ]
        if baseline is None:
            lines.extend([
                "",
                "No saved best calibration baseline was found, so this result was not graded.",
            ])
        else:
            lines.extend([
                f"Saved best: {baseline['mean_error_pct']:.1f}% of screen diagonal"
                + (f" ({baseline['mean_error_px']:.0f} px)" if "mean_error_px" in baseline else ""),
            ])
            if "zone_hit_rate" in baseline:
                lines.append(f"Saved best 3Γ—3 zone accuracy: {baseline['zone_hit_rate']:.0f}%")
            lines.append("")
            grade = comparison["grade"]
            if grade == "GOOD":
                delta = comparison["delta_percentage_points"]
                if delta < 0:
                    advice = f"This is {abs(delta):.1f} percentage points better than the saved best. You can proceed safely."
                else:
                    advice = "This is within 1 percentage point of the saved best. You can proceed safely."
            elif grade == "MODERATE":
                advice = "This is more than 1 and up to 5 percentage points worse than the saved best. Recalibration is recommended; you may still proceed."
            else:
                advice = "This is more than 5 percentage points worse than the saved best. Recalibration is strongly recommended; you may still proceed."
            lines.append(advice)
        return "\n".join(lines)

    def _watch_external_proc(self, proc, label, cancel_event=None):
        output = ""
        if label == "Validation" and proc.stdout is not None:
            try:
                output, _ = proc.communicate()
            except Exception as exc:
                _log(f"[browser_session] validation output read failed: {type(exc).__name__}: {exc}")
        elif label == "Calibration" and proc.stdout is not None:
            try:
                for line in proc.stdout:
                    print(line, end="", flush=True)
                    if cancel_event is None or not cancel_event.is_set():
                        self._update_calibration_progress_from_line(line)
            except Exception as exc:
                _log(f"[browser_session] calibration output read failed: {type(exc).__name__}: {exc}")
            proc.wait()
        else:
            proc.wait()
        _log(f"[browser_session] {label} process exited (code {proc.returncode})")
        if cancel_event is not None and cancel_event.is_set():
            self._set_status(f"{label} cancelled.")
            return
        if proc.returncode == CAMERA_ERROR_EXIT_CODE:
            self._set_status(CAMERA_ACCESS_MESSAGE)
            callback = ("insightuxShowCalibrationError" if label == "Calibration"
                        else "insightuxShowValidationError")
            try:
                self.window.evaluate_js(
                    f"window.{callback} && window.{callback}("
                    + json.dumps(CAMERA_ACCESS_MESSAGE) + ")")
            except Exception:
                pass
            return
        if label == "Calibration":
            if proc.returncode == 0:
                self._set_status("Calibration finished β€” measure its quality with independent validation.")
                try:
                    self.window.evaluate_js("window.insightuxShowCalibrationComplete && window.insightuxShowCalibrationComplete()")
                except Exception as exc:
                    _log(f"[browser_session] calibration result display failed: {type(exc).__name__}: {exc}")
            else:
                self._set_status("Calibration did not complete successfully. Please try again.")
                try:
                    self.window.evaluate_js(
                        "window.insightuxShowCalibrationError && window.insightuxShowCalibrationError("
                        f"{json.dumps('Calibration could not finish. Check camera placement and lighting, then try again.')})"
                    )
                except Exception as exc:
                    _log(f"[browser_session] calibration error display failed: {type(exc).__name__}: {exc}")
        else:
            metrics = self._parse_validation_output(output)
            if proc.returncode == 0 and metrics is not None:
                baseline = self._load_validation_baseline()
                comparison = self._compare_validation_result(metrics, baseline)
                result = {
                    **metrics,
                    **comparison,
                    "message": self._format_validation_result(metrics, baseline, comparison),
                }
                self._set_status(f"Validation complete β€” {comparison['grade'].replace('_', ' ').lower()}.")
                try:
                    self.window.evaluate_js(
                        "window.insightuxShowValidationResult && window.insightuxShowValidationResult("
                        f"{json.dumps(result, ensure_ascii=False)})"
                    )
                except Exception as exc:
                    _log(f"[browser_session] validation result display failed: {type(exc).__name__}: {exc}")
            else:
                self._set_status("Validation did not produce a complete 9-point result.")
                try:
                    self.window.evaluate_js(
                        "window.insightuxShowValidationError && window.insightuxShowValidationError("
                        f"{json.dumps('Validation did not measure all nine targets. Please retry validation or proceed without it.')})"
                    )
                except Exception as exc:
                    _log(f"[browser_session] validation error display failed: {type(exc).__name__}: {exc}")

    def _set_session_ui(self, is_tracking, report_pending=False):
        try:
            flag = "true" if is_tracking else "false"
            active_ms = int(round(self._active_elapsed_seconds() * 1000)) if is_tracking else 0
            paused = "true" if (is_tracking and self.page_transitioning) else "false"
            self.window.evaluate_js(
                f"window.insightuxSetSessionUI && window.insightuxSetSessionUI({flag}, {active_ms}, {paused}, {str(bool(report_pending)).lower()})"
            )
        except Exception:
            pass

    def _inject_tracking_overlay(self):
        try:
            self.window.evaluate_js(TRACKING_JS)
        except Exception as e:
            _log(f"[browser_session] overlay inject failed: {e}")

    def _inject_gaze_bridge(self):
        """Install the observational Phase 3 bridge after TRACKING_JS.



        This never changes gaze_worker(), model inference, calibration, smoothing,

        or the existing insightuxUpdate implementation; it only wraps the already

        published callback and forwards each call to the original first.

        """
        try:
            self.window.evaluate_js(INSTALL_GAZE_BRIDGE_JS)
        except Exception as e:
            _log(f"[browser_session] gaze bridge inject failed: {e}")

    def _gaze_bridge_loop(self):
        """Drain queued gaze samples in batches; never call WebView2 per gaze frame."""
        poll_ms = 100
        while not self.gaze_bridge_stop.wait(poll_ms / 1000.0):
            if not self.tracking or self.page_transitioning:
                continue
            try:
                raw = self.window.evaluate_js(DRAIN_GAZE_BRIDGE_JS)
                samples = self.gaze_bridge_processor.ingest_json(raw)
                if samples:
                    # Phase 3A persistence/hand-off. The Microlink heatmap
                    # consumes these same immutable samples separately.
                    path = os.path.join(self.current_session_dir, "gaze_page_log.jsonl")
                    with open(path, "a", encoding="utf-8") as f:
                        for sample in samples:
                            f.write(json.dumps({
                                "type": "gaze_page",
                                "t_ms": sample.timestamp_ms,
                                "fx": sample.fx,
                                "fy": sample.fy,
                                "scrollX": sample.scroll_x,
                                "scrollY": sample.scroll_y,
                                "viewport": [sample.viewport_width, sample.viewport_height],
                                "page": [sample.page_width, sample.page_height],
                                "pageX": sample.page_x,
                                "pageY": sample.page_y,
                                "url": sample.url,
                            }, ensure_ascii=False) + "\n")

                            # A page must first survive the 2-second stable-page
                            # gate before it owns a screenshot/heatmap session.
                            # Samples for confirmed pages are then routed to that
                            # exact URL-scoped session only.
                            ml_session = self.microlink_sessions.get(sample.url)
                            if ml_session is not None:
                                ml_session.ingest([sample])
            except Exception as e:
                _log(f"[browser_session] gaze bridge poll failed: {e}")

    def _inject_mouse_overlay(self):
        try:
            self.window.evaluate_js(MOUSE_JS)
        except Exception as e:
            _log(f"[browser_session] mouse overlay inject failed: {e}")

    def _set_mouse_tracking(self, on):
        try:
            flag = "true" if on else "false"
            self.window.evaluate_js(
                f"window.insightuxMouseSetTracking && window.insightuxMouseSetTracking({flag})"
            )
        except Exception:
            pass

    def _open_mouse_log(self, session_dir):
        self._close_mouse_log()
        path = os.path.join(session_dir, "mouse_log.jsonl")
        try:
            self.mouse_log_f = open(path, "w", buffering=1)
            self.mouse_log_f.write(json.dumps({"type": "meta", "t": round(time.time(), 4)}) + "\n")
            _log(f"[browser_session] writing mouse stream to {path}")
        except Exception as e:
            _log(f"[browser_session] could not open mouse log: {e}")
            self.mouse_log_f = None

    def _close_mouse_log(self):
        if self.mouse_log_f:
            try:
                self.mouse_log_f.close()
                _log("[browser_session] mouse log closed")
            except Exception:
                pass
            self.mouse_log_f = None

    def log_mouse_data(self, payload):
        """Called from the injected Mouse Tracker overlay (MOUSE_JS) roughly

        every 2s while tracking, with a batch of trail / heatmap / click /

        dwell records β€” same cadence as the extension's background.js sync

        loop, just persisted to mouse_log.jsonl instead of chrome.storage.



        Deliberately NOT @_require_token: MOUSE_JS is injected as its own

        separate evaluate_js() call (_inject_mouse_overlay()), a different

        top-level script from CHROME_JS with its own closure, so it has no

        way to see CHROME_JS's __IUX_TOK__ constant without either being

        merged into the same script or having the token attached to

        `window` β€” the latter would defeat the whole point, since any

        page's own script could then read it too. Accepted gap: this

        already no-ops (returns False) whenever self.mouse_log_f is closed,

        i.e. outside a session the user themselves started, so the worst

        case is a hostile page's script injecting bogus rows into the

        mouse log of a session already running β€” a data-integrity nuisance

        confined to that one file, not a way to start recording, read

        other sessions, or touch anything else."""
        if not self.mouse_log_f or self.page_transitioning:
            return False
        try:
            rec = dict(payload) if isinstance(payload, dict) else {}
            rec["type"] = "mouse_batch"
            rec["t"] = round(time.time(), 4)
            self.mouse_log_f.write(json.dumps(rec) + "\n")
        except Exception as e:
            _log(f"[browser_session] mouse log write failed: {e}")
        return True

    def _set_microlink_usage_ui(self):
        # Kept as a compatibility hook for the existing toolbar injection.
        # WebView2/CDP capture is local and has no Microlink API quota to display.
        return None

    def _set_status(self, text):
        try:
            self.window.evaluate_js(f"window.insightuxSetStatus && window.insightuxSetStatus({json.dumps(text)})")
        except Exception:
            pass


api = Api()


def _version_tuple(v):
    return tuple(int(p) for p in v.split(".") if p.isdigit())


def check_for_update():
    """Runs once in a background thread at startup. Publishing a new release

    is still fully manual (bump VERSION here + AppVersion in installer.iss +

    version.json, rebuild, push) β€” this only automates the *checking* side,

    per the confirmed scope. No internet / any failure here is silent:

    the user just doesn't see an update banner, never an error."""
    import urllib.request
    try:
        with urllib.request.urlopen(VERSION_CHECK_URL, timeout=4) as resp:
            data = json.loads(resp.read().decode("utf-8"))
        latest = data.get("latest", "")
        url = data.get("url", "")
        if latest and url and _version_tuple(latest) > _version_tuple(VERSION):
            api.update_info = {"version": latest, "url": url}
            api._notify_update(latest, url)
            _log(f"[browser_session] update available: {VERSION} -> {latest}")
    except Exception as e:
        _log(f"[browser_session] update check skipped: {e}")


# Runs on every page (login, landing, report, any website). Makes the saved
# theme authoritative: applies it on load, and saves it whenever any page's
# toggle button is used. Only uses the public helpers every page already has
# (insightuxGetTheme / insightuxToggleTheme), so each page's own internal
# state stays consistent.
THEME_SYNC_JS = r"""

(function(){

  if (window.__iuxThemeSync) return;

  window.__iuxThemeSync = true;



  function cur(){ try { return window.insightuxGetTheme && window.insightuxGetTheme(); } catch(e){ return null; } }

  function repaintButtons(){

    ['themeToggle', '__iux_theme_toggle'].forEach(function(id){

      const b = document.getElementById(id);

      if (!b || typeof iuxIcon !== 'function') return;

      const svg = b.querySelector('svg');

      const size = (svg && parseInt(svg.getAttribute('width'), 10)) || 16;

      b.innerHTML = iuxIcon(cur() === 'light' ? 'moon' : 'sun', size);

    });

  }

  function repaintCanvases(){

    (window.insightuxRepaintCanvases || []).forEach(function(fn){ try { fn(); } catch(e){} });

  }

  function start(){

    const api = window.pywebview && window.pywebview.api;

    if (!api || !api.get_theme || typeof window.insightuxToggleTheme !== 'function') return;



    const orig = window.insightuxToggleTheme;

    window.insightuxToggleTheme = function(){

      const r = orig.apply(this, arguments);

      try { api.set_theme(cur() || r); } catch(e){}

      return r;

    };



    api.get_theme().then(function(saved){

      if (saved !== 'light' && saved !== 'dark') {

        const c = cur();                       // nothing saved yet: adopt this page's

        if (c) { try { api.set_theme(c); } catch(e){} }

        return;

      }

      let guard = 0;

      while (cur() !== saved && guard++ < 2) orig();

      repaintButtons();

      repaintCanvases();

    });

  }

  if (window.pywebview && window.pywebview.api) start();

  else window.addEventListener('pywebviewready', start, { once: true });

})();

"""


def on_page_loaded(window):
    """Fires on every page load (navigation, back/forward, reload β€” not just

    the first page). The chrome must be re-injected every time since each

    navigation is a fresh document. If a session is already running, the

    gaze/mouse overlays need the same treatment or navigating mid-session

    would silently kill the dot and the mouse tracker on the new page."""
    try:
        window.evaluate_js(CHROME_JS)
    except Exception as e:
        _log(f"[browser_session] chrome inject failed (will retry): {e}")

    try:
        window.evaluate_js(THEME_SYNC_JS)
    except Exception as e:
        _log(f"[browser_session] theme sync inject failed: {e}")

    api._set_microlink_usage_ui()

    if api.tracking and api.microlink_capture_enabled:
        # The fresh document has no JS state. Keep the session visibly paused
        # until the stable-page gate completes; the active timer remains frozen.
        api.page_transitioning = True
        api._set_session_ui(True)
        api._set_mouse_tracking(False)
        # Do not resume immediately at load. Give the new document a short
        # stable-render window. Fast navigation through several links therefore
        # pauses recording and does not start screenshots for accidental pages.
        try:
            current_url = window.get_current_url() or ""
        except Exception:
            current_url = ""
        api._schedule_page_ready(current_url)

    # Same reasoning as the tracking re-sync above: CHROME_JS was just
    # re-injected fresh and has no memory of who's signed in, or who the
    # active tracking subject was.
    if api.current_user:
        api._set_profile_ui()
        api._set_subject_ui()

    # CHROME_JS was just re-injected fresh on this page and has no memory of
    # an update found on a previous page β€” re-tell it if one was found.
    if api.update_info:
        api._notify_update(api.update_info["version"], api.update_info["url"])


# =============================================================================
# GAZE WORKER β€” runs in a background thread, started/stopped via Api
# =============================================================================

def gaze_worker(window, stop_event, session_dir, api_ref, cap):
    # Reuse the verified capture; reopening could lose access to another app.
    try:
        pipeline = InsightUXPipeline(_user_onnx_path(), CALIBRATION_PATH)
        face_mesh = create_face_mesh(static_image_mode=False)
    except Exception:
        cap.release()
        raise

    # Same camera / face-position check shown before calibration and validation.
    # Recording is already paused here (start_tracking() sets page_transitioning),
    # so nothing is logged while the user lines up. It runs on this worker
    # thread, which also owns the OpenCV window, so it never touches the UI thread.
    api_ref._set_status("Checking camera and face position β€” adjust until the check passes...")
    cam_matrix_ref = [None]
    try:
        gate_passed = face_orientation_gate(
            face_mesh, cap, cam_matrix_ref, purpose="session", stop_event=stop_event
        )
    except CameraAccessError:
        gate_passed = False
        api_ref._abort_camera_session()
    except Exception as e:
        _log(f"[browser_session] face check failed, continuing without it: {type(e).__name__}: {e}")
        gate_passed = True
    if not gate_passed or stop_event.is_set():
        # Session was stopped while the check was open: nothing was recorded.
        cap.release()
        _log("[browser_session] session stopped during camera check")
        api_ref.tracking = False
        api_ref.microlink_capture_enabled = False
        api_ref.current_session_dir = None
        api_ref._set_mouse_tracking(False)
        api_ref._set_session_ui(False)
        api_ref._close_mouse_log()
        import shutil
        shutil.rmtree(session_dir, ignore_errors=True)
        return
    api_ref._set_status("Camera check passed β€” preparing page for recording...")

    logger    = GazeLogger(SCREEN_W, SCREEN_H, session_dir=session_dir)
    dom_path  = os.path.join(session_dir, "dom_log.jsonl")
    dom_f     = open(dom_path, "w", buffering=1)

    screens_dir = os.path.join(session_dir, "screenshots")
    os.makedirs(screens_dir, exist_ok=True)
    shot_count = 0
    last_shot_scroll = None
    last_shot_time = 0.0
    SCROLL_SHOT_THRESHOLD = 60   # px scrolled before a new snapshot is worth taking
    MAX_SHOT_INTERVAL      = 2.5  # seconds β€” take one anyway if you just sit still

    def maybe_capture_screenshot(scroll_y):
        """Grab a full-screen shot when the page has scrolled enough, or

        periodically even if it hasn't β€” this is what lets the report show

        the heatmap ON TOP of the actual page instead of floating in a void."""
        nonlocal shot_count, last_shot_scroll, last_shot_time
        now = time.time()
        scrolled_enough = last_shot_scroll is None or abs(scroll_y - last_shot_scroll) >= SCROLL_SHOT_THRESHOLD
        time_elapsed = (now - last_shot_time) >= MAX_SHOT_INTERVAL
        if not (scrolled_enough or time_elapsed):
            return None
        try:
            try:
                window.evaluate_js("window.__insightuxSetCaptureMode && window.__insightuxSetCaptureMode(true)")
            except Exception:
                pass
            time.sleep(0.05)  # let the hide actually repaint before the OS-level grab
            try:
                img = pyautogui.screenshot()
            finally:
                try:
                    window.evaluate_js("window.__insightuxSetCaptureMode && window.__insightuxSetCaptureMode(false)")
                except Exception:
                    pass
            # Force to the same pixel space as gaze coordinates (SCREEN_W x
            # SCREEN_H) β€” Windows DPI scaling can otherwise return a
            # screenshot at a different resolution than pyautogui.size(),
            # which would silently misalign every heatmap point.
            if img.size != (SCREEN_W, SCREEN_H):
                img = img.resize((SCREEN_W, SCREEN_H))
            shot_name = f"shot_{shot_count:04d}.png"
            img.save(os.path.join(screens_dir, shot_name))
            shot_count += 1
            last_shot_scroll = scroll_y
            last_shot_time = now
            return f"screenshots/{shot_name}"
        except Exception as e:
            _log(f"[browser_session] screenshot capture failed: {e}")
            return None

    _log(f"[browser_session] tracking started -> {session_dir}")

    cam_matrix    = cam_matrix_ref[0]
    last_x        = SCREEN_W / 2
    last_y        = SCREEN_H / 2
    fil_x         = OneEuroFilter(mincutoff=EURO_MINCUTOFF, beta=EURO_BETA)
    fil_y         = OneEuroFilter(mincutoff=EURO_MINCUTOFF, beta=EURO_BETA)
    angle_smoother = GazeAngleSmoother(window=ANGLE_SMOOTH_WINDOW)
    sm_pitch = sm_yaw = sm_roll = None
    no_face_count = 0
    frame_i       = 0

    camera_failed = False
    while not stop_event.is_set():
        # Navigation pause: keep the camera/thread alive, but do not record
        # gaze, DOM, screenshots, or publish gaze to the page while the browser
        # is rendering a new document. This keeps the transition out of the
        # analytical session without ending the session itself.
        if api_ref.page_transitioning:
            time.sleep(0.01)
            continue

        try:
            ret, frame = read_camera_frame(cap)
        except CameraAccessError:
            camera_failed = True
            api_ref._abort_camera_session()
            break

        if cam_matrix is None:
            cam_matrix = estimate_camera_matrix(frame.shape)

        rgb     = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        results = face_mesh.process(rgb)

        if not results.multi_face_landmarks:
            no_face_count += 1
            if no_face_count >= NO_FACE_RESET:
                last_x, last_y = SCREEN_W / 2, SCREEN_H / 2
                fil_x.reset(); fil_y.reset()
                angle_smoother.reset()
                sm_pitch = sm_yaw = sm_roll = None
                no_face_count = 0
            continue
        no_face_count = 0

        lms       = results.multi_face_landmarks[0].landmark
        head_pose = estimate_head_pose(lms, frame.shape, cam_matrix)
        if head_pose is None:
            continue

        if sm_pitch is None:
            sm_pitch, sm_yaw, sm_roll = head_pose.pitch, head_pose.yaw, head_pose.roll
        else:
            b = POSE_SMOOTH
            sm_pitch = b*sm_pitch + (1-b)*head_pose.pitch
            sm_yaw   = b*sm_yaw   + (1-b)*head_pose.yaw
            sm_roll  = b*sm_roll  + (1-b)*head_pose.roll
        head_pose = replace(head_pose, pitch=sm_pitch, yaw=sm_yaw, roll=sm_roll)

        pose_vec = normalize_pose(sm_pitch, sm_yaw, sm_roll)

        # Eye aperture β€” the vertical cue. Calibration decides whether this or
        # the CNN's pitch actually tracks screen-Y, and uses the better one.
        ear_now = 0.5 * (compute_ear(lms, LEFT_EAR_INDICES, frame.shape) +
                         compute_ear(lms, RIGHT_EAR_INDICES, frame.shape))

        def get_patch(eye_idx, ear_idx, iris_idx):
            s1 = step1_normalize(frame, lms, head_pose, eye_idx, ear_idx, iris_idx)
            if not s1.is_open:
                return None
            if PATCH_SOURCE == "norm":
                return s1.norm_crop
            ir = compute_iris_radius(lms, iris_idx, frame.shape)
            s2 = step2_illumination(s1, ir)
            return s2.blended if s2.is_usable else None

        left_patch  = get_patch(LEFT_EYE_INDICES,  LEFT_EAR_INDICES,  LEFT_IRIS_INDICES)
        right_patch = get_patch(RIGHT_EYE_INDICES, RIGHT_EAR_INDICES, RIGHT_IRIS_INDICES)
        if left_patch is None and right_patch is None:
            continue
        if left_patch  is None: left_patch  = right_patch
        if right_patch is None: right_patch = left_patch

        _, _, raw_pitch, raw_yaw = pipeline.predict_gaze_vector(left_patch, pose_vec, right_patch)
        pitch = compensate_pitch(raw_pitch, sm_pitch)
        yaw   = compensate_yaw(raw_yaw, sm_yaw)

        # Smooth the ANGLES before the RBF sees them. The RBF amplifies input
        # noise (steep gradient along the low-variance pitch axis), so noise
        # must be removed here β€” smoothing the screen coords afterwards cannot
        # undo amplification that already happened through a nonlinear map.
        pitch, yaw, ear_s = angle_smoother(pitch, yaw, ear_now)

        sx, sy = pipeline.calibration.predict(pitch, yaw, ear_s)
        sx = max(0.0, min(sx, SCREEN_W))
        sy = max(0.0, min(sy, SCREEN_H))

        jump = np.hypot(sx - last_x, sy - last_y)
        if jump > MAX_JUMP:
            sx = last_x + (sx - last_x) * 0.3
            sy = last_y + (sy - last_y) * 0.3
        last_x, last_y = sx, sy

        logger.log(sx, sy)

        now = time.time()
        fx = fil_x(sx / SCREEN_W, now)
        fy = fil_y(sy / SCREEN_H, now)
        try:
            window.evaluate_js(f"window.insightuxUpdate({fx:.5f},{fy:.5f})")
        except Exception:
            pass

        frame_i += 1
        if frame_i % DOM_EVERY == 0:
            try:
                raw = window.evaluate_js("window.insightuxAOIs()")
                if raw:
                    rec = json.loads(raw)
                    rec["type"] = "dom"
                    rec["t"] = round(time.time(), 4)
                    shot_ref = maybe_capture_screenshot(rec.get("scrollY", 0))
                    if shot_ref:
                        rec["screenshot"] = shot_ref
                    dom_f.write(json.dumps(rec) + "\n")
            except Exception:
                pass

        time.sleep(0.005)

    cap.release()
    logger.close()
    dom_f.close()
    if camera_failed:
        return  # Keep captured raw data, but do not claim successful completion.
    _log(f"[browser_session] session saved in {session_dir}")

    # Generate the complete base report first. The report is intentionally
    # NOT opened here. Microlink must finish, its full-page composite PNG
    # must be embedded into this exact HTML file, and only then may WebView2
    # navigate to it. This gives the immediate post-session report the same
    # finalized state that Previous Sessions sees later.
    try:
        report_path = Path(generate_report(session_dir)).resolve()
        _log(f"[browser_session] base report generated -> {report_path}")

        if not report_path.exists():
            raise FileNotFoundError(f"analysis_report.html was not created: {report_path}")

        api_ref.tracking = False
        api_ref.microlink_capture_enabled = False
        api_ref.current_session_dir = None

        # Microlink finalization owns the single report navigation. It runs
        # only after the complete analysis report already exists.
        finalized = api_ref._finalize_microlink_sessions(report_path)
        if finalized:
            _log(f"[browser_session] report ready -> {report_path}")
        else:
            _log(f"[browser_session] report generated but not opened because final Chrome heatmap report was incomplete -> {report_path}")
    except Exception as e:
        _log(f"[browser_session] report generation/finalization failed: {e}")
        api_ref.tracking = False
        api_ref.microlink_capture_enabled = False
        api_ref.current_session_dir = None


# =============================================================================
# MAIN
# =============================================================================

def _go_fullscreen(window):
    # Small delay so WebView2 fully initializes and grabs keyboard focus
    # BEFORE going fullscreen. Passing fullscreen=True straight to
    # create_window is what causes the "can't type" issue and the
    # AccessibilityObject.Bounds recursion crash on Windows β€” both trace
    # back to the WinForms host not finishing its focus/accessibility
    # setup before the fullscreen transition happens.
    time.sleep(0.4)
    try:
        window.toggle_fullscreen()
    except Exception as e:
        _log(f"[browser_session] fullscreen toggle failed: {e}")


if __name__ == "__main__":
    # A packaged build is one exe with no separate calibrate.py/validate.py
    # files to shell out to β€” --mode makes it a single self-dispatching
    # entry point instead. See _relaunch_args() above for the launch side.
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", choices=["browser", "calibrate", "validate"], default="browser")
    parser.add_argument("--capture-worker", nargs=1, metavar="PAYLOAD")
    args = parser.parse_args()

    if args.capture_worker is not None:
        from screenshots.chrome_fullpage_capture import ChromeFullPageCaptureService
        ChromeFullPageCaptureService._capture_one(json.loads(args.capture_worker[0]))
    elif args.mode == "calibrate":
        from calibration import calibrate
        calibrate.main()
    elif args.mode == "validate":
        from calibration import validate
        validate.main()
    else:
        # Opens on the login/profile picker, not the landing page β€” no
        # login state is persisted across restarts, so a password is
        # always required before any profile's sessions/calibration/
        # reports become reachable. A fresh listing of profiles is
        # written right before opening in case a previous run created one.
        window = webview.create_window(
            "InsightUX β€” Eye-Tracking Research Browser", _write_login_page(),
            width=SCREEN_W, height=SCREEN_H, maximized=True, js_api=api
        )
        api.window = window
        window.events.loaded += lambda: on_page_loaded(window)
        threading.Thread(target=check_for_update, daemon=True).start()

        # debug=True enables right-click > Inspect (DevTools) so you can see
        # the [insightux] console.log diagnostics from CHROME_JS directly β€”
        # keyboard handling runs entirely in the browser, so JS-side issues
        # never show up in this terminal, only in DevTools' Console tab.
        webview.start(debug=True)