File size: 331,306 Bytes
9df6ae5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { InputHTMLAttributes } from "react";
import type { FileEntry, Job, DownloadJob, VideoInfo, RemoteEntry, TeleboxEntry, BackblazeEntry, Tab, PixeldrainJob, QueueItem, EncodePreset, RemoteCredentials } from "./types";
import { api } from "./api";
import { CloseIcon, FolderIcon, DownloadIcon, UploadIcon, EditIcon, DeleteIcon, DragHandleIcon, ChevronUpIcon, ChevronDownIcon, SpinnerIcon, ListIcon, SelectAllIcon, ClearIcon } from "./icons";
import { AdvancedTrimCropModal } from "./components/AdvancedTrimCropModal";
import { CredentialsModal } from "./components/Modals";
import { normalizeRemoteUrl } from "./utils/credentials";

// ─── Helpers ──────────────────────────────────────────────────────────────────
function fmt(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
  return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
}

function fmtEta(s: number): string {
  if (!Number.isFinite(s) || s <= 0) return "0s";
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = Math.floor(s % 60);
  return [h && `${h}h`, m && `${m}m`, `${sec}s`].filter(Boolean).join(" ");
}

function secondsToHms(total: number): string {
  const h = Math.floor(total / 3600);
  const m = Math.floor((total % 3600) / 60);
  const s = Math.floor(total % 60);
  return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}

function hmsToSeconds(hms: string): number {
  const parts = hms.split(":").map(Number);
  if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  if (parts.length === 2) return parts[0] * 60 + parts[1];
  return parts[0] || 0;
}

function pad2(v: number): string {
  return String(Math.max(0, v)).padStart(2, "0");
}

function formatAspectRatio(width: number, height: number): string {
  const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
  const divisor = gcd(width, height);
  return `${width / divisor}:${height / divisor}`;
}

function toHmsString(h: number, m: number, s: number): string {
  return `${pad2(h)}:${pad2(m)}:${pad2(s)}`;
}

function clampParts(h: number, m: number, s: number, maxSeconds?: number): { h: number; m: number; s: number } {
  let hh = Math.max(0, h);
  let mm = Math.min(59, Math.max(0, m));
  let ss = Math.min(59, Math.max(0, s));
  if (maxSeconds !== undefined) {
    const total = Math.max(0, hh * 3600 + mm * 60 + ss);
    if (total > maxSeconds) {
      const clamped = Math.max(0, Math.floor(maxSeconds));
      hh = Math.floor(clamped / 3600);
      mm = Math.floor((clamped % 3600) / 60);
      ss = Math.floor(clamped % 60);
    }
  }
  return { h: hh, m: mm, s: ss };
}

function parseHmsParts(value: string): { h: number; m: number; s: number } {
  const parts = value.split(":").map((p) => parseInt(p, 10));
  if (parts.length === 3) return { h: parts[0] || 0, m: parts[1] || 0, s: parts[2] || 0 };
  if (parts.length === 2) return { h: 0, m: parts[0] || 0, s: parts[1] || 0 };
  if (parts.length === 1 && parts[0]) return { h: 0, m: 0, s: parts[0] || 0 };
  return { h: 0, m: 0, s: 0 };
}

function parseLooseTimeToSeconds(input: string): number | null {
  const value = input.trim();
  if (!value) return null;

  const parts = value.split(":").map((p) => p.trim());
  if (parts.some((p) => p === "" || Number.isNaN(Number(p)))) return null;

  if (parts.length === 2) {
    const [mm, ss] = parts.map(Number);
    if (mm < 0 || ss < 0 || ss >= 60) return null;
    return mm * 60 + ss;
  }

  if (parts.length === 3) {
    const [hh, mm, ss] = parts.map(Number);
    if (hh < 0 || mm < 0 || ss < 0 || mm >= 60 || ss >= 60) return null;
    return hh * 3600 + mm * 60 + ss;
  }

  return null;
}

function parsePastedSegments(text: string): { start: string; end: string }[] {
  const lines = text
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);

  const parsed: { start: string; end: string }[] = [];

  for (const line of lines) {
    const match = line.match(/(\d{1,2}:\d{2}(?::\d{2})?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?)/);
    if (!match) continue;

    const startSec = parseLooseTimeToSeconds(match[1]);
    const endSec = parseLooseTimeToSeconds(match[2]);

    if (startSec == null || endSec == null || endSec <= startSec) continue;

    parsed.push({
      start: secondsToHms(startSec),
      end: secondsToHms(endSec),
    });
  }

  return parsed;
}

type CropValues = {
  cropEnabled: boolean;
  cropLeft: number;
  cropRight: number;
  cropTop: number;
  cropBottom: number;
};

type DirectoryInputProps = InputHTMLAttributes<HTMLInputElement> & {
  webkitdirectory?: string;
  mozdirectory?: string;
};

function TimePartsInput({

  value,

  onChange,

  maxSeconds,

  allowEmpty = false,

}: {

  value: string;

  onChange: (next: string) => void;

  maxSeconds?: number;

  allowEmpty?: boolean;

}) {
  const parsed = parseHmsParts(value);
  const [hLocal, setHLocal] = useState(pad2(parsed.h));
  const [mLocal, setMLocal] = useState(pad2(parsed.m));
  const [sLocal, setSLocal] = useState(pad2(parsed.s));
  const hRef = useRef<HTMLInputElement>(null);
  const mRef = useRef<HTMLInputElement>(null);
  const sRef = useRef<HTMLInputElement>(null);
  const vals = useRef({ h: pad2(parsed.h), m: pad2(parsed.m), s: pad2(parsed.s) });

  useEffect(() => {
    const active = document.activeElement;
    if (active === hRef.current || active === mRef.current || active === sRef.current) return;
    const p = parseHmsParts(value);
    const h = pad2(p.h), m = pad2(p.m), s = pad2(p.s);
    setHLocal(h); setMLocal(m); setSLocal(s);
    vals.current = { h, m, s };
  }, [value]);

  const commit = () => {
    const hNum = parseInt(vals.current.h, 10) || 0;
    const mNum = Math.min(59, parseInt(vals.current.m, 10) || 0);
    const sNum = Math.min(59, parseInt(vals.current.s, 10) || 0);
    const clamped = clampParts(hNum, mNum, sNum, maxSeconds);
    onChange(toHmsString(clamped.h, clamped.m, clamped.s));
  };

  const handleInput = (field: "h" | "m" | "s", raw: string) => {
    const digits = raw.replace(/\D/g, "").slice(0, 2);
    vals.current[field] = digits;
    if (field === "h") setHLocal(digits);
    if (field === "m") setMLocal(digits);
    if (field === "s") setSLocal(digits);

    if (digits.length >= 2) {
      if (field === "h") { setTimeout(() => { mRef.current?.focus(); mRef.current?.select(); }, 0); }
      if (field === "m") { setTimeout(() => { sRef.current?.focus(); sRef.current?.select(); }, 0); }
      commit();
    }
  };

  const handleBlur = (field: "h" | "m" | "s") => {
    const num = parseInt(vals.current[field], 10) || 0;
    const clamped = field === "h" ? num : Math.min(59, num);
    const padded = pad2(clamped);
    vals.current[field] = padded;
    if (field === "h") setHLocal(padded);
    if (field === "m") setMLocal(padded);
    if (field === "s") setSLocal(padded);
    commit();
  };

  const handleKeyDown = (field: "h" | "m" | "s", e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Backspace" && e.currentTarget.value === "") {
      if (field === "m") { hRef.current?.focus(); hRef.current?.select(); }
      if (field === "s") { mRef.current?.focus(); mRef.current?.select(); }
    }
  };

  const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => { e.target.select(); };

  const fieldCls = "w-12 rounded-lg border border-slate-200 px-1 py-2 text-sm font-mono text-center focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100";

  return (
    <div className="flex items-center gap-1">

      <input ref={hRef} type="text" inputMode="numeric" maxLength={2}

        value={allowEmpty && !value.trim() ? "" : hLocal} placeholder="HH"

        onChange={(e) => handleInput("h", e.target.value)}

        onBlur={() => handleBlur("h")}

        onKeyDown={(e) => handleKeyDown("h", e)}

        onFocus={handleFocus}

        className={fieldCls} />

      <span className="text-slate-400 font-bold text-sm">:</span>

      <input ref={mRef} type="text" inputMode="numeric" maxLength={2}

        value={allowEmpty && !value.trim() ? "" : mLocal} placeholder="MM"

        onChange={(e) => handleInput("m", e.target.value)}

        onBlur={() => handleBlur("m")}

        onKeyDown={(e) => handleKeyDown("m", e)}

        onFocus={handleFocus}

        className={fieldCls} />

      <span className="text-slate-400 font-bold text-sm">:</span>

      <input ref={sRef} type="text" inputMode="numeric" maxLength={2}

        value={allowEmpty && !value.trim() ? "" : sLocal} placeholder="SS"

        onChange={(e) => handleInput("s", e.target.value)}

        onBlur={() => handleBlur("s")}

        onKeyDown={(e) => handleKeyDown("s", e)}

        onFocus={handleFocus}

        className={fieldCls} />

      {allowEmpty && value.trim() && (

        <button type="button" onClick={() => onChange("")}

          className="ml-1 text-xs text-slate-400 hover:text-slate-600">Clear</button>

      )}

    </div>
  );
}

// ─── File Type Helpers ────────────────────────────────────────────────────────
const MEDIA_EXTS = new Set([
  ".mp4",".mkv",".avi",".mov",".webm",".ts",".m2ts",".flv",".wmv",".mpg",".mpeg",
  ".mp3",".aac",".opus",".flac",".wav",".m4a",".ogg",".wma",".m4v",".3gp",".vob",
]);
const ARCHIVE_EXTS = new Set([
  ".zip",".tar",".gz",".tgz",".bz2",".xz",".rar",".7z",
]);
const SUBTITLE_EXTS = new Set([
  ".srt", ".ass", ".ssa", ".vtt", ".sub",
]);

function isMediaFile(name: string): boolean {
  const lower = name.toLowerCase();
  for (const ext of MEDIA_EXTS) {
    if (lower.endsWith(ext)) return true;
  }
  return false;
}

function isSubtitleFile(name: string): boolean {
  const lower = name.toLowerCase();
  for (const ext of SUBTITLE_EXTS) {
    if (lower.endsWith(ext)) return true;
  }
  return false;
}

function isArchiveFile(name: string): boolean {
  const lower = name.toLowerCase();
  if (lower.endsWith(".tar.gz") || lower.endsWith(".tar.xz") || lower.endsWith(".tar.bz2")) return true;
  for (const ext of ARCHIVE_EXTS) {
    if (lower.endsWith(ext)) return true;
  }
  return false;
}

// ─── Help Tooltip ────────────────────────────────────────────────────────────
function HelpTip({ text }: { text: string }) {
  const [show, setShow] = useState(false);
  return (
    <span className="relative inline-flex ml-1">

      <button

        type="button"

        onMouseEnter={() => setShow(true)}

        onMouseLeave={() => setShow(false)}

        onFocus={() => setShow(true)}

        onBlur={() => setShow(false)}

        onClick={(e) => { e.preventDefault(); setShow((v) => !v); }}

        className="inline-flex items-center justify-center h-4 w-4 rounded-full bg-slate-200 text-[9px] font-bold text-slate-500 hover:bg-violet-200 hover:text-violet-700 transition-colors cursor-help flex-shrink-0"

        aria-label="Help"

      >?</button>

      {show && (

        <div className="absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-1.5 w-64 rounded-lg bg-slate-800 px-3 py-2 text-[11px] leading-relaxed text-slate-100 shadow-xl pointer-events-none">

          {text}

          <div className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-x-4 border-x-transparent border-t-4 border-t-slate-800" />

        </div>

      )}

    </span>
  );
}

// ─── Toast ───────────────────────────────────────────────────────────────────
function Toast({ message, onDone }: { message: string; onDone: () => void }) {
  useEffect(() => {
    const t = setTimeout(onDone, 2500);
    return () => clearTimeout(t);
  }, [onDone]);
  return (
    <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[100] rounded-full bg-slate-800 px-5 py-2.5 text-xs font-semibold text-white shadow-xl">

      {message}

    </div>
  );
}

// ─── Upload Area ──────────────────────────────────────────────────────────────
// Helper to recursively read directory entries from drag-and-drop
async function* getFilesFromDataTransferItems(items: DataTransferItemList, prefix = ""): AsyncGenerator<File & { __folderPath?: string }> {
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.kind === "file") {
      const entry = item.webkitGetAsEntry?.();
      if (entry?.isFile) {
        const file = item.getAsFile();
        if (file) {
          if (prefix) {
            (file as any).__folderPath = prefix;
          }
          yield file as File & { __folderPath?: string };
        }
      } else if (entry?.isDirectory) {
        // Pass the directory name as the initial prefix
        yield* readDirectoryRecursive(entry as any, entry.name);
      }
    }
  }
}

async function* readDirectoryRecursive(dir: any, prefix = ""): AsyncGenerator<File & { __folderPath?: string }> {
  const reader = dir.createReader();
  const entries = await new Promise<any[]>((resolve, reject) => {
    reader.readEntries(resolve, reject);
  });

  for (const entry of entries) {
    const newPrefix = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isFile) {
      const file = await new Promise<File>((resolve, reject) => {
        (entry as any).file(resolve, reject);
      });
      (file as any).__folderPath = prefix;
      yield file as File & { __folderPath?: string };
    } else if (entry.isDirectory) {
      yield* readDirectoryRecursive(entry, newPrefix);
    }
  }
}

function UploadArea({

  onFilesSelected,

  busy,

  dragOver,

  onDragOver,

  onDragLeave,

  uploadInputRef,

  uploadFolderRef,

}: {

  onFilesSelected: (files: FileList | (File & { __folderPath?: string })[]) => void;

  busy: boolean;

  dragOver: boolean;

  onDragOver: (e: React.DragEvent) => void;

  onDragLeave: (e: React.DragEvent) => void;

  uploadInputRef: React.RefObject<HTMLInputElement | null>;

  uploadFolderRef: React.RefObject<HTMLInputElement | null>;

}) {
  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    onDragLeave(e);
    
    if (e.dataTransfer.items?.length) {
      try {
        // Try to read directory structure from drag-and-drop
        const allFiles: (File & { __folderPath?: string })[] = [];
        for await (const file of getFilesFromDataTransferItems(e.dataTransfer.items)) {
          allFiles.push(file);
        }
        if (allFiles.length > 0) {
          onFilesSelected(allFiles);
        } else if (e.dataTransfer.files) {
          onFilesSelected(e.dataTransfer.files);
        }
      } catch (err) {
        console.error("Error reading drag-and-drop items:", err);
        if (e.dataTransfer.files) {
          onFilesSelected(e.dataTransfer.files);
        }
      }
    } else if (e.dataTransfer.files) {
      onFilesSelected(e.dataTransfer.files);
    }
  };

  return (
    <div

      onDragOver={onDragOver}

      onDragLeave={onDragLeave}

      onDrop={handleDrop}

      className={`rounded-lg border-2 border-dashed p-4 text-center transition-colors ${

        dragOver

          ? "border-violet-400 bg-violet-50"

          : "border-slate-300 bg-slate-50 hover:border-slate-400"

      } ${busy ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}`}

    >

      <div className="text-sm font-semibold text-slate-600 mb-2">

        {busy ? "Uploading..." : "Drop files or folders here"}

      </div>

      <div className="flex gap-2 justify-center flex-wrap">

        <button

          type="button"

          onClick={() => uploadInputRef.current?.click()}

          disabled={busy}

          className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"

        >

          Select Files

        </button>

        <button

          type="button"

          onClick={() => uploadFolderRef.current?.click()}

          disabled={busy}

          className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"

        >

          Select Folder

        </button>

      </div>

      <input

        ref={uploadInputRef}

        type="file"

        multiple

        onChange={(e) => e.target.files && onFilesSelected(e.target.files)}

        className="hidden"

        disabled={busy}

      />

      <input

        {...({

          ref: uploadFolderRef,

          type: "file",

          webkitdirectory: "true",

          mozdirectory: "true",

          multiple: true,

          onChange: (e) => e.target.files && onFilesSelected(e.target.files),

          className: "hidden",

          disabled: busy,

        } as DirectoryInputProps)}

      />

    </div>
  );
}

// ─── Pixeldrain Upload Progress ───────────────────────────────────────────────
function PixeldrainProgress({ jobId, onClose }: { jobId: string; onClose: () => void }) {
  const [job, setJob] = useState<PixeldrainJob | null>(null);
  const [copied, setCopied] = useState(false);
  const pollInProgressRef = useRef(false);

  useEffect(() => {
    const poll = async () => {
      // Prevent concurrent requests
      if (pollInProgressRef.current) return;
      pollInProgressRef.current = true;

      try {
        const r = await fetch(`/api/pixeldrain-jobs/${jobId}`);
        const data = await r.json();
        setJob(data.job);
        if (data.job.status !== "running") {
          clearInterval(iv);
        }
      } catch { /* ignore */ } finally {
        pollInProgressRef.current = false;
      }
    };
    poll();
    // Increased polling interval from 800ms to 1500ms to reduce server load
    const iv = setInterval(poll, 1500);
    return () => clearInterval(iv);
  }, [jobId]);

  const copyUrl = () => {
    if (!job?.pixeldrainUrl) return;
    navigator.clipboard.writeText(job.pixeldrainUrl);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  if (!job) return null;
  const percent = job.totalBytes > 0 ? Math.min(100, (job.bytesUploaded / job.totalBytes) * 100) : null;

  return (
    <div className="rounded-xl border border-slate-200 bg-white p-4 space-y-3">

      <div className="flex items-start justify-between gap-2">

        <div className="min-w-0 flex-1">

          <p className="text-xs font-semibold text-slate-700 flex items-center gap-1.5">

            <span>☁️</span>

            <span className="truncate">{job.filename}</span>

          </p>

          <p className="text-[10px] text-slate-400 mt-0.5">Uploading to Pixeldrain…</p>

        </div>

        <div className="flex items-center gap-2 flex-shrink-0">

          <span className={`text-xs font-semibold capitalize ${

            job.status === "done" ? "text-emerald-600" :

            job.status === "failed" ? "text-red-500" : "text-violet-600"

          }`}>{job.status}</span>

          <button onClick={onClose} className="rounded p-1 text-slate-400 hover:text-slate-600 hover:bg-slate-100">

            <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />

            </svg>

          </button>

        </div>

      </div>

      <div className="space-y-1">

        <div className="relative h-2 w-full overflow-hidden rounded-full bg-slate-100">

          {percent !== null ? (

            <div className={`h-full rounded-full transition-all duration-300 ${

              job.status === "done" ? "bg-emerald-500" :

              job.status === "failed" ? "bg-red-400" : "bg-violet-500"

            }`} style={{ width: `${percent}%` }} />

          ) : (

            <div className="h-full w-1/3 rounded-full bg-violet-500 animate-[slide_1.2s_ease-in-out_infinite]" />

          )}

        </div>

        <div className="flex justify-between text-[10px] text-slate-400">

          <span>{fmt(job.bytesUploaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}</span>

          {percent !== null && <span>{percent.toFixed(1)}%</span>}

        </div>

      </div>

      {job.status === "done" && job.pixeldrainUrl && (

        <div className="flex items-center gap-2 rounded-lg bg-emerald-50 border border-emerald-200 px-3 py-2">

          <a href={job.pixeldrainUrl} target="_blank" rel="noreferrer"

            className="flex-1 truncate text-xs font-medium text-emerald-700 hover:underline">

            {job.pixeldrainUrl}

          </a>

          <button onClick={copyUrl}

            className="flex-shrink-0 rounded-md bg-emerald-100 hover:bg-emerald-200 px-2 py-1 text-[10px] font-semibold text-emerald-700 transition-colors">

            {copied ? "✓ Copied" : "Copy"}

          </button>

        </div>

      )}

      {job.status === "failed" && (

        <p className="text-xs text-red-500">{job.error || "Upload failed"}</p>

      )}

    </div>
  );
}
// ─── Merge Modal ──────────────────────────────────────────────────────────────
interface MergeItem { uid: string; file: FileEntry; }

function MergeModal({ files, onClose, onMergeStarted }: {

  files: FileEntry[];

  onClose: () => void;

  onMergeStarted: () => void;

}) {
  const [items, setItems] = useState<MergeItem[]>(() =>
    files.map((f) => ({ uid: `$${f.id}_$${Math.random().toString(16).slice(2)}`, file: f }))
  );
  const [outName, setOutName] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const dragUid = useRef<string | null>(null);
  const dragOverUid = useRef<string | null>(null);

  useEffect(() => {
    const firstFile = files[0];
    if (!firstFile) {
      setOutName("merged_output.mkv");
      return;
    }

    const name = firstFile.name;
    const lastDotIndex = name.lastIndexOf(".");

    if (lastDotIndex > 0) {
      const baseName = name.slice(0, lastDotIndex);
      const ext = name.slice(lastDotIndex);
      setOutName(`$${baseName}_merged$${ext}`);
    } else {
      setOutName(`${name}_merged.mkv`);
    }
  }, [files]);

  const moveUp = (idx: number) => {
    if (idx === 0) return;
    const next = [...items]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; setItems(next);
  };
  const moveDown = (idx: number) => {
    if (idx === items.length - 1) return;
    const next = [...items]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; setItems(next);
  };
  const handleDragStart = (uid: string) => { dragUid.current = uid; };
  const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; };
  const handleDrop = () => {
    if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return;
    const from = items.findIndex((i) => i.uid === dragUid.current);
    const to = items.findIndex((i) => i.uid === dragOverUid.current);
    if (from === -1 || to === -1) return;
    const next = [...items];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    setItems(next);
    dragUid.current = null; dragOverUid.current = null;
  };
  const removeItem = (uid: string) => setItems((prev) => prev.filter((i) => i.uid !== uid));

  const handleMerge = async () => {
    if (items.length < 2) { setError("Need at least 2 files to merge"); return; }
    if (!outName.trim()) { setError("Output filename is required"); return; }
    setError(null); setBusy(true);
    try {
      const r = await fetch("/api/merge", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ fileIds: items.map((i) => i.file.id), outputFilename: outName.trim() }),
      });
      const data = await r.json();
      if (data.error) { setError(data.error); setBusy(false); return; }
      onMergeStarted();
      onClose();
    } catch { setError("Failed to start merge"); setBusy(false); }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>

      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}>

        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0">

          <div className="flex items-center gap-2">

            <span className="text-lg">🔗</span>

            <h2 className="text-sm font-bold text-slate-800">Merge Files</h2>

            <span className="rounded-full bg-violet-100 px-2 py-0.5 text-xs font-semibold text-violet-700">{items.length} files</span>

          </div>

          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">

            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />

            </svg>

          </button>

        </div>

        <div className="flex-1 overflow-y-auto p-5 space-y-3">

          <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2">

            Drag rows or use ↑↓ to set order. Files joined top→bottom via stream copy (lossless, instant).

          </div>

          <div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100">

            {items.map((item, idx) => (

              <div key={item.uid} draggable onDragStart={() => handleDragStart(item.uid)}

                onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop}

                className="flex items-center gap-3 px-4 py-3 hover:bg-slate-50 cursor-grab active:cursor-grabbing transition-colors">

                <svg className="h-4 w-4 flex-shrink-0 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" />

                </svg>

                <span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-100 text-[11px] font-bold text-violet-700 flex-shrink-0">{idx + 1}</span>

                <div className="flex-1 min-w-0">

                  <p className="truncate text-sm font-medium text-slate-800" title={item.file.name}>{item.file.name}</p>

                  <p className="text-[10px] text-slate-400">{fmt(item.file.sizeBytes)} · {item.file.folder}</p>

                </div>

                <div className="flex items-center gap-1 flex-shrink-0">

                  <button onClick={() => moveUp(idx)} disabled={idx === 0}

                    className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">

                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

                      <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" />

                    </svg>

                  </button>

                  <button onClick={() => moveDown(idx)} disabled={idx === items.length - 1}

                    className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">

                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

                      <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />

                    </svg>

                  </button>

                  {items.length > 2 && (

                    <button onClick={() => removeItem(item.uid)}

                      className="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600">

                      <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

                        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />

                      </svg>

                    </button>

                  )}

                </div>

              </div>

            ))}

          </div>

          <div className="space-y-1">

            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label>

            <input type="text" value={outName} onChange={(e) => setOutName(e.target.value)}

              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />

          </div>

          {error && <p className="text-xs text-red-500">{error}</p>}

          <div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2">

            💡 Output saved to same folder as the first selected file. Stream copy = instant, lossless.

          </div>

        </div>

        <div className="px-5 pb-5 flex-shrink-0">

          <button onClick={handleMerge} disabled={busy || items.length < 2 || !outName.trim()}

            className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50">

            {busy ? "Starting Merge…" : `🔗 Merge ${items.length} Files`}

          </button>

        </div>

      </div>

    </div>
  );
}

// ─── Move File Modal ──────────────────────────────────────────────────────────
function MoveModal({ files, folders, onClose, onMoved }: {

  files: FileEntry[];

  folders: string[];

  onClose: () => void;

  onMoved: () => void;

}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const itemCount = files.length;

  const handleMove = async (targetFolder: string) => {
    if (files.every((f) => (f.folder || "/") === targetFolder)) { onClose(); return; }
    setBusy(true); setError(null);
    try {
      const ids = files.map((f) => f.id);
      const data = await api.batchMove(ids, targetFolder);
      if (data.error) { setError(data.error); setBusy(false); return; }
      onMoved();
      onClose();
    } catch { setError("Failed to move file(s)"); setBusy(false); }
  };

  const allFolders = Array.from(new Set(["/", ...folders])).sort((a, b) => {
    if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b);
  });

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>

      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm" onClick={(e) => e.stopPropagation()}>

        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">

          <div className="flex items-center gap-2 min-w-0">

            <span className="text-lg flex-shrink-0">↗️</span>

            <div className="min-w-0">

              <h2 className="text-sm font-bold text-slate-800">Move {itemCount === 1 ? "File" : `${itemCount} Files`}</h2>

              <p className="text-[10px] text-slate-400 truncate">

                {itemCount === 1 ? files[0].name : `${itemCount} selected files`}

              </p>

            </div>

          </div>

          <button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">

            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />

            </svg>

          </button>

        </div>

        <div className="p-4 space-y-2">

          <p className="text-xs text-slate-500 mb-3">Select destination folder:</p>

          {error && <p className="text-xs text-red-500 mb-2">{error}</p>}

          <div className="rounded-xl border border-slate-200 overflow-hidden divide-y divide-slate-100 max-h-64 overflow-y-auto">

            {allFolders.map((folder) => {

              const isCurrent = files.every((f) => (f.folder || "/") === folder);

              return (

                <button key={folder} onClick={() => !busy && handleMove(folder)} disabled={busy || isCurrent}

                  className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${

                    isCurrent ? "bg-violet-50 cursor-not-allowed" : "hover:bg-slate-50"

                  }`}>

                  <svg className={`h-4 w-4 flex-shrink-0 ${isCurrent ? "text-violet-500" : "text-amber-500"}`} fill="currentColor" viewBox="0 0 24 24">

                    <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" />

                  </svg>

                  <span className={`text-sm font-medium flex-1 truncate ${isCurrent ? "text-violet-700" : "text-slate-700"}`}>

                    {folder === "/" ? "/ (root)" : folder}

                  </span>

                  {isCurrent && (

                    <span className="text-[10px] text-violet-500 font-semibold flex-shrink-0">current</span>

                  )}

                </button>

              );

            })}

          </div>

          {busy && <p className="text-xs text-slate-400 text-center">Moving…</p>}

        </div>

      </div>

    </div>
  );
}

// ─── Create Folder Modal ──────────────────────────────────────────────────────
function CreateFolderModal({ onClose, onCreated }: { onClose: () => void; onCreated: (name: string) => void }) {
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleCreate = async () => {
    const trimmed = name.trim();
    if (!trimmed) { setError("Folder name is required"); return; }
    setBusy(true); setError(null);
    try {
      const data = await api.createFolder(trimmed);
      if (data.error) { setError(data.error); setBusy(false); return; }
      onCreated(data.folder ?? `/${trimmed}`);
      onClose();
    } catch { setError("Failed to create folder"); setBusy(false); }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>

      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xs" onClick={(e) => e.stopPropagation()}>

        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">

          <div className="flex items-center gap-2">

            <span className="text-lg">📁</span>

            <h2 className="text-sm font-bold text-slate-800">New Folder</h2>

          </div>

          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">

            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>

              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />

            </svg>

          </button>

        </div>

        <div className="p-5 space-y-4">

          <input autoFocus type="text" placeholder="Folder name…" value={name}

            onChange={(e) => setName(e.target.value)}

            onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); if (e.key === "Escape") onClose(); }}

            className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />

          {error && <p className="text-xs text-red-500">{error}</p>}

          <button onClick={handleCreate} disabled={busy || !name.trim()}

            className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors">

            {busy ? "Creating…" : "Create Folder"}

          </button>

        </div>

      </div>

    </div>
  );
}

// ─── Sub-components ───────────────────────────────────────────────────────────
function Badge({ children, color }: { children: React.ReactNode; color: string }) {
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${color}`}>

      {children}

    </span>
  );
}

function IconBtn({ title, onClick, children, danger, active, disabled }: {

  title: string; onClick: () => void; children: React.ReactNode;

  danger?: boolean; active?: boolean; disabled?: boolean;

}) {
  return (
    <button

      title={title}

      onClick={onClick}

      disabled={disabled}

      className={`inline-flex items-center justify-center rounded-md p-1 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${

        danger

          ? "text-red-400 hover:bg-red-50 hover:text-red-600"

          : active

            ? "bg-violet-100 text-violet-700"

            : "text-slate-400 hover:bg-slate-100 hover:text-slate-600"

      }`}

    >

      {children}

    </button>
  );
}
// ─── Info Modal ───────────────────────────────────────────────────────────────
function InfoModal({ file, onClose, initialShowEncode }: { file: FileEntry; onClose: () => void; initialShowEncode?: boolean }) {
  const [info, setInfo] = useState<VideoInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showEncodeSettings, setShowEncodeSettings] = useState(!!initialShowEncode);

  useEffect(() => {
    api.getFileInfo(file.id)
      .then((res) => { if (res.ok) setInfo(res.info); else setError("Failed to load info"); })
      .catch(() => setError("Failed to load info"))
      .finally(() => setLoading(false));
  }, [file.id]);

  const Row = ({ label, value }: { label: string; value: string }) => (
    <div className="flex items-baseline justify-between gap-4 py-2 border-b border-slate-100 last:border-0">

      <span className="text-xs font-semibold text-slate-500 whitespace-nowrap w-36 flex-shrink-0">{label}</span>

      <span className="text-xs text-slate-800 text-right font-mono break-all">{value}</span>

    </div>
  );

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-lg flex-shrink-0">🎬</span>
            <h2 className="text-sm font-bold text-slate-800 truncate">{file.name}</h2>
          </div>
          <button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="p-5">
          {loading && (
            <div className="py-10 text-center text-sm text-slate-400">
              <svg className="animate-spin h-6 w-6 mx-auto mb-2 text-violet-500" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
              </svg>
              Analyzing file…
            </div>
          )}
          {error && <div className="py-6 text-center text-sm text-red-500">{error}</div>}
          {info && (
            <div className="space-y-5">
              <div>
                <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">General</h3>
                <div className="rounded-xl bg-slate-50 px-4 py-1">
                  <Row label="File Size" value={info.fileSize} />
                  <Row label="Duration" value={info.duration} />
                </div>
              </div>
              {info.video && (
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">Video Stream</h3>
                  <div className="rounded-xl bg-slate-50 px-4 py-1">
                    <Row label="Resolution" value={info.video.resolution} />
                    <Row label="Video Codec" value={info.video.profile ? `${info.video.codec} (${info.video.profile})` : info.video.codec} />
                    <Row label="Frame Rate" value={info.video.frameRate} />
                    <Row label="Video Bitrate" value={info.video.bitrate} />
                    <Row label="Pixel Format" value={info.video.pixFmt} />
                    <Row label="Stream Size" value={info.video.streamSize} />
                  </div>
                </div>
              )}
              {info.audio && (
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">Audio Stream</h3>
                  <div className="rounded-xl bg-slate-50 px-4 py-1">
                    <Row label="Audio Codec" value={info.audio.codec} />
                    <Row label="Sample Rate" value={info.audio.sampleRate} />
                    <Row label="Channels" value={`${info.audio.channels}${info.audio.channelLayout ? ` (${info.audio.channelLayout})` : ""}`} />
                    <Row label="Audio Bitrate" value={info.audio.bitrate} />
                    <Row label="Stream Size" value={info.audio.streamSize} />
                  </div>
                </div>
              )}
              {info.audioStreams && info.audioStreams.length > 0 && (
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">
                    Audio Streams ({info.audioStreams.length})
                  </h3>
                  <div className="space-y-2">
                    {info.audioStreams.map((stream, i) => (
                      <div key={i} className="rounded-xl bg-slate-50 px-4 py-3">
                        <div className="mb-2 text-[11px] font-semibold text-slate-500">
                          Audio #{stream.index}
                        </div>
                        <Row label="Codec" value={stream.codec || "unknown"} />
                        <Row label="Language" value={stream.language || "unknown"} />
                        <Row label="Title" value={stream.title || "—"} />
                        <Row
                          label="Channels"
                          value={`${stream.channels}${stream.channelLayout && stream.channelLayout !== "unknown" ? ` (${stream.channelLayout})` : ""}`}
                        />
                        <Row label="Sample Rate" value={stream.sampleRate || "unknown"} />
                        <Row label="Bitrate" value={stream.bitrate || "unknown"} />
                        <Row label="Stream Size" value={stream.streamSize || "unknown"} />
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {info.subtitleStreams && info.subtitleStreams.length > 0 && (
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">
                    Subtitle Streams ({info.subtitleStreams.length})
                  </h3>
                  <div className="space-y-2">
                    {info.subtitleStreams.map((stream, i) => (
                      <div key={i} className="rounded-xl bg-slate-50 px-4 py-3">
                        <div className="mb-2 text-[11px] font-semibold text-slate-500">
                          Subtitle #{stream.index}
                        </div>
                        <Row label="Codec" value={stream.codec || "unknown"} />
                        <Row label="Language" value={stream.language || "unknown"} />
                        <Row label="Title" value={stream.title || "—"} />
                        <Row label="Default" value={stream.default ? "Yes" : "No"} />
                        <Row label="Forced" value={stream.forced ? "Yes" : "No"} />
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {!info.video && !info.audio && (!info.audioStreams || info.audioStreams.length === 0) && (!info.subtitleStreams || info.subtitleStreams.length === 0) && (
                <p className="text-sm text-slate-400 text-center py-4">No stream information available</p>
              )}

              {info.encodeSettings && (
                <div className="pt-2">
                  <button
                    onClick={() => setShowEncodeSettings((v) => !v)}
                    className="flex items-center gap-2 text-xs font-semibold text-violet-600 hover:text-violet-700"
                  >
                    <span>{showEncodeSettings ? "▼" : "▶"}</span>
                    Encoding Settings
                  </button>
                  {showEncodeSettings && (
                    <div className="mt-2 rounded-xl bg-slate-50 px-4 py-3 space-y-2">
                      <Row label="Input" value={info.encodeSettings.inputFilename || "unknown"} />
                      <Row label="Output" value={info.encodeSettings.outputFilename || "unknown"} />
                      {info.encodeSettings.resolution && (
                        <Row label="Actual Resolution" value={info.encodeSettings.resolution} />
                      )}
                      {info.encodeSettings.settings && (() => {
                        const s = info.encodeSettings!.settings as Record<string, unknown>;
                        const rows: Array<{ label: string; value: string }> = [];
                        if (s.codec) rows.push({ label: "Codec", value: String(s.codec).toUpperCase() });
                        if (s.mode) rows.push({ label: "Mode", value: s.mode === "crf-1pass" ? "CRF (1-pass)" : "VBR" });
                        if (s.crf !== undefined) rows.push({ label: "CRF", value: String(s.crf) });
                        if (s.videoBitrateKbps) rows.push({ label: "Video Bitrate", value: `${s.videoBitrateKbps} kbps` });
                        if (s.audioBitrateKbps) rows.push({ label: "Audio Bitrate", value: `${s.audioBitrateKbps} kbps (Opus)` });
                        if (s.resolution) rows.push({ label: "Resolution", value: String(s.resolution) });
                        if (s.frameRate) rows.push({ label: "Frame Rate", value: String(s.frameRate) });
                        if (s.preset !== undefined) rows.push({ label: "Preset", value: String(s.preset) });
                        if (s.h26xPreset) rows.push({ label: "H26x Preset", value: String(s.h26xPreset) });
                        if (s.aqMode !== undefined) rows.push({ label: "AQ Mode", value: s.aqMode === 0 ? "0 (Off)" : s.aqMode === 1 ? "1 (Variance)" : "2 (Complexity)" });
                        if (s.tiles) rows.push({ label: "Tiles", value: String(s.tiles) });
                        if (s.outputContainer) rows.push({ label: "Container", value: String(s.outputContainer).toUpperCase() });
                        if (s.audioChannels) rows.push({ label: "Audio Channels", value: String(s.audioChannels) });
                        if (s.forceStereo) rows.push({ label: "Force Stereo", value: "Yes" });
                        if (s.sceneChange !== undefined) rows.push({ label: "Scene Change", value: String(s.sceneChange) });
                        if (s.deinterlace) rows.push({ label: "Deinterlace", value: "Yes" });
                        if (s.denoise) rows.push({ label: "Denoise", value: "Yes" });
                        if (s.rotate && s.rotate !== "none") rows.push({ label: "Rotate", value: String(s.rotate) });
                        if (s.speed && Number(s.speed) !== 1) rows.push({ label: "Speed", value: `${s.speed}×` });
                        if (s.brightness && Number(s.brightness) !== 0) rows.push({ label: "Brightness", value: String(s.brightness) });
                        if (s.contrast && Number(s.contrast) !== 1) rows.push({ label: "Contrast", value: String(s.contrast) });
                        if (s.saturation && Number(s.saturation) !== 1) rows.push({ label: "Saturation", value: String(s.saturation) });
                        if (s.stripSubtitles) rows.push({ label: "Strip Subtitles", value: "Yes" });
                        if (s.stripMetadata) rows.push({ label: "Strip Metadata", value: "Yes" });
                        if (s.subtitleFile) rows.push({ label: "Subtitle File", value: String(s.subtitleFile) });
                        if (s.subtitleLang) rows.push({ label: "Subtitle Language", value: String(s.subtitleLang) });
                        if (s.subtitleBurn) rows.push({ label: "Subtitle Burn-in", value: "Yes" });
                        if (s.startTime) rows.push({ label: "Start Time", value: String(s.startTime) });
                        if (s.endTime) rows.push({ label: "End Time", value: String(s.endTime) });

                        return rows.length > 0 ? (
                          <div className="space-y-1 mt-2">
                            {rows.map((r, i) => (
                              <div key={i} className="flex items-baseline justify-between gap-2 text-[11px]">
                                <span className="text-slate-500">{r.label}:</span>
                                <span className="text-slate-700 font-medium">{r.value}</span>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <p className="text-[10px] text-slate-400 mt-2">No settings available</p>
                        );
                      })()}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [seekStep, setSeekStep] = useState(6);

  const seek = (delta: number) => {
    const v = videoRef.current;
    if (!v) return;
    v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta));
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement).tagName;
      if (tag === "INPUT" || tag === "TEXTAREA") return;
      if (e.key === "ArrowLeft") { e.preventDefault(); seek(-seekStep); }
      if (e.key === "ArrowRight") { e.preventDefault(); seek(seekStep); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [seekStep]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-4xl rounded-3xl bg-slate-950 shadow-2xl overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between gap-3 px-5 py-4 border-b border-slate-800 bg-slate-900">
          <div className="min-w-0">
            <p className="text-sm font-semibold text-white truncate">Preview: {title}</p>
            <p className="text-xs text-slate-400">Video playback uses the browser's media player.</p>
          </div>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-800 hover:text-white transition-colors">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="bg-black p-4">
          <video ref={videoRef} className="w-full max-h-[70vh] rounded-3xl bg-black" controls playsInline src={url} />
          <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <button
                onClick={() => seek(-seekStep)}
                className="rounded-full bg-slate-800 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700 transition-colors"
              >
                −{seekStep}s
              </button>
              <button
                onClick={() => seek(seekStep)}
                className="rounded-full bg-slate-800 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700 transition-colors"
              >
                +{seekStep}s
              </button>
              <label className="flex items-center gap-1.5 text-xs text-slate-400">
                Step:
                <input
                  type="number"
                  min={1}
                  max={600}
                  value={seekStep}
                  onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))}
                  className="w-14 rounded bg-slate-800 border border-slate-700 px-2 py-1 text-white text-xs text-center"
                />
                s
              </label>
            </div>
            <div className="flex items-center gap-3 text-xs text-slate-400">
              <p>If playback fails, open the file directly.</p>
              <a href={url} target="_blank" rel="noreferrer" className="rounded-full bg-slate-800 px-3 py-1 text-slate-200 hover:bg-slate-700 transition-colors">Open raw file</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Crop Modal ─────────────────────────────────────────────────────────────
function CropModal({ file, onClose, onDone }: {
  file: FileEntry;
  onClose: () => void;
  onDone: (values: CropValues) => void;
}) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [cropEnabled, setCropEnabled] = useState(false);
  const [cropLeft, setCropLeft] = useState(0);
  const [cropRight, setCropRight] = useState(0);
  const [cropTop, setCropTop] = useState(0);
  const [cropBottom, setCropBottom] = useState(0);
  const [seekStep, setSeekStep] = useState(6);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number } | null>(null);
  const [zoomLevel, setZoomLevel] = useState(100);
  const [dragAnchor, setDragAnchor] = useState<{ x: number; y: number; left: number; right: number; top: number; bottom: number } | null>(null);

  const applyPreset = (preset: "lt" | "rt" | "up" | "low") => {
    const map: Record<typeof preset, CropValues> = {
      lt: { cropEnabled: true, cropLeft: 20, cropRight: 20, cropTop: 10, cropBottom: 10 },
      rt: { cropEnabled: true, cropLeft: 10, cropRight: 20, cropTop: 10, cropBottom: 10 },
      up: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 20, cropBottom: 10 },
      low: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 10, cropBottom: 20 },
    };
    updateFromValues(map[preset]);
  };

  const updateFromValues = (values: CropValues) => {
    setCropEnabled(values.cropEnabled);
    setCropLeft(values.cropLeft);
    setCropRight(values.cropRight);
    setCropTop(values.cropTop);
    setCropBottom(values.cropBottom);
  };

  useEffect(() => {
    // First check localStorage
    const saved = localStorage.getItem(`crop-${file.id}`);
    if (saved) {
      try {
        updateFromValues(JSON.parse(saved));
        return; // Use localStorage if found
      } catch {}
    }
    // Then check server for savedCropSettings (from .crop.json sidecar)
    api.getFileInfo(file.id).then((res) => {
      if (res.ok && res.info?.savedCropSettings) {
        const s = res.info.savedCropSettings;
        updateFromValues({
          cropEnabled: Boolean(s.cropEnabled),
          cropLeft: Number(s.cropLeft ?? 0),
          cropRight: Number(s.cropRight ?? 0),
          cropTop: Number(s.cropTop ?? 0),
          cropBottom: Number(s.cropBottom ?? 0),
        });
      }
    }).catch(() => {}); // Ignore errors
  }, [file.id]);

  const handleDone = () => {
    const values = { cropEnabled, cropLeft, cropRight, cropTop, cropBottom };
    try { localStorage.setItem(`crop-${file.id}`, JSON.stringify(values)); } catch {}
    onDone(values);
  };

  const cropOutputSize = useMemo(() => {
    if (!videoDimensions) return null;
    const width = Math.max(1, Math.round(videoDimensions.width * (1 - (cropLeft + cropRight) / 100)));
    const height = Math.max(1, Math.round(videoDimensions.height * (1 - (cropTop + cropBottom) / 100)));
    return { width, height };
  }, [videoDimensions, cropLeft, cropRight, cropTop, cropBottom]);

  const seekVideo = (delta: number) => {
    const v = videoRef.current;
    if (!v) return;
    v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta));
  };

  const togglePlayback = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) {
      void v.play();
      setIsVideoPlaying(true);
    } else {
      v.pause();
      setIsVideoPlaying(false);
    }
  };

  const centerCrop = () => {
    setCropEnabled(true);
    setCropLeft(10);
    setCropRight(10);
    setCropTop(10);
    setCropBottom(10);
  };

  const adjustZoom = (delta: number) => {
    setZoomLevel((prev) => Math.max(50, Math.min(200, prev + delta)));
  };

  const handleCropPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!cropEnabled) return;
    event.preventDefault();
    event.currentTarget.setPointerCapture(event.pointerId);
    setDragAnchor({
      x: event.clientX,
      y: event.clientY,
      left: cropLeft,
      right: cropRight,
      top: cropTop,
      bottom: cropBottom,
    });
  };

  const handleCropPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!dragAnchor) return;
    const rect = event.currentTarget.getBoundingClientRect();
    const deltaX = ((event.clientX - dragAnchor.x) / rect.width) * 100;
    const deltaY = ((event.clientY - dragAnchor.y) / rect.height) * 100;

    const nextLeft = Math.max(0, Math.min(45, dragAnchor.left + deltaX));
    const nextRight = Math.max(0, Math.min(45, dragAnchor.right - deltaX));
    const nextTop = Math.max(0, Math.min(45, dragAnchor.top + deltaY));
    const nextBottom = Math.max(0, Math.min(45, dragAnchor.bottom - deltaY));

    setCropLeft(nextLeft);
    setCropRight(nextRight);
    setCropTop(nextTop);
    setCropBottom(nextBottom);
  };

  const handleCropPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    if (dragAnchor) {
      event.currentTarget.releasePointerCapture(event.pointerId);
      setDragAnchor(null);
    }
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement).tagName;
      if (tag === "INPUT" || tag === "TEXTAREA") return;
      if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); }
      if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [seekStep]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/45 p-4 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-3xl overflow-hidden rounded-3xl bg-white shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4">
          <div>
            <h2 className="text-sm font-bold text-slate-900">Crop preview</h2>
            <p className="text-xs text-slate-500">Trim the visible area from the left, right, top, and bottom before encoding.</p>
          </div>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="grid gap-5 p-5 lg:grid-cols-[1.2fr_0.8fr]">
          <div className="space-y-3">
            <div className="relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-950">
              <div className="overflow-hidden rounded-2xl" style={{ transform: `scale(${zoomLevel / 100})`, transformOrigin: "center center" }}>
                <video
                  ref={videoRef}
                  src={`/api/files/${encodeURIComponent(file.id)}/stream`}
                  controls
                  playsInline
                  className="w-full rounded-2xl bg-black"
                onPlay={() => setIsVideoPlaying(true)}
                onPause={() => setIsVideoPlaying(false)}
                onEnded={() => setIsVideoPlaying(false)}
                  onLoadedMetadata={() => {
                    const video = videoRef.current;
                    if (video) {
                      setVideoDimensions({ width: video.videoWidth || 0, height: video.videoHeight || 0 });
                    }
                  }}
                />
              </div>
              <div className="absolute inset-0">
                <div className="absolute inset-0 rounded-2xl bg-black/55" />
                <div
                  className={`absolute rounded-xl border-2 border-white/90 shadow-[0_0_0_9999px_rgba(0,0,0,0.55)] transition-[top,bottom,left,right] duration-75 ${cropEnabled ? "cursor-move" : "cursor-default"}`}
                  style={{
                    top: `${cropTop}%`,
                    bottom: `${cropBottom}%`,
                    left: `${cropLeft}%`,
                    right: `${cropRight}%`,
                  }}
                  onPointerDown={handleCropPointerDown}
                  onPointerMove={handleCropPointerMove}
                  onPointerUp={handleCropPointerUp}
                  onPointerCancel={handleCropPointerUp}
                />
              </div>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <button
                type="button"
                onClick={togglePlayback}
                className="rounded-full bg-slate-900 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700"
              >
                {isVideoPlaying ? "Pause" : "Play"}
              </button>
              <button
                type="button"
                onClick={() => adjustZoom(-10)}
                className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
              >
                − Zoom
              </button>
              <button
                type="button"
                onClick={() => adjustZoom(10)}
                className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
              >
                + Zoom
              </button>
              <button
                type="button"
                onClick={() => setZoomLevel(100)}
                className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
              >
                Reset zoom
              </button>
              <span className={`rounded-full px-2.5 py-1 text-xs font-semibold ${zoomLevel === 100 ? "bg-slate-100 text-slate-600" : "bg-violet-100 text-violet-700"}`}>
                {zoomLevel === 100 ? "100% (default)" : `${zoomLevel}%`}
              </span>
              <button
                type="button"
                onClick={centerCrop}
                className="rounded-full bg-violet-600 px-3 py-1.5 text-sm font-semibold text-white hover:bg-violet-700"
              >
                Center crop
              </button>
              <button
                type="button"
                onClick={() => seekVideo(-seekStep)}
                className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
              >
                −{seekStep}s
              </button>
              <button
                type="button"
                onClick={() => seekVideo(seekStep)}
                className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
              >
                +{seekStep}s
              </button>
              <label className="flex items-center gap-1.5 text-xs text-slate-500">
                Step:
                <input
                  type="number"
                  min={1}
                  max={600}
                  value={seekStep}
                  onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))}
                  className="w-14 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs text-center"
                />
                s
              </label>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-xs text-slate-500">
              <p className="font-semibold text-slate-700">Preview</p>
              <p className="mt-1">The visible rectangle updates as you adjust the crop values. Drag the highlighted box directly in the preview or use the sliders and the play/seek controls while you crop.</p>
              {cropOutputSize && (
                <div className="mt-2 flex flex-wrap gap-2">
                  <span className="rounded-full bg-white px-2.5 py-1 font-semibold text-slate-700">Output: {cropOutputSize.width}×{cropOutputSize.height}</span>
                  <span className="rounded-full bg-white px-2.5 py-1 font-semibold text-slate-700">Aspect: {formatAspectRatio(cropOutputSize.width, cropOutputSize.height)}</span>
                </div>
              )}
            </div>
          </div>
          <div className="space-y-4">
            <label className="flex items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
              <span>Enable crop</span>
              <input type="checkbox" checked={cropEnabled} onChange={(e) => setCropEnabled(e.target.checked)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" />
            </label>
            <div className="space-y-3 rounded-2xl border border-slate-200 bg-white p-3">
              <div className="flex flex-wrap gap-2">
                {([
                  ["lt", "LT"],
                  ["rt", "RT"],
                  ["up", "UP"],
                  ["low", "LOW"],
                ] as const).map(([key, label]) => (
                  <button
                    key={key}
                    type="button"
                    onClick={() => applyPreset(key)}
                    disabled={!cropEnabled}
                    className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    {label}
                  </button>
                ))}
              </div>
              {[
                { key: "cropLeft", label: "Left", value: cropLeft, setter: setCropLeft },
                { key: "cropRight", label: "Right", value: cropRight, setter: setCropRight },
                { key: "cropTop", label: "Top", value: cropTop, setter: setCropTop },
                { key: "cropBottom", label: "Bottom", value: cropBottom, setter: setCropBottom },
              ].map((field) => (
                <div key={field.key} className="space-y-1.5">
                  <div className="flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-slate-500">
                    <span>{field.label}</span>
                    <span>{field.value}%</span>
                  </div>
                  <input
                    type="range"
                    min={0}
                    max={45}
                    step={1}
                    value={field.value}
                    disabled={!cropEnabled}
                    onChange={(e) => field.setter(Number(e.target.value))}
                    className="w-full accent-violet-600 disabled:cursor-not-allowed disabled:opacity-60"
                  />
                </div>
              ))}
            </div>
            <div className="flex flex-wrap gap-2">
              <button type="button" onClick={() => { setCropEnabled(false); setCropLeft(0); setCropRight(0); setCropTop(0); setCropBottom(0); }} className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Reset</button>
              <button type="button" onClick={handleDone} className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700">Done</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Trim Modal ───────────────────────────────────────────────────────────────
function TrimModal({ file, onClose, onTrimStarted }: {
  file: FileEntry;
  onClose: () => void;
  onTrimStarted: () => void;
}) {
  type TrimSegment = { id: string; start: string; end: string };
  const [duration, setDuration] = useState<number | null>(null);
  const [segments, setSegments] = useState<TrimSegment[]>([]);
  const [activeSegmentId, setActiveSegmentId] = useState("");
  const [outName, setOutName] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pasteText, setPasteText] = useState("");
  const videoRef = useRef<HTMLVideoElement>(null);
  const [previewCurrentTime, setPreviewCurrentTime] = useState(0);
  const [pendingClipStart, setPendingClipStart] = useState<number | null>(null);
  const [seekStep, setSeekStep] = useState(6);

  const seekVideo = (delta: number) => {
    const v = videoRef.current;
    if (!v) return;
    v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta));
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement).tagName;
      if (tag === "INPUT" || tag === "TEXTAREA") return;
      if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); }
      if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [seekStep]);

  useEffect(() => {
    api.getFileInfo(file.id).then((res) => {
      if (res.ok && res.info.durationSeconds) {
        const d = res.info.durationSeconds;
        setDuration(d);
      }
    }).finally(() => setLoading(false));

    const ext = file.name.match(/(\.[^.]+)$/)?.[1] || "";
    const base = file.name.replace(/(\.[^.]+)$/, "");
    setOutName(`${base}_trim${ext}`);
  }, [file]);

  useEffect(() => {
    if (segments.length && !segments.some((segment) => segment.id === activeSegmentId)) {
      setActiveSegmentId(segments[0].id);
    }
    if (!segments.length && activeSegmentId) {
      setActiveSegmentId("");
    }
  }, [segments, activeSegmentId]);

  const activeSegment = segments.find((segment) => segment.id === activeSegmentId) || segments[0] || null;
  const startSec = activeSegment ? hmsToSeconds(activeSegment.start) : 0;
  const endSec = activeSegment ? hmsToSeconds(activeSegment.end) : 0;
  const trimDuration = Math.max(0, endSec - startSec);

  const updateSegment = (id: string, field: "start" | "end", value: string) => {
    setSegments((prev) => prev.map((segment) => segment.id === id ? { ...segment, [field]: value } : segment));
  };

  const addSegment = () => {
    const id = `seg_${Math.random().toString(16).slice(2)}`;
    const lastEnd = segments.length ? hmsToSeconds(segments[segments.length - 1].end) : 0;
    const nextStart = duration ? Math.min(lastEnd, Math.floor(duration)) : lastEnd;
    const newSegment = { id, start: secondsToHms(nextStart), end: secondsToHms(nextStart) };
    setSegments((prev) => [...prev, newSegment]);
    setActiveSegmentId(id);
  };

  const removeSegment = (id: string) => {
    setSegments((prev) => prev.filter((segment) => segment.id !== id));
  };

  const moveSegment = (idx: number, direction: -1 | 1) => {
    setSegments((prev) => {
      const next = [...prev];
      const target = idx + direction;
      if (target < 0 || target >= next.length) return next;
      [next[idx], next[target]] = [next[target], next[idx]];
      return next;
    });
  };

  const handlePasteImport = () => {
    const parsed = parsePastedSegments(pasteText);

    if (!parsed.length) {
      setError("No valid clip ranges found in pasted text");
      return;
    }

    if (duration) {
      for (const seg of parsed) {
        if (hmsToSeconds(seg.end) > duration) {
          setError("One or more pasted segments exceed the file duration");
          return;
        }
      }
    }

    const nextSegments = parsed.map((seg) => ({
      id: `seg_${Math.random().toString(16).slice(2)}`,
      start: seg.start,
      end: seg.end,
    }));

    setSegments(nextSegments);
    setActiveSegmentId(nextSegments[0].id);
    setError(null);
  };

  const captureClipStart = () => {
    const t = Math.floor(videoRef.current?.currentTime ?? 0);
    setPreviewCurrentTime(t);
    setPendingClipStart(t);
    setError(null);
  };

  const captureClipEnd = () => {
    const t = Math.floor(videoRef.current?.currentTime ?? 0);
    setPreviewCurrentTime(t);

    if (pendingClipStart == null) {
      setError("Set clip start first.");
      return;
    }

    if (t <= pendingClipStart) {
      setError("Clip end must be after clip start.");
      return;
    }

    const seg = {
      id: `seg_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`,
      start: secondsToHms(pendingClipStart),
      end: secondsToHms(t),
    };

    setSegments((prev) => [...prev, seg]);
    setActiveSegmentId(seg.id);
    setPendingClipStart(null);
    setError(null);
  };

  const undoLastCapturedClip = () => {
    setSegments((prev) => {
      if (!prev.length) return prev;
      const next = prev.slice(0, -1);
      setActiveSegmentId(next.length ? next[next.length - 1].id : "");
      return next;
    });
    setError(null);
  };

  const clearCapturedClips = () => {
    setSegments([]);
    setActiveSegmentId("");
    setPendingClipStart(null);
    setError(null);
  };

  const handleTrim = async () => {
    const normalized = segments.map((segment) => ({
      startTime: hmsToSeconds(segment.start),
      endTime: hmsToSeconds(segment.end),
    }));

    for (const segment of normalized) {
      if (segment.endTime <= segment.startTime) {
        setError("Each segment needs an end time after its start time");
        return;
      }
      if (duration && segment.endTime > duration) {
        setError("One or more segments exceed the file duration");
        return;
      }
    }

    if (!outName.trim()) {
      setError("Output filename is required");
      return;
    }

    setError(null);
    setBusy(true);
    try {
      await api.trimSegments(file.id, normalized, outName.trim());
      onTrimStarted();
      onClose();
    } catch {
      setError("Failed to start trim job");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0">
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-lg flex-shrink-0">✂️</span>
            <div className="min-w-0">
              <h2 className="text-sm font-bold text-slate-800 truncate">Trim & Merge segments</h2>
              <p className="text-[11px] text-slate-500 truncate">Create multiple ranges and merge them into one seamless file.</p>
            </div>
          </div>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        {/* ── Always-visible OSD bar ── */}
        {!loading && (
          <div className="flex-shrink-0 flex flex-wrap items-center gap-x-5 gap-y-1 px-5 py-2 border-b border-slate-100 bg-slate-50 text-xs text-slate-600">
            <span>
              <span className="font-semibold">Duration:</span>{" "}
              {duration != null ? secondsToHms(Math.floor(duration)) : "—"}
            </span>
            <span>
              <span className="font-semibold">Current:</span>{" "}
              {secondsToHms(Math.floor(previewCurrentTime))}
            </span>
            <span>
              <span className="font-semibold">Pending start:</span>{" "}
              {pendingClipStart == null ? "—" : secondsToHms(Math.floor(pendingClipStart))}
            </span>
          </div>
        )}
        <div className="flex-1 overflow-y-auto p-5 space-y-4">
          {loading ? (
            <div className="py-6 text-center text-sm text-slate-400">Loading file info…</div>
          ) : (
            <>

              {/* ── Video player + seek + set start/end ── */}
              <div className="space-y-3">
                <video
                  ref={videoRef}
                  src={`/api/files/${encodeURIComponent(file.id)}/stream`}
                  controls
                  className="w-full rounded-2xl border border-slate-200 bg-black"
                  onTimeUpdate={() => setPreviewCurrentTime(Math.floor(videoRef.current?.currentTime ?? 0))}
                  onLoadedMetadata={() => setPreviewCurrentTime(Math.floor(videoRef.current?.currentTime ?? 0))}
                />
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => seekVideo(-seekStep)}
                    className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
                  >
                    −{seekStep}s
                  </button>
                  <button
                    type="button"
                    onClick={() => seekVideo(seekStep)}
                    className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200"
                  >
                    +{seekStep}s
                  </button>
                  <label className="flex items-center gap-1.5 text-xs text-slate-500">
                    Step:
                    <input
                      type="number"
                      min={1}
                      max={600}
                      value={seekStep}
                      onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))}
                      className="w-14 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs text-center"
                    />
                    s
                  </label>
                </div>
                <div className="rounded-xl border border-slate-200 bg-slate-50 p-3">
                  <div className="flex flex-wrap gap-2">
                    <button
                      type="button"
                      onClick={captureClipStart}
                      className="rounded-full bg-violet-600 px-3 py-2 text-sm font-semibold text-white hover:bg-violet-700"
                    >
                      Set Start
                    </button>
                    <button
                      type="button"
                      onClick={captureClipEnd}
                      className="rounded-full bg-emerald-600 px-3 py-2 text-sm font-semibold text-white hover:bg-emerald-700"
                    >
                      Set End
                    </button>
                    <button
                      type="button"
                      onClick={undoLastCapturedClip}
                      className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200"
                    >
                      Undo Last Clip
                    </button>
                    <button
                      type="button"
                      onClick={clearCapturedClips}
                      className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200"
                    >
                      Clear Clips
                    </button>
                  </div>
                  <p className="mt-3 text-xs text-slate-500">
                    While previewing: click Set Start, then Set End. Each start/end pair is added automatically as a new clip.
                  </p>
                </div>
              </div>

              {/* ── Paste clip list ── */}
              <div className="space-y-2 rounded-xl border border-slate-200 bg-slate-50 p-3">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                  Paste clip list
                </label>
                <textarea
                  value={pasteText}
                  onChange={(e) => setPasteText(e.target.value)}
                  placeholder={`Clip 1: 08:56 - 12:22
Clip 2: 17:05 - 22:49
Clip 3: 28:19 - 33:02
Clip 4: 39:49 - 42:57`}
                  className="min-h-[120px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                />
                <div className="flex items-center justify-between gap-2">
                  <span className="text-xs text-slate-500">
                    Supports mm:ss or hh:mm:ss per line.
                  </span>
                  <button
                    type="button"
                    onClick={handlePasteImport}
                    className="rounded-lg bg-violet-600 px-3 py-2 text-sm font-semibold text-white hover:bg-violet-700"
                  >
                    Import clips
                  </button>
                </div>
              </div>

              {/* ── Segments list ── */}
              {segments.length > 0 && (
                <div className="space-y-3">
                  {segments.map((segment, idx) => {
                    const segmentStart = hmsToSeconds(segment.start);
                    const segmentEnd = hmsToSeconds(segment.end);
                    const segmentLen = Math.max(0, segmentEnd - segmentStart);
                    const isActive = segment.id === activeSegmentId;
                    return (
                      <div
                        key={segment.id}
                        onClick={() => setActiveSegmentId(segment.id)}
                        className={`rounded-2xl border px-4 py-3 cursor-pointer ${
                          isActive ? "border-violet-300 bg-violet-50" : "border-slate-200 bg-white"
                        }`}
                      >
                        <div className="flex items-center justify-between gap-2">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <span className="text-xs font-semibold text-slate-700">
                                {segment.start} → {segment.end}
                              </span>
                              <span className="text-xs text-slate-400">
                                ({secondsToHms(Math.floor(segmentLen))})
                              </span>
                            </div>
                          </div>
                          <div className="flex items-center gap-1">
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                moveSegment(idx, -1);
                              }}
                              disabled={idx === 0}
                              className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30"
                              title="Move up"
                            >
                              ↑
                            </button>
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                moveSegment(idx, 1);
                              }}
                              disabled={idx === segments.length - 1}
                              className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30"
                              title="Move down"
                            >
                              ↓
                            </button>
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                removeSegment(segment.id);
                              }}
                              className="rounded p-1 text-slate-400 hover:text-red-600"
                              title="Remove segment"
                            >
                              ✕
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              <div className="flex items-center gap-2">
                <button type="button" onClick={addSegment}
                  className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200">
                  + Add segment
                </button>
                <span className="text-xs text-slate-500">Use the segment list to trim multiple slices and merge them seamlessly.</span>
              </div>

              {duration && activeSegment && (
                <div className="space-y-2">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <div className="text-[11px] text-slate-500 uppercase tracking-wider">Start (drag)</div>
                      <input type="range" min={0} max={Math.floor(duration)} step={1} value={startSec}
                        onChange={(e) => updateSegment(activeSegment.id, "start", secondsToHms(Number(e.target.value)))} className="w-full accent-violet-600" />
                    </div>
                    <div>
                      <div className="text-[11px] text-slate-500 uppercase tracking-wider">End (drag)</div>
                      <input type="range" min={0} max={Math.floor(duration)} step={1} value={endSec}
                        onChange={(e) => updateSegment(activeSegment.id, "end", secondsToHms(Number(e.target.value)))} className="w-full accent-violet-600" />
                    </div>
                  </div>
                  <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
                    Active segment: {secondsToHms(startSec)} → {secondsToHms(endSec)} • {trimDuration > 0 ? `Length ${secondsToHms(Math.floor(trimDuration))}` : "Empty range"}
                  </div>
                </div>
              )}

              <div className="space-y-1">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label>
                <input type="text" value={outName} onChange={(e) => setOutName(e.target.value)}
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />
              </div>
              {error && <p className="text-xs text-red-500">{error}</p>}
              <div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
                💡 Output saved to same folder as source. All segments are joined without pauses.
              </div>
              <button onClick={handleTrim} disabled={busy || !outName.trim() || !segments.length}
                className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50">
                {busy ? "Starting Trim…" : segments.length > 1 ? "✂️ Trim & Merge" : "✂️ Trim"}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Download Job Progress Bar ────────────────────────────────────────────────
function DownloadProgress({ jobId, onDone }: { jobId: string; onDone?: () => void }) {
  const [job, setJob] = useState<DownloadJob | null>(null);
  const doneRef = useRef(false);

  useEffect(() => {
    let iv: number | undefined;

    const poll = async () => {
      try {
        const data = await api.getDownloadJob(jobId);
        setJob(data.job);
        if (data.job.status !== "running") {
          if (iv) window.clearInterval(iv);
          // Only auto-dismiss on success; failures stay visible until user dismisses
          if (data.job.status === "done" && !doneRef.current) {
            doneRef.current = true;
            onDone?.();
          }
        }
      } catch {
        if (iv) window.clearInterval(iv);
      }
    };

    poll();
    iv = window.setInterval(poll, 1000);
    return () => { if (iv) window.clearInterval(iv); };
  }, [jobId, onDone]);

  if (!job) return null;

  const pct = job.totalBytes > 0 ? Math.min(100, (job.bytesDownloaded / job.totalBytes) * 100) : null;
  const finished = job.status !== "running";

  return (
    <div className={`rounded-2xl border bg-white/90 p-4 shadow-sm backdrop-blur ${job.status === "failed" ? "border-red-200" : "border-slate-200"}`}>
      <div className="mb-2 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-slate-800">{job.filename || "Downloading…"}</p>
          <p className="truncate text-xs text-slate-500">{job.url}</p>
        </div>
        <Badge color={
          job.status === "done"
            ? "bg-emerald-100 text-emerald-700"
            : job.status === "failed"
              ? "bg-red-100 text-red-700"
              : job.status === "stopped"
                ? "bg-slate-200 text-slate-700"
                : "bg-violet-100 text-violet-700"
        }>
          {job.status}
        </Badge>
      </div>

      <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100">
        {pct == null ? (
          <div className="h-full w-1/3 animate-pulse rounded-full bg-violet-500" />
        ) : (
          <div
            className={`h-full rounded-full transition-all ${job.status === "failed" ? "bg-red-400" : "bg-violet-500"}`}
            style={{ width: `${pct}%` }}
          />
        )}
      </div>

      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>
          {fmt(job.bytesDownloaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}
          {job.status === "running" && job.speedBytesPerSec && job.speedBytesPerSec > 0
            ? <span className="ml-2 text-violet-500 font-medium">{fmt(job.speedBytesPerSec)}/s</span>
            : null}
        </span>
        <span className="flex items-center gap-1.5">
          {job.useAria2 && job.status === "running" && (
            <span className="rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-700">⚡ aria2c</span>
          )}
          {pct == null ? "…" : `${pct.toFixed(1)}%`}
        </span>
      </div>

      {job.error && <p className="mt-2 text-xs text-red-500">{job.error}</p>}

      {finished && (
        <div className="mt-3 flex justify-end gap-2">
          {job.status === "running" && (
            <button
              onClick={() => api.stopDownloadJob(job.id)}
              className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50"
            >
              Stop
            </button>
          )}
          <button
            onClick={() => onDone?.()}
            className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50"
          >
            Dismiss
          </button>
        </div>
      )}

      {!finished && (
        <div className="mt-3 flex justify-end">
          <button
            onClick={() => api.stopDownloadJob(job.id)}
            className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50"
          >
            Stop
          </button>
        </div>
      )}
    </div>
  );
}

// ─── Remote Download Progress Bar ─────────────────────────────────────────────
function RemoteDownloadProgress({ jobId, onDone }: { jobId: string; onDone?: () => void }) {
  const [job, setJob] = useState<DownloadJob | null>(null);
  const doneRef = useRef(false);

  useEffect(() => {
    let iv: number | undefined;

    const poll = async () => {
      try {
        const data = await api.getRemoteDownloadJob(jobId);
        setJob(data.job);
        if (data.job.status !== "running") {
          if (iv) window.clearInterval(iv);
          if (!doneRef.current) {
            doneRef.current = true;
            onDone?.();
          }
        }
      } catch {
        if (iv) window.clearInterval(iv);
      }
    };

    poll();
    iv = window.setInterval(poll, 1000);
    return () => { if (iv) window.clearInterval(iv); };
  }, [jobId, onDone]);

  if (!job) return null;

  const pct = job.totalBytes > 0 ? Math.min(100, (job.bytesDownloaded / job.totalBytes) * 100) : null;

  return (
    <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm backdrop-blur">
      <div className="mb-2 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-slate-800">{job.filename || "Downloading…"}</p>
          <p className="truncate text-xs text-slate-500">{job.url}</p>
        </div>
        <Badge color={
          job.status === "done"
            ? "bg-emerald-100 text-emerald-700"
            : job.status === "failed"
              ? "bg-red-100 text-red-700"
              : job.status === "stopped"
                ? "bg-slate-200 text-slate-700"
                : "bg-violet-100 text-violet-700"
        }>
          {job.status}
        </Badge>
      </div>

      <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100">
        {pct == null ? (
          <div className="h-full w-1/3 animate-pulse rounded-full bg-violet-500" />
        ) : (
          <div className="h-full rounded-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} />
        )}
      </div>

      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>{fmt(job.bytesDownloaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}</span>
        <span>{pct == null ? "…" : `${pct.toFixed(1)}%`}</span>
      </div>

      {job.error && <p className="mt-2 text-xs text-red-500">{job.error}</p>}

      {job.status === "running" && (
        <div className="mt-3 flex justify-end">
          <button
            onClick={() => api.stopRemoteDownloadJob(job.id)}
            className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50"
          >
            Stop
          </button>
        </div>
      )}
    </div>
  );
}

// ─── Upload Progress ──────────────────────────────────────────────────────────
function UploadProgress({ progress, onClose }: { progress: { bytesUploaded: number; totalBytes: number; fileCount: number; startTime: number } | null; onClose: () => void }) {
  const [stats, setStats] = useState<{ speed: number; eta: number }>({ speed: 0, eta: 0 });

  useEffect(() => {
    if (!progress) return;
    const elapsed = (Date.now() - progress.startTime) / 1000;
    if (elapsed > 0) {
      const speed = progress.bytesUploaded / elapsed;
      const remaining = progress.totalBytes - progress.bytesUploaded;
      const eta = speed > 0 ? remaining / speed : 0;
      setStats({ speed, eta });
    }
  }, [progress]);

  if (!progress) return null;

  const pct = progress.totalBytes > 0 ? Math.min(100, (progress.bytesUploaded / progress.totalBytes) * 100) : 0;

  return (
    <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm backdrop-blur">
      <div className="mb-2 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <p className="text-sm font-semibold text-slate-800">Uploading {progress.fileCount} file(s)</p>
          <p className="text-xs text-slate-500">
            {fmt(stats.speed)}/s · ETA {stats.eta > 0 ? fmtEta(stats.eta) : "calculating..."}
          </p>
        </div>
        <Badge color="bg-violet-100 text-violet-700">
          uploading
        </Badge>
      </div>

      <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100">
        <div className="h-full rounded-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} />
      </div>

      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>{fmt(progress.bytesUploaded)} / {fmt(progress.totalBytes)}</span>
        <span>{pct.toFixed(1)}%</span>
      </div>
    </div>
  );
}

// ─── Main App ─────────────────────────────────────────────────────────────────

function HighlightedText({ text, highlight }: { text: string; highlight: string }) {
  if (!highlight.trim()) return <>{text}</>;
  const escaped = highlight.replace(/[.*+?^\${}()|[\]\\]/g, '\\$&');
  const parts = text.split(new RegExp(`(${escaped})`, 'gi'));
  return (
    <>
      {parts.map((part, i) =>
        part.toLowerCase() === highlight.toLowerCase() ? (
          <mark key={i} className="rounded bg-yellow-200 px-1">{part}</mark>
        ) : (
          part
        )
      )}
    </>
  );
}

export default function App() {
  const [tab, setTab] = useState<Tab>("files");
  const [searchTerm, setSearchTerm] = useState("");
  const [extensionFilter, setExtensionFilter] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");

  // Debounce search input
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(searchTerm), 300);
    return () => clearTimeout(t);
  }, [searchTerm]);

  const [files, setFiles] = useState<FileEntry[]>([]);
  const [folders, setFolders] = useState<string[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string>("/");
  const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);
  const [loadingFiles, setLoadingFiles] = useState(true);
  const [fileSearch, setFileSearch] = useState("");
  const [remoteSearch, setRemoteSearch] = useState("");

  const [selectedForEncode, setSelectedForEncode] = useState<string>("");
  const [jobs, setJobs] = useState<Job[]>([]);
  const [downloadJobId, setDownloadJobId] = useState<string | null>(null);
  const [remoteDownloadJobId, setRemoteDownloadJobId] = useState<string | null>(null);
  const [pixeldrainJobIds, setPixeldrainJobIds] = useState<string[]>([]);
  const [toast, setToast] = useState<string | null>(null);

  const [showInfoFile, setShowInfoFile] = useState<FileEntry | null>(null);
  const [showPreviewFile, setShowPreviewFile] = useState<FileEntry | null>(null);
  const [showTrimFile, setShowTrimFile] = useState<FileEntry | null>(null);
  const [showCropFile, setShowCropFile] = useState<FileEntry | null>(null);
  const [showAdvancedTrimCropFile, setShowAdvancedTrimCropFile] = useState<FileEntry | null>(null);
  const [showMoveFiles, setShowMoveFiles] = useState<FileEntry[] | null>(null);
  const [showMergeFiles, setShowMergeFiles] = useState<FileEntry[] | null>(null);
  const [showCreateFolder, setShowCreateFolder] = useState(false);
  const [showCredentialsModal, setShowCredentialsModal] = useState(false);

  // Per-remote URL credentials storage
  const [remoteCredentials, setRemoteCredentials] = useState<Record<string, RemoteCredentials>>(() => {
    try {
      const saved = localStorage.getItem("remoteCredentials");
      return saved ? JSON.parse(saved) : {};
    } catch {
      return {};
    }
  });

  const [remoteUrl, setRemoteUrl] = useState("");
  const [remoteEntries, setRemoteEntries] = useState<RemoteEntry[]>([]);
  const [remoteLoading, setRemoteLoading] = useState(false);
  const [remoteError, setRemoteError] = useState<string | null>(null);
  const [remoteSelected, setRemoteSelected] = useState<string[]>([]);
  const remoteUploadRef = useRef<HTMLInputElement>(null);
  const [remoteUrlHistory, setRemoteUrlHistory] = useState<string[]>(() => {
    try { return JSON.parse(localStorage.getItem("remoteUrlHistory") || "[]"); } catch { return []; }
  });
  const [remoteShowHistory, setRemoteShowHistory] = useState(false);
  const remoteInputRef = useRef<HTMLInputElement>(null);

  // Get credentials for current remote URL
  const getCurrentRemoteCredentials = (url: string = remoteUrl): RemoteCredentials => {
    const normalizedUrl = normalizeRemoteUrl(url);
    return remoteCredentials[normalizedUrl] || { hfToken: '', hfS3AccessKeyId: '', hfS3SecretAccessKey: '' };
  };

    // Current URL's credentials
    const currentRemoteCreds = getCurrentRemoteCredentials(remoteUrl);
    const [remoteHfToken, setRemoteHfToken] = useState(currentRemoteCreds.hfToken);
    const [remoteHfS3AccessKeyId, setRemoteHfS3AccessKeyId] = useState(currentRemoteCreds.hfS3AccessKeyId);
    const [remoteHfS3SecretAccessKey, setRemoteHfS3SecretAccessKey] = useState(currentRemoteCreds.hfS3SecretAccessKey);

    // Update credentials for current remote URL
    const updateCurrentRemoteCredentials = (url: string, creds: Partial<RemoteCredentials>) => {
      const normalizedUrl = normalizeRemoteUrl(url);
      if (!normalizedUrl) return;
      
      setRemoteCredentials((prev) => {
        const newCreds = { ...prev };
        if (!newCreds[normalizedUrl]) {
          newCreds[normalizedUrl] = { hfToken: '', hfS3AccessKeyId: '', hfS3SecretAccessKey: '' };
        }
        if (creds.hfToken !== undefined) newCreds[normalizedUrl].hfToken = creds.hfToken;
        if (creds.hfS3AccessKeyId !== undefined) newCreds[normalizedUrl].hfS3AccessKeyId = creds.hfS3AccessKeyId;
        if (creds.hfS3SecretAccessKey !== undefined) newCreds[normalizedUrl].hfS3SecretAccessKey = creds.hfS3SecretAccessKey;
        
        try { localStorage.setItem("remoteCredentials", JSON.stringify(newCreds)); } catch {}
        return newCreds;
      });
    };

    // Load credentials when remoteUrl changes
    useEffect(() => {
      if (remoteUrl.trim()) {
        const creds = getCurrentRemoteCredentials(remoteUrl);
        setRemoteHfToken(creds.hfToken);
        setRemoteHfS3AccessKeyId(creds.hfS3AccessKeyId);
        setRemoteHfS3SecretAccessKey(creds.hfS3SecretAccessKey);
      }
    }, [remoteUrl]);

    // Save credentials to localStorage and remoteCredentials whenever they change
    useEffect(() => {
      if (!remoteUrl.trim()) return;
      updateCurrentRemoteCredentials(remoteUrl, {
        hfToken: remoteHfToken,
        hfS3AccessKeyId: remoteHfS3AccessKeyId,
        hfS3SecretAccessKey: remoteHfS3SecretAccessKey,
      });
    }, [remoteHfToken, remoteHfS3AccessKeyId, remoteHfS3SecretAccessKey, remoteUrl]);

  const saveRemoteUrlToHistory = (url: string) => {
    const base = url.trim();
    if (!base) return;
    setRemoteUrlHistory((prev) => {
      const next = [base, ...prev.filter((u) => u !== base)].slice(0, 20);
      try { localStorage.setItem("remoteUrlHistory", JSON.stringify(next)); } catch {}
      return next;
    });
  };
  const removeRemoteUrlFromHistory = (url: string) => {
    setRemoteUrlHistory((prev) => {
      const next = prev.filter((u) => u !== url);
      try { localStorage.setItem("remoteUrlHistory", JSON.stringify(next)); } catch {}
      return next;
    });
  };

  const [teleboxToken, setTeleboxToken] = useState("");
  const [teleboxWebToken, setTeleboxWebToken] = useState("");
  const [teleboxEntries, setTeleboxEntries] = useState<TeleboxEntry[]>([]);
  const [teleboxLoading, setTeleboxLoading] = useState(false);
  const [teleboxError, setTeleboxError] = useState<string | null>(null);
  const [teleboxSelected, setTeleboxSelected] = useState<string[]>([]);
  const [teleboxPid, setTeleboxPid] = useState(0);
  const [teleboxPath, setTeleboxPath] = useState<{ id: number; name: string }[]>([]);
  const teleboxUploadRef = useRef<HTMLInputElement>(null);

  // ── Generic S3-compatible storage state (Qencode media storage, Backblaze, etc) ──
  const [b2KeyId, setB2KeyId] = useState("");
  const [b2AppKey, setB2AppKey] = useState("");
  const [b2BucketName, setB2BucketName] = useState(() => {
    try { return localStorage.getItem("s3BucketName") || ""; } catch { return ""; }
  });
  // Path-style S3 management API host, e.g. "us-west.s3.qencode.com" (Qencode) or
  // "s3.us-east-005.backblazeb2.com" (Backblaze B2). Different providers use
  // different hosts, so this must be entered explicitly rather than assumed.
  const [b2Host, setB2Host] = useState(() => {
    try { return localStorage.getItem("s3Host") || "s3.us-east-005.backblazeb2.com"; } catch { return "s3.us-east-005.backblazeb2.com"; }
  });
  // Virtual-hosted CDN/playback host (e.g. https://<bucket>.media-storage.<region>.qencode.com).
  // Used ONLY for signed-URL playback links (Qencode-specific feature) — NOT for
  // list/upload/download/delete, which use the path-style host above instead.
  const [b2EndpointUrl, setB2EndpointUrl] = useState(() => {
    try { return localStorage.getItem("s3EndpointUrl") || ""; } catch { return ""; }
  });
  const [b2Region, setB2Region] = useState(() => {
    try { return localStorage.getItem("s3Region") || "us-east-005"; } catch { return "us-east-005"; }
  });
  const [b2Entries, setB2Entries] = useState<BackblazeEntry[]>([]);
  const [b2Loading, setB2Loading] = useState(false);
  const [b2Error, setB2Error] = useState<string | null>(null);
  const [b2Selected, setB2Selected] = useState<string[]>([]);
  const [b2Prefix, setB2Prefix] = useState("");
  const b2UploadRef = useRef<HTMLInputElement>(null);
  const [b2CfProxyUrl, setB2CfProxyUrl] = useState("");
  const [b2UploadingFileIds, setB2UploadingFileIds] = useState<Set<string>>(new Set());
  const [b2DownloadJobId, setB2DownloadJobId] = useState<string | null>(null);

  const setB2BucketNamePersist = (v: string) => {
    setB2BucketName(v);
    try { localStorage.setItem("s3BucketName", v); } catch {}
  };
  const setB2HostPersist = (v: string) => {
    setB2Host(v);
    try { localStorage.setItem("s3Host", v); } catch {}
  };
  const setB2EndpointUrlPersist = (v: string) => {
    setB2EndpointUrl(v);
    try { localStorage.setItem("s3EndpointUrl", v); } catch {}
  };
  const setB2RegionPersist = (v: string) => {
    setB2Region(v);
    try { localStorage.setItem("s3Region", v); } catch {}
  };

  // ── Saved storage connections (named presets) so switching providers/buckets
  // doesn't require re-typing bucket/host/region/keys every time. ──────────────
  type SavedS3Connection = {
    name: string;
    bucketName: string;
    region: string;
    host: string;
    endpointUrl: string;
    keyId: string;
    appKey: string;
  };
  const [b2SavedConnections, setB2SavedConnections] = useState<SavedS3Connection[]>(() => {
    try { return JSON.parse(localStorage.getItem("s3SavedConnections") || "[]"); } catch { return []; }
  });
  const [b2SelectedConnectionName, setB2SelectedConnectionName] = useState("");

  const persistSavedConnections = (list: SavedS3Connection[]) => {
    setB2SavedConnections(list);
    try { localStorage.setItem("s3SavedConnections", JSON.stringify(list)); } catch {}
  };

  const loadSavedConnection = (name: string) => {
    setB2SelectedConnectionName(name);
    const conn = b2SavedConnections.find((c) => c.name === name);
    if (!conn) return;
    setB2BucketNamePersist(conn.bucketName);
    setB2RegionPersist(conn.region);
    setB2HostPersist(conn.host);
    setB2EndpointUrlPersist(conn.endpointUrl);
    setB2KeyId(conn.keyId);
    setB2AppKey(conn.appKey);
  };

  const saveCurrentConnection = () => {
    const defaultName = b2BucketName.trim() || "Untitled connection";
    const name = (window.prompt("Save this connection as:", b2SelectedConnectionName || defaultName) || "").trim();
    if (!name) return;
    const conn: SavedS3Connection = {
      name, bucketName: b2BucketName.trim(), region: b2Region.trim(), host: b2Host.trim(),
      endpointUrl: b2EndpointUrl.trim(), keyId: b2KeyId.trim(), appKey: b2AppKey.trim(),
    };
    const next = [...b2SavedConnections.filter((c) => c.name !== name), conn];
    persistSavedConnections(next);
    setB2SelectedConnectionName(name);
    setToast(`Saved connection "${name}"`);
  };

  const deleteSavedConnection = (name: string) => {
    if (!confirm(`Delete saved connection "${name}"?`)) return;
    persistSavedConnections(b2SavedConnections.filter((c) => c.name !== name));
    if (b2SelectedConnectionName === name) setB2SelectedConnectionName("");
  };

  const browseS3 = async (prefix = b2Prefix) => {
    if (!b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()) return;
    setB2Loading(true);
    setB2Error(null);
    setB2Selected([]);
    const res = await api.s3List(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), prefix);
    setB2Loading(false);
    if (res.ok) {
      setB2Entries(res.entries);
      setB2Prefix(prefix);
    } else {
      setB2Error(res.error || "Failed to browse bucket");
    }
  };

  const uploadFilesToS3 = async (fileList: FileList | null) => {
    if (!fileList?.length || !b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()) return;
    for (const file of Array.from(fileList)) {
      const res = await api.s3Upload(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), file, b2Prefix);
      if (!res.ok && res.error) alert(`${file.name}: ${res.error}`);
    }
    setToast("Storage upload finished");
    browseS3();
  };

  const downloadFromS3 = async (key: string) => {
    const res = await api.s3Download(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-east-005", b2Host.trim(), key, selectedFolder || undefined, b2CfProxyUrl.trim() || undefined);
    if (res.jobId) {
      setB2DownloadJobId(res.jobId);
    } else {
      setToast(`Download failed: ${res.error || "unknown error"}`);
    }
  };

  const deleteFromS3 = async (key: string) => {
    if (!confirm(`Delete "${key}" from storage? This cannot be undone.`)) return;
    const res = await api.s3Delete(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), key);
    if (res.ok) {
      setToast("Deleted from storage");
      browseS3();
    } else {
      setToast(`Delete failed: ${res.error || "unknown error"}`);
    }
  };

  const toggleB2Selected = (key: string) => {
    setB2Selected((prev) => prev.includes(key) ? prev.filter((v) => v !== key) : [...prev, key]);
  };

  const getS3SignedLink = async (key: string) => {
    // Prefer the CF proxy URL — use ?b2File=&b2Bucket=&kid=&key= (native B2
    // download-by-name mode) so the link works for ANY filename including those
    // with spaces, parentheses, or other special characters.
    if (b2CfProxyUrl.trim() && b2BucketName.trim()) {
      const base = b2CfProxyUrl.trim().replace(/\/+$/, "");
      const b2File   = btoa(key);
      const b2Bucket = btoa(b2BucketName.trim());
      const kid      = btoa(b2KeyId.trim());
      const keyB64   = btoa(b2AppKey.trim());
      const url = `${base}?b2File=${encodeURIComponent(b2File)}&b2Bucket=${encodeURIComponent(b2Bucket)}&kid=${encodeURIComponent(kid)}&key=${encodeURIComponent(keyB64)}`;
      try {
        await navigator.clipboard.writeText(url);
        setToast("Direct link copied — free via Cloudflare proxy");
      } catch {
        setToast(url);
      }
      return;
    }
    // Fallback: S3 presigned URL (no CF proxy configured). Works anywhere but
    // egress goes through B2 directly and counts against bandwidth.
    if (b2KeyId.trim() && b2AppKey.trim() && b2BucketName.trim() && b2Host.trim()) {
      const res = await api.s3Presign(
        b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(),
        b2Region.trim() || "us-east-005", b2Host.trim(), key, 3600
      );
      if (res.ok && res.url) {
        try {
          await navigator.clipboard.writeText(res.url);
          setToast("Presigned link copied (valid 1 hour) — note: counts against B2 bandwidth");
        } catch {
          setToast(res.url);
        }
      } else {
        setToast(`Failed to create presigned link: ${res.error || "unknown error"}`);
      }
      return;
    }
    setToast("Enter a CF proxy URL or storage credentials to generate a link");
  };

  const isHfBucketUrlClient = (u: string) => /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/.test(u.trim());
  const remoteBucketMatch = remoteUrl.trim().match(/^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/);
  const remoteBucketPath = remoteBucketMatch ? (remoteBucketMatch[3] || "") : "";
  const remoteBreadcrumbParts = remoteBucketPath ? remoteBucketPath.split("/").filter(Boolean) : [];

  const [queue, setQueue] = useState<QueueItem[]>([]);
  const [presets, setPresets] = useState<EncodePreset[]>([]);
  const [presetLabel, setPresetLabel] = useState("");
  const [fileSortBy, setFileSortBy] = useState<"date" | "size" | "name">("date");
  const [fileSortDir, setFileSortDir] = useState<"asc" | "desc">("desc");
  const [downloadUrlInput, setDownloadUrlInput] = useState("");
  const [downloadUserInput, setDownloadUserInput] = useState("admin");
  const [downloadPassInput, setDownloadPassInput] = useState("1234");
  const [downloadBusy, setDownloadBusy] = useState(false);
  const [showDownloadAuth, setShowDownloadAuth] = useState(true);
  const [useFastDownload, setUseFastDownload] = useState(false);

  // ── Auto-upload to S3 after encode ───────────────────────────────────────────
  const [encodeAutoS3, setEncodeAutoS3] = useState(() => {
    try { return localStorage.getItem("encodeAutoS3") === "1"; } catch { return false; }
  });
  const setEncodeAutoS3Persist = (v: boolean) => {
    setEncodeAutoS3(v);
    try { localStorage.setItem("encodeAutoS3", v ? "1" : "0"); } catch {}
  };
  const autoS3JobIdsRef = useRef<Set<string>>(new Set());
  const prevJobStatusesRef = useRef<Map<string, string>>(new Map());

  const [uploadDragOver, setUploadDragOver] = useState(false);
  const [uploadBusy, setUploadBusy] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<{ bytesUploaded: number; totalBytes: number; fileCount: number; startTime: number } | null>(null);
  const uploadInputRef = useRef<HTMLInputElement | null>(null);
  const uploadFolderRef = useRef<HTMLInputElement | null>(null);
  const [forceStartMode, setForceStartMode] = useState(false);
  const [uploadDirectToRemote, setUploadDirectToRemoteState] = useState(() => {
    try { return localStorage.getItem("uploadDirectToRemote") === "1"; } catch { return false; }
  });
  const setUploadDirectToRemote = (v: boolean) => {
    setUploadDirectToRemoteState(v);
    try { localStorage.setItem("uploadDirectToRemote", v ? "1" : "0"); } catch {}
  };

  const [settings, setSettings] = useState<Record<string, unknown>>({
    codec: "av1",
    mode: "crf-1pass",
    crf: 45,
    videoBitrateKbps: 1200,
    audioBitrateKbps: 64,
    resolution: "original",
    frameRate: "original",
    preset: 8,
    h26xPreset: "medium",
    aqMode: 1,
    tiles: "2x2",
    outputContainer: "mkv",
    outputFilename: "",
    outputFormat: "video",
    stripSubtitles: false,
    stripMetadata: false,
    subtitleFile: "",
    subtitleLang: "eng",
    subtitleBurn: false,
    startTime: "",
    endTime: "",
    deinterlace: false,
    denoise: false,
    rotate: "none",
    speed: 1,
    brightness: 0,
    contrast: 1,
    saturation: 1,
    audioChannels: "same",
    sameAsOriginalAudio: false,
    sameAsOriginalVideo: false,
    cropEnabled: false,
    cropLeft: 0,
    cropRight: 0,
    cropTop: 0,
    cropBottom: 0,
    scaleWidth: "",
    scaleHeight: "",
    forceStereo: false,
    sceneChange: true,
  });

  const isAudioOnly = String(settings.outputFormat) === "audio";
  const copiesVideo = Boolean(settings.sameAsOriginalVideo);
  const copiesAudio = Boolean(settings.sameAsOriginalAudio);

  const selectedFile = files.find((f) => f.id === selectedForEncode) || null;
  const normalizedSearch = (fileSearch.trim() || debouncedSearch.trim()).toLowerCase();
  const isSearching = !!normalizedSearch;
  const visibleFiles = files.filter((f) => {
    const folder = f.folder || "/";
    if (selectedFolder !== "/" && folder !== selectedFolder) return false;
    if (selectedFolder === "/" && folder !== "/") return false;
    return true;
  });
  // When a search term is active, search across ALL files (all folders); otherwise use folder-scoped list
  const filteredVisibleFiles = (isSearching ? files : visibleFiles).filter((f) => {
    if (!normalizedSearch) return true;
    const haystack = `${f.name} ${f.folder || "/"}`.toLowerCase();
    return haystack.includes(normalizedSearch);
  });
  const sortedVisibleFiles = [...filteredVisibleFiles].sort((a, b) => {
    let result = 0;
    if (fileSortBy === "date") result = a.createdAt - b.createdAt;
    else if (fileSortBy === "size") result = a.sizeBytes - b.sizeBytes;
    else result = a.name.localeCompare(b.name);
    return fileSortDir === "asc" ? result : -result;
  });
  const selectedFiles = files.filter((f) => selectedFileIds.includes(f.id));
  const selectedMediaFiles = selectedFiles.filter((f) => isMediaFile(f.name));
  const selectedArchiveFiles = selectedFiles.filter((f) => isArchiveFile(f.name));
  const selectedSubtitleFiles = files.filter((f) => isSubtitleFile(f.name));

  const refreshFiles = useCallback(async () => {
    setLoadingFiles(true);
    try {
      const data = await api.getFiles();
      const all = [...(data.downloaded || []), ...(data.encoded || [])].sort((a, b) => b.createdAt - a.createdAt);
      setFiles(all);
      setFolders(data.folders || []);
      setSelectedFolder((prev) => {
        const allFolders = new Set(["/", ...(data.folders || [])]);
        return allFolders.has(prev) ? prev : "/";
      });
      setSelectedFileIds((prev) => prev.filter((id) => all.some((f) => f.id === id)));
      setSelectedForEncode((prev) => {
        if (prev && all.some((f) => f.id === prev)) return prev;
        const firstMedia = all.find((f) => isMediaFile(f.name));
        return firstMedia?.id || "";
      });
    } finally {
      setLoadingFiles(false);
    }
  }, []);

  const refreshJobs = useCallback(async () => {
    try {
      const next = await api.getJobs();
      setJobs(next.sort((a, b) => b.createdAt - a.createdAt));
    } catch {
      // ignore
    }
  }, []);

  useEffect(() => {
    refreshFiles();
    refreshJobs();
  }, [refreshFiles, refreshJobs]);

  // ── Server-side settings: load on mount ──────────────────────────────────────
  const settingsLoadedRef = useRef(false);

  useEffect(() => {
    (async () => {
      try {
        const s = await api.getSettings() as Record<string, unknown>;
        // Hydrate all credential state from server (server is source of truth)
        if (typeof s.b2KeyId === "string") setB2KeyId(s.b2KeyId);
        if (typeof s.b2AppKey === "string") setB2AppKey(s.b2AppKey);
        if (typeof s.b2BucketName === "string") { setB2BucketName(s.b2BucketName); try { localStorage.setItem("s3BucketName", s.b2BucketName); } catch {} }
        if (typeof s.b2Host === "string") { setB2Host(s.b2Host); try { localStorage.setItem("s3Host", s.b2Host); } catch {} }
        if (typeof s.b2EndpointUrl === "string") { setB2EndpointUrl(s.b2EndpointUrl); try { localStorage.setItem("s3EndpointUrl", s.b2EndpointUrl); } catch {} }
        if (typeof s.b2Region === "string") { setB2Region(s.b2Region); try { localStorage.setItem("s3Region", s.b2Region); } catch {} }
        if (typeof s.b2CfProxyUrl === "string") setB2CfProxyUrl(s.b2CfProxyUrl);
        if (Array.isArray(s.b2SavedConnections)) { setB2SavedConnections(s.b2SavedConnections as SavedS3Connection[]); try { localStorage.setItem("s3SavedConnections", JSON.stringify(s.b2SavedConnections)); } catch {} }
        if (typeof s.remoteUrl === "string") setRemoteUrl(s.remoteUrl);
        if (Array.isArray(s.remoteUrlHistory)) { setRemoteUrlHistory(s.remoteUrlHistory as string[]); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(s.remoteUrlHistory)); } catch {} }
        
        // Load per-remote credentials
        if (s.remoteCredentials && typeof s.remoteCredentials === 'object') {
          setRemoteCredentials(s.remoteCredentials as Record<string, RemoteCredentials>);
          try { localStorage.setItem("remoteCredentials", JSON.stringify(s.remoteCredentials)); } catch {}
        }
        
        // Legacy credentials - will be used as fallback
        if (typeof s.remoteHfToken === "string") setRemoteHfToken(s.remoteHfToken);
        if (typeof s.remoteHfS3AccessKeyId === "string") setRemoteHfS3AccessKeyId(s.remoteHfS3AccessKeyId);
        if (typeof s.remoteHfS3SecretAccessKey === "string") setRemoteHfS3SecretAccessKey(s.remoteHfS3SecretAccessKey);
        if (typeof s.teleboxToken === "string") setTeleboxToken(s.teleboxToken);
        if (typeof s.teleboxWebToken === "string") setTeleboxWebToken(s.teleboxWebToken);
        if (typeof s.encodeAutoS3 === "boolean") { setEncodeAutoS3(s.encodeAutoS3); try { localStorage.setItem("encodeAutoS3", s.encodeAutoS3 ? "1" : "0"); } catch {} }
        if (typeof s.uploadDirectToRemote === "boolean") { setUploadDirectToRemoteState(s.uploadDirectToRemote); try { localStorage.setItem("uploadDirectToRemote", s.uploadDirectToRemote ? "1" : "0"); } catch {} }
        if (Array.isArray(s.encodePresets)) setPresets(s.encodePresets as EncodePreset[]);
        else {
          // fallback: load encode presets from localStorage if not on server yet
          const saved = localStorage.getItem("encode_presets_v1");
          if (saved) { try { setPresets(JSON.parse(saved)); } catch {} }
        }
      } catch { /* server unreachable, fall back to localStorage */ }
      settingsLoadedRef.current = true;
    })();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ── Server-side settings: debounced save on any credential change ─────────────
  useEffect(() => {
    if (!settingsLoadedRef.current) return;
    const timer = setTimeout(() => {
      api.saveSettings({
        b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections,
        remoteUrl, remoteCredentials, remoteUrlHistory,
        teleboxToken, teleboxWebToken,
        encodeAutoS3, uploadDirectToRemote,
        encodePresets: presets,
      });
    }, 600);
    return () => clearTimeout(timer);
  }, [
    b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections,
    remoteUrl, remoteCredentials, remoteUrlHistory,
    teleboxToken, teleboxWebToken,
    encodeAutoS3, uploadDirectToRemote,
    presets,
  ]);

  useEffect(() => {
    if (!selectedFile) return;
    const ext = String(settings.outputContainer || "mkv");
    const base = selectedFile.name.replace(/\.[^.]+$/, "");
    setSettings((prev) => ({
      ...prev,
      outputFilename: `${base}_encoded.${ext}`,
    }));
  }, [selectedFile?.id, settings.outputContainer]);

  const toggleSelected = (id: string) => {
    setSelectedFileIds((prev) => prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]);
  };

  const clearSelected = () => setSelectedFileIds([]);

  const selectAllVisible = () => {
    setSelectedFileIds(filteredVisibleFiles.map((f) => f.id));
  };

  const deleteOne = async (file: FileEntry) => {
    if (!confirm(`Delete "${file.name}"?`)) return;
    await api.deleteFile(file.id);
    setToast("File deleted");
    refreshFiles();
  };

  const deleteSelected = async () => {
    if (!selectedFileIds.length) return;
    if (!confirm(`Delete ${selectedFileIds.length} selected file(s)?`)) return;
    await api.batchDelete(selectedFileIds);
    setToast(`${selectedFileIds.length} file(s) deleted`);
    clearSelected();
    refreshFiles();
  };

  const uploadSelectedToPixeldrain = async () => {
    if (!selectedFileIds.length) return;
    const res = await api.batchPixeldrain(selectedFileIds);
    setPixeldrainJobIds((prev) => [...res.jobIds, ...prev]);
    setToast(`Started ${res.jobIds.length} Pixeldrain upload(s)`);
  };

  const unzipSelected = async () => {
    if (!selectedArchiveFiles.length) return;
    for (const file of selectedArchiveFiles) {
      const res = await api.unzipFile(file.id);
      if (res.ok) {
        setToast(`Extracted ${file.name}`);
      }
    }
    refreshFiles();
  };

  const zipSelected = async () => {
    if (!selectedFileIds.length) return;
    const res = await api.batchZip(selectedFileIds);
    if (res.ok) {
      setToast(`Created ZIP: ${res.filename}`);
      refreshFiles();
    }
  };

  const renameFile = async (file: FileEntry) => {
    const next = prompt("New file name:", file.name);
    if (!next || next.trim() === file.name) return;
    const res = await api.renameFile(file.id, next.trim());
    if (res?.name) {
      setToast("File renamed");
      refreshFiles();
    }
  };

  const renameFolder = async (folderPath: string) => {
    if (folderPath === "/") return;
    const currentName = folderPath.split("/").filter(Boolean).pop() || "";
    const next = prompt("New folder name:", currentName);
    if (!next || next.trim() === currentName) return;
    const res = await api.renameFolder(folderPath, next.trim());
    if (res.ok) {
      setToast("Folder renamed");
      setSelectedFolder((prev) => prev === folderPath ? folderPath.replace(/[^/]+$/, next.trim()) : prev);
      refreshFiles();
    } else if (res.error) {
      alert(res.error);
    }
  };

  const deleteFolder = async (folderPath: string) => {
    if (folderPath === "/") return;
    if (!confirm(`Delete folder "${folderPath}" and all files inside it?`)) return;
    const res = await api.deleteFolder(folderPath);
    if (res.ok) {
      setToast("Folder deleted");
      setSelectedFolder("/");
      refreshFiles();
    } else if (res.error) {
      alert(res.error);
    }
  };

  const startUrlDownload = async () => {
    const url = downloadUrlInput.trim();
    if (!url) {
      setToast("Enter a URL first");
      return;
    }

    const username = downloadUserInput.trim() || undefined;
    const password = downloadPassInput.trim() || undefined;

    setDownloadBusy(true);
    try {
      const data = await api.startDownloadUrl(url, username, password, useFastDownload);
      setDownloadJobId(data.jobId);
      setToast("Download started");
      setTab("files");
    } catch (err) {
      console.error("Download failed:", err);
      setToast("Download failed");
    } finally {
      setDownloadBusy(false);
    }
  };

  const startEncode = async () => {
    if (!selectedFile) {
      setToast("Select a media file first");
      return;
    }

    // Check if there are running jobs and not in force-start mode
    if (!forceStartMode && runningJobs.length > 0) {
      addToQueue();
      setToast("Added to queue - waiting for current job to finish");
      return;
    }

    const outputContainer = String(settings.outputContainer || "mkv");
    const base = selectedFile.name.replace(/\.[^.]+$/, "");
    const outputFilename = String(settings.outputFilename || `${base}_encoded.${outputContainer}`);

    const normalizedSettings: Record<string, unknown> = {
      ...settings,
      fileId: selectedFile.id,
      inputFilename: selectedFile.relativePath || selectedFile.name,
      outputFilename,
      frameRate: settings.frameRate === "same" ? "original" : settings.frameRate,
      cropEnabled: Boolean(settings.cropEnabled),
      cropLeft: Number(settings.cropLeft ?? 0),
      cropRight: Number(settings.cropRight ?? 0),
      cropTop: Number(settings.cropTop ?? 0),
      cropBottom: Number(settings.cropBottom ?? 0),
      audioChannels:
        settings.audioChannels === "2"
          ? "stereo"
          : settings.audioChannels === "1"
            ? "mono"
            : settings.audioChannels,
      rotate:
        settings.rotate === "clockwise"
          ? "90cw"
          : settings.rotate === "counterclockwise"
            ? "90ccw"
            : settings.rotate,
      copyVideo: Boolean(settings.sameAsOriginalVideo),
      copyAudio: Boolean(settings.sameAsOriginalAudio),
    };

    try {
      const job = await api.startEncode(normalizedSettings);
      if (encodeAutoS3) autoS3JobIdsRef.current.add(job.id);
      setQueue((prev) => prev.map((q) => q.file.id === selectedFile.id && q.status === "waiting"
        ? { ...q, status: "encoding", jobId: job.id, settings: normalizedSettings }
        : q));
      setForceStartMode(false);
      setToast("Encode started");
      setTab("jobs");
      refreshJobs();
    } catch (err) {
      console.error("Encode failed:", err);
      setToast(err instanceof Error ? err.message : "Failed to start encode");
    }
  };

  const addToQueue = () => {
    if (!selectedFile) return;
    const uid = `queue_$${Math.random().toString(16).slice(2)}_$${Date.now().toString(16)}`;
    const preset = presets.find((p) => p.label === presetLabel);
    const item: QueueItem = {
      uid,
      file: selectedFile,
      status: "waiting",
      jobId: null,
      settings: {
        ...settings,
        fileId: selectedFile.id,
        inputFilename: selectedFile.relativePath || selectedFile.name,
        outputFilename: String(settings.outputFilename || `${selectedFile.name.replace(/\.[^.]+$/, "")}_encoded.${String(settings.outputContainer || "mkv")}`),
        frameRate: settings.frameRate === "same" ? "original" : settings.frameRate,
        cropEnabled: Boolean(settings.cropEnabled),
        cropLeft: Number(settings.cropLeft ?? 0),
        cropRight: Number(settings.cropRight ?? 0),
        cropTop: Number(settings.cropTop ?? 0),
        cropBottom: Number(settings.cropBottom ?? 0),
        audioChannels:
          settings.audioChannels === "2"
            ? "stereo"
            : settings.audioChannels === "1"
              ? "mono"
              : settings.audioChannels,
        rotate:
          settings.rotate === "clockwise"
            ? "90cw"
            : settings.rotate === "counterclockwise"
              ? "90ccw"
              : settings.rotate,
      },
      presetLabel: preset?.label || "",
    };
    setQueue((prev) => [...prev, item]);
    setToast("Added to queue");
  };

  const removeQueueItem = (uid: string) => {
    setQueue((prev) => prev.filter((q) => q.uid !== uid));
  };

  const startQueue = async () => {
    for (const item of queue) {
      if (item.status !== "waiting") continue;
      setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "encoding" } : q));
      try {
        const job = await api.startEncode(item.settings);
        setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, jobId: job.id } : q));
        let done = false;
        while (!done) {
          await new Promise((r) => setTimeout(r, 1500));
          const latest = await api.getJob(job.id);
          if (latest.status === "done") {
            setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "done", jobId: job.id } : q));
            done = true;
          } else if (latest.status === "failed" || latest.status === "stopped") {
            setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "failed", jobId: job.id } : q));
            done = true;
          }
        }
      } catch {
        setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "failed" } : q));
      }
    }
    setToast("Queue finished");
    refreshJobs();
    refreshFiles();
  };

  const savePreset = () => {
    const label = prompt("Preset name:", presetLabel || "My preset");
    if (!label?.trim()) return;
    const preset: EncodePreset = {
      id: Date.now(),
      label: label.trim(),
      settings: { ...settings },
    };
    setPresets((prev) => [preset, ...prev]);
    setPresetLabel(preset.label);
    setToast("Preset saved");
  };

  const loadPreset = (label: string) => {
    const preset = presets.find((p) => p.label === label);
    if (!preset) return;
    setPresetLabel(preset.label);
    setSettings((prev) => ({
      ...prev,
      ...preset.settings,
      outputFilename: prev.outputFilename,
    }));
    setToast("Preset loaded");
  };

  const deletePreset = (id: number) => {
    setPresets((prev) => prev.filter((p) => p.id !== id));
    setToast("Preset deleted");
  };

  const browseRemote = async (urlOverride?: string) => {
    const url = (urlOverride ?? remoteUrl).trim();
    if (!url) return;
    setRemoteShowHistory(false);
    setRemoteLoading(true);
    setRemoteError(null);
    try {
      // Get credentials for this specific URL
      const creds = getCurrentRemoteCredentials(url);
      const res = await api.remoteList(url, creds.hfToken.trim() || undefined);
      if (res.ok) {
        setRemoteEntries(res.entries || []);
        saveRemoteUrlToHistory(url);
      } else {
        setRemoteError(res.error || "Failed to fetch");
      }
    } finally {
      setRemoteLoading(false);
    }
  };

  const browseTelebox = async (nextPid = teleboxPid, nextPath = teleboxPath) => {
    if (!teleboxToken.trim()) {
      setTeleboxError("TeleBox token is required");
      return;
    }
    setTeleboxLoading(true);
    setTeleboxError(null);
    try {
      const res = await api.teleboxList(teleboxToken.trim(), nextPid);
      if (!res.ok) {
        setTeleboxError(res.error || "Failed to load TeleBox");
        setTeleboxEntries([]);
      } else {
        setTeleboxEntries(res.entries || []);
        setTeleboxPid(nextPid);
        setTeleboxPath(nextPath);
      }
    } finally {
      setTeleboxLoading(false);
    }
  };

  const openTeleboxFolder = async (entry: TeleboxEntry) => {
    const nextPath = [...teleboxPath, { id: Number(entry.id), name: entry.name }];
    await browseTelebox(Number(entry.id), nextPath);
  };

  const goTeleboxRoot = async () => {
    await browseTelebox(0, []);
  };

  const goTeleboxCrumb = async (idx: number) => {
    const nextPath = teleboxPath.slice(0, idx + 1);
    const nextPid = nextPath[idx]?.id ?? 0;
    await browseTelebox(nextPid, nextPath);
  };

  const createTeleboxFolder = async () => {
    if (!teleboxToken.trim()) {
      setTeleboxError("TeleBox token is required");
      return;
    }
    const name = prompt("New TeleBox folder name:");
    if (!name || !name.trim()) return;
    const res = await api.teleboxCreateFolder(teleboxToken.trim(), teleboxPid, name.trim());
    if (!res.ok) {
      setTeleboxError(res.error || "Failed to create folder");
      return;
    }
    setToast(`Created TeleBox folder: ${name.trim()}`);
    browseTelebox();
  };

  const toggleTeleboxSelected = (id: string) => {
    setTeleboxSelected((prev) => prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]);
  };

  const teleboxDownloadSelected = async () => {
    if (!teleboxWebToken.trim()) {
      setTeleboxError("TeleBox web session token is required for download");
      return;
    }
    const selectedItems = teleboxEntries.filter((e) => teleboxSelected.includes(e.id) && !e.isDir && e.itemId);
    let started = 0;
    for (const entry of selectedItems) {
      const res = await api.teleboxDownload(teleboxWebToken.trim(), String(entry.itemId), entry.name, selectedFolder);
      if (res.jobId) {
        setRemoteDownloadJobId(res.jobId);
        started++;
      } else if (!res.ok) {
        setTeleboxError(res.error || "TeleBox download failed");
      }
    }
    if (started > 0) setToast(`Started ${started} TeleBox download(s)`);
  };

  const uploadTeleboxFiles = async (files: FileList | null) => {
    if (!files?.length) return;
    if (!teleboxToken.trim()) {
      setTeleboxError("TeleBox token is required");
      return;
    }
    const res = await api.teleboxUpload(teleboxToken.trim(), teleboxPid, files);
    if (!res.ok) {
      setTeleboxError(res.error || "TeleBox upload failed");
      return;
    }
    setToast(`Uploaded ${files.length} file(s) to TeleBox`);
    browseTelebox();
  };

  const remoteDownloadSelected = async () => {
    if (!remoteSelected.length || !remoteUrl.trim()) return;
    let started = 0;
    for (const name of remoteSelected) {
      try {
        const entry = remoteEntries.find((e) => e.name === name);
        const creds = getCurrentRemoteCredentials(remoteUrl);
        const res = await api.remoteDownload(
          remoteUrl.trim(),
          name,
          selectedFolder,
          entry?.downloadUrl,
          {
            hfPath: entry?.hfPath,
            hfOrg: entry?.hfOrg,
            hfBucket: entry?.hfBucket,
          },
          creds.hfToken.trim()
        );
        if (res.error) {
          setToast(`Download failed: ${res.error}`);
          continue;
        }
        if (res.jobId) {
          console.log("Remote download job started:", res.jobId);
          setRemoteDownloadJobId(res.jobId);
          started++;
        }
      } catch (err) {
        setToast(`Download error: ${err instanceof Error ? err.message : "Unknown"}`);
      }
    }
    if (started > 0) {
      setToast(`Started ${started} remote download(s)`);
    }
  };
  const remoteRenameEntry = async (name: string) => {
    const next = prompt("New remote name:", name);
    if (!next || next.trim() === name || !remoteUrl.trim()) return;
    const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim());
    const creds = getCurrentRemoteCredentials(remoteUrl);
    if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) {
      setToast("S3 credentials required for HF bucket operations");
      return;
    }
    const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim(), hfToken: creds.hfToken.trim() } : undefined;
    const res = await api.remoteRename(remoteUrl.trim(), name, next.trim(), hfCreds);
    if (res.ok) {
      setToast("Remote item renamed");
      browseRemote();
    } else if (res.error) {
      alert(res.error);
    }
  };

  const remoteDeleteEntry = async (name: string) => {
    if (!remoteUrl.trim()) return;
    if (!confirm(`Delete remote item "${name}"?`)) return;
    const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim());
    const creds = getCurrentRemoteCredentials(remoteUrl);
    if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) {
      setToast("S3 credentials required for HF bucket operations");
      return;
    }
    const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() } : undefined;
    const res = await api.remoteDelete(remoteUrl.trim(), name, hfCreds);
    if (res.ok) {
      setToast("Remote item deleted");
      setRemoteSelected((prev) => prev.filter((v) => v !== name));
      browseRemote();
    } else if (res.error) {
      alert(res.error);
    }
  };

  const remoteMoveEntry = async (name: string) => {
    if (!remoteUrl.trim()) return;
    const targetFolder = prompt(`Move "${name}" to folder (e.g. "SubFolder" or "/" for root):`, "/");
    if (!targetFolder || !targetFolder.trim()) return;
    const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim());
    const creds = getCurrentRemoteCredentials(remoteUrl);
    if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) {
      setToast("S3 credentials required for HF bucket operations");
      return;
    }
    const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim(), hfToken: creds.hfToken.trim() } : undefined;
    const res = await api.remoteMove(remoteUrl.trim(), name, targetFolder.trim(), hfCreds);
    if (res.ok) {
      setToast(`Moved "${name}" to ${targetFolder.trim()}`);
      browseRemote();
    } else if (res.error) {
      alert(res.error);
    }
  };

  const remoteUploadFiles = async (fileList: FileList | null) => {
    if (!fileList?.length || !remoteUrl.trim()) return;
    const creds = getCurrentRemoteCredentials(remoteUrl);
    const hfCreds = { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() };
    for (const file of Array.from(fileList)) {
      const res = await api.remoteUpload(remoteUrl.trim(), file, hfCreds);
      if (!res.ok && res.error) {
        alert(`${file.name}: ${res.error}`);
      }
    }
    setToast("Remote upload finished");
    browseRemote();
  };

  const toggleRemoteSelected = (name: string) => {
    setRemoteSelected((prev) => prev.includes(name) ? prev.filter((v) => v !== name) : [...prev, name]);
  };

  const uploadFileToRemote = async (file: FileEntry) => {
    const target = remoteUrl.trim() || prompt("Remote server URL to upload to:", "") || "";
    if (!target.trim()) return;
    if (target.trim() !== remoteUrl.trim()) setRemoteUrl(target.trim());
    setToast(`Uploading ${file.name} to remote…`);
    
    // Check if this is an HF bucket and if we have S3 credentials
    const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(target.trim());
    if (isHfBucket && (!remoteHfS3AccessKeyId.trim() || !remoteHfS3SecretAccessKey.trim())) {
      setToast("For HF buckets, you need S3 credentials. Get them at huggingface.co/settings/tokens → token menu → 'Generate S3 credentials'");
      return;
    }
    
    const hfCreds = { accessKeyId: remoteHfS3AccessKeyId.trim(), secretAccessKey: remoteHfS3SecretAccessKey.trim() };
    const res = await api.uploadFileToRemote(file.id, target.trim(), hfCreds);
    if (res.ok) {
      saveRemoteUrlToHistory(target.trim());
      setToast(`Uploaded ${file.name} to remote`);
    } else {
      setToast(`Remote upload failed: ${res.error || "unknown error"}`);
    }
  };

  const uploadFileToB2 = async (file: FileEntry) => {
    const connOk = b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim();
    if (!connOk) {
      setToast("Configure Backblaze B2 credentials in the Storage tab first");
      return;
    }
    setB2UploadingFileIds((prev) => new Set(prev).add(file.id));
    setToast(`Uploading ${file.name} to Backblaze…`);
    try {
      const res = await api.s3UploadLocal(
        null, file.id,
        b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(),
        b2Region.trim() || "us-west", b2Host.trim(), b2Prefix || undefined
      );
      if (res.ok) {
        setToast(`Uploaded to Backblaze: ${res.filename ?? file.name}`);
      } else {
        setToast(`Backblaze upload failed: ${res.error || "unknown error"}`);
      }
    } finally {
      setB2UploadingFileIds((prev) => { const next = new Set(prev); next.delete(file.id); return next; });
    }
  };

  const stopJob = async (id: string) => {
    await api.stopJob(id);
    setToast("Job stop requested");
    refreshJobs();
  };

  const handleFileUpload = async (fileListOrArray: FileList | (File & { __folderPath?: string })[]) => {
    if (!fileListOrArray || (Array.isArray(fileListOrArray) ? fileListOrArray.length === 0 : fileListOrArray.length === 0)) return;

    if (uploadDirectToRemote) {
      const target = remoteUrl.trim();
      if (!target) {
        setToast("Enter a remote server URL first");
        return;
      }
      const files = Array.from(fileListOrArray);
      setUploadBusy(true);
      const totalBytes = files.reduce((sum, f) => sum + (f as File).size, 0);
      setUploadProgress({ bytesUploaded: 0, totalBytes, fileCount: files.length, startTime: Date.now() });
      let uploaded = 0;
      let bytesDone = 0;
      let failed = 0;
      const creds = getCurrentRemoteCredentials(target);
      const hfCreds = { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() };
      try {
        for (const file of files) {
          try {
            const res = await api.remoteUpload(target, file as File, hfCreds);
            if (res.ok) {
              uploaded++;
            } else {
              failed++;
              console.error("Remote upload failed:", res.error);
            }
          } catch (err) {
            failed++;
            console.error("Remote upload error:", err);
          }
          bytesDone += (file as File).size;
          setUploadProgress(prev => prev ? { ...prev, bytesUploaded: bytesDone } : null);
        }
        saveRemoteUrlToHistory(target);
        setToast(
          failed
            ? `Uploaded ${uploaded}/${files.length} file(s) to remote (${failed} failed)`
            : `Uploaded ${uploaded} file(s) directly to remote`
        );
      } finally {
        setUploadBusy(false);
        setTimeout(() => setUploadProgress(null), 2000);
        if (uploadInputRef.current) uploadInputRef.current.value = "";
        if (uploadFolderRef.current) uploadFolderRef.current.value = "";
      }
      return;
    }

    setUploadBusy(true);
    setUploadProgress({ bytesUploaded: 0, totalBytes: 0, fileCount: 0, startTime: Date.now() });
    
    try {
      const files = Array.from(fileListOrArray);
      const formData = new FormData();
      let totalBytes = 0;
      
      // Add files and their relative paths, calculate total size
      for (let i = 0; i < files.length; i++) {
        const file = files[i] as any;
        formData.append("files", file);
        totalBytes += file.size;
        
        // Include folder structure if available (from webkitRelativePath or custom path)
        if (file.webkitRelativePath) {
          const pathParts = file.webkitRelativePath.split("/");
          if (pathParts.length > 1) {
            const folderPath = pathParts.slice(0, -1).join("/");
            formData.append(`folderPath_${i}`, folderPath);
          }
        } else if (file.__folderPath) {
          formData.append(`folderPath_${i}`, file.__folderPath);
        }
      }
      
      if (selectedFolder && selectedFolder !== "/") {
        formData.append("folderPath", selectedFolder);
      }
      
      // Update progress with file count and total size
      setUploadProgress(prev => prev ? { ...prev, totalBytes, fileCount: files.length } : null);
      
      // Use XMLHttpRequest for upload progress tracking
      await new Promise<void>((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        xhr.upload.addEventListener("progress", (e) => {
          if (e.lengthComputable) {
            setUploadProgress(prev => prev ? { ...prev, bytesUploaded: e.loaded } : null);
          }
        });
        
        xhr.addEventListener("load", () => {
          if (xhr.status === 200) {
            try {
              const data = JSON.parse(xhr.responseText);
              if (data.ok) {
                setToast(`Uploaded ${files.length} file(s)`);
                refreshFiles();
                resolve();
              } else {
                reject(new Error(data.error || "Upload failed"));
              }
            } catch (err) {
              reject(err);
            }
          } else {
            reject(new Error(`Upload failed with status ${xhr.status}`));
          }
        });
        
        xhr.addEventListener("error", () => {
          reject(new Error("Upload failed"));
        });
        
        xhr.open("POST", "/api/files/upload");
        xhr.send(formData);
      });
    } catch (err) {
      console.error("Upload error:", err);
      setToast(`Upload error: ${err instanceof Error ? err.message : "Unknown error"}`);
    } finally {
      setUploadBusy(false);
      setTimeout(() => setUploadProgress(null), 2000);
      if (uploadInputRef.current) uploadInputRef.current.value = "";
      if (uploadFolderRef.current) uploadFolderRef.current.value = "";
    }
  };

  const runningJobs = jobs.filter((j) => j.status === "running");
  const finishedJobs = jobs.filter((j) => j.status !== "running");

  // ─── Real-time job polling ────────────────────────────────────────────────
  // Poll jobs every 1.5s while there are running jobs for live progress updates
  useEffect(() => {
    if (runningJobs.length === 0) return;
    const iv = setInterval(() => {
      refreshJobs();
    }, 1500);
    return () => clearInterval(iv);
  }, [runningJobs.length, refreshJobs]);

  // ─── Auto-upload to S3 when encode job completes ──────────────────────────
  useEffect(() => {
    for (const job of jobs) {
      const prev = prevJobStatusesRef.current.get(job.id);
      if (prev === "running" && job.status === "done" && autoS3JobIdsRef.current.has(job.id)) {
        autoS3JobIdsRef.current.delete(job.id);
        const connOk = b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim();
        if (connOk) {
          (async () => {
            setToast("Uploading encoded file to S3…");
            const res = await api.s3UploadLocal(
              job.id, null,
              b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(),
              b2Region.trim() || "us-west", b2Host.trim(), b2Prefix || undefined
            );
            if (res.ok) {
              setToast(`Uploaded to S3: ${res.filename}`);
              browseS3();
            } else {
              setToast(`S3 upload failed: ${res.error || "unknown error"}`);
            }
          })();
        }
      }
      prevJobStatusesRef.current.set(job.id, job.status);
    }
  }, [jobs]);

  // Auto-start next queue item when a job finishes
  useEffect(() => {
    const queueWaiting = queue.filter((q) => q.status === "waiting");
    const hasRunningJobs = runningJobs.length > 0;

    if (queueWaiting.length > 0 && !hasRunningJobs) {
      const timer = setTimeout(() => {
        const nextItem = queueWaiting[0];
        if (nextItem) {
          setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "encoding" } : q));
          (async () => {
            try {
              const job = await api.startEncode(nextItem.settings);
              setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, jobId: job.id } : q));
            } catch (err) {
              console.error("Failed to start queue item:", err);
              setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "failed" } : q));
            }
          })();
        }
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, [queue, jobs]);

  const isFileSelected = (id: string) => selectedFileIds.includes(id);

  const handleSortFiles = (key: "date" | "size" | "name") => {
    if (fileSortBy === key) {
      setFileSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setFileSortBy(key);
      setFileSortDir(key === "name" ? "asc" : "desc");
    }
  };

  const sortIndicator = (key: "date" | "size" | "name") =>
    fileSortBy === key ? (fileSortDir === "asc" ? " ▲" : " ▼") : "";

  // ─── Compact bulk action button style ───────────────────────────────────────
  const bulkBtn = "rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-[11px] font-semibold text-slate-600 hover:bg-slate-50 hover:border-slate-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors whitespace-nowrap";
  const bulkBtnDanger = "rounded-lg border border-red-200 bg-white px-2.5 py-1.5 text-[11px] font-semibold text-red-600 hover:bg-red-50 hover:border-red-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors whitespace-nowrap";

    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50 text-slate-900">
        <div className="mx-auto max-w-7xl px-3 sm:px-6 lg:px-8">
           {/* Sticky header with app title, tabs, and refresh buttons - all pinned when scrolling */}
           <header className="sticky top-0 z-50 mb-4 flex flex-col gap-2 rounded-2xl border border-slate-200 bg-white/90 px-4 py-3 shadow-lg backdrop-blur-sm">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-center gap-3">
                <div className="inline-flex items-center gap-2 rounded-full bg-violet-100 px-3 py-1 text-xs font-semibold text-violet-700">
                  OgA-Encoder
                </div>
                <h1 className="hidden text-xl font-black tracking-tight text-slate-900 sm:block">Encode, Trim, Merge, Move</h1>
              </div>

              {/* Tab navigation - on same line as title in header */}
              <div className="flex w-full items-center gap-1 overflow-x-auto sm:w-auto sm:flex-wrap">
                {([
                  ["files", "Files", files.length, `${new Set(["/", ...folders]).size} folders`],
                  ["encode", "Encode", queue.length, "queue"],
                  ["jobs", "Jobs", runningJobs.length, "running"],
                  ["remote", "Remote", remoteEntries.length, "entries"],
                  ["telebox", "TeleBox", teleboxEntries.length, "cloud"],
                  ["backblaze", "Storage", b2Entries.length, "S3 bucket"],
                ] as [Tab, string, number, string][]).map(([value, label, count, meta]) => (
                  <button
                    key={value}
                    onClick={() => setTab(value)}
                    className={`min-w-[110px] flex-shrink-0 rounded-lg border px-3 py-2 text-left transition ${
                      tab === value
                        ? "border-violet-500 bg-violet-600 text-white shadow-sm"
                        : "border-slate-200 bg-white text-slate-700 hover:bg-slate-50"
                    }`}
                  >
                    <div className="flex items-center justify-between gap-2">
                      <div className="min-w-0">
                        <div className="text-xs font-semibold">{label}</div>
                        <div className={`text-[10px] ${tab === value ? "text-violet-100" : "text-slate-400"}`}>
                          {meta}
                        </div>
                      </div>
                      <span className={`rounded-full px-1.5 py-0.5 text-[10px] font-bold ${
                        tab === value
                          ? "bg-white/20 text-white"
                          : "bg-slate-100 text-slate-600"
                      }`}>
                        {count}
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Refresh buttons - under tabs but still in header area */}
            <div className="flex w-full items-center gap-2 rounded-xl border border-slate-200 bg-white/50 px-4 py-2 sm:flex-wrap">
              <button
                onClick={refreshFiles}
                className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:border-violet-200 hover:text-violet-700"
              >
                Refresh Files
              </button>
              <button
                onClick={refreshJobs}
                className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:border-violet-200 hover:text-violet-700"
              >
                Refresh Jobs
              </button>
            </div>
          </header>

          {/* ══════════════════════════════════════════════════════════════════════
              FIX 3: Compact download bar — single row, much smaller footprint
             ══════════════════════════════════════════════════════════════════════ */}
          <div className="mb-3 rounded-xl border border-slate-200 bg-white/90 px-3 py-2 shadow-sm backdrop-blur">
            <div className="flex items-center gap-2 flex-wrap">
              <svg className="h-4 w-4 flex-shrink-0 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" />
              </svg>
              <input
                type="text"
                value={downloadUrlInput}
                onChange={(e) => setDownloadUrlInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); startUrlDownload(); } }}
                placeholder="Paste download URL…"
                className="min-w-0 flex-1 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100"
              />
              {showDownloadAuth && (
                <>
                  <input
                    type="text"
                    value={downloadUserInput}
                    onChange={(e) => setDownloadUserInput(e.target.value)}
                    placeholder="User"
                    className="w-24 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100"
                  />
                  <input
                    type="password"
                    value={downloadPassInput}
                    onChange={(e) => setDownloadPassInput(e.target.value)}
                    onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); startUrlDownload(); } }}
                    placeholder="Pass"
                    className="w-24 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100"
                  />
                </>
              )}
              <button
                type="button"
                onClick={() => setShowDownloadAuth((v) => !v)}
                className="rounded-lg border border-slate-200 px-2 py-1.5 text-[10px] font-semibold text-slate-500 hover:bg-slate-50 hover:text-slate-700 transition-colors"
                title="Toggle auth fields"
              >
                {showDownloadAuth ? "Hide auth" : "🔑 Auth"}
              </button>
              <button
                type="button"
                onClick={() => setUseFastDownload((v) => !v)}
                title="Fast mode uses yt-dlp + aria2c with 16 parallel connections"
                className={`rounded-lg border px-2 py-1.5 text-[10px] font-semibold transition-colors ${
                  useFastDownload
                    ? "border-amber-400 bg-amber-50 text-amber-700 hover:bg-amber-100"
                    : "border-slate-200 text-slate-500 hover:bg-slate-50 hover:text-slate-700"
                }`}
              >
                ⚡ Fast
              </button>
              <button
                onClick={startUrlDownload}
                disabled={downloadBusy || !downloadUrlInput.trim()}
                className="rounded-lg bg-violet-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors"
              >
                {downloadBusy ? "…" : "Download"}
              </button>
            </div>
          </div>

         {downloadJobId && (
          <div className="mb-4">
            <DownloadProgress
              jobId={downloadJobId}
              onDone={() => {
                refreshFiles();
                refreshJobs();
                setDownloadJobId(null);
              }}
            />
          </div>
        )}

        {remoteDownloadJobId && (
          <div className="mb-4">
            <RemoteDownloadProgress
              jobId={remoteDownloadJobId}
              onDone={() => {
                refreshFiles();
                refreshJobs();
                setRemoteDownloadJobId(null);
              }}
            />
          </div>
        )}

        {b2DownloadJobId && (
          <div className="mb-4">
            <DownloadProgress
              jobId={b2DownloadJobId}
              onDone={() => {
                refreshFiles();
                setB2DownloadJobId(null);
              }}
            />
          </div>
        )}

        {!!pixeldrainJobIds.length && (
          <div className="mb-4 space-y-3">
            {pixeldrainJobIds.map((jobId) => (
              <PixeldrainProgress
                key={jobId}
                jobId={jobId}
                onClose={() => setPixeldrainJobIds((prev) => prev.filter((id) => id !== jobId))}
              />
            ))}
          </div>
        )}

        {tab === "files" && (
          <section className="space-y-4">
            <UploadArea
              onFilesSelected={handleFileUpload}
              busy={uploadBusy}
              dragOver={uploadDragOver}
              onDragOver={(e) => { e.preventDefault(); setUploadDragOver(true); }}
              onDragLeave={(e) => { e.preventDefault(); setUploadDragOver(false); }}
              uploadInputRef={uploadInputRef}
              uploadFolderRef={uploadFolderRef}
            />

            {/* Upload Progress */}
            {uploadProgress && (
              <UploadProgress
                progress={uploadProgress}
                onClose={() => setUploadProgress(null)}
              />
            )}

            {/* ══════════════════════════════════════════════════════════════════
                FIX 2: Folder filter — always visible actions, long names truncate
               ══════════════════════════════════════════════════════════════════ */}
            <div className="rounded-2xl border border-slate-200 bg-white/90 p-3 shadow-sm">
              <div className="flex items-center justify-between mb-2">
                <h2 className="text-xs font-bold uppercase tracking-wider text-slate-500">Folders</h2>
                <button
                  onClick={() => setShowCreateFolder(true)}
                  className="rounded-lg bg-violet-600 px-2.5 py-1 text-[10px] font-semibold text-white hover:bg-violet-700"
                >
                  + New
                </button>
              </div>
              <div className="flex flex-wrap gap-1.5">
                {/* Root folder */}
                <div className="inline-flex items-center">
                  <button
                    onClick={() => setSelectedFolder("/")}
                    className={`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition ${
                      selectedFolder === "/"
                        ? "bg-violet-100 text-violet-700 ring-1 ring-violet-300"
                        : "bg-slate-50 text-slate-600 hover:bg-slate-100"
                    }`}
                  >
                    <span className="text-[10px]">📂</span>
                    <span>/ root</span>
                    <span className="rounded-full bg-white/80 px-1.5 text-[10px] text-slate-400">{files.filter((f) => (f.folder || "/") === "/").length}</span>
                  </button>
                  <a href="/api/folders/zip?folder=/" download className="ml-0.5 rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-violet-600 transition-colors" title="Download root as ZIP">
                    <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" /></svg>
                  </a>
                </div>

                {Array.from(new Set(folders))
                  .sort((a, b) => a.localeCompare(b))
                  .map((folder) => {
                    const count = files.filter((f) => (f.folder || "/") === folder).length;
                    const active = selectedFolder === folder;
                    return (
                      <div key={folder} className="inline-flex items-center group">
                        <button
                          onClick={() => setSelectedFolder(folder)}
                          className={`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition max-w-[200px] ${
                            active
                              ? "bg-violet-100 text-violet-700 ring-1 ring-violet-300"
                              : "bg-slate-50 text-slate-600 hover:bg-slate-100"
                          }`}
                          title={folder}
                        >
                          <span className="text-[10px] flex-shrink-0">📁</span>
                          <span className="truncate">{folder}</span>
                          <span className="flex-shrink-0 rounded-full bg-white/80 px-1.5 text-[10px] text-slate-400">{count}</span>
                        </button>
                        {/* FIX 2: Always-visible rename/delete — no hover-hidden */}
                        <button
                          onClick={() => renameFolder(folder)}
                          className="ml-0.5 rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-slate-600 transition-colors"
                          title="Rename folder"
                        >
                          <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" />
                          </svg>
                        </button>
                        <button
                          onClick={() => deleteFolder(folder)}
                          className="rounded p-1 text-slate-300 hover:bg-red-50 hover:text-red-500 transition-colors"
                          title="Delete folder"
                        >
                          <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673A2.25 2.25 0 0 1 15.916 21.75H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" />
                          </svg>
                        </button>
                        <a
                          href={`/api/folders/zip?folder=${encodeURIComponent(folder)}`}
                          download
                          className="rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-violet-600 transition-colors"
                          title="Download folder as ZIP"
                        >
                          <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" />
                          </svg>
                        </a>
                      </div>
                    );
                  })}
              </div>
            </div>

            {/* ══════════════════════════════════════════════════════════════════
                FIX 1: Bulk actions — only appear when files are selected,
                shown as a compact sticky bar above the file list
               ══════════════════════════════════════════════════════════════════ */}
            {selectedFileIds.length > 0 && (
              <div className="sticky top-0 z-30 rounded-xl border border-violet-200 bg-violet-50/95 px-3 py-2 shadow-sm backdrop-blur-sm">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs font-bold text-violet-700 flex-shrink-0">
                    {selectedFileIds.length} selected
                  </span>
                  <div className="h-4 w-px bg-violet-200 flex-shrink-0" />
                  <button onClick={selectAllVisible} disabled={!filteredVisibleFiles.length} className={bulkBtn}>Select all visible</button>
                  <button onClick={clearSelected} className={bulkBtn}>Clear</button>
                  <button onClick={() => setShowMoveFiles(selectedFiles)} className={bulkBtn}>Move</button>
                  <button onClick={zipSelected} className={bulkBtn}>Zip</button>
                  {selectedArchiveFiles.length > 0 && (
                    <button onClick={unzipSelected} className={bulkBtn}>Unzip</button>
                  )}
                  {selectedMediaFiles.length >= 2 && (
                    <button onClick={() => setShowMergeFiles(selectedMediaFiles)} className={bulkBtn}>Merge</button>
                  )}
                  <button onClick={uploadSelectedToPixeldrain} className={bulkBtn}>Pixeldrain</button>
                  <button onClick={deleteSelected} className={bulkBtnDanger}>Delete</button>
                </div>
              </div>
            )}

            {/* File table / cards — now full width, no sidebar */}
            <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm">
              <div className="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  {isSearching ? (
                    <>
                      <h2 className="text-sm font-bold text-slate-900">
                        Search results
                        <span className="ml-2 text-xs font-normal text-slate-400">across all folders</span>
                      </h2>
                      <p className="text-xs text-slate-500">
                        {filteredVisibleFiles.length} file{filteredVisibleFiles.length !== 1 ? "s" : ""} matching &ldquo;{normalizedSearch}&rdquo;
                      </p>
                    </>
                  ) : (
                    <>
                      <h2 className="text-sm font-bold text-slate-900">Files in {selectedFolder === "/" ? "/ (root)" : selectedFolder}</h2>
                      <p className="text-xs text-slate-500">
                        {loadingFiles ? "Loading files…" : `${visibleFiles.length} file(s) in this folder`}
                      </p>
                    </>
                  )}
                </div>
                <div className="flex items-center gap-3 text-xs text-slate-500">
                  {!isSearching && (
                    <span className="rounded-full bg-slate-100 px-2.5 py-1 font-semibold text-slate-700">
                      {filteredVisibleFiles.length} matching
                    </span>
                  )}
                  <span>Sort:</span>
                  <button type="button" onClick={() => handleSortFiles("name")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "name" ? "text-violet-600" : ""}`}>
                    Name{sortIndicator("name")}
                  </button>
                  <button type="button" onClick={() => handleSortFiles("size")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "size" ? "text-violet-600" : ""}`}>
                    Size{sortIndicator("size")}
                  </button>
                  <button type="button" onClick={() => handleSortFiles("date")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "date" ? "text-violet-600" : ""}`}>
                    Date{sortIndicator("date")}
                  </button>
                </div>
              </div>
              <div className="flex flex-col gap-2 px-3 py-2 sm:flex-row">
                {/* Search input with clear button */}
                <div className="relative flex-1">
                  <svg className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0Z" />
                  </svg>
                  <input
                    type="text"
                    value={fileSearch}
                    onChange={(e) => setFileSearch(e.target.value)}
                    placeholder="Search all folders…"
                    className="w-full rounded-xl border border-slate-200 py-2 pl-9 pr-8 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                  />
                  {fileSearch && (
                    <button
                      onClick={() => setFileSearch("")}
                      className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
                      title="Clear search"
                    >
                      <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                      </svg>
                    </button>
                  )}
                </div>
                <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600">
                  <span className="font-semibold">Filter:</span>
                  <select
                    value={extensionFilter}
                    onChange={(e) => setExtensionFilter(e.target.value)}
                    className="rounded border border-slate-200 bg-white px-2 py-1 text-xs"
                  >
                    <option value="">All types</option>
                    <option value="video">Video</option>
                    <option value="archive">Archive</option>
                    <option value="subtitle">Subtitle</option>
                  </select>
                </div>
              </div>
            </div>


              {/* MOBILE_FILE_CARDS_START */}
              <div className="md:hidden">
                {loadingFiles ? (
                  <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-8 text-center text-sm text-slate-400">
                    Loading files…
                  </div>
                ) : !sortedVisibleFiles.length ? (
                  <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-8 text-center text-sm text-slate-400">
                    {isSearching ? `No files match "${normalizedSearch}"` : "No files in this folder."}
                  </div>
                ) : (
                  <div className="divide-y divide-slate-100">
                    {sortedVisibleFiles.map((file) => {
                      const selected = isFileSelected(file.id);
                      const media = isMediaFile(file.name);
                      const archive = isArchiveFile(file.name);
                      const downloadUrl = `/api/files/${encodeURIComponent(file.id)}/download`;
                      const uploadInFlight = b2UploadingFileIds.has(file.id);
                      const queueItem = queue.find((q) => q.file.id === file.id && (q.status === "waiting" || q.status === "encoding"));
                      const activityBadge = uploadInFlight ? (
                        <Badge color="bg-amber-100 text-amber-700">uploading</Badge>
                      ) : queueItem ? (
                        <Badge color="bg-orange-100 text-orange-700">{queueItem.status === "waiting" ? "queued" : "processing"}</Badge>
                      ) : null;

                      const smallBtn =
                        "inline-flex h-8 min-w-8 items-center justify-center rounded-lg border border-slate-200 bg-white px-2 text-[11px] font-semibold text-slate-600 hover:bg-slate-50";

                      return (
                        <div key={file.id} className={`space-y-3 px-4 py-4 ${selected ? "bg-violet-50/70" : "bg-white"}`}>
                          <div className="flex items-start gap-3">
                            <input
                              type="checkbox"
                              checked={selected}
                              onChange={() => toggleSelected(file.id)}
                              className="mt-1 h-4 w-4 flex-shrink-0 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                            />

                            <div className="min-w-0 flex-1">
                              <div className="break-words text-sm font-bold leading-snug text-slate-900">
                                {file.name}
                              </div>

                              <div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
                                <Badge color={file.source === "encoded" ? "bg-violet-100 text-violet-700" : "bg-sky-100 text-sky-700"}>{file.source}</Badge>
                                {media && <Badge color="bg-emerald-100 text-emerald-700">media</Badge>}
                                {archive && <Badge color="bg-amber-100 text-amber-700">archive</Badge>}
                                {isSubtitleFile(file.name) && <Badge color="bg-sky-100 text-sky-700">subtitle</Badge>}
                                {activityBadge}
                                <span>{fmt(file.sizeBytes)}</span>
                              </div>

                              {isSearching && (
                                <div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400">
                                  <svg className="h-3 w-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-2.12-2.12a1.5 1.5 0 0 0-1.061-.44H4.5A2.25 2.25 0 0 0 2.25 6v12a2.25 2.25 0 0 0 2.25 2.25h15A2.25 2.25 0 0 0 21.75 18V9a2.25 2.25 0 0 0-2.25-2.25h-5.379a1.5 1.5 0 0 1-1.06-.44Z" />
                                  </svg>
                                  <span className="font-mono">{file.folder || "/"}</span>
                                </div>
                              )}

                              <div className="mt-1 text-[11px] text-slate-400">
                                {new Date(file.createdAt).toLocaleString([], {
                                  year: "2-digit",
                                  month: "2-digit",
                                  day: "2-digit",
                                  hour: "2-digit",
                                  minute: "2-digit",
                                })}
                              </div>
                            </div>
                          </div>

                          <div className="flex flex-wrap gap-1.5 pl-7">
                            <button type="button" title="Info" onClick={() => setShowInfoFile(file)} className={smallBtn}>
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25 12 17.25m0-9.75h.008v.008H12V7.5Zm9 4.5a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                              </svg>
                              Info
                            </button>

                            {media && (
                              <button type="button" title="Preview" onClick={() => setShowPreviewFile(file)} className={smallBtn}>
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.574 0 3.286L8.03 20.99c-1.25.687-2.779-.216-2.779-1.643V5.653Z" />
                                </svg>
                                Preview
                              </button>
                            )}

                            {media && (
                              <button
                                type="button"
                                title="Encode"
                                onClick={() => {
                                  setSelectedForEncode(file.id);
                                  setTab("encode");
                                }}
                                className={smallBtn}
                              >
                                Encode
                              </button>
                            )}

                            {media && (
                              <button type="button" title="Trim" onClick={() => setShowTrimFile(file)} className={smallBtn}>
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <circle cx="6" cy="6" r="3" />
                                  <circle cx="6" cy="18" r="3" />
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M20 4 8.12 15.88M20 20 8.12 8.12" />
                                </svg>
                                Trim
                              </button>
                            )}

                            {media && (
                              <button type="button" title="Crop" onClick={() => setShowCropFile(file)} className={smallBtn}>
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <rect x="4" y="4" width="16" height="16" rx="2" />
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M8 8h8v8" />
                                </svg>
                                Crop
                              </button>
                            )}

                            {media && (
                              <button type="button" title="Advanced Trim & Crop" onClick={() => setShowAdvancedTrimCropFile(file)} className={smallBtn}>
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <rect x="2" y="2" width="20" height="20" rx="2" />
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 4l16 16" />
                                </svg>
                                Adv TC
                              </button>
                            )}

                            <button
                              type="button"
                              title="Copy download link"
                              onClick={async () => {
                                await navigator.clipboard.writeText(window.location.origin + downloadUrl);
                                setToast("Download link copied");
                              }}
                              className={smallBtn}
                            >
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125H6.375a1.125 1.125 0 0 1-1.125-1.125V9.375c0-.621.504-1.125 1.125-1.125H9.75m6-6h3.375c.621 0 1.125.504 1.125 1.125v8.25c0 .621-.504 1.125-1.125 1.125h-8.25A1.125 1.125 0 0 1 9.75 11.625v-8.25c0-.621.504-1.125 1.125-1.125h4.875Z" />
                              </svg>
                              Copy
                            </button>

                            <a href={downloadUrl} target="_blank" rel="noreferrer" title="Download file" className={smallBtn}>
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v10.5m0 0 4-4m-4 4-4-4M4.5 20.25h15" />
                              </svg>
                              Download
                            </a>

                            <button
                              type="button"
                              title="Upload to Pixeldrain"
                              onClick={async () => {
                                const res = await api.uploadToPixeldrain(file.id);
                                setPixeldrainJobIds((prev) => [res.jobId, ...prev]);
                                setToast(`Started Pixeldrain upload: ${file.name}`);
                              }}
                              className={smallBtn}
                            >
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M12 16V4m0 12-4-4m4 4 4-4M4 20h16" />
                              </svg>
                              Upload
                            </button>

                            <button
                              type="button"
                              title="Upload to remote server"
                              onClick={() => uploadFileToRemote(file)}
                              className={smallBtn}
                            >
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 18A4.5 4.5 0 1 1 8.746 9.176 5.25 5.25 0 1 1 18 13.5h-1.5" />
                                <path strokeLinecap="round" strokeLinejoin="round" d="M12 12v9m0 0-3-3m3 3 3-3" />
                              </svg>
                              To remote
                            </button>

                            <button
                              type="button"
                              title="Upload to Backblaze B2"
                              disabled={b2UploadingFileIds.has(file.id)}
                              onClick={() => uploadFileToB2(file)}
                              className={smallBtn + (b2UploadingFileIds.has(file.id) ? " opacity-50 cursor-not-allowed" : "")}
                            >
                              {b2UploadingFileIds.has(file.id) ? (
                                <svg className="mr-1 h-3.5 w-3.5 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v3m0 12v3M3 12h3m12 0h3M5.636 5.636l2.122 2.122m8.485 8.485 2.122 2.122M5.636 18.364l2.122-2.122m8.485-8.485 2.122-2.122" />
                                </svg>
                              ) : (
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" />
                                </svg>
                              )}
                              To B2
                            </button>

                            <button type="button" title="Rename" onClick={() => renameFile(file)} className={smallBtn}>
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" />
                              </svg>
                              Rename
                            </button>

                            <button type="button" title="Move" onClick={() => setShowMoveFiles([file])} className={smallBtn}>
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12 8.25 6m-6 6 6 6M21.75 5.25v13.5a1.5 1.5 0 0 1-1.5 1.5H9.75" />
                              </svg>
                              Move
                            </button>

                            {archive && (
                              <button
                                type="button"
                                title="Unzip"
                                onClick={async () => {
                                  const res = await api.unzipFile(file.id);
                                  if (res.ok) {
                                    setToast(`Extracted ${file.name}`);
                                    refreshFiles();
                                  }
                                }}
                                className={smallBtn}
                              >
                                <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 7.5h16.5M6.75 7.5V6a2.25 2.25 0 0 1 2.25-2.25h6A2.25 2.25 0 0 1 17.25 6v1.5M6 7.5h12l-.9 10.2a2.25 2.25 0 0 1-2.242 2.05H9.142A2.25 2.25 0 0 1 6.9 17.7L6 7.5Zm6 3v5.25m0 0 2.25-2.25M12 15.75l-2.25-2.25" />
                                </svg>
                                Unzip
                              </button>
                            )}

                            <button
                              type="button"
                              title="Delete"
                              onClick={() => deleteOne(file)}
                              className="inline-flex h-8 min-w-8 items-center justify-center rounded-lg border border-red-200 bg-white px-2 text-[11px] font-semibold text-red-500 hover:bg-red-50"
                            >
                              <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673A2.25 2.25 0 0 1 15.916 21.75H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" />
                              </svg>
                              Delete
                            </button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
              {/* MOBILE_FILE_CARDS_END */}

              <div className="hidden md:block overflow-x-auto">
                <table className="w-full table-fixed divide-y divide-slate-100">
                  <thead className="bg-slate-50/80">
                    <tr className="text-left text-xs uppercase tracking-wider text-slate-500">
                      <th className="w-10 px-3 py-3">Sel</th>
                      <th className="px-4 py-3">Name</th>
                      <th className="w-24 px-3 py-3">Size</th>
                      <th className="w-64 px-3 py-3 text-right">Actions</th>
                      <th className="w-36 px-3 py-3">Created</th>
                      <th className="w-24 px-3 py-3">Source</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {loadingFiles ? (
                      <tr>
                        <td colSpan={6} className="px-4 py-10 text-center text-sm text-slate-400">
                          Loading files…
                        </td>
                      </tr>
                    ) : !sortedVisibleFiles.length ? (
                      <tr>
                        <td colSpan={6} className="px-4 py-10 text-center text-sm text-slate-400">
                          {isSearching ? `No files match "${normalizedSearch}"` : "No files in this folder."}
                        </td>
                      </tr>
                    ) : (
                      sortedVisibleFiles.map((file) => {
                        const selected = isFileSelected(file.id);
                        const media = isMediaFile(file.name);
                        const archive = isArchiveFile(file.name);
                        const previewUrl = `/api/files/${encodeURIComponent(file.id)}/download`;
                        const uploadInFlight = b2UploadingFileIds.has(file.id);
                        const queueItem = queue.find((q) => q.file.id === file.id && (q.status === "waiting" || q.status === "encoding"));
                        const activityBadge = uploadInFlight ? (
                          <Badge color="bg-amber-100 text-amber-700">uploading</Badge>
                        ) : queueItem ? (
                          <Badge color="bg-orange-100 text-orange-700">{queueItem.status === "waiting" ? "queued" : "processing"}</Badge>
                        ) : null;
                        return (
                          <tr key={file.id} className={selected ? "bg-violet-50/70" : "hover:bg-slate-50/60"}>
                            <td className="px-3 py-2 align-top">
                              <input
                                type="checkbox"
                                checked={selected}
                                onChange={() => toggleSelected(file.id)}
                                className="mt-1 h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                              />
                            </td>
                            <td className="px-3 py-2 align-top">
                              <div className="min-w-0">
                                <div className="truncate text-sm font-semibold text-slate-800" title={file.name}>
                                  {file.name}
                                </div>
                                <div className="mt-1 flex flex-wrap gap-1">
                                  <Badge color={file.source === "encoded" ? "bg-violet-100 text-violet-700" : "bg-sky-100 text-sky-700"}>{file.source}</Badge>
                                  {media && <Badge color="bg-emerald-100 text-emerald-700">media</Badge>}
                                  {archive && <Badge color="bg-amber-100 text-amber-700">archive</Badge>}
                                  {isSubtitleFile(file.name) && <Badge color="bg-sky-100 text-sky-700">subtitle</Badge>}
                                  {activityBadge}
                                  {isSearching && (
                                    <span className="inline-flex items-center gap-0.5 rounded-full bg-slate-100 px-1.5 py-0.5 text-[10px] font-mono text-slate-500">
                                      <svg className="h-2.5 w-2.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-2.12-2.12a1.5 1.5 0 0 0-1.061-.44H4.5A2.25 2.25 0 0 0 2.25 6v12a2.25 2.25 0 0 0 2.25 2.25h15A2.25 2.25 0 0 0 21.75 18V9a2.25 2.25 0 0 0-2.25-2.25h-5.379a1.5 1.5 0 0 1-1.06-.44Z" /></svg>
                                      {file.folder || "/"}
                                    </span>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td className="px-3 py-2 align-top text-sm text-slate-500">{fmt(file.sizeBytes)}</td>
                            <td className="w-64 px-3 py-2 align-middle">
                              <div className="flex items-center justify-end gap-1">
                                <button
                                  title="Info"
                                  onClick={() => setShowInfoFile(file)}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25 12 17.25m0-9.75h.008v.008H12V7.5Zm9 4.5a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                  </svg>
                                </button>

                                {media && (
                                  <button
                                    title="Preview"
                                    onClick={() => setShowPreviewFile(file)}
                                    className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                    type="button"
                                  >
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.574 0 3.286L8.03 20.99c-1.25.687-2.779-.216-2.779-1.643V5.653Z" />
                                    </svg>
                                  </button>
                                )}

                                {media && (
                                  <button
                                    title="Encode"
                                    onClick={() => {
                                      setSelectedForEncode(file.id);
                                      setTab("encode");
                                    }}
                                    className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                    type="button"
                                  >
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <rect x="4" y="4" width="16" height="16" rx="2" />
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M9 9h6v6H9zM9 2v2m6-2v2M9 20v2m6-2v2M20 9h2m-2 6h2M2 9h2m-2 6h2" />
                                    </svg>
                                  </button>
                                )}

                                {media && (
                                  <button
                                    title="Trim"
                                    onClick={() => setShowTrimFile(file)}
                                    className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                    type="button"
                                  >
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <circle cx="6" cy="6" r="3" />
                                      <circle cx="6" cy="18" r="3" />
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M20 4 8.12 15.88M20 20 8.12 8.12" />
                                    </svg>
                                  </button>
                                )}

                                {media && (
                                  <button
                                    title="Crop"
                                    onClick={() => setShowCropFile(file)}
                                    className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                    type="button"
                                  >
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <rect x="4" y="4" width="16" height="16" rx="2" />
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M8 8h8v8" />
                                    </svg>
                                  </button>
                                )}

                                {media && (
                                  <button
                                    title="Advanced Trim & Crop"
                                    onClick={() => setShowAdvancedTrimCropFile(file)}
                                    className="inline-flex h-7 items-center justify-center rounded-md px-1.5 text-xs font-semibold text-violet-600 hover:bg-violet-50 hover:text-violet-700"
                                    type="button"
                                  >
                                    Adv TC
                                  </button>
                                )}

                                <button
                                  title="Upload to Pixeldrain"
                                  onClick={async () => {
                                    const res = await api.uploadToPixeldrain(file.id);
                                    setPixeldrainJobIds((prev) => [res.jobId, ...prev]);
                                    setToast(`Started Pixeldrain upload: ${file.name}`);
                                  }}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 18A4.5 4.5 0 1 1 8.746 9.176 5.25 5.25 0 1 1 18 13.5h-1.5" />
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 12v9m0 0-3-3m3 3 3-3" />
                                  </svg>
                                </button>

                                <button
                                  title="Upload to remote server"
                                  onClick={() => uploadFileToRemote(file)}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" />
                                  </svg>
                                </button>

                                <button
                                  title="Upload to Backblaze B2"
                                  disabled={b2UploadingFileIds.has(file.id)}
                                  onClick={() => uploadFileToB2(file)}
                                  className={`inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-sky-50 hover:text-sky-600${b2UploadingFileIds.has(file.id) ? " cursor-not-allowed text-sky-300" : " text-slate-500"}`}
                                  type="button"
                                >
                                  {b2UploadingFileIds.has(file.id) ? (
                                    <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v3m0 12v3M3 12h3m12 0h3M5.636 5.636l2.122 2.122m8.485 8.485 2.122 2.122M5.636 18.364l2.122-2.122m8.485-8.485 2.122-2.122" />
                                    </svg>
                                  ) : (
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" />
                                    </svg>
                                  )}
                                </button>

                                <button
                                  title="Rename"
                                  onClick={() => renameFile(file)}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" />
                                  </svg>
                                </button>

                                <button
                                  title="Move"
                                  onClick={() => setShowMoveFiles([file])}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0-4.5-4.5M19.5 12l-4.5 4.5" />
                                  </svg>
                                </button>

                                {archive && (
                                  <button
                                    title="Unzip"
                                    onClick={async () => {
                                      const res = await api.unzipFile(file.id);
                                      if (res.ok) {
                                        setToast(`Extracted ${file.name}`);
                                        refreshFiles();
                                      }
                                    }}
                                    className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                    type="button"
                                  >
                                    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M3 7.5A1.5 1.5 0 0 1 4.5 6h4.379a1.5 1.5 0 0 1 1.06.44l1.182 1.181a1.5 1.5 0 0 0 1.06.44H19.5A1.5 1.5 0 0 1 21 9.56v8.94A1.5 1.5 0 0 1 19.5 20h-15A1.5 1.5 0 0 1 3 18.5v-11Z" />
                                    </svg>
                                  </button>
                                )}

                                <a
                                  href={previewUrl}
                                  target="_blank"
                                  rel="noreferrer"
                                  title="Download file"
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H19.5m0 0V12m0-6-7.5 7.5-3-3L4.5 15" />
                                  </svg>
                                </a>

                                <button
                                  title="Copy download link"
                                  onClick={async () => {
                                    const fullUrl = window.location.origin + `/api/files/${encodeURIComponent(file.id)}/download`;
                                    await navigator.clipboard.writeText(fullUrl);
                                    setToast("Download link copied");
                                  }}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 17.25h3a3 3 0 0 0 0-6h-3m-7.5 0h-3a3 3 0 0 0 0 6h3" />
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M8.25 12h7.5" />
                                  </svg>
                                </button>

                                <button
                                  title="Delete"
                                  onClick={() => deleteOne(file)}
                                  className="inline-flex h-7 w-7 items-center justify-center rounded-md text-red-400 hover:bg-red-50 hover:text-red-600"
                                  type="button"
                                >
                                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673A2.25 2.25 0 0 1 15.916 21.75H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" />
                                  </svg>
                                </button>
                              </div>
                            </td>
                            <td className="px-3 py-2 align-top text-sm text-slate-500">
                              {new Date(file.createdAt).toLocaleString([], {
                                year: "2-digit",
                                month: "2-digit",
                                day: "2-digit",
                                hour: "2-digit",
                                minute: "2-digit",
                              })}
                            </td>
                            <td className="px-3 py-2 align-top text-sm text-slate-500">{file.source}</td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
          </section>
        )}
        {tab === "encode" && (
          <section className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
            <div className="space-y-6">
              <div className="rounded-2xl border border-slate-200 bg-white/90 p-5 shadow-sm">
                <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                  <div>
                    <h2 className="text-sm font-bold text-slate-900">Encoder</h2>
                    <p className="text-xs text-slate-500">Pick a local media file and configure FFmpeg settings.</p>
                  </div>
                  {remoteBucketMatch && (
                  <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span>
                      <button
                        type="button"
                        onClick={() => {
                          const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}`;
                          setRemoteUrl(_u);
                          browseRemote(_u);
                        }}
                        className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50"
                      >
                        {remoteBucketMatch[1]}/{remoteBucketMatch[2]}
                      </button>
                      {remoteBreadcrumbParts.map((part, idx) => (
                        <div key={`${part}_${idx}`} className="flex items-center gap-2">
                          <span className="text-slate-300">/</span>
                          <button
                            type="button"
                            onClick={() => {
                              const nextPath = remoteBreadcrumbParts.slice(0, idx + 1).join("/");
                              const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`;
                              setRemoteUrl(_u);
                              browseRemote(_u);
                            }}
                            className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700"
                          >
                            {part}
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="flex flex-wrap items-center gap-2">
                    <select
                      value={selectedForEncode}
                      onChange={(e) => setSelectedForEncode(e.target.value)}
                      className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                    >
                      <option value="">Select media file…</option>
                      {files.filter((f) => isMediaFile(f.name)).map((file) => (
                        <option key={file.id} value={file.id}>
                          {file.name}
                        </option>
                      ))}
                    </select>
                    {selectedFile && (
                      <>
                        <button
                          onClick={() => setShowInfoFile(selectedFile)}
                          className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        >
                          File info
                        </button>
                        <button
                          onClick={() => setShowCropFile(selectedFile)}
                          className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        >
                          Crop preview
                        </button>
                      </>
                    )}
                  </div>
                </div>

                {!selectedFile ? (
                  <div className="mt-6 rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500">
                    Select a media file to begin encoding.
                  </div>
                ) : (
                  <div className="mt-6 space-y-6">
                    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                      {/* Output format */}
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Output format
                        </label>
                        <select
                          value={String(settings.outputFormat)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, outputFormat: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="video">Video</option>
                          <option value="audio">Audio only</option>
                        </select>
                      </div>

                      {/* Codec — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Codec
                          <HelpTip text="Choose the video codec. AV1 gives best compression but is slower. H.264 is fastest and most compatible." />
                        </label>
                        <select
                          value={String(settings.codec)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, codec: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="av1">AV1</option>
                          <option value="h264">H.264</option>
                          <option value="h265">H.265 / HEVC</option>
                          <option value="vp9">VP9</option>
                        </select>
                      </div>
                      )}

                      {/* Mode — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Mode
                          <HelpTip text="CRF keeps visual quality more constant. VBR targets a bitrate." />
                        </label>
                        <select
                          value={String(settings.mode)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, mode: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="crf-1pass">CRF (1-pass)</option>
                          <option value="vbr">VBR bitrate</option>
                        </select>
                      </div>
                      )}

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Output container
                        </label>
                        <select
                          value={String(settings.outputContainer)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, outputContainer: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          {isAudioOnly ? (
                            <>
                              <option value="opus">Opus (.opus)</option>
                              <option value="mp3">MP3 (.mp3)</option>
                              <option value="aac">AAC (.aac)</option>
                              <option value="flac">FLAC (.flac)</option>
                              <option value="wav">WAV (.wav)</option>
                              <option value="m4a">M4A (.m4a)</option>
                            </>
                          ) : (
                            <>
                              <option value="mkv">MKV</option>
                              <option value="mp4">MP4</option>
                              <option value="webm">WEBM</option>
                            </>
                          )}
                        </select>
                      </div>

                      {/* CRF / Video bitrate — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (
                        String(settings.mode) === "crf-1pass" ? (
                        <div className="space-y-1.5">
                          <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                            CRF
                            <HelpTip text="Lower CRF = better quality and bigger size. Higher CRF = smaller files." />
                          </label>
                          <input
                            type="number"
                            min={0}
                            max={63}
                            value={Number(settings.crf)}
                            onChange={(e) => setSettings((prev) => ({ ...prev, crf: Number(e.target.value) }))}
                            className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                          />
                        </div>
                        ) : (
                        <div className="space-y-1.5">
                          <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                            Video bitrate (kbps)
                          </label>
                          <input
                            type="number"
                            min={100}
                            step={50}
                            value={Number(settings.videoBitrateKbps)}
                            onChange={(e) => setSettings((prev) => ({ ...prev, videoBitrateKbps: Number(e.target.value) }))}
                            className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                          />
                        </div>
                        )
                      )}

                      {/* Audio bitrate — hidden when copying audio */}
                      {!copiesAudio && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Opus audio (kbps)
                        </label>
                        <select
                          value={String(settings.audioBitrateKbps)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, audioBitrateKbps: Number(e.target.value) }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          {[32, 48, 64, 80, 96, 128, 160, 192, 256, 320].map((v) => (
                            <option key={v} value={v}>{v} kbps</option>
                          ))}
                        </select>
                      </div>
                      )}

                      {/* Resolution — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Resolution
                        </label>
                        <select
                          value={String(settings.resolution)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, resolution: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="same">Same as source</option>
                          <option value="2160p">2160p</option>
                          <option value="1440p">1440p</option>
                          <option value="1080p">1080p</option>
                          <option value="720p">720p</option>
                          <option value="480p">480p</option>
                          <option value="360p">360p</option>
                          <option value="custom">Custom</option>
                        </select>
                      </div>
                      )}

                      {!isAudioOnly && !copiesVideo && String(settings.resolution) === "custom" && (
                        <>
                          <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                              Custom width
                            </label>
                            <input
                              type="number"
                              min={2}
                              step={2}
                              value={String(settings.scaleWidth || "")}
                              onChange={(e) => setSettings((prev) => ({ ...prev, scaleWidth: e.target.value }))}
                              placeholder="1280"
                              className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                            />
                          </div>

                          <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                              Custom height
                            </label>
                            <input
                              type="number"
                              min={2}
                              step={2}
                              value={String(settings.scaleHeight || "")}
                              onChange={(e) => setSettings((prev) => ({ ...prev, scaleHeight: e.target.value }))}
                              placeholder="720"
                              className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                            />
                          </div>
                        </>
                      )}

                      {/* Frame rate — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Frame rate
                        </label>
                        <select
                          value={String(settings.frameRate)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, frameRate: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="same">Same as source</option>
                          <option value="24">24</option>
                          <option value="25">25</option>
                          <option value="30">30</option>
                          <option value="50">50</option>
                          <option value="60">60</option>
                        </select>
                      </div>
                      )}

                      {/* Audio channels — hidden when copying audio */}
                      {!copiesAudio && (
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Audio channels
                        </label>
                        <select
                          value={String(settings.audioChannels)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, audioChannels: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="same">Same as source</option>
                          <option value="1">Mono</option>
                          <option value="2">Stereo</option>
                        </select>
                      </div>
                      )}

                      {/* H26x preset — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && (String(settings.codec) === "h264" || String(settings.codec) === "h265") && (
                        <div className="space-y-1.5">
                          <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                            H26x preset
                          </label>
                          <select
                            value={String(settings.h26xPreset)}
                            onChange={(e) => setSettings((prev) => ({ ...prev, h26xPreset: e.target.value }))}
                            className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                          >
                            <option value="ultrafast">ultrafast</option>
                            <option value="superfast">superfast</option>
                            <option value="veryfast">veryfast</option>
                            <option value="faster">faster</option>
                            <option value="fast">fast</option>
                            <option value="medium">medium</option>
                            <option value="slow">slow</option>
                            <option value="slower">slower</option>
                            <option value="veryslow">veryslow</option>
                          </select>
                        </div>
                      )}

                      {/* AV1 params — hidden for audio-only or copy-video */}
                      {!isAudioOnly && !copiesVideo && String(settings.codec) === "av1" && (
                        <>
                          <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                              AV1 preset
                            </label>
                            <input
                              type="number"
                              min={0}
                              max={13}
                              value={Number(settings.preset)}
                              onChange={(e) => setSettings((prev) => ({ ...prev, preset: Number(e.target.value) }))}
                              className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                            />
                          </div>

                          <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                              AQ mode
                            </label>
                            <select
                              value={String(settings.aqMode)}
                              onChange={(e) => setSettings((prev) => ({ ...prev, aqMode: Number(e.target.value) }))}
                              className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                            >
                              <option value="0">0 - Off</option>
                              <option value="1">1 - Variance</option>
                              <option value="2">2 - Complexity</option>
                            </select>
                          </div>

                          <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                              Tiles
                            </label>
                            <select
                              value={String(settings.tiles)}
                              onChange={(e) => setSettings((prev) => ({ ...prev, tiles: e.target.value }))}
                              className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                            >
                              <option value="0">Off</option>
                              <option value="2">2x2</option>
                              <option value="4">4x4</option>
                            </select>
                          </div>
                        </>
                      )}
                    </div>

                    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Start time
                        </label>
                        <TimePartsInput
                          value={String(settings.startTime || "")}
                          allowEmpty
                          onChange={(value) => setSettings((prev) => ({ ...prev, startTime: value }))}
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          End time
                        </label>
                        <TimePartsInput
                          value={String(settings.endTime || "")}
                          allowEmpty
                          onChange={(value) => setSettings((prev) => ({ ...prev, endTime: value }))}
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Speed
                        </label>
                        <input
                          type="number"
                          min={0.25}
                          max={4}
                          step={0.05}
                          value={Number(settings.speed)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, speed: Number(e.target.value) }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Brightness
                        </label>
                        <input
                          type="number"
                          step={0.05}
                          value={Number(settings.brightness)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, brightness: Number(e.target.value) }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Contrast
                        </label>
                        <input
                          type="number"
                          min={0}
                          step={0.05}
                          value={Number(settings.contrast)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, contrast: Number(e.target.value) }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Saturation
                        </label>
                        <input
                          type="number"
                          min={0}
                          step={0.05}
                          value={Number(settings.saturation)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, saturation: Number(e.target.value) }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Rotate
                        </label>
                        <select
                          value={String(settings.rotate)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, rotate: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="none">None</option>
                          <option value="clockwise">90° clockwise</option>
                          <option value="counterclockwise">90° counter-clockwise</option>
                          <option value="180">180°</option>
                        </select>
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Subtitle file
                        </label>
                        <select
                          value={String(settings.subtitleFile)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, subtitleFile: e.target.value }))}
                          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        >
                          <option value="">None</option>
                          {selectedSubtitleFiles.map((file) => (
                            <option key={file.id} value={file.name}>
                              {file.name}
                            </option>
                          ))}
                        </select>
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Subtitle language
                        </label>
                        <input
                          type="text"
                          value={String(settings.subtitleLang)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, subtitleLang: e.target.value }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>

                      <div className="space-y-1.5">
                        <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                          Output filename
                        </label>
                        <input
                          type="text"
                          value={String(settings.outputFilename)}
                          onChange={(e) => setSettings((prev) => ({ ...prev, outputFilename: e.target.value }))}
                          className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                        />
                      </div>
                    </div>

                    <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                      {([
                        ["stripSubtitles", "Strip embedded subtitles", false],
                        ["stripMetadata", "Strip metadata", false],
                        ["sameAsOriginalAudio", "Same as original audio", false],
                        ["sameAsOriginalVideo", "Same as original video", true],
                        ["subtitleBurn", "Burn subtitle into video", true],
                        ["deinterlace", "Deinterlace", true],
                        ["denoise", "Denoise", true],
                        ["forceStereo", "Force stereo output", false],
                        ["sceneChange", "Scene change detection", true],
                      ] as [string, string, boolean][])
                        .filter(([, , videoOnly]) => !isAudioOnly || !videoOnly)
                        .map(([key, label]) => (
                        <label key={key} className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                          <input
                            type="checkbox"
                            checked={Boolean(settings[key])}
                            onChange={(e) => setSettings((prev) => ({ ...prev, [key]: e.target.checked }))}
                            className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                          />
                          <span>{label}</span>
                        </label>
                      ))}
                    </div>

                    <div className="flex flex-wrap items-center gap-3">
                      <button
                        onClick={startEncode}
                        disabled={!selectedForEncode}
                        className={`rounded-xl px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50 ${
                          forceStartMode
                            ? "bg-orange-600 hover:bg-orange-700"
                            : "bg-violet-600 hover:bg-violet-700"
                        }`}
                        title={forceStartMode ? "Force Start Mode: Will ignore running jobs" : "Start encoding"}
                      >
                        {forceStartMode ? "Start (Force)" : "Start encode"}
                      </button>
                      <button
                        onClick={addToQueue}
                        disabled={!selectedForEncode}
                        className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                      >
                        Add to queue
                      </button>
                      <button
                        onClick={savePreset}
                        className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                      >
                        Save preset
                      </button>
                      {(b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim()) ? (
                        <label
                          title="When checked, the encoded output is automatically uploaded to the currently configured S3/Backblaze connection after the job completes."
                          className={`flex cursor-pointer items-center gap-2 rounded-xl border px-3 py-2 text-sm ${
                            encodeAutoS3
                              ? "border-violet-400 bg-violet-50 text-violet-700"
                              : "border-slate-200 bg-slate-50 text-slate-600"
                          }`}
                        >
                          <input
                            type="checkbox"
                            checked={encodeAutoS3}
                            onChange={(e) => setEncodeAutoS3Persist(e.target.checked)}
                            className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                          />
                          Save to S3 after encode
                        </label>
                      ) : (
                        <span className="text-xs text-slate-400" title="Configure S3/Backblaze credentials in the Storage tab to enable auto-upload after encode.">
                          ☁ S3 not configured
                        </span>
                      )}
                    </div>

                    <div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
                      <div className="flex items-center justify-between gap-2">
                        <div>
                          <h3 className="text-sm font-semibold text-slate-900">Saved presets</h3>
                          <p className="text-xs text-slate-500">These are stored in the app settings and available on this device.</p>
                        </div>
                      </div>
                      {presets.length ? (
                        <div className="mt-3 space-y-2">
                          {presets.map((preset) => (
                            <div key={preset.id} className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2">
                              <div className="min-w-0">
                                <div className="truncate text-sm font-semibold text-slate-800">{preset.label}</div>
                                <div className="text-xs text-slate-500">
                                  {String(preset.settings.outputFormat || "video")} • {String(preset.settings.codec || "av1")} • {String(preset.settings.outputContainer || "mkv")}
                                </div>
                              </div>
                              <div className="flex flex-wrap items-center gap-2">
                                <button
                                  type="button"
                                  onClick={() => loadPreset(preset.label)}
                                  className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                >
                                  Load
                                </button>
                                <button
                                  type="button"
                                  onClick={() => deletePreset(preset.id)}
                                  className="rounded-lg border border-red-200 px-2.5 py-1 text-xs font-semibold text-red-600 hover:bg-red-50"
                                >
                                  Delete
                                </button>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="mt-3 text-sm text-slate-500">No presets saved yet. Use “Save preset” to keep the current encoder settings.</p>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </section>
        )}
        {tab === "jobs" && (
          <section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_256px]">
            <div className="space-y-6">
              <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm">
                <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
                  <div>
                    <h2 className="text-sm font-bold text-slate-900">Running jobs</h2>
                    <p className="text-xs text-slate-500">Live FFmpeg tasks and progress polling</p>
                  </div>
                  <button
                    onClick={refreshJobs}
                    className="rounded-xl border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                  >
                    Refresh
                  </button>
                </div>

                <div className="p-5 space-y-4">
                  {!runningJobs.length ? (
                    <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500">
                      No running jobs right now.
                    </div>
                  ) : (
                    runningJobs.map((job) => {
                      const settings = job.settings || {};
                      const isTrim = settings.type === "trim";
                      const isMerge = settings.type === "merge";
                      const pct = Math.max(0, Math.min(100, Number(job.progress?.percent || 0)));
                      return (
                        <div key={job.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                          {/* Header row: name + badge + stop button */}
                          <div className="flex min-w-0 items-start justify-between gap-3">
                            <div className="min-w-0 flex-1">
                              <div className="flex min-w-0 flex-wrap items-center gap-2">
                                <p className="min-w-0 truncate text-sm font-bold text-slate-900">
                                  {String(settings.outputFilename || settings.inputFilename || "Job")}
                                </p>
                                <Badge color="bg-violet-100 text-violet-700">running</Badge>
                                {job.batchIndex != null && job.batchTotal != null && (
                                  <span className="text-[11px] text-slate-400">Batch {job.batchIndex + 1}/{job.batchTotal}</span>
                                )}
                              </div>
                              <p className="mt-0.5 text-xs text-slate-500">
                                {isMerge
                                  ? `Merge ${Array.isArray(settings.fileIds) ? settings.fileIds.length : 0} files · stream copy`
                                  : isTrim
                                    ? Array.isArray(settings.segments)
                                      ? `Trim & merge ${(settings.segments as { startTime: number; endTime: number }[]).length} segments · stream copy`
                                      : `Trim ${secondsToHms(Number(settings.startTime ?? 0))} → ${secondsToHms(Number(settings.endTime ?? 0))} · stream copy`
                                    : `${String(settings.codec || "").toUpperCase()} · ${String(settings.resolution || "same")} · ${String(settings.mode || "")} ${String(settings.mode || "").includes("crf") ? `CRF ${settings.crf}` : ""}`}
                              </p>
                              <p className="mt-1 truncate text-[11px] text-slate-400">
                                {job.outputFolder || "/"}
                              </p>
                            </div>
                            <button
                              onClick={() => stopJob(job.id)}
                              className="flex-shrink-0 rounded-xl border border-red-200 px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50"
                            >
                              Stop
                            </button>
                          </div>

                          {/* Progress bar */}
                          <div className="mt-3">
                            <div className="mb-1.5 flex items-center justify-between text-xs">
                              <span className="font-semibold text-slate-800">{pct.toFixed(1)}%</span>
                              <span className="text-slate-500">
                                {job.progress?.bitrateKbps ? `${job.progress.bitrateKbps.toFixed(0)} kbps` : ""}
                              </span>
                            </div>
                            <div className="h-2 overflow-hidden rounded-full bg-slate-100">
                              <div className="h-full rounded-full bg-violet-600 transition-all" style={{ width: `${pct}%` }} />
                            </div>
                          </div>

                          {/* Stats row — 2 cols on xs, 4 cols on sm+ */}
                          <div className="mt-3 grid grid-cols-2 gap-x-4 gap-y-1 sm:grid-cols-4 text-xs text-slate-500">
                            <div className="flex justify-between gap-1">
                              <span>ETA</span>
                              <span className="font-medium text-slate-700">{fmtEta(Number(job.progress?.etaSeconds || 0))}</span>
                            </div>
                            <div className="flex justify-between gap-1">
                              <span>Speed</span>
                              <span className="font-medium text-slate-700">
                                {job.progress?.speed && job.progress.speed > 0 ? `${job.progress.speed.toFixed(2)}×` : "…"}
                              </span>
                            </div>
                            <div className="flex justify-between gap-1">
                              <span>FPS</span>
                              <span className="font-medium text-slate-700">
                                {job.progress?.fps ? job.progress.fps.toFixed(1) : "…"}
                              </span>
                            </div>
                            <div className="flex justify-between gap-1">
                              <span>Size</span>
                              <span className="font-medium text-slate-700">{fmt(Number(job.progress?.sizeOutBytes || 0))}</span>
                            </div>
                          </div>

                          {!!job.progress?.log?.length && (
                            <details className="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
                              <summary className="cursor-pointer text-xs font-semibold text-slate-700">Recent log</summary>
                              <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-slate-600">
                                {job.progress.log.slice(-20).join("\n")}
                              </pre>
                            </details>
                          )}
                        </div>
                      );
                    })
                  )}
                </div>
              </div>

              <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm">
                <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
                  <div>
                    <h2 className="text-sm font-bold text-slate-900">Finished jobs</h2>
                    <p className="text-xs text-slate-500">Completed, failed, and stopped tasks</p>
                  </div>
                  {finishedJobs.length > 0 && (
                    <button
                      onClick={async () => {
                        await api.clearFinishedJobs();
                        await refreshJobs();
                      }}
                      className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs font-semibold text-red-600 hover:bg-red-100 transition-colors"
                    >
                      Clear finished
                    </button>
                  )}
                </div>

                <div className="p-5 space-y-4">
                  {!finishedJobs.length ? (
                    <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500">
                      No finished jobs yet.
                    </div>
                  ) : (
                    finishedJobs.map((job) => {
                      const settings = job.settings || {};
                      const isTrim = settings.type === "trim";
                      const isMerge = settings.type === "merge";
                      const isEncode = !isTrim && !isMerge;

                      const badgeColor =
                        job.status === "done"
                          ? "bg-emerald-100 text-emerald-700"
                          : job.status === "failed"
                            ? "bg-red-100 text-red-700"
                            : "bg-slate-200 text-slate-700";

                      return (
                        <div key={job.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                          {/* Header: name + badge + size/pct */}
                          <div className="flex min-w-0 items-start justify-between gap-3">
                            <div className="min-w-0 flex-1">
                              <div className="flex min-w-0 flex-wrap items-center gap-2">
                                <p className="min-w-0 truncate text-sm font-bold text-slate-900">
                                  {String(settings.outputFilename || settings.inputFilename || "Job")}
                                </p>
                                <Badge color={badgeColor}>{job.status}</Badge>
                              </div>
                              <p className="mt-0.5 text-xs text-slate-500">
                                {isMerge
                                  ? `Merge ${Array.isArray(settings.fileIds) ? settings.fileIds.length : 0} files · stream copy`
                                  : isTrim
                                    ? Array.isArray(settings.segments)
                                      ? `Trim & merge ${(settings.segments as { startTime: number; endTime: number }[]).length} segments · stream copy`
                                      : `Trim ${secondsToHms(Number(settings.startTime ?? 0))} → ${secondsToHms(Number(settings.endTime ?? 0))} · stream copy`
                                    : `${String(settings.codec || "").toUpperCase()} · ${String(settings.resolution || "same")} · ${String(settings.mode || "")} ${String(settings.mode || "").includes("crf") ? `CRF ${settings.crf}` : ""}`}
                              </p>
                            </div>
                            <div className="flex-shrink-0 text-right text-[11px] text-slate-500">
                              <div className="font-medium text-slate-700">
                                {job.progress?.percent ? `${job.progress.percent.toFixed(1)}%` : job.status === "done" ? "100%" : "—"}
                              </div>
                              <div>{fmt(Number(job.progress?.sizeOutBytes || 0))}</div>
                            </div>
                          </div>

                          {/* Meta row */}
                          <div className="mt-2 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-slate-400">
                            <span className="truncate max-w-[16ch] sm:max-w-none">{job.id}</span>
                            <span>{new Date(job.createdAt).toLocaleString()}</span>
                            {job.outputFolder && <span className="truncate">{job.outputFolder}</span>}
                          </div>

                          {/* Encode tag pills */}
                          {isEncode && (
                            <div className="mt-2 flex flex-wrap gap-1.5 text-[11px]">
                              {settings.audioBitrateKbps != null && (
                                <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600">
                                  Audio {String(settings.audioBitrateKbps)} kbps
                                </span>
                              )}
                              {settings.outputContainer != null && (
                                <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600">
                                  {String(settings.outputContainer).toUpperCase()}
                                </span>
                              )}
                              {settings.frameRate != null && String(settings.frameRate) !== "same" && (
                                <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600">
                                  {String(settings.frameRate)} fps
                                </span>
                              )}
                            </div>
                          )}

                          {!!job.progress?.log?.length && (
                            <details className="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
                              <summary className="cursor-pointer text-xs font-semibold text-slate-700">View log</summary>
                              <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-slate-600">
                                {job.progress.log.join("\n")}
                              </pre>
                            </details>
                          )}
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            </div>

            <aside className="space-y-4">
              <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm">
                <h3 className="mb-3 text-sm font-bold text-slate-900">Job summary</h3>
                <div className="grid grid-cols-2 gap-2">
                  <div className="rounded-xl bg-slate-50 px-3 py-2.5">
                    <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Running</p>
                    <p className="mt-0.5 text-xl font-black text-slate-900">{runningJobs.length}</p>
                  </div>
                  <div className="rounded-xl bg-slate-50 px-3 py-2.5">
                    <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Finished</p>
                    <p className="mt-0.5 text-xl font-black text-slate-900">{finishedJobs.length}</p>
                  </div>
                  <div className="rounded-xl bg-slate-50 px-3 py-2.5">
                    <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Succeeded</p>
                    <p className="mt-0.5 text-xl font-black text-emerald-600">{jobs.filter((j) => j.status === "done").length}</p>
                  </div>
                  <div className="rounded-xl bg-slate-50 px-3 py-2.5">
                    <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Failed/Stopped</p>
                    <p className="mt-0.5 text-xl font-black text-red-500">
                      {jobs.filter((j) => j.status === "failed" || j.status === "stopped").length}
                    </p>
                  </div>
                </div>
              </div>

              <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm">
                <h3 className="mb-2 text-sm font-bold text-slate-900">Notes</h3>
                <div className="space-y-1.5 text-xs text-slate-500">
                  <p>• Trim jobs with pasted clips appear as "Trim & merge X segments".</p>
                  <p>• Merge and trim use stream copy for fast lossless output.</p>
                  <p>• Refresh if a job looks stale or polling was interrupted.</p>
                </div>
              </div>
            </aside>
          </section>
        )}
        {tab === "remote" && (
          <section className="space-y-6">
            <div className="rounded-2xl border border-slate-200 bg-white/95 shadow-sm">
              <div className="border-b border-slate-100 px-6 py-5">
                <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
                  <div>
                    <h2 className="text-base font-bold text-slate-900">Remote browser</h2>
                    <p className="text-sm text-slate-500">Browse remote app servers or Hugging Face storage buckets, then download items into your selected local folder.</p>
                  </div>
                  <button
                    onClick={() => setShowCredentialsModal(true)}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors"
                  >
                    <span>🔑</span>
                    <span>Manage Credentials</span>
                  </button>
                </div>
              </div>

              <div className="p-6 space-y-5">
                <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]">
                  <div className="relative min-w-0 w-full">
                    <input
                      ref={remoteInputRef}
                      type="text"
                      value={remoteUrl}
                      onChange={(e) => setRemoteUrl(e.target.value)}
                      onFocus={() => setRemoteShowHistory(true)}
                      onBlur={() => setTimeout(() => setRemoteShowHistory(false), 150)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          setRemoteShowHistory(false);
                          browseRemote();
                        } else if (e.key === "Escape") {
                          setRemoteShowHistory(false);
                        }
                      }}
                      placeholder="https://example.com or https://huggingface.co/buckets/org/bucket/tree/path"
                      className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                    />
                    {remoteShowHistory && remoteUrlHistory.length > 0 && (
                      <div className="absolute z-20 mt-1 w-full overflow-hidden rounded-xl border border-slate-200 bg-white shadow-lg">
                        <div className="max-h-60 overflow-y-auto py-1">
                          {remoteUrlHistory
                            .filter((u) => !remoteUrl.trim() || u.toLowerCase().includes(remoteUrl.trim().toLowerCase()))
                            .map((u) => (
                              <div
                                key={u}
                                className="group flex items-center gap-2 px-3 py-2 hover:bg-violet-50"
                              >
                                <button
                                  type="button"
                                  onMouseDown={(e) => e.preventDefault()}
                                  onClick={() => {
                                    setRemoteUrl(u);
                                    setRemoteShowHistory(false);
                                    // Load credentials for this URL
                                    const creds = getCurrentRemoteCredentials(u);
                                    setRemoteHfToken(creds.hfToken);
                                    setRemoteHfS3AccessKeyId(creds.hfS3AccessKeyId);
                                    setRemoteHfS3SecretAccessKey(creds.hfS3SecretAccessKey);
                                    browseRemote(u);
                                  }}
                                  className="min-w-0 flex-1 truncate text-left text-sm text-slate-700"
                                  title={u}
                                >
                                  {u}
                                </button>
                                <button
                                  type="button"
                                  onMouseDown={(e) => e.preventDefault()}
                                  onClick={() => removeRemoteUrlFromHistory(u)}
                                  className="shrink-0 rounded-md p-1 text-slate-400 opacity-0 hover:bg-slate-100 hover:text-red-500 group-hover:opacity-100"
                                  title="Remove from history"
                                >
                                  <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                                  </svg>
                                </button>
                              </div>
                            ))}
                        </div>
                      </div>
                    )}
                  </div>
                  <button
                    onClick={() => browseRemote()}
                    disabled={remoteLoading || !remoteUrl.trim()}
                    className="w-full rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 sm:w-auto"
                  >
                    {remoteLoading ? "Browsing…" : "Browse"}
                  </button>
                </div>

                <input
                  type="password"
                  value={remoteHfToken}
                  onChange={(e) => {
                    setRemoteHfToken(e.target.value);
                    updateCurrentRemoteCredentials(remoteUrl, { hfToken: e.target.value });
                  }}
                  placeholder="HF token (optional, only needed for private buckets)"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                />

                {remoteBucketMatch && (
                  <div className="rounded-xl border border-amber-200 bg-amber-50/70 p-3 space-y-2">
                    <p className="text-xs text-amber-800">
                      Uploading to a Hugging Face bucket needs S3 credentials, not the HF token above.
                      Generate them from an access token with <strong>Write</strong> permission at{" "}
                      <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline">
                        huggingface.co/settings/tokens
                      </a>{" "}
                      → token menu → "Generate S3 credentials".
                    </p>
                    <div className="grid gap-2 sm:grid-cols-2">
                      <input
                        type="text"
                        value={remoteHfS3AccessKeyId}
                        onChange={(e) => {
                          setRemoteHfS3AccessKeyId(e.target.value);
                          updateCurrentRemoteCredentials(remoteUrl, { hfS3AccessKeyId: e.target.value });
                        }}
                        placeholder="HF S3 Access Key ID (HFAK…)"
                        className="min-w-0 w-full rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                      />
                      <input
                        type="password"
                        value={remoteHfS3SecretAccessKey}
                        onChange={(e) => setRemoteHfS3SecretAccessKey(e.target.value)}
                        placeholder="HF S3 Secret Access Key"
                        className="min-w-0 w-full rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                      />
                    </div>
                  </div>
                )}

                {remoteError && (
                  <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
                    {remoteError}
                  </div>
                )}

                {remoteBucketMatch && (
                  <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span>
                      <button
                        type="button"
                        onClick={() => {
                          const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}`;
                          setRemoteUrl(_u);
                          browseRemote(_u);
                        }}
                        className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50"
                      >
                        {remoteBucketMatch[1]}/{remoteBucketMatch[2]}
                      </button>
                      {remoteBreadcrumbParts.map((part, idx) => (
                        <div key={`${part}_${idx}`} className="flex items-center gap-2">
                          <span className="text-slate-300">/</span>
                          <button
                            type="button"
                            onClick={() => {
                              const nextPath = remoteBreadcrumbParts.slice(0, idx + 1).join("/");
                              const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`;
                              setRemoteUrl(_u);
                              browseRemote(_u);
                            }}
                            className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700"
                          >
                            {part}
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="flex flex-wrap items-center gap-2">
                  <button
                    onClick={remoteDownloadSelected}
                    disabled={!remoteSelected.length || !remoteUrl.trim()}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" />
                    </svg>
                    Download selected
                  </button>

                  <button
                    onClick={() => remoteUploadRef.current?.click()}
                    disabled={!remoteUrl.trim()}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 16V4m0 12-4-4m4 4 4-4M4 20h16" />
                    </svg>
                    Upload
                  </button>
                  <input
                    ref={remoteUploadRef}
                    type="file"
                    multiple
                    className="hidden"
                    onChange={(e) => {
                      remoteUploadFiles(e.target.files);
                      e.currentTarget.value = "";
                    }}
                  />

                  <button
                    onClick={() => setRemoteSelected(remoteEntries.map((e) => e.name))}
                    disabled={!remoteEntries.length}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 6.75h15m-15 5.25h15m-15 5.25h15" />
                    </svg>
                    Select all
                  </button>

                  <button
                    onClick={() => setRemoteSelected([])}
                    disabled={!remoteSelected.length}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                    </svg>
                    Clear
                  </button>
                </div>

                <input
                  type="text"
                  value={remoteSearch}
                  onChange={(e) => setRemoteSearch(e.target.value)}
                  placeholder="Search remote entries by name…"
                  className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"
                />

                <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white">
                  <div className="overflow-x-auto">
                    <table className="min-w-full table-fixed divide-y divide-slate-100">
                    <thead className="bg-slate-50/80">
                      <tr className="text-left text-xs uppercase tracking-wider text-slate-500">
                        <th className="w-14 px-4 py-3">Sel</th>
                        <th className="w-full px-4 py-3">Name</th>
                        <th className="w-28 px-4 py-3">Type</th>
                        <th className="w-32 px-4 py-3">Size</th>
                        <th className="w-44 px-4 py-3 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {!remoteEntries.length ? (
                        <tr>
                          <td colSpan={5} className="px-4 py-14 text-center text-sm text-slate-400">
                            {remoteLoading ? "Loading remote entries…" : "No remote entries loaded yet."}
                          </td>
                        </tr>
                      ) : (
                        remoteEntries
                          .filter((entry) =>
                            !remoteSearch.trim() || entry.name.toLowerCase().includes(remoteSearch.trim().toLowerCase())
                          )
                          .map((entry) => {
                          const selected = remoteSelected.includes(entry.name);
                          return (
                            <tr key={entry.name} className={selected ? "bg-violet-50/80" : "hover:bg-slate-50/70"}>
                              <td className="px-4 py-3">
                                <input
                                  type="checkbox"
                                  checked={selected}
                                  onChange={() => toggleRemoteSelected(entry.name)}
                                  className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                                />
                              </td>
                              <td className="max-w-0 w-full px-4 py-3">
                                <div className="flex min-w-0 items-center gap-2">
                                  <span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-slate-100 text-base">
                                    {entry.isDir ? "📁" : "📄"}
                                  </span>
                                  {entry.isDir ? (
                                    <button
                                      type="button"
                                      onClick={() => {
                                        if (remoteBucketMatch) {
                                          const nextPath = remoteBucketPath ? `${remoteBucketPath}/${entry.name}` : entry.name;
                                          const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`;
                                          setRemoteUrl(_u);
                                          browseRemote(_u);
                                        }
                                      }}
                                      className="block min-w-0 truncate text-left text-sm font-medium text-violet-700 hover:underline"
                                      title={entry.name}
                                    >
                                      {entry.name}
                                    </button>
                                  ) : (
                                    <span className="block min-w-0 truncate text-sm font-medium text-slate-800" title={entry.name}>{entry.name}</span>
                                  )}
                                </div>
                              </td>
                              <td className="px-4 py-3 text-sm text-slate-500">
                                <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ${
                                  entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600"
                                }`}>
                                  {entry.isDir ? "folder" : (entry.type || "file")}
                                </span>
                              </td>
                              <td className="px-4 py-3 text-sm tabular-nums text-slate-500">{entry.sizeStr || (entry.size != null ? fmt(entry.size) : "—")}</td>
                              <td className="px-4 py-3">
                                <div className="flex justify-end gap-1 whitespace-nowrap">
                                  <IconBtn
                                    title={entry.isDir ? "Download folder" : "Download"}
                                    onClick={async () => {
                                      if (entry.isDir) {
                                        const res = await api.remoteDownloadFolder(
                                          remoteUrl.trim(),
                                          entry.name,
                                          selectedFolder,
                                          remoteHfToken.trim()
                                        );
                                        if (res.error) {
                                          setToast(`Folder download failed: ${res.error}`);
                                        } else {
                                          setToast(`Started ${res.count || 0} downloads from folder: ${entry.name}`);
                                        }
                                      } else {
                                        const res = await api.remoteDownload(
                                          remoteUrl.trim(),
                                          entry.name,
                                          selectedFolder,
                                          (entry as { downloadUrl?: string }).downloadUrl,
                                          {
                                            hfPath: (entry as { hfPath?: string }).hfPath,
                                            hfOrg: (entry as { hfOrg?: string }).hfOrg,
                                            hfBucket: (entry as { hfBucket?: string }).hfBucket,
                                          },
                                          remoteHfToken.trim()
                                        );
                                        if (res.jobId) {
                                          setRemoteDownloadJobId(res.jobId);
                                          setToast(`Started download: ${entry.name}`);
                                        } else if (res.error) {
                                          setToast(`Download failed: ${res.error}`);
                                        }
                                      }
                                    }}
                                  >
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" />
                                    </svg>
                                  </IconBtn>
                                  <IconBtn title="Rename" onClick={() => remoteRenameEntry(entry.name)}>
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" />
                                    </svg>
                                  </IconBtn>
                                  <IconBtn title="Move" onClick={() => remoteMoveEntry(entry.name)}>
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0-4.5-4.5M19.5 12l-4.5 4.5" />
                                    </svg>
                                  </IconBtn>
                                  <IconBtn title="Delete" onClick={() => remoteDeleteEntry(entry.name)} danger>
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                      <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673A2.25 2.25 0 0 1 15.916 21.75H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" />
                                    </svg>
                                  </IconBtn>
                                </div>
                              </td>
                              <td className="px-4 py-3 text-sm text-slate-500">
                                <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ${
                                  entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600"
                                }`}>
                                  {entry.isDir ? "folder" : (entry.type || "file")}
                                </span>
                              </td>
                            </tr>
                          );
                        })
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          </section>
        )}


        {tab === "telebox" && (
          <section className="space-y-6">
            <div className="rounded-2xl border border-slate-200 bg-white/95 shadow-sm">
              <div className="border-b border-slate-100 px-6 py-5">
                <h2 className="text-base font-bold text-slate-900">TeleBox</h2>
                <p className="text-sm text-slate-500">Browse your TeleBox storage, upload files, and download items into your selected local folder.</p>
              </div>

              <div className="space-y-5 p-6">
                <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]">
                  <div className="space-y-2">
                    <input
                      type="password"
                      value={teleboxToken}
                      onChange={(e) => setTeleboxToken(e.target.value)}
                      placeholder="TeleBox API token (list/upload)"
                      className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                    />
                    <input
                      type="password"
                      value={teleboxWebToken}
                      onChange={(e) => setTeleboxWebToken(e.target.value)}
                      placeholder="TeleBox web session token (download)"
                      className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                    />
                  </div>
                  <button
                    onClick={() => browseTelebox(teleboxPid, teleboxPath)}
                    disabled={teleboxLoading || !teleboxToken.trim()}
                    className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50"
                  >
                    {teleboxLoading ? "Loading…" : "Load"}
                  </button>
                </div>

                {teleboxError && (
                  <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
                    {teleboxError}
                  </div>
                )}

                <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span>
                    <button
                      type="button"
                      onClick={goTeleboxRoot}
                      className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50"
                    >
                      Root
                    </button>
                    {teleboxPath.map((part, idx) => (
                      <div key={`${part.id}_${idx}`} className="flex items-center gap-2">
                        <span className="text-slate-300">/</span>
                        <button
                          type="button"
                          onClick={() => goTeleboxCrumb(idx)}
                          className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700"
                        >
                          {part.name}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="flex flex-wrap items-center gap-2">
                  <button
                    onClick={teleboxDownloadSelected}
                    disabled={!teleboxSelected.length || !teleboxToken.trim()}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Download selected to {selectedFolder === "/" ? "/ (root)" : selectedFolder}
                  </button>

                  <button
                    onClick={() => teleboxUploadRef.current?.click()}
                    disabled={!teleboxToken.trim()}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Upload file(s)
                  </button>

                  <input
                    ref={teleboxUploadRef}
                    type="file"
                    multiple
                    className="hidden"
                    onChange={(e) => {
                      uploadTeleboxFiles(e.target.files);
                      e.currentTarget.value = "";
                    }}
                  />

                  <button
                    onClick={createTeleboxFolder}
                    disabled={!teleboxToken.trim()}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    New folder
                  </button>

                  <button
                    onClick={() => setTeleboxSelected(teleboxEntries.map((e) => e.id))}
                    disabled={!teleboxEntries.length}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Select all
                  </button>

                  <button
                    onClick={() => setTeleboxSelected([])}
                    disabled={!teleboxSelected.length}
                    className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Clear
                  </button>
                </div>

                <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white">
                  <div className="overflow-x-auto">
                    <table className="min-w-full table-fixed divide-y divide-slate-100">
                      <colgroup>
                        <col className="w-14" />
                        <col />
                        <col className="w-28" />
                        <col className="w-28" />
                      </colgroup>
                      <thead className="bg-slate-50/80">
                        <tr className="text-left text-xs uppercase tracking-wider text-slate-500">
                          <th className="px-4 py-3">Sel</th>
                          <th className="w-full px-4 py-3">Name</th>
                          <th className="px-4 py-3">Size</th>
                          <th className="px-4 py-3">Type</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {!teleboxEntries.length ? (
                          <tr>
                            <td colSpan={4} className="px-4 py-14 text-center text-sm text-slate-400">
                              {teleboxLoading ? "Loading TeleBox entries…" : "No TeleBox entries loaded yet."}
                            </td>
                          </tr>
                        ) : (
                          teleboxEntries.map((entry) => {
                            const selected = teleboxSelected.includes(entry.id);
                            return (
                              <tr key={entry.id} className={selected ? "bg-violet-50/80" : "hover:bg-slate-50/70"}>
                                <td className="px-4 py-3">
                                  <input
                                    type="checkbox"
                                    checked={selected}
                                    onChange={() => toggleTeleboxSelected(entry.id)}
                                    className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500"
                                  />
                                </td>
                                <td className="min-w-0 px-4 py-3">
                                  <div className="flex min-w-0 items-center gap-2">
                                    <span className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-slate-100 text-xs">
                                      {entry.isDir ? "📁" : "📄"}
                                    </span>
                                    {entry.isDir ? (
                                      <button
                                        type="button"
                                        onClick={() => openTeleboxFolder(entry)}
                                        className="block max-w-full min-w-0 flex-1 truncate text-left text-sm font-medium text-violet-700 hover:underline"
                                        title={entry.name}
                                      >
                                        {entry.name}
                                      </button>
                                    ) : (
                                      <span className="block max-w-full min-w-0 flex-1 truncate text-sm font-medium text-slate-800" title={entry.name}>
                                        {entry.name}
                                      </span>
                                    )}
                                  </div>
                                </td>
                                <td className="px-4 py-3 text-sm tabular-nums text-slate-500">
                                  {entry.sizeStr || (entry.size != null ? fmt(entry.size) : "—")}
                                </td>
                                <td className="px-4 py-3 text-sm text-slate-500">
                                  <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ${
                                    entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600"
                                  }`}>
                                    {entry.isDir ? "folder" : (entry.subType || entry.type || "file")}
                                  </span>
                                </td>
                              </tr>
                            );
                          })
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </section>
        )}

        {tab === "backblaze" && (
          <section className="space-y-4">
            <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm space-y-3">
              <div>
                <div className="text-xs font-bold uppercase tracking-wider text-slate-500">S3-compatible storage</div>
                <p className="mt-0.5 text-xs text-slate-400">
                  Works with Qencode media storage, Backblaze B2, or any other S3-compatible bucket. Enter the bucket name and the provider's path-style S3 API host — for Qencode that's <code>&lt;region&gt;.s3.qencode.com</code>, for Backblaze B2 it's <code>s3.&lt;region&gt;.backblazeb2.com</code>.
                </p>
              </div>

              {b2SavedConnections.length > 0 && (
                <div className="flex flex-wrap items-center gap-2">
                  <select
                    value={b2SelectedConnectionName}
                    onChange={(e) => loadSavedConnection(e.target.value)}
                    className="min-w-0 flex-1 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                  >
                    <option value="">Choose a saved connection…</option>
                    {b2SavedConnections.map((c) => (
                      <option key={c.name} value={c.name}>{c.name}</option>
                    ))}
                  </select>
                  {b2SelectedConnectionName && (
                    <button
                      onClick={() => deleteSavedConnection(b2SelectedConnectionName)}
                      className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50"
                    >
                      Delete
                    </button>
                  )}
                </div>
              )}
              <div className="grid gap-2 sm:grid-cols-2">
                <input
                  type="text"
                  value={b2BucketName}
                  onChange={(e) => setB2BucketNamePersist(e.target.value)}
                  placeholder="Bucket name (e.g. ogamaa)"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                />
                <input
                  type="text"
                  value={b2Region}
                  onChange={(e) => setB2RegionPersist(e.target.value)}
                  placeholder="Region (e.g. us-east-005)"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                />
                <input
                  type="text"
                  value={b2Host}
                  onChange={(e) => setB2HostPersist(e.target.value)}
                  placeholder="S3 API host (e.g. s3.us-east-005.backblazeb2.com)"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100 sm:col-span-2"
                />
                <input
                  type="text"
                  value={b2KeyId}
                  onChange={(e) => setB2KeyId(e.target.value)}
                  placeholder="Access Key ID"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                />
                <input
                  type="password"
                  value={b2AppKey}
                  onChange={(e) => setB2AppKey(e.target.value)}
                  placeholder="Secret Access Key"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100"
                />
                <input
                  type="text"
                  value={b2EndpointUrl}
                  onChange={(e) => setB2EndpointUrlPersist(e.target.value)}
                  placeholder="Playback/CDN URL, for shareable links only (e.g. https://ogamaa.media-storage.us-west.qencode.com)"
                  className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100 sm:col-span-2"
                />
                <div className="sm:col-span-2 space-y-1">
                  <input
                    type="text"
                    value={b2CfProxyUrl}
                    onChange={(e) => setB2CfProxyUrl(e.target.value)}
                    placeholder="Cloudflare proxy URL for free downloads (e.g. https://files.medpass.sryze.cc)"
                    className="min-w-0 w-full rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100"
                  />
                  <p className="text-xs text-slate-400 px-1">
                    When set, downloads route through Cloudflare (free, bypasses B2 bandwidth cap). Leave blank to use direct S3.
                  </p>
                </div>
                <div className="flex gap-2 sm:col-span-2">
                  <button
                    onClick={() => browseS3("")}
                    disabled={b2Loading || !b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()}
                    className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50"
                  >
                    {b2Loading ? "Browsing…" : "Browse"}
                  </button>
                  <button
                    onClick={saveCurrentConnection}
                    disabled={!b2BucketName.trim() || !b2Host.trim()}
                    className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Save connection
                  </button>
                </div>
              </div>

              {b2Error && (
                <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
                  {b2Error}
                </div>
              )}

              <div className="flex items-center justify-between gap-2">
                <div className="flex min-w-0 items-center gap-1 overflow-x-auto text-xs text-slate-500">
                  <button onClick={() => browseS3("")} className="rounded px-1.5 py-0.5 hover:bg-slate-100 font-semibold text-violet-600">root</button>
                  {b2Prefix.split("/").filter(Boolean).map((part, idx, arr) => (
                    <span key={idx} className="flex items-center gap-1">
                      <span>/</span>
                      <button
                        onClick={() => browseS3(arr.slice(0, idx + 1).join("/") + "/")}
                        className="rounded px-1.5 py-0.5 hover:bg-slate-100"
                      >
                        {part}
                      </button>
                    </span>
                  ))}
                </div>
                <div className="flex items-center gap-2">
                  <input ref={b2UploadRef} type="file" multiple className="hidden" onChange={(e) => uploadFilesToS3(e.target.files)} />
                  <button
                    onClick={() => b2UploadRef.current?.click()}
                    disabled={!b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()}
                    className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                  >
                    Upload here
                  </button>
                </div>
              </div>

              <div className="overflow-x-auto rounded-xl border border-slate-200">
                <table className="w-full text-left text-sm">
                  <thead className="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
                    <tr>
                      <th className="px-4 py-2">Name</th>
                      <th className="px-4 py-2">Size</th>
                      <th className="px-4 py-2">Modified</th>
                      <th className="px-4 py-2 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {b2Entries.length === 0 && (
                      <tr><td colSpan={4} className="px-4 py-6 text-center text-sm text-slate-400">
                        {b2Loading ? "Loading…" : "No entries yet — enter credentials and click Browse."}
                      </td></tr>
                    )}
                    {b2Entries.map((entry) => (
                      <tr key={entry.key} className="hover:bg-slate-50/70">
                        <td className="px-4 py-2">
                          {entry.isDir ? (
                            <button onClick={() => browseS3(entry.key)} className="font-medium text-violet-600 hover:underline">
                              📁 {entry.name}
                            </button>
                          ) : (
                            <span>{entry.name}</span>
                          )}
                        </td>
                        <td className="px-4 py-2 text-slate-500">{entry.sizeStr || (entry.isDir ? "—" : "")}</td>
                        <td className="px-4 py-2 text-slate-500">{entry.lastModified || "—"}</td>
                        <td className="px-4 py-2 text-right">
                          {!entry.isDir && (
                            <div className="inline-flex items-center gap-1.5">
                              <IconBtn title="Get shareable link (1 hour)" onClick={() => getS3SignedLink(entry.key)}>
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244" />
                                </svg>
                              </IconBtn>
                              <IconBtn title="Download" onClick={() => downloadFromS3(entry.key)}>
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" />
                                </svg>
                              </IconBtn>
                              <IconBtn title="Delete" onClick={() => deleteFromS3(entry.key)} danger>
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673A2.25 2.25 0 0 1 15.916 21.75H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" />
                                </svg>
                              </IconBtn>
                            </div>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </section>
        )}

        {showInfoFile && (
          <InfoModal
            file={showInfoFile}
            onClose={() => setShowInfoFile(null)}
          />
        )}

        {showPreviewFile && (
          <PreviewModal
            title={showPreviewFile.name}
            url={`/api/files/${encodeURIComponent(showPreviewFile.id)}/stream`}
            onClose={() => setShowPreviewFile(null)}
          />
        )}

        {showCropFile && (
          <CropModal
            file={showCropFile}
            onClose={() => setShowCropFile(null)}
            onDone={(values) => {
              setSettings((prev) => ({ ...prev, cropEnabled: values.cropEnabled, cropLeft: values.cropLeft, cropRight: values.cropRight, cropTop: values.cropTop, cropBottom: values.cropBottom }));
              setSelectedForEncode(showCropFile.id);
              setTab("encode");
              setShowCropFile(null);
              setToast(values.cropEnabled ? "Crop settings applied" : "Crop settings cleared");
            }}
          />
        )}
        {showTrimFile && (
          <TrimModal
            file={showTrimFile}
            onClose={() => setShowTrimFile(null)}
            onTrimStarted={() => {
              setToast("Trim job started");
              refreshJobs();
            }}
          />
        )}

        {showAdvancedTrimCropFile && (
          <AdvancedTrimCropModal
            file={showAdvancedTrimCropFile}
            onClose={() => setShowAdvancedTrimCropFile(null)}
            onProcessingStarted={() => {
              setToast("Advanced trim & crop job started");
              refreshJobs();
            }}
          />
        )}

        {showMoveFiles && (
          <MoveModal
            files={showMoveFiles}
            folders={folders}
            onClose={() => setShowMoveFiles(null)}
            onMoved={() => {
              setToast("Move completed");
              clearSelected();
              refreshFiles();
            }}
          />
        )}

        {showMergeFiles && (
          <MergeModal
            files={showMergeFiles}
            onClose={() => setShowMergeFiles(null)}
            onMergeStarted={() => {
              setToast("Merge job started");
              refreshJobs();
            }}
          />
        )}

        {showCreateFolder && (
          <CreateFolderModal
            onClose={() => setShowCreateFolder(false)}
            onCreated={(folder) => {
              setToast(`Folder created: ${folder}`);
              refreshFiles();
            }}
          />
        )}

        {showCredentialsModal && (
          <CredentialsModal
            settings={{
              b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections,
              remoteUrl, remoteCredentials, remoteUrlHistory,
              teleboxToken, teleboxWebToken,
              encodeAutoS3, uploadDirectToRemote,
              encodePresets: presets,
            }}
            onClose={() => setShowCredentialsModal(false)}
            onSettingsUpdated={(newSettings) => {
              // Update all the settings from the merged credentials
              if (typeof newSettings.b2KeyId === "string") setB2KeyId(newSettings.b2KeyId);
              if (typeof newSettings.b2AppKey === "string") setB2AppKey(newSettings.b2AppKey);
              if (typeof newSettings.b2BucketName === "string") { setB2BucketName(newSettings.b2BucketName); try { localStorage.setItem("s3BucketName", newSettings.b2BucketName); } catch {} }
              if (typeof newSettings.b2Host === "string") { setB2Host(newSettings.b2Host); try { localStorage.setItem("s3Host", newSettings.b2Host); } catch {} }
              if (typeof newSettings.b2EndpointUrl === "string") { setB2EndpointUrl(newSettings.b2EndpointUrl); try { localStorage.setItem("s3EndpointUrl", newSettings.b2EndpointUrl); } catch {} }
              if (typeof newSettings.b2Region === "string") { setB2Region(newSettings.b2Region); try { localStorage.setItem("s3Region", newSettings.b2Region); } catch {} }
              if (typeof newSettings.b2CfProxyUrl === "string") setB2CfProxyUrl(newSettings.b2CfProxyUrl);
              if (Array.isArray(newSettings.b2SavedConnections)) { setB2SavedConnections(newSettings.b2SavedConnections as SavedS3Connection[]); try { localStorage.setItem("s3SavedConnections", JSON.stringify(newSettings.b2SavedConnections)); } catch {} }
              if (typeof newSettings.remoteUrl === "string") setRemoteUrl(newSettings.remoteUrl);
              if (newSettings.remoteCredentials && typeof newSettings.remoteCredentials === 'object') {
                setRemoteCredentials(newSettings.remoteCredentials as Record<string, RemoteCredentials>);
                try { localStorage.setItem("remoteCredentials", JSON.stringify(newSettings.remoteCredentials)); } catch {}
              }
              if (Array.isArray(newSettings.remoteUrlHistory)) { setRemoteUrlHistory(newSettings.remoteUrlHistory as string[]); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(newSettings.remoteUrlHistory)); } catch {} }
              if (typeof newSettings.remoteHfToken === "string") setRemoteHfToken(newSettings.remoteHfToken);
              if (typeof newSettings.remoteHfS3AccessKeyId === "string") setRemoteHfS3AccessKeyId(newSettings.remoteHfS3AccessKeyId);
              if (typeof newSettings.remoteHfS3SecretAccessKey === "string") setRemoteHfS3SecretAccessKey(newSettings.remoteHfS3SecretAccessKey);
              if (typeof newSettings.teleboxToken === "string") setTeleboxToken(newSettings.teleboxToken);
              if (typeof newSettings.teleboxWebToken === "string") setTeleboxWebToken(newSettings.teleboxWebToken);
              if (typeof newSettings.encodeAutoS3 === "boolean") { setEncodeAutoS3(newSettings.encodeAutoS3); try { localStorage.setItem("encodeAutoS3", newSettings.encodeAutoS3 ? "1" : "0"); } catch {} }
              if (typeof newSettings.uploadDirectToRemote === "boolean") { setUploadDirectToRemoteState(newSettings.uploadDirectToRemote); try { localStorage.setItem("uploadDirectToRemote", newSettings.uploadDirectToRemote ? "1" : "0"); } catch {} }
              if (Array.isArray(newSettings.encodePresets)) setPresets(newSettings.encodePresets as EncodePreset[]);
            }}
          />
        )}

        {toast && <Toast message={toast} onDone={() => setToast(null)} />}
      </div>
    </div>
  );
}