File size: 270,024 Bytes
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024e9c4
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useRef, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"

import {
  Bot,
  User,
  Send,
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  RotateCcw,
  X,
  Copy,
  Share2,
  ThumbsUp,
  ThumbsDown,
  FileText,
  Paperclip,
  ShoppingCart,
  Info,
  Star,
  Headphones,
  Search,
  Package,
  Heart,
  CreditCard,
  Shield,
  Zap,
  Crown,
  TrendingUp,
  Filter,
  Edit,
  Bell,
  AlertCircle,
  HelpCircle,
  MessageCircle,
  Mail,
  Settings,
} from "lucide-react"
import "./AIChatAssistant.css"
import { useSelector } from "react-redux"
import {
  useGetProductsQuery,
} from "../store/slices/productApiSlice"
import { getFullApiUrl } from "../utils/apiConfig"
import {
  useGetWishlistsQuery,
  useGetCartsQuery,
  useGetOrdersQuery,
} from "../store/slices/userApiSlice"

const AIChatAssistant = ({ isOpen: externalIsOpen, setIsOpen: setExternalIsOpen, style }) => {

  const [internalIsOpen, setInternalIsOpen] = useState(false)
  const isOpen = externalIsOpen !== undefined ? externalIsOpen : internalIsOpen
  const setIsOpen = setExternalIsOpen || setInternalIsOpen

  const [isFullScreen, setIsFullScreen] = useState(true)
  const [messages, setMessages] = useState([])
  const [inputMessage, setInputMessage] = useState("")
  const [isTyping, setIsTyping] = useState(false)
  const [isSpeaking, setIsSpeaking] = useState(false)
  const [isListening, setIsListening] = useState(false)
  const [voiceEnabled, setVoiceEnabled] = useState(false)
  const [showTooltip, setShowTooltip] = useState(true)
  const [tooltipTimeoutRef] = useState(useRef(null))

  const inputRef = useRef(null)
  const messagesEndRef = useRef(null)
  const recognitionRef = useRef(null)

  const { userData, isLoggedIn } = useSelector((state) => state.auth)
  const userId = userData?._id
  const user = userData 

  const { data: productsData, isLoading: productsLoading } = useGetProductsQuery()
  const { data: wishlistsData, isLoading: wishlistsLoading } = useGetWishlistsQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })
  const { data: cartsData, isLoading: cartsLoading } = useGetCartsQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })
  const { data: ordersData, isLoading: ordersLoading } = useGetOrdersQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })

  const [currentSearchResults, setCurrentSearchResults] = useState([])
  const [currentCartItems, setCurrentCartItems] = useState([])
  const [currentWishlistItems, setCurrentWishlistItems] = useState([])
  const [currentOrders, setCurrentOrders] = useState([])
  const [isProcessing, setIsProcessing] = useState(false)
  const [currentTask, setCurrentTask] = useState(null)
  const [searchHistory, setSearchHistory] = useState([])

  const [conversationContext, setConversationContext] = useState({
    currentTopic: null,
    lastAction: null,
    userPreferences: {
      favoriteCategories: [],
      favoriteBrands: [],
      priceRange: { min: 0, max: 50000 },
      preferredPaymentMethods: [],
      shoppingFrequency: 'occasional',
      interests: []
    },
    searchHistory: [],
    currentFilters: {},
    pendingAction: null,
    conversationFlow: [],
    userPersonality: {
      communicationStyle: 'friendly',
      decisionStyle: 'careful',
      urgencyLevel: 'normal',
      techSavviness: 'moderate'
    },
    sessionData: {
      startTime: new Date(),
      messageCount: 0,
      topicsDiscussed: [],
      satisfactionLevel: 5
    }
  })

  const [currentSubActions, setCurrentSubActions] = useState(null)
  const [subActionHistory, setSubActionHistory] = useState([])
  const [fallbackProductsData, setFallbackProductsData] = useState({ products: [] })

  useEffect(() => {
    const fetchFallbackProducts = async () => {
    
      if ((!productsData?.products || productsData.products.length === 0) && 
          (!fallbackProductsData?.products || fallbackProductsData.products.length === 0)) {
        try {
          const response = await fetch(`${getFullApiUrl()}/products`)
          if (response.ok) {
            const data = await response.json()
            if (data.success && Array.isArray(data.products)) {
              setFallbackProductsData({ products: data.products })
            }
          }
        } catch (error) {
          
        }
      }
    }

    fetchFallbackProducts()
  }, [productsData, fallbackProductsData])

  const quickActions = [
    {
      action: 'search_products',
      label: 'Search Products',
      icon: Search,
      color: '#667eea',
      subActions: [
        { action: 'search_by_name', label: 'Search by Name', icon: Search, color: '#667eea' },
        { action: 'search_by_category', label: 'Search by Category', icon: Package, color: '#764ba2' },
        { action: 'search_by_price', label: 'Search by Price', icon: CreditCard, color: '#f093fb' },
        { action: 'search_by_brand', label: 'Search by Brand', icon: Crown, color: '#667eea' },
        { action: 'advanced_search', label: 'Advanced Search', icon: Filter, color: '#764ba2' },
        { action: 'trending_products', label: 'Trending Products', icon: TrendingUp, color: '#f093fb' },
        { action: 'view_products', label: 'View All Products', icon: Package, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'cart_management',
      label: 'My Cart',
      icon: ShoppingCart,
      color: '#764ba2',
      subActions: [
        { action: 'view_cart', label: 'View Cart', icon: ShoppingCart, color: '#764ba2' },
        { action: 'navigate_to_cart', label: 'Manage Cart', icon: Edit, color: '#f093fb' },
        { action: 'checkout', label: 'Proceed to Checkout', icon: CreditCard, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'wishlist_management',
      label: 'My Wishlist',
      icon: Heart,
      color: '#f093fb',
      subActions: [
        { action: 'view_wishlist', label: 'View Wishlist', icon: Heart, color: '#f093fb' },
        { action: 'navigate_to_wishlist', label: 'Manage Wishlist', icon: Edit, color: '#667eea' },
        { action: 'share_wishlist', label: 'Share Wishlist', icon: Share2, color: '#f093fb' },
        { action: 'price_alerts', label: 'Price Alerts', icon: Bell, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'order_tracking',
      label: 'Track Orders',
      icon: Package,
      color: '#667eea',
      subActions: [
        { action: 'view_orders', label: 'View All Orders', icon: Package, color: '#667eea' },
        { action: 'navigate_to_orders', label: 'Manage Orders', icon: Edit, color: '#764ba2' },
        { action: 'track_specific_order', label: 'Track Specific Order', icon: Search, color: '#764ba2' },
        { action: 'order_status', label: 'Check Order Status', icon: Info, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'payment_help',
      label: 'Payment Help',
      icon: CreditCard,
      color: '#764ba2',
      subActions: [
        { action: 'payment_methods', label: 'Payment Methods', icon: CreditCard, color: '#764ba2' },
        { action: 'payment_issues', label: 'Payment Issues', icon: AlertCircle, color: '#f093fb' },
        { action: 'refund_status', label: 'Refund Status', icon: RotateCcw, color: '#667eea' },
        { action: 'billing_help', label: 'Billing Help', icon: FileText, color: '#764ba2' },
        { action: 'security_info', label: 'Security Info', icon: Shield, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },

    {
      action: 'recommendations',
      label: 'Recommendations',
      icon: Star,
      color: '#667eea',
      subActions: [
        { action: 'personalized_recommendations', label: 'Personalized', icon: Star, color: '#667eea' },
        { action: 'trending_recommendations', label: 'Trending', icon: TrendingUp, color: '#764ba2' },
        { action: 'category_recommendations', label: 'By Category', icon: Package, color: '#f093fb' },
        { action: 'price_recommendations', label: 'By Price Range', icon: CreditCard, color: '#667eea' },
        { action: 'similar_products', label: 'Similar Products', icon: Copy, color: '#764ba2' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'customer_support',
      label: 'Customer Support',
      icon: Headphones,
      color: '#764ba2',
      subActions: [
        { action: 'contact_support', label: 'Contact Support', icon: Headphones, color: '#764ba2' },
        { action: 'faq', label: 'FAQ', icon: HelpCircle, color: '#f093fb' },
        { action: 'live_chat', label: 'Live Chat', icon: MessageCircle, color: '#667eea' },
        { action: 'email_support', label: 'Email Support', icon: Mail, color: '#764ba2' },
        { action: 'technical_help', label: 'Technical Help', icon: Settings, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    }
  ]

  const suggestions = [
    "Show me trending products",
    "Help me find a gift",
    "Track my order",
    "Customer support"
  ]

  const quickReplies = [
    "Yes, please!",
    "No, thanks",
    "Tell me more",
    "I need help"
  ]

  const contextualSuggestions = {
    general: ["What's trending today?", "Show me Premium watches", "Help me find a gift", "Check my order status"],
    product: ["Tell me more about this item", "Show similar products", "Check availability", "Add to wishlist"],
    order: ["Track my recent order", "Change delivery address", "Cancel an order", "Return policy"],
    support: ["Speak to a human agent", "Report an issue", "Account settings", "Billing questions"],
  }

  useEffect(() => {
    if (productsData?.products) {
      setCurrentSearchResults(productsData.products)
    }
  }, [productsData])

  useEffect(() => {
    if (cartsData?.carts?.[0]?.cartItems) {
      const mappedCartItems = cartsData.carts[0].cartItems.map(item => ({
        ...item,
        quantity: item.qty || 1, 
        productId: item.productId,
        name: item.name,
        price: item.price,
        category: item.category,
        image: item.image
      }))
      setCurrentCartItems(mappedCartItems)
    }
  }, [cartsData])

  useEffect(() => {

    if (wishlistsData?.wishlist) {
      const mappedWishlistItems = wishlistsData.wishlist.map(item => ({
        ...item,
        productId: item.productId,
        name: item.name,
        price: item.price,
        category: item.category,
        image: item.image
      }))
      setCurrentWishlistItems(mappedWishlistItems)
    }
  }, [wishlistsData, wishlistsLoading, userId])

  useEffect(() => {
    if (ordersData?.orders) {
      const mappedOrders = ordersData.orders.map(order => ({
        ...order,
        orderItems: order.orderItems?.map(item => ({
          ...item,
          quantity: item.qty || 1, 
          productId: item.productId,
          name: item.name,
          price: item.price,
          category: item.category
        })) || []
      }))
      setCurrentOrders(mappedOrders)
    }
  }, [ordersData])

  useEffect(() => {
    if (messages.length === 0) {
      const timeOfDay = new Date().getHours()
      let greeting = ''

      if (timeOfDay < 12) {
        greeting = 'Good morning'
      } else if (timeOfDay < 17) {
        greeting = 'Good afternoon'
      } else {
        greeting = 'Good evening'
      }

      setMessages([
        {
          id: 1,
          type: "ai",
          message: `${greeting}! 👋 I'm your personalized AI shopping assistant at MKCart! 🤖\n\nI'm here to make your shopping experience amazing with:\n\n🎯 Smart Functions & Sub-Functions:\n\n🔍 Search Products\n• Search by Name\n• Search by Category\n• Search by Price Range\n• Search by Brand\n• Advanced Search\n• Trending Products\n\n🛒 Cart Management\n• View Cart\n• Add to Cart\n• Remove from Cart\n• Update Quantity\n• Clear Cart\n• Proceed to Checkout\n\n💖 Wishlist Management\n• View Wishlist\n• Add to Wishlist\n• Remove from Wishlist\n• Share Wishlist\n• Price Alerts\n\n📦 Order Tracking\n• View All Orders\n• Track Specific Order\n• Check Order Status\n• Cancel Order\n• Return Order\n\n⭐ Recommendations\n• Personalized Picks\n• Trending Items\n• Category Recommendations\n• Price-based Recommendations\n• Similar Products\n\n💳 Payment Help\n• Payment Methods\n• Payment Issues\n• Refund Status\n• Billing Help\n• Security Info\n\n📋 Product Details\n• Product Information\n• Product Reviews\n• Compare Products\n• Check Availability\n• Specifications\n\n🎧 Customer Support\n• Contact Support\n• FAQ\n• Live Chat\n• Email Support\n• Technical Help\n\n🎤 Voice Interaction: I can understand and respond to voice commands!\n\n💬 ChatGPT-like Experience: I provide intelligent, contextual responses and remember our conversations.\n\nWhat would you like to explore today? Just type or speak naturally!`,
          timestamp: new Date(),
        },
      ])
    }
  }, [])

  const searchProducts = async (keyword, filters = {}) => {
    try {
      
      const searchParams = new URLSearchParams({
        keyword: keyword || '',
        category: filters.category || '',
        minPrice: filters.minPrice || '',
        maxPrice: filters.maxPrice || '',
        brand: filters.brand || '',
        rating: filters.rating || '',
        availability: filters.availability || '',
        stock: filters.stock || '',
        seller: filters.seller || '',
        premiumBadge: filters.premiumBadge || ''
      })

      const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)

      if (!response.ok) {
        throw new Error(`API request failed: ${response.status}`)
      }

      const data = await response.json()

      if (data.success && data.products && Array.isArray(data.products)) {
        setCurrentSearchResults(data.products)

        const productList = data.products.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
        ).join('\n')

        const suggestions = [
          keyword.toLowerCase().includes('phone') ? 'smartphone' : 'electronics',
          keyword.toLowerCase().includes('shirt') ? 'clothing' : 'fashion',
          keyword.toLowerCase().includes('book') ? 'literature' : 'books'
        ]

        const popularSearches = ['smartphones', 'laptops', 'shoes', 'watches', 'headphones']
        const categories = ['Electronics', 'Fashion', 'Home & Garden', 'Sports', 'Beauty']

        let searchResponse = getRandomResponse(responseLibraries.search, 'results')
          .replace('{query}', keyword)
          .replace('{count}', data.products.length)
          .replace('{products}', productList)

        if (data.products.length < 3) {
          const suggestionResponse = getRandomResponse(responseLibraries.search, 'suggestions')
            .replace('{suggestion1}', suggestions[0])
            .replace('{suggestion2}', suggestions[1])
            .replace('{suggestion3}', suggestions[2])
            .replace('{popular1}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{popular2}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{category1}', categories[Math.floor(Math.random() * categories.length)])
            .replace('{category2}', categories[Math.floor(Math.random() * categories.length)])

          searchResponse += `\n\n${suggestionResponse}`
        }

        if (filters.brand && data.products.length === 0) {
          const fallbackResults = await searchProducts(filters.brand)
          if (fallbackResults.products && fallbackResults.products.length > 0) {
            return {
              success: true,
              products: fallbackResults.products,
              message: `🏷️ Found ${fallbackResults.products.length} products related to "${filters.brand}":\n\n${fallbackResults.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
            }
          }
        }

        return {
          success: true,
          products: data.products,
          message: searchResponse
        }
      }

      if (productsData?.products) {
        let filteredProducts = productsData.products

        if (keyword) {
          filteredProducts = filteredProducts.filter(product =>
            product.name?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.description?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.category?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.seller?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.PremiumBadge?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.specifications?.Material?.toLowerCase().includes(keyword.toLowerCase())
          )
        }

        if (filters.category) {
          filteredProducts = filteredProducts.filter(product =>
            product.category?.toLowerCase().includes(filters.category.toLowerCase())
          )
        }

        if (filters.brand) {
          const brandFilter = filters.brand.toLowerCase()
          filteredProducts = filteredProducts.filter(product => {
          
            const productName = product.name?.toLowerCase() || ''
            const productBrand = product.brand?.toLowerCase() || ''
            const productSeller = product.seller?.toLowerCase() || ''
            const productManufacturer = product.manufacturer?.toLowerCase() || ''
            const productCompany = product.company?.toLowerCase() || ''
            const productMake = product.make?.toLowerCase() || ''

            const productDescription = product.description?.toLowerCase() || ''
            const productSpecs = JSON.stringify(product.specifications || {}).toLowerCase()
            
            return productName.includes(brandFilter) ||
                   productBrand.includes(brandFilter) ||
                   productSeller.includes(brandFilter) ||
                   productManufacturer.includes(brandFilter) ||
                   productCompany.includes(brandFilter) ||
                   productMake.includes(brandFilter) ||
                   productDescription.includes(brandFilter) ||
                   productSpecs.includes(brandFilter)
          })
        }

        if (filters.minPrice || filters.maxPrice) {
          filteredProducts = filteredProducts.filter(product => {
            const price = parseFloat(product.price) || 0
            const minPrice = parseFloat(filters.minPrice) || 0
            const maxPrice = parseFloat(filters.maxPrice) || Infinity

            if (maxPrice === Infinity) {
              
              return price >= minPrice
            } else if (minPrice === 0) {
              
              return price <= maxPrice
            } else {
              
              return price >= minPrice && price <= maxPrice
            }
          })
        }

        if (filters.stock) {
          filteredProducts = filteredProducts.filter(product =>
            product.stock > 0
          )
        }

        if (filters.premiumBadge) {
          filteredProducts = filteredProducts.filter(product =>
            product.PremiumBadge
          )
        }

        filteredProducts.sort((a, b) => {
          
          if (b.ratings !== a.ratings) {
            return b.ratings - a.ratings
          }
          
          return a.price - b.price
        })

        setCurrentSearchResults(filteredProducts)

        if (filteredProducts.length > 0) {
          const productList = filteredProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
          ).join('\n')

          let searchResponse = getRandomResponse(responseLibraries.search, 'results')
            .replace('{query}', keyword)
            .replace('{count}', filteredProducts.length)
            .replace('{products}', productList)

          return {
            success: true,
            products: filteredProducts,
            message: searchResponse
          }
        } else {
          
          const suggestions = [
            keyword.toLowerCase().includes('phone') ? 'smartphone' : 'electronics',
            keyword.toLowerCase().includes('shirt') ? 'clothing' : 'fashion',
            keyword.toLowerCase().includes('book') ? 'literature' : 'books'
          ]

          const popularSearches = ['smartphones', 'laptops', 'shoes', 'watches', 'headphones']
          const categories = ['Electronics', 'Fashion', 'Home & Garden', 'Sports', 'Beauty']

          let noResultsResponse = getRandomResponse(responseLibraries.search, 'noResults')
            .replace('{query}', keyword)

          const suggestionResponse = getRandomResponse(responseLibraries.search, 'suggestions')
            .replace('{suggestion1}', suggestions[0])
            .replace('{suggestion2}', suggestions[1])
            .replace('{suggestion3}', suggestions[2])
            .replace('{popular1}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{popular2}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{category1}', categories[Math.floor(Math.random() * categories.length)])
            .replace('{category2}', categories[Math.floor(Math.random() * categories.length)])

          noResultsResponse += `\n\n${suggestionResponse}`

          return {
            success: false,
            products: [],
            message: noResultsResponse
          }
        }
      }

      return {
        success: false,
        products: [],
        message: "Sorry, I couldn't search for products right now. Please try again later."
      }
    } catch (error) {

      if (productsData?.products) {
        const filteredProducts = productsData.products.filter(product =>
          product.name?.toLowerCase().includes((keyword || '').toLowerCase())
        )
        setCurrentSearchResults(filteredProducts)

        return {
          success: true,
          products: filteredProducts,
          message: `Found ${filteredProducts.length} products matching "${keyword}":\n\n` +
            filteredProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
            ).join('\n')
        }
      }

      return {
        success: false,
        products: [],
        message: "Sorry, there was an error searching for products. Please try again."
      }
    }
  }

  const getCartSummary = () => {
    if (!currentCartItems || currentCartItems.length === 0) {
      return {
        count: 0,
        total: 0,
        items: [],
        message: getRandomResponse(responseLibraries.cart, 'empty')
      }
    }

    const validItems = currentCartItems.filter(item =>
      item && item.productId && (item.name || item.productName)
    )

    const total = validItems.reduce((sum, item) => {
      const quantity = parseInt(item.quantity || item.qty || 1)
      const price = parseFloat(item.price || item.productPrice || 0)
      return sum + (price * quantity)
    }, 0)

    const subtotal = Math.round(total * 100) / 100
    const shipping = subtotal > 999 ? 'Free' : '₹99'
    const tax = Math.round(subtotal * 0.18 * 100) / 100 
    const finalTotal = subtotal + (shipping === 'Free' ? 0 : 99) + tax

    const itemsList = validItems.map(item => {
      const quantity = parseInt(item.quantity || item.qty || 1)
      const price = parseFloat(item.price || item.productPrice || 0)
      const itemTotal = quantity * price
      return `• ${item.name || item.productName} x${quantity} - ₹${itemTotal}`
    }).join('\n')

    const recommendations = generateRandomData.products()
    const recommendationsList = `• ${recommendations.name} - ${recommendations.price} (${recommendations.rating}⭐)`

    let cartResponse = getRandomResponse(responseLibraries.cart, 'items')
      .replace('{items}', itemsList)
      .replace('{subtotal}', `₹${subtotal}`)
      .replace('{shipping}', shipping)
      .replace('{tax}', `₹${tax}`)
      .replace('{total}', `₹${finalTotal}`)

    if (validItems.length > 0) {
      const recommendationResponse = getRandomResponse(responseLibraries.cart, 'recommendations')
        .replace('{recommendations}', recommendationsList)
      cartResponse += `\n\n${recommendationResponse}`
    }

    return {
      count: validItems.length,
      total: finalTotal,
      items: validItems.map(item => ({
        ...item,
        productId: item.productId || item._id,
        name: item.name || item.productName || 'Unknown Product',
        quantity: parseInt(item.quantity || item.qty || 1),
        price: parseFloat(item.price || item.productPrice || 0),
        category: item.category || 'General',
        image: item.image || item.productImage || ''
      })),
      message: cartResponse,
      subtotal: subtotal,
      shipping: shipping,
      tax: tax
    }
  }

  const getWishlistSummary = () => {
    console.log('getWishlistSummary called with currentWishlistItems:', currentWishlistItems)
    if (!currentWishlistItems || currentWishlistItems.length === 0) {
      console.log('No wishlist items found, returning empty summary')
      return {
        count: 0,
        items: [],
        message: getRandomResponse(responseLibraries.wishlist, 'empty')
      }
    }

    const validItems = currentWishlistItems.filter(item =>
      item && item.productId && (item.name || item.productName)
    )

    console.log('Valid wishlist items found:', validItems.length)

    const itemsList = validItems.map(item => {
      const price = parseFloat(item.price || item.productPrice || 0)
      const rating = item.rating || 4.0
      return `• ${item.name || item.productName} - ₹${price} (${rating}⭐)`
    }).join('\n')

    const hasPriceDrops = Math.random() > 0.7 
    let wishlistResponse = getRandomResponse(responseLibraries.wishlist, 'items')
      .replace('{items}', itemsList)

    if (hasPriceDrops && validItems.length > 0) {
      const priceDropItem = validItems[Math.floor(Math.random() * validItems.length)]
      const originalPrice = parseFloat(priceDropItem.price || priceDropItem.productPrice || 0)
      const newPrice = Math.round(originalPrice * 0.8) 

      const priceDropsList = `• ${priceDropItem.name || priceDropItem.productName} - Now ₹${newPrice} (was ₹${originalPrice})`

      const priceAlertResponse = getRandomResponse(responseLibraries.wishlist, 'priceAlerts')
        .replace('{priceDrops}', priceDropsList)

      wishlistResponse += `\n\n${priceAlertResponse}`
    }

    return {
      count: validItems.length,
      items: validItems.map(item => ({
        ...item,
        productId: item.productId || item._id,
        name: item.name || item.productName || 'Unknown Product',
        price: parseFloat(item.price || item.productPrice || 0),
        category: item.category || 'General',
        image: item.image || item.productImage || '',
        rating: item.rating || 0
      })),
      message: wishlistResponse
    }
  }

  const getOrderSummary = () => {
    if (!currentOrders || currentOrders.length === 0) {
      return {
        count: 0,
        items: [],
        message: "📦 No orders found in your account.\n\n💡 Start shopping to see your order history here!\n\n✨ New customer? Welcome! Your orders will appear here once you make your first purchase."
      }
    }

    const validOrders = currentOrders.filter(order =>
      order && (order._id || order.orderId)
    )

    const ordersList = validOrders.slice(0, 5).map(order => {
      const orderId = order._id || order.orderId
      const amount = parseFloat(order.amount || order.total || 0)
      const status = order.status || 'Processing'
      const orderDate = new Date(order.createdAt || order.orderDate || new Date())
      const formattedDate = orderDate.toLocaleDateString('en-IN')

      return `• Order #${orderId.slice(-6)} - ₹${amount} (${status}) - ${formattedDate}`
    }).join('\n')

    let orderResponse = getRandomResponse(responseLibraries.tracking, 'multiple')
      .replace('{orders}', ordersList)

    const statusCounts = validOrders.reduce((acc, order) => {
      const status = order.status || 'Processing'
      acc[status] = (acc[status] || 0) + 1
      return acc
    }, {})

    const statusSummary = Object.entries(statusCounts)
      .map(([status, count]) => `${status}: ${count}`)
      .join(', ')

    orderResponse += `\n\n📊 Order Status Summary:\n${statusSummary}`

    return {
      count: validOrders.length,
      items: validOrders.map(order => ({
        ...order,
        orderId: order._id || order.orderId,
        amount: parseFloat(order.amount || order.total || 0),
        status: order.status || 'Processing',
        orderDate: order.createdAt || order.orderDate || new Date(),
        orderItems: (order.orderItems || []).map(item => ({
          ...item,
          productId: item.productId || item._id,
          name: item.name || item.productName || 'Unknown Product',
          quantity: parseInt(item.quantity || item.qty || 1),
          price: parseFloat(item.price || item.productPrice || 0)
        }))
      })),
      message: orderResponse
    }
  }

  const generateRecommendations = async () => {
   
    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    
    if (!availableProducts || !Array.isArray(availableProducts) || availableProducts.length === 0) {
     
      const trendingProducts = await getTrendingProducts()
      return trendingProducts
    }

    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()

    const userItems = [...cartSummary.items, ...wishlistSummary.items]
    const userCategories = [...new Set(userItems.map(item => item.category).filter(Boolean))]
    const userBrands = [...new Set(userItems.map(item => item.brand).filter(Boolean))]

    let recommendations = []

    if (userCategories.length > 0) {
      const categoryRecs = availableProducts
        .filter(product =>
          userCategories.includes(product.category) &&
          !userItems.some(item => item.productId === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 3)
      recommendations.push(...categoryRecs)
    }

    if (userBrands.length > 0) {
      const brandRecs = availableProducts
        .filter(product =>
          userBrands.includes(product.brand) &&
          !userItems.some(item => item.productId === product._id) &&
          !recommendations.some(rec => rec._id === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 2)
      recommendations.push(...brandRecs)
    }

    if (recommendations.length < 5) {
      const trendingRecs = availableProducts
        .filter(product =>
          !userItems.some(item => item.productId === product._id) &&
          !recommendations.some(rec => rec._id === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5 - recommendations.length)
      recommendations.push(...trendingRecs)
    }

    return recommendations.slice(0, 5)
  }

  useEffect(() => {
    if (typeof window !== "undefined") {
      
      if ("webkitSpeechRecognition" in window || "SpeechRecognition" in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
        recognitionRef.current = new SpeechRecognition()
        recognitionRef.current.continuous = false
        recognitionRef.current.interimResults = false
        recognitionRef.current.lang = "en-US"

        recognitionRef.current.onstart = () => {
          setIsListening(true)
          
          const aiMessage = {
            id: Date.now(),
            type: "ai",
            message: "🎤 I'm listening... Please speak clearly!",
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, aiMessage])
        }

        recognitionRef.current.onresult = (event) => {
          const transcript = event.results[0][0].transcript
          setInputMessage(transcript)
          setIsListening(false)

          const aiMessage = {
            id: Date.now(),
            type: "ai",
            message: `🎤 I heard: "${transcript}"\n\nProcessing your voice command...`,
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, aiMessage])

          setTimeout(() => {
            handleSendMessage()
          }, 1000)
        }

        recognitionRef.current.onerror = (event) => {
          setIsListening(false)
          console.error('Speech recognition error:', event.error)

          const errorMessage = {
            id: Date.now(),
            type: "ai",
            message: "❌ Sorry, I couldn't understand that. Please try speaking again or type your message.",
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, errorMessage])
        }

        recognitionRef.current.onend = () => {
          setIsListening(false)
        }
      }

    }
  }, [])

  useEffect(() => {
    if (messages.length > 0) {
      const lastMessage = messages[messages.length - 1]
      if (lastMessage.type === 'ai') {
        scrollToBottom()
      }
    }
  }, [messages])

  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
    }, 100) 
  }

  const handleDirectKeywords = async (userMessage, lowerMessage) => {
    
    const productKeywords = ['iphone', 'laptop', 'shoes', 'headphones', 'watch', 'camera', 'phone', 'tablet', 'computer', 'mouse', 'keyboard', 'speaker', 'earphones', 'samsung', 'apple', 'dell', 'hp', 'lenovo', 'nike', 'adidas', 'puma', 'sony', 'lg', 'canon', 'nikon']

    const categoryKeywords = ['mobile phones', 'accessories', 'laptops', 'headphones', 'shoes', 'electronics', 'men', 'women', 'toys', 'musical instruments', 'mobile', 'phones', 'phone', 'laptop', 'computer', 'headphone', 'earphones', 'shoe', 'footwear', 'electronic', 'tech', 'toy', 'music', 'instrument', 'smartphone', 'notebook', 'pc', 'audio', 'sound', 'sneakers', 'boots', 'gadgets', 'devices', 'games', 'play', 'children', 'kids']

    const actionKeywords = {
      'cart': ['cart', 'basket', 'shopping cart', 'add to cart', 'remove from cart', 'view cart', 'show cart', 'checkout', 'buy', 'purchase'],
      'wishlist': ['wishlist', 'favorites', 'favourite', 'save', 'wish', 'add to wishlist', 'remove from wishlist', 'view wishlist', 'show wishlist'],
      'orders': ['order', 'orders', 'track', 'tracking', 'delivery', 'shipping', 'status', 'my orders', 'order status', 'track order'],
      'price': ['price', 'cost', 'budget', 'under', 'above', 'between', 'cheap', 'expensive', 'affordable', 'deal', 'discount', 'sale'],
      'help': ['help', 'support', 'assist', 'problem', 'issue', 'trouble', 'question', 'how', 'what', 'why'],
      'recommendations': ['recommend', 'suggestion', 'advise', 'best', 'top', 'popular', 'trending', 'trend', 'suggest'],
      'compare': ['compare', 'comparison', 'vs', 'versus', 'difference', 'similar', 'alike'],
      'availability': ['stock', 'available', 'availability', 'in stock', 'out of stock', 'check stock', 'inventory'],
      'reviews': ['review', 'reviews', 'rating', 'ratings', 'stars', 'feedback', 'opinion'],
      'specifications': ['specs', 'specifications', 'details', 'features', 'technical', 'specification'],
      'payment': ['payment', 'pay', 'credit card', 'debit card', 'upi', 'cash', 'billing', 'payment method'],
      'return': ['return', 'refund', 'exchange', 'replace', 'cancel', 'cancellation'],
      'contact': ['contact', 'support', 'help', 'email', 'phone', 'call', 'chat', 'live chat'],
      'account': ['account', 'profile', 'settings', 'login', 'sign in', 'register', 'sign up', 'password']
    }

    for (const keyword of productKeywords) {
      if (lowerMessage.includes(keyword)) {
        const results = await searchProducts(keyword)
        if (results.products && results.products.length > 0) {
          return {
            response: `🔍 I found ${results.length} products matching "${keyword}":\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`,
            contextUpdate: { currentTopic: 'search_results', lastAction: 'direct_search' }
          }
        }
      }
    }

    for (const keyword of categoryKeywords) {
      if (lowerMessage.includes(keyword)) {
        const categoryProducts = await getCategoryProducts(keyword)

        if (categoryProducts.length > 0) {
          return {
            response: `📦 I found ${categoryProducts.length} products in the ${keyword} category:\n\n${categoryProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${keyword} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks`,
            contextUpdate: { currentTopic: 'search_results', lastAction: 'category_search' }
          }
        }
      }
    }

    for (const [action, keywords] of Object.entries(actionKeywords)) {
      for (const keyword of keywords) {
        if (lowerMessage.includes(keyword)) {
          switch (action) {
            case 'cart':
              const cartSummary = getCartSummary()
              return {
                response: cartSummary.message,
                contextUpdate: { currentTopic: 'cart', lastAction: 'view_cart' },
                action: () => cartActions()
              }

            case 'wishlist':
              const wishlistSummary = getWishlistSummary()
              return {
                response: wishlistSummary.message,
                contextUpdate: { currentTopic: 'wishlist', lastAction: 'view_wishlist' },
                action: () => wishlistActions()
              }

            case 'orders':
              const orderSummary = getOrderSummary()
              return {
                response: orderSummary.message,
                contextUpdate: { currentTopic: 'orders', lastAction: 'view_orders' },
                action: () => orderActions()
              }

            case 'price':
              
              const pricePatterns = [
                
                { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
                
                { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
                
                { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
                
                { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
                
                { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
                
                { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
                
                { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
                
                { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
              ]

              let minPrice = 0
              let maxPrice = 0
              let priceRangeFound = false

              for (const { pattern, type } of pricePatterns) {
                const match = userMessage.match(pattern)
                if (match) {
                  priceRangeFound = true

                  if (type === 'range') {
                    minPrice = parseInt(match[1])
                    maxPrice = parseInt(match[2])
                  } else if (type === 'under') {
                    minPrice = 0
                    maxPrice = parseInt(match[1])
                  } else if (type === 'above') {
                    minPrice = parseInt(match[1])
                    maxPrice = Infinity
                  }
                  break
                }
              }

              if (priceRangeFound) {
                const results = await searchProducts('', { minPrice, maxPrice })

                const filteredResults = (results.products || []).filter(product => {
                  const price = parseFloat(product.price) || 0
                  if (maxPrice === Infinity) {
                    return price >= minPrice
                  } else {
                    return price >= minPrice && price <= maxPrice
                  }
                })

                if (filteredResults.length > 0) {
                  const rangeText = maxPrice === Infinity
                    ? `₹${minPrice}+`
                    : minPrice === 0
                      ? `Under ₹${maxPrice}`
                      : `₹${minPrice} - ₹${maxPrice}`

                  return {
                    response: `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
                      `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
                    ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`,
                    contextUpdate: { currentTopic: 'search_results', lastAction: 'price_search' }
                  }
                } else {
                  const rangeText = maxPrice === Infinity
                    ? `₹${minPrice}+`
                    : minPrice === 0
                      ? `Under ₹${maxPrice}`
                      : `₹${minPrice} - ₹${maxPrice}`

                  return {
                    response: `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`,
                    contextUpdate: { currentTopic: 'search_results', lastAction: 'price_search' }
                  }
                }
              }
              break

            case 'help':
              return {
                response: `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 Search & Discovery\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 Shopping Experience\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 Payment & Orders\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 Customer Support\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\nWhat specific help do you need?`,
                contextUpdate: { currentTopic: 'help', lastAction: 'help_request' }
              }

            case 'recommendations':
              const recommendations = await generateRecommendations()
              if (recommendations.length > 0) {
                return {
                  response: `⭐ Personalized Recommendations for you:\n\n${recommendations.slice(0, 5).map(product =>
                    `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                  ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get category-specific picks\n• Find similar products`,
                  contextUpdate: { currentTopic: 'recommendations', lastAction: 'view_recommendations' }
                }
              } else {
                const trendingProducts = await getTrendingProducts()
                return {
                  response: `⭐ Here are some trending products:\n\n${trendingProducts.slice(0, 5).map(product =>
                    `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                  ).join('')}\n\nWould you like to:\n• Add any to cart\n• Browse categories\n• Search for specific items\n• Get personalized picks`,
                  contextUpdate: { currentTopic: 'recommendations', lastAction: 'view_recommendations' }
                }
              }

            case 'compare':
              return {
                response: `📊 Product Comparison!\n\nI can help you compare products:\n\n• Compare prices and features\n• Side-by-side specifications\n• User reviews and ratings\n• Value for money analysis\n\nWhat products would you like to compare?\n\nExamples:\n• "Compare iPhone vs Samsung"\n• "Compare laptop brands"\n• "Compare shoes prices"`,
                contextUpdate: { currentTopic: 'compare', lastAction: 'compare_request' }
              }

            case 'availability':
              return {
                response: `📦 Stock Availability Check!\n\nI can check stock for any product:\n\n• Real-time inventory status\n• Stock notifications\n• Alternative sellers\n• Similar products in stock\n\nWhat product would you like me to check?\n\nExamples:\n• "Check iPhone stock"\n• "Is laptop available"\n• "Shoe availability"`,
                contextUpdate: { currentTopic: 'availability', lastAction: 'availability_check' }
              }

            case 'reviews':
              return {
                response: `⭐ Product Reviews!\n\nI can show you reviews for any product:\n\n• User ratings and feedback\n• Detailed reviews\n• Pros and cons\n• Verified purchase reviews\n\nWhat product would you like reviews for?\n\nExamples:\n• "iPhone reviews"\n• "Laptop ratings"\n• "Shoe feedback"`,
                contextUpdate: { currentTopic: 'reviews', lastAction: 'reviews_request' }
              }

            case 'specifications':
              return {
                response: `📋 Product Specifications!\n\nI can show detailed specs for any product:\n\n• Technical specifications\n• Features and capabilities\n• Size and dimensions\n• Material and build quality\n\nWhat product would you like specs for?\n\nExamples:\n• "iPhone specifications"\n• "Laptop specs"\n• "Shoe details"`,
                contextUpdate: { currentTopic: 'specifications', lastAction: 'specs_request' }
              }

            case 'payment':
              return {
                response: `💳 Payment Methods!\n\nWe accept various payment methods:\n\n• Credit/Debit Cards\n• UPI (Google Pay, PhonePe, Paytm)\n• Net Banking\n• Cash on Delivery\n• EMI options available\n\nWould you like to:\n• Learn about payment security\n• Check EMI eligibility\n• Set up payment preferences\n• Get billing help`,
                contextUpdate: { currentTopic: 'payment', lastAction: 'payment_info' }
              }

            case 'return':
              return {
                response: `🔄 Returns & Refunds!\n\nOur return policy:\n\n• 7-day return window\n• Easy return process\n• Full refund guarantee\n• Free return shipping\n• Exchange options available\n\nWould you like to:\n• Start a return\n• Check return status\n• Learn about return policy\n• Contact support`,
                contextUpdate: { currentTopic: 'return', lastAction: 'return_info' }
              }

            case 'contact':
              return {
                response: `📞 Contact Support!\n\nI can help you get in touch:\n\n• Live Chat: Available 24/7\n• Email: support@mkcart.com\n• Phone: +91-XXXXXXXXXX\n• WhatsApp: +91-XXXXXXXXXX\n\nWould you like to:\n• Start live chat\n• Send email\n• Call support\n• Report an issue`,
                contextUpdate: { currentTopic: 'contact', lastAction: 'contact_request' }
              }

            case 'account':
              return {
                response: `👤 Account Management!\n\nI can help with your account:\n\n• Profile settings\n• Order history\n• Saved addresses\n• Payment methods\n• Account preferences\n\nWould you like to:\n• View profile\n• Update settings\n• Check order history\n• Manage addresses`,
                contextUpdate: { currentTopic: 'account', lastAction: 'account_request' }
              }
          }
        }
      }
    }

    return null 
  }

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isTyping) return

    const userMessage = inputMessage.trim()
    setInputMessage("")

    const newUserMessage = {
      id: Date.now(),
      message: userMessage,
      type: "user",
      timestamp: new Date(),
    }

    setMessages(prev => [...prev, newUserMessage])

    setIsProcessing(true)
    setCurrentTask('Processing your request...')

    const typingMessage = {
      id: Date.now() + 1,
      type: "ai",
      message: "🤔 Thinking...",
      timestamp: new Date(),
      isTyping: true
    }
    setMessages(prev => [...prev, typingMessage])

    try {
      const lowerMessage = userMessage.toLowerCase()
      let response = ""
      let actionTaken = false
      let contextUpdate = {}

      const nluAnalysis = comprehensiveNLU(userMessage)
      const { intent, sentiment, entities, emotions, urgency, personality, context, confidence, suggestions, responseType } = nluAnalysis

      updateConversationMemory(userMessage, null, {
        intent,
        sentiment,
        entities,
        emotions,
        urgency,
        personality,
        context,
        confidence,
        responseType
      })

      const directKeywordResult = await handleDirectKeywords(userMessage, lowerMessage)
      if (directKeywordResult) {
        response = directKeywordResult.response
        contextUpdate = directKeywordResult.contextUpdate
        actionTaken = true

        if (directKeywordResult.action) {
          try {
            const actionResult = directKeywordResult.action()
            if (actionResult && actionResult.success) {
              
              response += `\n\n${actionResult.message}`
            }
          } catch (error) {
            
          }
        }
      }
      
      else if (conversationContext.pendingAction) {
        
        const pendingActionWithMessage = {
          ...conversationContext.pendingAction,
          userMessage: userMessage
        }
        const pendingResult = await handlePendingAction(pendingActionWithMessage)

        response = pendingResult
        contextUpdate = { pendingAction: null }
        actionTaken = true
      }
      
      else if (conversationContext.currentTopic === 'add_to_cart') {
        response = `🛒 To add items to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nI can help you:\n• Search for products\n• Navigate to cart page\n• Show product recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'add_to_cart' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'remove_from_cart') {
        response = `🛒 To remove items from your cart, please navigate to the cart page where you can manage your items.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'remove_from_cart' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'update_quantity') {
        response = `🛒 To update quantities in your cart, please navigate to the cart page where you can modify item quantities.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'update_quantity' }
        actionTaken = true
      }

      else if (lowerMessage.includes('search') || lowerMessage.includes('find') || lowerMessage.includes('look for') ||
        (conversationContext.currentTopic === 'advanced_search' && userMessage.trim())) {

        const combinedFilterMatch = userMessage.match(/(\w+)\s+(under|above|between)\s+(\d+)(?:\s+and\s+(\d+))?/i)

        if (combinedFilterMatch) {
          const keyword = combinedFilterMatch[1]
          const filterType = combinedFilterMatch[2].toLowerCase()
          const price1 = parseInt(combinedFilterMatch[3])
          const price2 = parseInt(combinedFilterMatch[4])

          let minPrice = 0
          let maxPrice = 0

          if (filterType === 'under') {
            maxPrice = price1
          } else if (filterType === 'above') {
            minPrice = price1
            maxPrice = Infinity
          } else if (filterType === 'between') {
            minPrice = price1
            maxPrice = price2
          }

          const results = await searchProducts(keyword, { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `🔍 I found ${filteredResults.length} products matching "${keyword}" ${rangeText}:\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
          } else {
            response = `🔍 No products found matching "${keyword}" ${rangeText}.\n\nWould you like me to:\n• Try a different price range\n• Search for similar products\n• Browse all products\n• Get recommendations`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'advanced_search' }
          actionTaken = true
        } else {
          
          const searchTerm = userMessage.replace(/search|find|look for/gi, '').trim()
          if (searchTerm) {
            const results = await searchProducts(searchTerm)
            if (results.products && results.products.length > 0) {
              response = `🔍 I found ${results.length} products matching "${searchTerm}":\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
              ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
            } else {
              response = `🔍 No products found matching "${searchTerm}".\n\nWould you like me to:\n• Search with different keywords\n• Browse all products\n• Show trending items\n• Get recommendations`
            }
            contextUpdate = { currentTopic: 'search', lastAction: 'search', searchHistory: [...conversationContext.searchHistory, searchTerm] }
            actionTaken = true
          }
        }
      }

      else if (lowerMessage.includes('cart') || lowerMessage.includes('shopping cart')) {
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          response = `🛒 Your cart has ${cartSummary.count} items:\n\n${cartSummary.items.map(item =>
            `• ${item.name} - Qty: ${item.quantity} - ₹${item.price * item.quantity}\n`
          ).join('')}\n\nTotal: ₹${cartSummary.total}\n\nI can help you:\n• Update quantities\n• Remove items\n• Add more products\n• Proceed to checkout\n• Apply discounts`
        } else {
          response = `🛒 Your cart is empty. Would you like me to:\n• Show trending products\n• Search for specific items\n• Show personalized recommendations\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'cart', lastAction: 'view_cart' }
        actionTaken = true
      }

      else if (lowerMessage.includes('wishlist') || lowerMessage.includes('favorites')) {
        const wishlistSummary = getWishlistSummary()
        if (wishlistSummary.count > 0) {
          response = `💖 Your wishlist has ${wishlistSummary.count} items:\n\n${wishlistSummary.items.map(item =>
            `• ${item.name} - ₹${item.price} - ${item.category}\n`
          ).join('')}\n\nI can help you:\n• Add items to cart\n• Remove items\n• Share wishlist\n• Get price alerts\n• Find similar items`
        } else {
          response = `💖 Your wishlist is empty. Would you like me to:\n• Show trending products\n• Search for items to add\n• Show personalized picks\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'wishlist', lastAction: 'view_wishlist' }
        actionTaken = true
      }

      else if (lowerMessage.includes('order') || lowerMessage.includes('track') || lowerMessage.includes('delivery')) {
        const orderSummary = getOrderSummary()
        if (orderSummary.count > 0) {
          response = `📦 You have ${orderSummary.count} orders:\n\n${orderSummary.items.map(order =>
            `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
          ).join('')}\n\nI can help you:\n• Track specific orders\n• Check delivery status\n• Cancel orders\n• Return items\n• Contact support`
        } else {
          response = `📦 You don't have any orders yet. Would you like me to:\n• Show your cart\n• Browse products\n• Show trending items\n• Help you place your first order`
        }
        contextUpdate = { currentTopic: 'orders', lastAction: 'view_orders' }
        actionTaken = true
      }

      else if (lowerMessage.includes('add to cart') || lowerMessage.includes('buy') || lowerMessage.includes('purchase')) {
        
        const productName = userMessage.replace(/add to cart|buy|purchase/gi, '').trim()
        if (productName) {
          const product = currentSearchResults.find(p =>
            p.name.toLowerCase().includes(productName.toLowerCase())
          )
          if (product) {
            response = `🛒 To add "${product.name}" to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nPrice: ₹${product.price}\nCategory: ${product.category}\n\nI can help you:\n• Navigate to cart page\n• Search for more products\n• Show recommendations\n• Continue shopping`
            contextUpdate = { currentTopic: 'cart', lastAction: 'add_to_cart', pendingAction: null }
            actionTaken = true
          } else {
            response = `I couldn't find "${productName}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories\n• Check if it's available`
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_price') {
        
        const pricePatterns = [
          
          { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
          
          { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
          
          { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
        ]

        let minPrice = 0
        let maxPrice = 0
        let priceRangeFound = false

        for (const { pattern, type } of pricePatterns) {
          const match = userMessage.match(pattern)
          if (match) {
            priceRangeFound = true

            if (type === 'range') {
              minPrice = parseInt(match[1])
              maxPrice = parseInt(match[2])
            } else if (type === 'under') {
              minPrice = 0
              maxPrice = parseInt(match[1])
            } else if (type === 'above') {
              minPrice = parseInt(match[1])
              maxPrice = Infinity
            }
            break
          }
        }

        if (priceRangeFound) {
          const results = await searchProducts('', { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
            contextUpdate = { currentTopic: 'search_results', lastAction: 'price_search' }
            actionTaken = true
          } else {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`
            contextUpdate = { currentTopic: 'search_results', lastAction: 'price_search' }
            actionTaken = true
          }
        } else {
          response = `💰 Please specify your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n• "Between 1000 and 2000"\n\nWhat's your budget range?`
          contextUpdate = { currentTopic: 'search_by_price', lastAction: 'search_by_price' }
          actionTaken = true
        }
      }
      else if (conversationContext.currentTopic === 'search_by_name') {
        
        let productName = userMessage.trim()

        if (productName && !productName.includes(' ')) {
          
          const results = await searchProducts(productName)
          if (results.products && results.products.length > 0) {
            response = `🔍 I found ${results.length} products matching "${productName}":\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
          } else {
            response = `🔍 No products found matching "${productName}".\n\nWould you like me to:\n• Search with different keywords\n• Browse all products\n• Show trending items\n• Get recommendations`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_name' }
          actionTaken = true
        } else {
          
          productName = extractProductName(userMessage)

          if (!productName || productName.trim() === '') {
            response = `🔍 Please tell me what product you're looking for!\n\nExamples:\n• "iPhone"\n• "laptop"\n• "shoes"\n• "headphones"\n\nWhat would you like to search for?`
            contextUpdate = { currentTopic: 'search_by_name', lastAction: 'search_by_name' }
            actionTaken = true
          } else {
            const results = await searchProducts(productName)
            if (results.products && results.products.length > 0) {
              response = `🔍 Real-time Search Results for "${productName}":\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
              ).join('')}\n\nI can help you:\n• Add any to cart\n• Add to wishlist\n• See more results\n• Search for something else\n• Get recommendations\n• Compare products\n• Check stock availability`
            } else {
              response = `🔍 No products found for "${productName}".\n\nWould you like to:\n• Try different keywords\n• Browse all products\n• Show trending items\n• Get recommendations\n• Search by category`
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_name' }
            actionTaken = true
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_category') {
        const category = extractCategory(userMessage)

        const categoryMap = {
          'mobile phones': ['mobile phones', 'mobile', 'phones', 'smartphone', 'phone', 'mobile devices'],
          'accessories': ['accessories', 'accessory', 'add-ons', 'extras'],
          'laptops': ['laptops', 'laptop', 'computer', 'notebook', 'pc'],
          'headphones': ['headphones', 'headphone', 'earphones', 'audio', 'sound'],
          'shoes': ['shoes', 'shoe', 'footwear', 'sneakers', 'boots'],
          'electronics': ['electronics', 'electronic', 'tech', 'technology', 'gadgets', 'devices'],
          'men': ['men', 'mens', 'male', 'gents'],
          'women': ['women', 'womens', 'female', 'ladies'],
          'toys': ['toys', 'toy', 'games', 'play', 'children', 'kids'],
          'musical instruments': ['musical instruments', 'music', 'instrument', 'musical']
        }

        let matchedCategory = category
        for (const [mainCategory, variations] of Object.entries(categoryMap)) {
          if (variations.some(v => category.toLowerCase().includes(v))) {
            matchedCategory = mainCategory
            break
          }
        }

        const categoryProducts = await getCategoryProducts(matchedCategory)

        if (categoryProducts.length > 0) {
          response = `📦 Great choice! Here are ${categoryProducts.length} products in the ${matchedCategory} category:\n\n${categoryProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
          ).join('')}\n\nI can help you:\n• Add any to cart\n• See more ${matchedCategory} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks\n• Browse other categories`
        } else {
          const availableCategories = await getAvailableCategories()
          const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
          response = `📦 I found some ${matchedCategory} products, but let me show you what's available:\n\nAvailable categories:\n${categoryList}\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items\n• Get recommendations`
        }
        contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_category' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'search_by_price') {

        const priceMatch = userMessage.match(/(\d+)\s*-\s*(\d+)|under\s+(\d+)|above\s+(\d+)|(\d+)\s*to\s*(\d+)/i)

        if (priceMatch) {
          let minPrice = 0
          let maxPrice = 0

          if (priceMatch[1] && priceMatch[2]) {
            
            minPrice = parseInt(priceMatch[1])
            maxPrice = parseInt(priceMatch[2])
           
          } else if (priceMatch[3]) {
            
            maxPrice = parseInt(priceMatch[3])
           
          } else if (priceMatch[4]) {
            
            minPrice = parseInt(priceMatch[4])
           
          } else if (priceMatch[5] && priceMatch[6]) {
            
            minPrice = parseInt(priceMatch[5])
            maxPrice = parseInt(priceMatch[6])
           
          }

          const results = await searchProducts('', { minPrice, maxPrice })

          if (results.products && results.products.length > 0) {
            response = `💰 Products in your price range (₹${minPrice}${maxPrice > 0 ? ` - ₹${maxPrice}` : '+'}):\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
          } else {
            response = `💰 No products found in your price range (₹${minPrice}${maxPrice > 0 ? ` - ₹${maxPrice}` : '+'}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_price' }
          actionTaken = true
        } else {

          const numbers = userMessage.match(/\d+/g)
          if (numbers && numbers.length >= 2) {
            const minPrice = parseInt(numbers[0])
            const maxPrice = parseInt(numbers[1])

            const results = await searchProducts('', { minPrice, maxPrice })

            if (results.products && results.products.length > 0) {
              response = `💰 Products in your price range (₹${minPrice} - ₹${maxPrice}):\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
            } else {
              response = `💰 No products found in your price range (₹${minPrice} - ₹${maxPrice}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_price' }
            actionTaken = true
          } else {
            response = `💰 Please specify your price range:\n\nExamples:\n• "1000-5000"\n• "Under 2000"\n• "Above 5000"\n• "1000 to 5000"\n\nWhat's your budget?`
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_brand') {
        
        let brand = userMessage.trim().toLowerCase()

        if (brand && !brand.includes(' ')) {
          
          const results = await searchProducts('', { brand: brand })
          if (results.products && results.products.length > 0) {
            response = `🏷️ ${brand.charAt(0).toUpperCase() + brand.slice(1)} products:\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${brand.charAt(0).toUpperCase() + brand.slice(1)} products\n• Browse other brands\n• Get recommendations`
          } else {
       
            const alternativeResults = await searchProducts(brand)
            if (alternativeResults.products && alternativeResults.products.length > 0) {
              response = `🏷️ Found ${alternativeResults.products.length} products related to "${brand}":\n\n${alternativeResults.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
            } else {
              response = `🏷️ No products found for ${brand.charAt(0).toUpperCase() + brand.slice(1)} brand.\n\nWould you like to:\n• Try a different brand\n• Browse all products\n• Show trending items\n• Search by category`
            }
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_brand' }
          actionTaken = true
        } else {
          
          brand = extractBrand(userMessage)

          if (!brand || brand.trim() === '') {
            response = `🏷️ Please tell me which brand you're looking for!\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• Asus, Acer, MSI\n• And many more!\n\nWhich brand are you looking for?`
            contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand' }
            actionTaken = true
          } else {
            const results = await searchProducts('', { brand: brand })
            if (results.products && results.products.length > 0) {
              response = `🏷️ ${brand} products:\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${brand} products\n• Browse other brands\n• Get recommendations`
            } else {
              
              const alternativeResults = await searchProducts(brand)
              if (alternativeResults.products && alternativeResults.products.length > 0) {
                response = `🏷️ Found ${alternativeResults.products.length} products related to "${brand}":\n\n${alternativeResults.products.slice(0, 5).map(product =>
                  `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
              } else {
                response = `🏷️ No products found for ${brand} brand.\n\nWould you like to:\n• Try a different brand\n• Browse all products\n• Show trending items\n• Search by category`
              }
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_brand' }
            actionTaken = true
          }
        }
      }

      else if (lowerMessage.includes('remove') || lowerMessage.includes('delete')) {
        if (conversationContext.currentTopic === 'cart') {
          response = `To remove items from your cart, please tell me:\n• The product name you want to remove\n• Or say "show cart" to see all items\n• Or say "clear cart" to remove everything`
        } else if (conversationContext.currentTopic === 'wishlist') {
          response = `To remove items from your wishlist, please tell me:\n• The product name you want to remove\n• Or say "show wishlist" to see all items\n• Or say "clear wishlist" to remove everything`
        } else {
          response = `I can help you remove items from:\n• Your cart - say "remove from cart"\n• Your wishlist - say "remove from wishlist"\n\nWhat would you like to remove?`
        }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'clear_cart') {
        if (lowerMessage.includes('yes') || lowerMessage.includes('confirm')) {
          
          const cartItems = getCartSummary().items
          let clearedCount = 0

          response = `🛒 To clear your cart, please navigate to the cart page where you can remove all items.\n\nI can help you:\n• Navigate to cart page\n• Browse products\n• Search for items\n• View recommendations`
          contextUpdate = { currentTopic: null, lastAction: 'clear_cart' }
          actionTaken = true
        } else {
          response = `Cart clearing cancelled. Your cart still has ${getCartSummary().count} items.\n\nWould you like to:\n• View your cart\n• Update quantities\n• Remove specific items\n• Continue shopping`
        }
      }

      else if (conversationContext.currentTopic === 'add_to_wishlist') {
        const productName = extractProductName(userMessage)

        if (!productName || productName.trim() === '') {
          response = `➕ Please tell me what product you'd like to add to your wishlist!\n\nExamples:\n• "Add iPhone to wishlist"\n• "Save laptop"\n• "Wishlist shoes"\n\nWhat would you like to add?`
          contextUpdate = { currentTopic: 'add_to_wishlist', lastAction: 'add_to_wishlist' }
          actionTaken = true
        } else {
          
          const results = await searchProducts(productName)
          const product = results.find(p =>
            p.name && p.name.toLowerCase().includes(productName.toLowerCase())
          )

          if (product) {
            
            const existingItem = currentWishlistItems.find(item => item.productId === product._id)
            if (existingItem) {
              response = `ℹ️ "${product.name}" is already in your wishlist!\n\nWould you like to:\n• View your wishlist\n• Add to cart\n• Search for other products\n• Continue shopping`
            } else {
              response = `💖 To add "${product.name}" to your wishlist, please navigate to the product page and use the "Add to Wishlist" button.\n\n📊 Product Details:\n• Price: ₹${product.price}\n• Category: ${product.category}\n• Seller: ${product.seller}\n• Rating: ⭐${product.ratings || 'N/A'}\n• Stock: ${product.stock} available\n• ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations\n• Continue shopping`
            }
          } else {
            response = `I couldn't find "${productName}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories\n• Search by name`
          }
          contextUpdate = { currentTopic: 'wishlist', lastAction: 'add_to_wishlist' }
          actionTaken = true
        }
      } else if (conversationContext.currentTopic === 'remove_from_wishlist') {
        const wishlistItems = getWishlistSummary().items;
        const product = wishlistItems.find(item =>
          item.name &&
          userMessage &&
          item.name.toLowerCase().includes(userMessage.toLowerCase())
        );

        if (product) {
          response = `💖 To remove "${product.name}" from your wishlist, please navigate to the wishlist page where you can manage your saved items.\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations\n• Continue shopping`
        } else {
          response = `I couldn't find "${userMessage}" in your wishlist. Your current items:\n\n${wishlistItems.map(item =>
            `• ${item.name} - ₹${item.price}\n`
          ).join('')}\n\nTo manage your wishlist items, please navigate to the wishlist page.`
        }
        contextUpdate = { currentTopic: 'wishlist', lastAction: 'remove_from_wishlist' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'track_specific_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails) {
            response = `📦 Order #${orderId.slice(-6)} Details:\n\nStatus: ${orderDetails.status}\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'orders', lastAction: 'track_order' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Track order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'order_status') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderStatus = getOrderStatus(orderId)

          if (orderStatus) {
            response = `📊 Order #${orderId.slice(-6)} Status:\n\nStatus: ${orderStatus.status}\nLast Updated: ${orderStatus.lastUpdated}\nEstimated Delivery: ${orderStatus.estimatedDelivery}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'orders', lastAction: 'check_status' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Check status 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'cancel_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails && orderDetails.status === 'pending') {
            response = `❌ Cancel Order #${orderId.slice(-6)}\n\nAre you sure you want to cancel this order?\n\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nType "yes" to confirm or "no" to cancel.`
            contextUpdate = { currentTopic: 'cancel_order', lastAction: 'cancel_order', pendingAction: { type: 'cancel_order', orderId } }
          } else if (orderDetails) {
            response = `❌ Order #${orderId.slice(-6)} cannot be cancelled.\n\nStatus: ${orderDetails.status}\n\nOnly pending orders can be cancelled.\n\nWould you like to:\n• Return items\n• Contact support\n• Track delivery`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Cancel order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'return_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails) {
            response = `🔄 Return Order #${orderId.slice(-6)}\n\nI can help you return items from this order.\n\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Return all items\n• Return specific items\n• Contact support\n• Track return status`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'return_order', lastAction: 'return_order' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Return order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'payment_issues') {
        response = `⚠️ Payment Issue Support\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nPlease describe your specific issue, and I'll guide you through the resolution process.`
        contextUpdate = { currentTopic: 'payment_support', lastAction: 'payment_issues' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'refund_status') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          response = `💰 Refund Status for Order #${orderId.slice(-6)}\n\nI'll check your refund status.\n\nRefund Status: Processing\nEstimated Time: 5-7 business days\n\nWould you like to:\n• Track refund progress\n• Contact support\n• Check other orders`
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Check refund 123456"`
        }
        contextUpdate = { currentTopic: 'refund_status', lastAction: 'refund_status' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'category_recommendations') {
        const category = userMessage.toLowerCase()
        const categoryProducts = productsData?.filter(p =>
          p.category.toLowerCase().includes(category)
        ) || []

        if (categoryProducts.length > 0) {
          response = `📦 ${userMessage} Recommendations:\n\n${categoryProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} - ⭐${product.rating || 'N/A'}\n`
          ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${userMessage} products\n• Browse other categories\n• Get personalized picks`
        } else {
          response = `No products found in ${userMessage} category.\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items`
        }
        contextUpdate = { currentTopic: 'category_recommendations', lastAction: 'category_recommendations' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'price_recommendations') {
        const priceMatch = userMessage.match(/(\d+)-(\d+)|under (\d+)|above (\d+)/i)
        if (priceMatch) {
          let minPrice = 0
          let maxPrice = 0

          if (priceMatch[1] && priceMatch[2]) {
            minPrice = parseInt(priceMatch[1])
            maxPrice = parseInt(priceMatch[2])
          } else if (priceMatch[3]) {
            maxPrice = parseInt(priceMatch[3])
          } else if (priceMatch[4]) {
            minPrice = parseInt(priceMatch[4])
          }

          const priceProducts = productsData?.filter(p =>
            p.price >= minPrice && (maxPrice === 0 || p.price <= maxPrice)
          ) || []

          if (priceProducts.length > 0) {
            response = `💰 Recommendations in your price range:\n\n${priceProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get personalized picks`
          } else {
            response = `No products found in your price range.\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
          }
          contextUpdate = { currentTopic: 'price_recommendations', lastAction: 'price_recommendations' }
          actionTaken = true
        } else {
          response = `Please specify your price range:\n\nExamples:\n• "1000-5000"\n• "Under 2000"\n• "Above 5000"\n\nWhat's your budget?`
        }
      }

      else if (conversationContext.currentTopic === 'similar_products') {
        const productsArray = productsData?.products || []
  const product = productsArray.find(p =>
          p.name.toLowerCase().includes(userMessage.toLowerCase())
        )

        if (product) {
          const similarProducts = productsData?.filter(p =>
            p.category === product.category && p._id !== product._id
          ).slice(0, 5) || []

          if (similarProducts.length > 0) {
            response = `🔄 Similar products to ${product.name}:\n\n${similarProducts.map(p =>
              `• ${p.name} - ₹${p.price} - ⭐${p.rating || 'N/A'}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• Add to wishlist\n• See more similar products\n• Compare products`
          } else {
            response = `No similar products found for ${product.name}.\n\nWould you like to:\n• Browse ${product.category} products\n• Show trending items\n• Get recommendations`
          }
        } else {
          response = `I couldn't find "${userMessage}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'similar_products', lastAction: 'similar_products' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'technical_help') {
        response = `🔧 Technical Support\n\nI can help you with:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nPlease describe your specific technical issue, and I'll guide you through the resolution process.`
        contextUpdate = { currentTopic: 'technical_support', lastAction: 'technical_help' }
        actionTaken = true
      }

      else if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
        if (conversationContext.lastAction === 'search') {
          response = `💰 Price information for your search results:\n\n${currentSearchResults.slice(0, 5).map(product =>
            `• ${product.name}: ₹${product.price}\n`
          ).join('')}\n\nI can help you:\n• Filter by price range\n• Find cheaper alternatives\n• Compare prices\n• Set price alerts`
        } else {
          response = `💰 I can help you with pricing:\n• Search for products and see prices\n• Compare prices across products\n• Find deals and discounts\n• Set price alerts\n\nWhat would you like to know about?`
        }
        contextUpdate = { currentTopic: 'pricing', lastAction: 'price_inquiry' }
        actionTaken = true
      }

      else if (lowerMessage.includes('recommend') || lowerMessage.includes('suggestion') || lowerMessage.includes('similar')) {
        const recommendations = await generateRecommendations()
        if (recommendations.length > 0) {
          response = `⭐ Based on your preferences, here are my recommendations:\n\n${recommendations.map(product =>
            `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
          ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get trending items\n• Browse by category`
        } else {
          response = `⭐ I'd be happy to recommend products! Please:\n• Browse some products first\n• Add items to your wishlist\n• Tell me what you're looking for\n• Let me show you trending items`
        }
        contextUpdate = { currentTopic: 'recommendations', lastAction: 'get_recommendations' }
        actionTaken = true
      }

      else if (lowerMessage.includes('help') || lowerMessage.includes('support') || lowerMessage.includes('assist')) {
        response = `🆘 I'm here to help! Here's what I can do:\n\n🛒 Shopping:\n• Search products\n• Add to cart\n• View wishlist\n• Track orders\n\n📊 Account:\n• Check cart status\n• View order history\n• Manage wishlist\n• Payment help\n\n🔍 Search:\n• Find specific products\n• Browse categories\n• Get recommendations\n• Price comparisons\n\n💬 Support:\n• Order tracking\n• Return assistance\n• Payment issues\n• General questions\n\nWhat would you like help with?`
        contextUpdate = { currentTopic: 'help', lastAction: 'help_request' }
        actionTaken = true
      }

      else if (lowerMessage.includes('hello') || lowerMessage.includes('hi') || lowerMessage.includes('hey')) {
        const cartSummary = getCartSummary()
        const wishlistSummary = getWishlistSummary()
        const userInsights = getUserInsights()
        const timeOfDay = new Date().getHours()

        let greeting = ''
        if (timeOfDay < 12) {
          greeting = 'Good morning'
        } else if (timeOfDay < 17) {
          greeting = 'Good afternoon'
        } else {
          greeting = 'Good evening'
        }

        let personalization = ''
        if (userInsights.favoriteCategory !== 'No preference') {
          personalization = `I noticed you love ${userInsights.favoriteCategory} products! `
        }

        response = `${greeting}! 👋 Welcome back to MKCart! I'm your personalized AI shopping assistant. 🤖\n\n${personalization}I'm here to make your shopping experience amazing!\n\n📊 Your Shopping Summary:\n• Cart: ${cartSummary.count} items (₹${cartSummary.total})\n• Wishlist: ${wishlistSummary.count} items\n• Orders: ${getOrderSummary().count} orders\n\n🎯 I can help you with:\n\n🔍 Smart Search\n• Search by name, category, price, brand\n• Advanced filters and sorting\n• Trending and popular items\n\n🛒 Cart Management\n• Add, remove, update quantities\n• Quick checkout process\n• Save for later options\n\n💖 Wishlist Features\n• Save favorite items\n• Price drop alerts\n• Share with friends\n\n📦 Order Tracking\n• Real-time order status\n• Delivery tracking\n• Easy returns and refunds\n\n⭐ Personalized Experience\n• Smart recommendations\n• Based on your preferences\n• Deals and discounts\n\n🎤 Voice Commands\n• Speak naturally to me\n• I understand voice input\n• Hands-free shopping\n\n💬 ChatGPT-like Experience\n• Intelligent conversations\n• Context-aware responses\n• Memory of our chats\n\nWhat would you like to explore today? Just type or speak naturally! 😊`
        contextUpdate = { currentTopic: 'greeting', lastAction: 'greeting' }
        actionTaken = true
      }

      else if (lowerMessage.includes('thank') || lowerMessage.includes('thanks')) {
        response = `😊 You're welcome! I'm here to make your shopping experience amazing.\n\nIs there anything else I can help you with?\n\n• Continue shopping\n• Check your cart\n• Browse recommendations\n• Track orders`
        contextUpdate = { currentTopic: 'gratitude', lastAction: 'thank_you' }
        actionTaken = true
      }

      else if (lowerMessage.includes('bye') || lowerMessage.includes('goodbye')) {
        response = `👋 Goodbye! Thanks for shopping with MKCart!\n\nDon't forget to:\n• Check your cart before leaving\n• Save items to wishlist\n• Track your orders\n\nCome back anytime! I'll be here to help! 😊`
        contextUpdate = { currentTopic: 'farewell', lastAction: 'goodbye' }
        actionTaken = true
      }

      else if (lowerMessage.includes('how are you') || lowerMessage.includes('how do you do')) {
        response = `🤖 I'm doing great, thank you for asking! I'm here and ready to help you with all your shopping needs.\n\nI can assist you with:\n• Finding products\n• Managing your cart\n• Tracking orders\n• Getting recommendations\n\nHow can I help you today?`
        contextUpdate = { currentTopic: 'wellbeing', lastAction: 'how_are_you' }
        actionTaken = true
      }

      else if (lowerMessage.includes('recommend') || lowerMessage.includes('suggestion')) {
        const recommendations = await generateRecommendations()
        response = `🎯 Here are some personalized recommendations for you:\n\n${recommendations.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Search for specific items\n• Browse categories`
        contextUpdate = { currentTopic: 'recommendations', lastAction: 'get_recommendations' }
        actionTaken = true
      }

      else if (lowerMessage.includes('trending') || lowerMessage.includes('popular')) {
        const trendingProducts = await getTrendingProducts()
        response = `🔥 Here are the trending products right now:\n\n${trendingProducts.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks\n• Browse by category`
        contextUpdate = { currentTopic: 'trending', lastAction: 'view_trending' }
        actionTaken = true
      }

      else if (lowerMessage.includes('brand') && (lowerMessage.includes('search') || lowerMessage.includes('find') || lowerMessage.includes('show'))) {
        response = `🏷️ Search by Brand\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• Asus, Acer, MSI\n• And many more!\n\nWhich brand are you looking for?`
        contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand' }
        actionTaken = true
      }

      else if (lowerMessage.includes('view') && lowerMessage.includes('products')) {
        response = `📦 Navigate to Products Page\n\nI'm taking you to the products page where you can:\n• Browse all products\n• Filter by category\n• Sort by price, rating, popularity\n• Search for specific items\n• Add items to cart or wishlist\n• View product details\n\nNavigating now...`
        productsActions()
        contextUpdate = { currentTopic: 'view_products', lastAction: 'view_products' }
        actionTaken = true
      }

      else if (lowerMessage.includes('track') && (lowerMessage.includes('order') || lowerMessage.includes('delivery'))) {
        const orderId = extractOrderId(userMessage)
        if (orderId) {
          const orderStatus = await getOrderStatus(orderId)
          if (orderStatus) {
            response = `📦 Real-time Order #${orderStatus.orderId.slice(-6)} Status:\n\n📊 Order Details:\n• Status: ${orderStatus.status}\n• Description: ${orderStatus.statusDescription}\n• Amount: ₹${orderStatus.amount}\n• Payment: ${orderStatus.paymentMethod}\n• Transaction ID: ${orderStatus.transactionId}\n\n🚚 Delivery Info:\n• Last Updated: ${orderStatus.lastUpdated}\n• Estimated Delivery: ${orderStatus.estimatedDelivery}\n• Tracking Number: ${orderStatus.trackingNumber || 'Not available'}\n• Address: ${orderStatus.deliveryAddress}\n\n${orderStatus.canCancel ? '❌ Can Cancel: Yes' : ''}\n${orderStatus.canReturn ? '🔄 Can Return: Yes' : ''}\n${orderStatus.canTrack ? '📍 Can Track: Yes' : ''}\n\nWould you like to:\n• Get detailed order info\n• Cancel order\n• Contact support\n• Track other orders\n• View all orders`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products\n• View recent orders`
          }
        } else {
          response = `📦 Please provide your order ID!\n\nExamples:\n• "Track order 123456"\n• "Check status of order ABC123"\n• "Where is my order 789"\n\nWhat's your order ID?`
        }
        contextUpdate = { currentTopic: 'order_tracking', lastAction: 'track_order' }
        actionTaken = true
      }

      else if (lowerMessage.includes('stock') || lowerMessage.includes('available') || lowerMessage.includes('inventory')) {
        const productName = extractProductName(userMessage)
        if (productName) {
          const results = await searchProducts(productName)
          const product = results.find(p => p.name.toLowerCase().includes(productName.toLowerCase()))
          if (product) {
            const inventory = await checkInventory(product._id)
            if (inventory) {
              response = `📦 Real-time Inventory Check for "${product.name}":\n\n📊 Stock Information:\n• Available: ${inventory.stock} units\n• Status: ${inventory.status}\n• Seller: ${inventory.seller}\n• Price: ₹${inventory.price}\n• Category: ${inventory.category}\n• Last Updated: ${inventory.lastUpdated}\n\n${inventory.lowStock ? `⚠️ ${inventory.lowStock}` : ''}\n\nWould you like to:\n• Add to cart\n• Add to wishlist\n• Check similar products\n• Get price alerts\n• View product details`
            } else {
              response = `❌ Unable to check inventory for "${product.name}". Please try again.`
            }
          } else {
            response = `❌ Product "${productName}" not found. Would you like to:\n• Search for similar products\n• Browse categories\n• Show trending items`
          }
        } else {
          response = `📦 Please tell me which product you want to check!\n\nExamples:\n• "Check stock for iPhone"\n• "Is Samsung available"\n• "Inventory for laptop"\n\nWhat product would you like to check?`
        }
        contextUpdate = { currentTopic: 'inventory_check', lastAction: 'check_inventory' }
        actionTaken = true
      }

      else if (lowerMessage.includes('deals') || lowerMessage.includes('offers') || lowerMessage.includes('discount')) {
        const deals = getDealsAndOffers()
        response = `🎉 Here are the best deals and offers:\n\n${deals.slice(0, 5).map(deal =>
          `• ${deal.name} - ${deal.discount}% OFF - ₹${deal.price}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more deals\n• Get price alerts\n• Check your wishlist`
        contextUpdate = { currentTopic: 'deals', lastAction: 'view_deals' }
        actionTaken = true
      }

      else if (lowerMessage.includes('pay') || lowerMessage.includes('checkout') || lowerMessage.includes('purchase')) {
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          const paymentMethod = extractPaymentMethod(userMessage) || 'Credit Card'
          const orderItems = cartSummary.items.map(item => ({
            productId: item.productId,
            name: item.name,
            quantity: item.qty,
            price: item.price
          }))

          response = `💳 Real-time Payment Processing\n\n📊 Order Summary:\n• Total Items: ${cartSummary.count}\n• Total Amount: ₹${cartSummary.total}\n• Payment Method: ${paymentMethod}\n\n🛒 Items in Cart:\n${cartSummary.items.map(item =>
            `• ${item.name} - Qty: ${item.qty} - ₹${item.price * item.qty}\n`
          ).join('')}\n\nWould you like to:\n• Proceed with payment\n• Change payment method\n• Add more items\n• Apply discount code\n• Review order details`

          contextUpdate = {
            currentTopic: 'payment_processing',
            lastAction: 'initiate_payment',
            pendingAction: {
              type: 'process_payment',
              amount: cartSummary.total,
              method: paymentMethod,
              orderItems: orderItems
            }
          }
        } else {
          response = `🛒 Your cart is empty!\n\nWould you like to:\n• Browse products\n• Search for items\n• View recommendations\n• Check trending items`
        }
        actionTaken = true
      }

      else {
        
        const lowerMessage = userMessage.toLowerCase()

        if (lowerMessage.includes('fashion') || lowerMessage.includes('clothing') || lowerMessage.includes('dress')) {
          response = `👗 Fashion & Clothing!\n\nI can help you find the perfect fashion items:\n\n• Casual wear and formal attire\n• Shoes, bags, and accessories\n• Seasonal collections\n• Trending styles\n• Size and fit guidance\n\nWould you like me to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized fashion picks`
          contextUpdate = { currentTopic: 'fashion', lastAction: 'fashion_inquiry' }
        }
        else if (lowerMessage.includes('electronics') || lowerMessage.includes('phone') || lowerMessage.includes('laptop')) {
          response = `📱 Electronics & Tech!\n\nI can help you find the latest electronics:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\nWould you like me to:\n• Show trending electronics\n• Search for specific devices\n• Compare products\n• Get tech recommendations`
          contextUpdate = { currentTopic: 'electronics', lastAction: 'electronics_inquiry' }
        }
        else if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
          response = `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\nWould you like me to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
          contextUpdate = { currentTopic: 'pricing', lastAction: 'price_inquiry' }
        }
        else if (lowerMessage.includes('help') || lowerMessage.includes('support') || lowerMessage.includes('assist')) {
          response = `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 **Search & Discovery**\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 **Shopping Experience**\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 **Payment & Orders**\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 **Customer Support**\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\nWhat specific help do you need?`
          contextUpdate = { currentTopic: 'help', lastAction: 'help_request' }
        }
        else {
          
          let baseResponse = ""

          if (responseType === 'specific' && confidence > 0.8) {
            
            baseResponse = generateContextualResponse(userMessage, intent, sentiment, entities)
          } else if (responseType === 'contextual' && confidence > 0.5) {
            
            baseResponse = generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
          } else {
            
            const keywordResult = processIntelligentKeywords(userMessage)
            if (keywordResult) {
              baseResponse = keywordResult.response
              contextUpdate = keywordResult.contextUpdate || { currentTopic: 'general', lastAction: 'keyword_response' }
            } else {
              
              baseResponse = generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
              contextUpdate = { currentTopic: 'general', lastAction: 'ai_response' }
            }
          }

          let enhancedResponse = baseResponse

          if (personality === 'formal') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'formal') + "\n\n" + enhancedResponse
          } else if (personality === 'casual') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'casual') + "\n\n" + enhancedResponse
          } else if (personality === 'friendly') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'friendly') + "\n\n" + enhancedResponse
          }

          if (emotions.length > 0) {
            const primaryEmotion = emotions[0]
            const emotionResponse = getRandomResponse(responseLibraries.emotions, primaryEmotion)
            enhancedResponse = emotionResponse + "\n\n" + enhancedResponse
          }

          if (urgency === 'high') {
            const urgencyResponse = getRandomResponse(responseLibraries.urgency, 'high')
            enhancedResponse = urgencyResponse + "\n\n" + enhancedResponse
          }

          if (context === 'firstTime') {
            const contextResponse = getRandomResponse(responseLibraries.context, 'firstTime')
            enhancedResponse = contextResponse + "\n\n" + enhancedResponse
          }

          if (suggestions.length > 0) {
            enhancedResponse += "\n\n💡 Quick suggestions:\n" + suggestions.map(suggestion => `• ${suggestion}`).join('\n')
          }

          response = enhancedResponse
          actionTaken = true
        }
      }

      if (actionTaken) {
        setConversationContext(prev => ({
          ...prev,
          ...contextUpdate,
          conversationFlow: [...prev.conversationFlow, { user: userMessage, ai: response }]
        }))

        updateConversationMemory(userMessage, response, contextUpdate)
      }

      setMessages(prev => prev.filter(msg => !msg.isTyping))

      const aiMessage = {
        id: Date.now(),
        message: response,
        type: "ai",
        timestamp: new Date(),
      }

      setMessages(prev => [...prev, aiMessage])

      if (voiceEnabled) {
        speakMessage(response)
      }

      setTimeout(() => {
        scrollToBottom()
      }, 200)

    } catch (error) {

      let errorResponse = ''
      if (error.message.includes('toLowerCase')) {
        errorResponse = `❌ I had trouble understanding your request. Please try:\n\n• "Add iPhone to cart"\n• "Add 2 laptops"\n• "Add shoes quantity 3"\n\nMake sure to specify a product name!`
      } else if (error.message.includes('fetch')) {
        errorResponse = `❌ Connection issue. Please check:\n\n• Your internet connection\n• Try refreshing the page\n• Contact support if the issue persists`
      } else {
        errorResponse = `❌ I encountered an error while processing your request.\n\nError: ${error.message}\n\nPlease try:\n• Refreshing the page\n• Using different keywords\n• Contacting support if the issue persists\n\nI'm here to help you with:\n• Product searches\n• Cart management\n• Order tracking\n• General assistance`
      }

      const errorMessage = {
        id: Date.now(),
        message: errorResponse,
        type: "ai",
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, errorMessage])

      setTimeout(() => {
        scrollToBottom()
      }, 200)
    } finally {
      setIsProcessing(false)
      setCurrentTask(null)
    }
  }

  const startListening = () => {
    if (recognitionRef.current && !isListening) {
      recognitionRef.current.start()
    }
  }

  const stopListening = () => {
    if (recognitionRef.current && isListening) {
      recognitionRef.current.stop()
    }
  }

  const speakMessage = (text) => {
    if (window.speechSynthesis && voiceEnabled) {
      setIsSpeaking(true)
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.rate = 0.9
      utterance.pitch = 1
      utterance.volume = 0.8

      utterance.onend = () => {
        setIsSpeaking(false)
      }

      window.speechSynthesis.speak(utterance)
    }
  }

  const stopSpeaking = () => {
    if (window.speechSynthesis) {
      window.speechSynthesis.cancel()
      setIsSpeaking(false)
    }
  }

  const handleQuickAction = async (action) => {
    let message = ""
    let contextUpdate = {}
    let actionTaken = false

    try {
      
      const mainAction = quickActions.find(qa => qa.action === action)
      if (mainAction && mainAction.subActions) {
        
        setCurrentSubActions(mainAction.subActions)
        setSubActionHistory(prev => [...prev, { action: action, label: mainAction.label }])

        message = `🎯 ${mainAction.label}\n\nWhat would you like to do?\n\nI can help you with:\n${mainAction.subActions.slice(0, -1).map(sub =>
          `• ${sub.label}\n`
        ).join('')}\n• ${mainAction.subActions[mainAction.subActions.length - 1].label}`

        contextUpdate = { currentTopic: action, lastAction: action, pendingAction: null }
        actionTaken = true
      } else if (action === 'back_to_main') {
        
        setCurrentSubActions(null)
        setSubActionHistory([])

        message = "I'm here to help! How can I assist you today?"
        contextUpdate = { currentTopic: null, lastAction: null, pendingAction: null }
        actionTaken = true
      } else {
        
        switch (action) {
          case "search_by_name":
            message = `🔍 Search by Name\n\nJust tell me the product name you're looking for!\n\nExamples:\n• "iPhone"\n• "laptop"\n• "shoes"\n• "headphones"\n\nWhat product would you like to search for?`
            contextUpdate = { currentTopic: 'search_by_name', lastAction: 'search_by_name', pendingAction: { type: 'search_by_name' } }
            break

          case "search_by_category":
            const availableCategories = await getAvailableCategories()
            const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
            message = `📦 Search by Category\n\nAvailable categories:\n${categoryList}\n\nWhich category interests you?`
            contextUpdate = { currentTopic: 'search_by_category', lastAction: 'search_by_category', pendingAction: { type: 'search_by_category', userMessage: '' } }
            break

          case "search_by_price":
            message = `💰 Search by Price\n\nTell me your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n\nWhat's your budget range?`
            contextUpdate = { currentTopic: 'search_by_price', lastAction: 'search_by_price', pendingAction: { type: 'search_by_price', userMessage: '' } }
            break

          case "search_by_brand":
            message = `🏷️ Search by Brand\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• And many more!\n\nWhich brand are you looking for?`
            contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand', pendingAction: { type: 'search_by_brand' } }
            break

          case "advanced_search":
            message = `🔧 Advanced Search\n\nI can help you search with multiple filters:\n\n• Category + Price Range\n• Brand + Rating\n• Availability + Features\n• And more combinations!\n\nWhat filters would you like to apply?`
            contextUpdate = { currentTopic: 'advanced_search', lastAction: 'advanced_search', pendingAction: { type: 'advanced_search' } }
            break

          case "trending_products":
            const trendingProducts = await getTrendingProducts()
            if (trendingProducts.length > 0) {
              message = `🔥 Trending Products\n\nHere are the most popular products right now:\n\n${trendingProducts.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks`
            } else {
              message = `🔥 Trending Products\n\nCurrently no trending products available.\n\nWould you like to:\n• Browse all products\n• Search for specific items\n• Get recommendations`
            }
            contextUpdate = { currentTopic: 'trending_products', lastAction: 'view_trending' }
            break

          case "view_cart":
            const cartSummary = getCartSummary()
            if (cartSummary.count > 0) {
              message = `🛒 Your Cart\n\nYou have ${cartSummary.count} items:\n\n${cartSummary.items.map(item =>
                `• ${item.name} - Qty: ${item.quantity} - ₹${item.price * item.quantity}\n`
              ).join('')}\n\nTotal: ₹${cartSummary.total}\n\nI can help you:\n• Update quantities\n• Remove items\n• Add more products\n• Proceed to checkout`
            } else {
              message = `🛒 Your cart is empty.\n\nWould you like me to:\n• Show trending products\n• Search for items\n• Show recommendations\n• Browse categories`
            }
            contextUpdate = { currentTopic: 'view_cart', lastAction: 'view_cart' }
            break

          case "navigate_to_cart":
            const cartSummaryForNav = getCartSummary()
            if (cartSummaryForNav.count > 0) {
              message = `🛒 Navigate to Cart Page\n\nYour cart has ${cartSummaryForNav.count} items (Total: ₹${cartSummaryForNav.total})\n\nI'm taking you to the cart page where you can:\n• Add/remove items\n• Update quantities\n• Clear cart\n• Proceed to checkout\n\nNavigating now...`
              cartActions()
            } else {
              message = `🛒 Navigate to Cart Page\n\nYour cart is empty.\n\nI'm taking you to the cart page where you can:\n• Browse products\n• Add items to cart\n• View recommendations\n\nNavigating now...`
              cartActions()
            }
            contextUpdate = { currentTopic: 'cart', lastAction: 'navigate_to_cart' }
            break

          case "checkout":
            const checkoutCart = getCartSummary()
            if (checkoutCart.count > 0) {
              message = `💳 Proceed to Checkout\n\nCheckout Summary:\n• Items: ${checkoutCart.count}\n• Total: ₹${checkoutCart.total}\n\nI can help you:\n• Review your cart\n• Apply discount codes\n• Choose payment method\n• Complete purchase\n\nWould you like to proceed?`
            } else {
              message = `Your cart is empty. Would you like to:\n• Browse products\n• Search for items\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'checkout', lastAction: 'checkout', pendingAction: { type: 'checkout' } }
            break

          case "view_wishlist":
            const wishlistSummaryForView = getWishlistSummary()
            if (wishlistSummaryForView.count > 0) {
              message = `💖 Your Wishlist\n\nYou have ${wishlistSummaryForView.count} items:\n\n${wishlistSummaryForView.items.map(item =>
                `• ${item.name} - ₹${item.price} - ${item.category}\n`
              ).join('')}\n\nI can help you:\n• Add items to cart\n• Remove items\n• Share wishlist\n• Get price alerts`
            } else {
              message = `💖 Your wishlist is empty.\n\nWould you like to:\n• Browse products\n• Search for items\n• Get recommendations\n• View trending items`
            }
            contextUpdate = { currentTopic: 'view_wishlist', lastAction: 'view_wishlist' }
            break

          case "navigate_to_wishlist":
            const wishlistSummaryForNav = getWishlistSummary()
            if (wishlistSummaryForNav.count > 0) {
              message = `💖 Navigate to Wishlist Page\n\nYour wishlist has ${wishlistSummaryForNav.count} items\n\nI'm taking you to the wishlist page where you can:\n• Add/remove items\n• Move items to cart\n• Share wishlist\n• Set price alerts\n\nNavigating now...`
              wishlistActions()
            } else {
              message = `💖 Navigate to Wishlist Page\n\nYour wishlist is empty.\n\nI'm taking you to the wishlist page where you can:\n• Browse products\n• Add items to wishlist\n• View recommendations\n\nNavigating now...`
              wishlistActions()
            }
            contextUpdate = { currentTopic: 'wishlist', lastAction: 'navigate_to_wishlist' }
            break

          case "share_wishlist":
            const shareWishlist = getWishlistSummary()
            if (shareWishlist.count > 0) {
              message = `📤 Share Wishlist\n\nYour wishlist has ${shareWishlist.count} items:\n\n${shareWishlist.items.map(item =>
                `• ${item.name} - ₹${item.price}\n`
              ).join('')}\n\nI can help you:\n• Generate share link\n• Send via email\n• Share on social media\n• Create gift registry`
            } else {
              message = `Your wishlist is empty. Would you like to:\n• Add some products\n• Browse categories\n• Search for items`
            }
            contextUpdate = { currentTopic: 'share_wishlist', lastAction: 'share_wishlist' }
            break

          case "price_alerts":
            const priceWishlist = getWishlistSummary()
            if (priceWishlist.count > 0) {
              message = `🔔 Price Alerts\n\nI can set up price alerts for your wishlist items:\n\n${priceWishlist.items.map(item =>
                `• ${item.name} - Current: ₹${item.price}\n`
              ).join('')}\n\nWould you like to:\n• Set price drop alerts\n• Track price changes\n• Get notified of deals\n• Compare prices`
            } else {
              message = `Your wishlist is empty. Would you like to:\n• Add products to track\n• Browse trending items\n• Search for products`
            }
            contextUpdate = { currentTopic: 'price_alerts', lastAction: 'price_alerts' }
            break

          case "view_orders":
            const orderSummary = getOrderSummary()
            if (orderSummary.count > 0) {
              message = `📦 Your Orders\n\nYou have ${orderSummary.count} orders:\n\n${orderSummary.items.map(order =>
                `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
              ).join('')}\n\nI can help you:\n• Track specific orders\n• Check delivery status\n• Cancel orders\n• Return items`
            } else {
              message = `📦 You don't have any orders yet.\n\nWould you like to:\n• Browse products\n• Add items to cart\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'view_orders', lastAction: 'view_orders' }
            break

          case "track_specific_order":
            const ordersToTrack = getOrderSummary()
            if (ordersToTrack.count > 0) {
              message = `🔍 Track Specific Order\n\nYour recent orders:\n\n${ordersToTrack.items.map(order =>
                `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
              ).join('')}\n\nWhich order would you like to track?\n\nJust tell me the order number!`
            } else {
              message = `You don't have any orders to track. Would you like to:\n• Browse products\n• Add items to cart\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'track_specific_order', lastAction: 'track_specific_order', pendingAction: { type: 'track_specific_order' } }
            break

          case "navigate_to_orders":
            const orderSummaryForNav = getOrderSummary()
            if (orderSummaryForNav.count > 0) {
              message = `📦 Navigate to Orders Page\n\nYou have ${orderSummaryForNav.count} orders\n\nI'm taking you to the orders page where you can:\n• View order details\n• Track deliveries\n• Cancel orders\n• Return items\n• Check status\n\nNavigating now...`
              orderActions()
            } else {
              message = `📦 Navigate to Orders Page\n\nYou don't have any orders yet.\n\nI'm taking you to the orders page where you can:\n• View order history\n• Track future orders\n• Manage returns\n\nNavigating now...`
              orderActions()
            }
            contextUpdate = { currentTopic: 'orders', lastAction: 'navigate_to_orders' }
            break

          case "order_status":
            message = `📊 Check Order Status\n\nI can help you check the status of any order!\n\nJust tell me:\n• Order number\n• Or describe your order\n\nWhat order would you like to check?`
            contextUpdate = { currentTopic: 'order_status', lastAction: 'order_status', pendingAction: { type: 'order_status' } }
            break

          case "payment_methods":
            message = `💳 Payment Methods\n\nWe accept:\n\n• Credit/Debit Cards\n• UPI (Google Pay, PhonePe, etc.)\n• Net Banking\n• Digital Wallets\n• EMI Options\n• Gift Cards\n\nAll transactions are secure with SSL encryption!\n\nWhich payment method would you like to know more about?`
            contextUpdate = { currentTopic: 'payment_methods', lastAction: 'payment_methods' }
            break

          case "payment_issues":
            message = `⚠️ Payment Issues\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nWhat payment issue are you experiencing?`
            contextUpdate = { currentTopic: 'payment_issues', lastAction: 'payment_issues', pendingAction: { type: 'payment_issues' } }
            break

          case "refund_status":
            message = `💰 Refund Status\n\nI can help you check your refund status!\n\nJust tell me:\n• Order number\n• Or describe your return\n\nWhat refund would you like to check?`
            contextUpdate = { currentTopic: 'refund_status', lastAction: 'refund_status', pendingAction: { type: 'refund_status' } }
            break

          case "billing_help":
            message = `📄 Billing Help\n\nI can assist with:\n\n• Invoice generation\n• Tax calculations\n• Billing address\n• Payment receipts\n• Corporate billing\n• Bulk orders\n\nWhat billing help do you need?`
            contextUpdate = { currentTopic: 'billing_help', lastAction: 'billing_help' }
            break

          case "security_info":
            message = `🔒 Security Information\n\nYour security is our priority:\n\n• SSL encrypted transactions\n• PCI DSS compliant\n• Secure payment gateways\n• Data protection\n• Privacy policy\n• Fraud protection\n\nAll your data is safe with us!`
            contextUpdate = { currentTopic: 'security_info', lastAction: 'security_info' }
            break

          case "personalized_recommendations":
            const personalizedRecs = await generateRecommendations()
            if (personalizedRecs.length > 0) {
              message = `⭐ Personalized Recommendations\n\nBased on your preferences:\n\n${personalizedRecs.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get recommendations by category`
            } else {
              message = `⭐ Personalized Recommendations\n\nI don't have enough data for personalized recommendations yet.\n\nWould you like to:\n• Browse trending products\n• Search for items\n• View all products`
            }
            contextUpdate = { currentTopic: 'personalized_recommendations', lastAction: 'personalized_recommendations' }
            break

          case "trending_recommendations":
            const trendingRecs = await getTrendingProducts()
            if (trendingRecs.length > 0) {
              message = `🔥 Trending Recommendations\n\nMost popular right now:\n\n${trendingRecs.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks`
            } else {
              message = `🔥 Trending Recommendations\n\nCurrently no trending products available.\n\nWould you like to:\n• Browse all products\n• Search for specific items\n• Get personalized picks`
            }
            contextUpdate = { currentTopic: 'trending_recommendations', lastAction: 'trending_recommendations' }
            break

          case "category_recommendations":
            message = `📦 Recommendations by Category\n\nTell me which category you're interested in:\n\n• Electronics\n• Fashion\n• Home & Garden\n• Sports\n• Books\n• Beauty\n• And more!\n\nWhich category would you like recommendations for?`
            contextUpdate = { currentTopic: 'category_recommendations', lastAction: 'category_recommendations', pendingAction: { type: 'category_recommendations' } }
            break

          case "price_recommendations":
            message = `💰 Recommendations by Price\n\nTell me your budget range:\n\n• Under ₹1000\n• ₹1000-5000\n• ₹5000-10000\n• Above ₹10000\n\nWhat's your budget for recommendations?`
            contextUpdate = { currentTopic: 'price_recommendations', lastAction: 'price_recommendations', pendingAction: { type: 'price_recommendations' } }
            break

          case "similar_products":
            message = `🔄 Similar Products\n\nI can find similar products for you!\n\nJust tell me:\n• Product name\n• Or describe what you're looking for\n\nWhat product would you like similar items for?`
            contextUpdate = { currentTopic: 'similar_products', lastAction: 'similar_products', pendingAction: { type: 'similar_products' } }
            break

          case "contact_support":
            message = `🎧 Contact Support\n\nI can help you connect with our support team:\n\n• Live Chat: Available 24/7\n• Email: support@mkcart.com\n• Phone: +91-XXXXXXXXXX\n• Response Time: Within 2 hours\n\nWhat support do you need?`
            contextUpdate = { currentTopic: 'contact_support', lastAction: 'contact_support' }
            break

          case "faq":
            message = `❓ FAQ\n\nCommon questions:\n\n• How to track orders?\n• How to return items?\n• Payment methods accepted?\n• Delivery time?\n• Refund policy?\n• Account issues?\n\nWhat would you like to know?`
            contextUpdate = { currentTopic: 'faq', lastAction: 'faq' }
            break

          case "live_chat":
            message = `💬 Live Chat\n\nOur live chat is available 24/7!\n\n• Instant responses\n• Real-time assistance\n• File sharing\n• Screen sharing\n• Multi-language support\n\nWould you like to start a live chat?`
            contextUpdate = { currentTopic: 'live_chat', lastAction: 'live_chat' }
            break

          case "email_support":
            message = `📧 Email Support\n\nYou can email us at:\n\n• General: support@mkcart.com\n• Orders: orders@mkcart.com\n• Technical: tech@mkcart.com\n• Billing: billing@mkcart.com\n\nResponse time: Within 2 hours\n\nWhat would you like to email about?`
            contextUpdate = { currentTopic: 'email_support', lastAction: 'email_support' }
            break

          case "technical_help":
            message = `🔧 Technical Help\n\nI can help with technical issues:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nWhat technical issue are you experiencing?`
            contextUpdate = { currentTopic: 'technical_help', lastAction: 'technical_help', pendingAction: { type: 'technical_help' } }
            break

          case "view_products":
            message = `📦 Navigate to Products Page\n\nI'm taking you to the products page where you can:\n• Browse all products\n• Filter by category\n• Sort by price, rating, popularity\n• Search for specific items\n• Add items to cart or wishlist\n• View product details\n\nNavigating now...`
           
            productsActions()

            contextUpdate = { currentTopic: 'view_products', lastAction: 'view_products' }
            break

          default:
            message = `I understand you want to ${action}. Let me help you with that!\n\nWhat specific information or action do you need?`
            contextUpdate = { currentTopic: action, lastAction: action }
        }
        actionTaken = true
      }

      if (actionTaken) {
        
        const aiMessage = {
          id: Date.now() + 1,
          type: "ai",
          message: message,
          timestamp: new Date(),
        }

        setMessages(prev => [...prev, aiMessage])
        setConversationContext(prev => ({ ...prev, ...contextUpdate }))

        if (voiceEnabled) {
          speakMessage(message)
        }

        setTimeout(() => {
          scrollToBottom()
        }, 200)
      }
    } catch (error) {
      
      const errorMessage = {
        id: Date.now() + 1,
        type: "ai",
        message: "Sorry, I encountered an error. Please try again or contact support if the problem persists.",
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, errorMessage])

      setTimeout(() => {
        scrollToBottom()
      }, 200)
    }
  }

  const handleSuggestionClick = (suggestion) => {
    handleSendMessage(suggestion)
  }

  const handleQuickReply = (reply) => {
    handleSendMessage(reply)
  }

  const copyMessage = (message) => {
    navigator.clipboard.writeText(message)
    
  }

  const shareMessage = (message) => {
    if (navigator.share) {
      navigator.share({
        title: "MKCart AI Assistant",
        text: message,
      })
    }
  }

  const rateMessage = (messageId, rating) => {
    setMessages((prev) => prev.map((msg) => (msg.id === messageId ? { ...msg, rating: rating } : msg)))
  }

  const handleFileUpload = (event) => {
    const file = event.target.files[0]
    if (file) {
      const fileMessage = {
        id: Date.now(),
        type: "user",
        message: `Uploaded file: ${file.name}`,
        timestamp: new Date(),
        file: file,
        fileType: file.type,
      }
      setMessages((prev) => [...prev, fileMessage])

      setTimeout(() => {
        const aiResponse = {
          id: Date.now() + 1,
          type: "ai",
          message: "I've received your file. Let me analyze it and provide you with relevant information.",
          timestamp: new Date(),
        }
        setMessages((prev) => [...prev, aiResponse])
      }, 1000)
    }
  }

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const openChat = () => {
    setIsOpen(true)
    setIsFullScreen(true) 
    setShowTooltip(false) 
  }

  const closeChat = () => {
    setIsOpen(false)
    setIsFullScreen(true) 
  }

  const clearChat = () => {
    setMessages([
      {
        id: Date.now(),
        type: "ai",
        message: "Chat cleared! How can I help you today?",
        timestamp: new Date(),
      },
    ])
    setConversationContext({
      currentTopic: null,
      lastAction: null,
      userPreferences: {},
      searchHistory: [],
      currentFilters: {},
      pendingAction: null,
      conversationFlow: []
    })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const handleMouseEnter = () => {
    setShowTooltip(true)
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
  }

  const handleMouseLeave = () => {
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
    tooltipTimeoutRef.current = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)

    return () => {
      clearTimeout(timer)
      if (tooltipTimeoutRef.current) {
        clearTimeout(tooltipTimeoutRef.current)
      }
    }
  }, [])

  const advancedSearch = async (filters) => {
    try {
      const searchParams = new URLSearchParams({
        keyword: filters.keyword || '',
        category: filters.category || '',
        minPrice: filters.minPrice || '',
        maxPrice: filters.maxPrice || '',
        brand: filters.brand || '',
        rating: filters.rating || '',
        availability: filters.availability || ''
      })

      const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)
      const data = await response.json()

      if (data.success) {
        setCurrentSearchResults(data.products)
        setSearchHistory(prev => [...prev, { query: filters.keyword, results: data.products.length, timestamp: new Date() }])
        return data.products
      }
      return []
    } catch (error) {
      
      return []
    }
  }

  const navigateToPage = (path, message) => {
    window.location.href = path
    return {
      success: true,
      message: message
    }
  }

  const cartActions = () => navigateToPage('/cart', "Navigating to your cart page where you can manage your items.")
  const wishlistActions = () => navigateToPage('/wishlist', "Navigating to your wishlist page where you can manage your saved items.")
  const orderActions = () => navigateToPage('/orders', "Navigating to your orders page where you can manage your orders.")
  const productsActions = () => navigateToPage('/productlist', "Navigating to the products page where you can browse all products.")

  const fetchOrderData = async (orderId) => {
    try {
      const orderResponse = await fetch(`${getFullApiUrl()}/user/orders/${orderId}`)
      const orderData = await orderResponse.json()

      let order
      if (orderData.success && orderData.order) {
        order = orderData.order
      } else {
        order = ordersData?.find(order => order._id === orderId || order._id.includes(orderId))
      }
      return order
    } catch (error) {
     
      return null
    }
  }

  const getOrderDetails = async (orderId) => {
    const order = await fetchOrderData(orderId)
    if (order) {
      return {
        _id: order._id,
        orderId: order.orderId || order._id,
        status: order.status || 'Processing',
        amount: order.amount || 0,
        items: order.orderItems || [],
        paymentMethod: order.paymentMethod || 'Not specified',
        transactionId: order.transactionId || '',
        orderDate: order.createdAt || new Date(),
        estimatedDelivery: order.estimatedDelivery || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString(),
        deliveryAddress: order.deliveryAddress || 'User Address',
        trackingNumber: order.trackingNumber || '',
        lastUpdated: new Date().toLocaleDateString()
      }
    }
    return null
  }

  const getOrderStatus = async (orderId) => {
    const order = await fetchOrderData(orderId)
    if (order) {
      const status = order.status || 'Processing'
      const statusDetails = {
        'Confirmed': 'Order confirmed and being prepared',
        'Processing': 'Order is being processed',
        'Shipped': 'Order has been shipped',
        'In Transit': 'Order is in transit',
        'Delivered': 'Order has been delivered',
        'Cancelled': 'Order has been cancelled',
        'Returned': 'Order has been returned'
      }

      return {
        orderId: order.orderId || order._id,
        status: status,
        statusDescription: statusDetails[status] || 'Order status unknown',
        lastUpdated: new Date().toLocaleDateString(),
        estimatedDelivery: order.estimatedDelivery || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString(),
        trackingNumber: order.trackingNumber || '',
        deliveryAddress: order.deliveryAddress || 'User Address',
        amount: order.amount || 0,
        paymentMethod: order.paymentMethod || 'Not specified',
        transactionId: order.transactionId || '',
        canCancel: ['Confirmed', 'Processing'].includes(status),
        canReturn: status === 'Delivered',
        canTrack: ['Shipped', 'In Transit'].includes(status)
      }
    }
    return null
  }

  const processPayment = async (amount, method, orderItems = []) => {
    try {
      
      await new Promise(resolve => setTimeout(resolve, 2000))

      const paymentResult = {
        success: Math.random() > 0.1, 
        transactionId: `TXN${Date.now()}`,
        amount: amount,
        method: method,
        timestamp: new Date(),
        orderId: `ORD${Date.now()}`,
        status: 'Processing'
      }

      if (paymentResult.success) {
        
        const orderData = {
          orderItems: orderItems,
          amount: amount,
          paymentMethod: method,
          status: 'Confirmed',
          transactionId: paymentResult.transactionId,
          orderId: paymentResult.orderId,
          deliveryAddress: 'User Address', 
          estimatedDelivery: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString()
        }

        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          
          setCurrentCartItems([])
        }
      }

      return paymentResult
    } catch (error) {
      
      return { success: false, error: 'Payment failed' }
    }
  }

  const getPersonalizedRecommendations = () => {
    if (!productsData?.products) return []

    const cartItems = getCartSummary().items
    const wishlistItems = getWishlistSummary().items
    const userItems = [...cartItems, ...wishlistItems]
    const userCategories = [...new Set(userItems.map(item => item.category).filter(Boolean))]
    const userBrands = [...new Set(userItems.map(item => item.brand).filter(Boolean))]

    return [...productsData.products]
      .filter(product =>
        userCategories.includes(product.category) ||
        userBrands.includes(product.brand)
      )
      .sort((a, b) => (b.rating || 0) - (a.rating || 0))
      .slice(0, 8)
  }

const getTrendingProducts = async () => {
  try {
    
    const searchParams = new URLSearchParams({
      keyword: '', 
      rating: '4', 
      availability: 'in stock' 
    })

    const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)

    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`)
    }

    const data = await response.json()

    if (data.success && data.products && Array.isArray(data.products)) {
      
      return data.products
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }

    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    if (availableProducts && Array.isArray(availableProducts)) {
      return [...availableProducts]
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }

    return []
  } catch (error) {

    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    if (availableProducts && Array.isArray(availableProducts)) {
      return [...availableProducts]
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }
    return []
  }
}

  const getCategoryProducts = async (category) => {
    try {
      
      const response = await fetch(`${getFullApiUrl()}/products?category=${encodeURIComponent(category)}`)
      const data = await response.json()

      if (data.success && data.products) {
        
        let categoryProducts
        if (category.toLowerCase() === 'men') {
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
        return categoryProducts
      }

      if (productsData?.products) {
        
        if (category.toLowerCase() === 'men') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
      }

      return []
    } catch (error) {

      if (productsData?.products) {
        
        if (category.toLowerCase() === 'men') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
      }
      return []
    }
  }

  const getAvailableCategories = async () => {
    try {
      
      const response = await fetch(`${getFullApiUrl()}/products`)
      const data = await response.json()

      if (data.success && data.products) {
        
        const categories = [...new Set(data.products.map(product => product.category).filter(Boolean))]
        return categories.sort()
      }

      return [
        'Mobile Phones',
        'Accessories',
        'Laptops',
        'Headphones',
        'Shoes',
        'Electronics',
        'Men',
        'Women',
        'Toys',
        'Musical Instruments'
      ]
    } catch (error) {
      
      return [
        'Mobile Phones',
        'Accessories',
        'Laptops',
        'Headphones',
        'Shoes',
        'Electronics',
        'Men',
        'Women',
        'Toys',
        'Musical Instruments'
      ]
    }
  }

  const getDealsAndOffers = () => {
    if (!productsData?.products) return []

    return [...productsData.products]
      .filter(product => product.discount > 0)
      .sort((a, b) => (b.discount || 0) - (a.discount || 0))
      .slice(0, 5)
  }

  const getUserInsights = () => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const orderSummary = getOrderSummary()

    const favoriteCategory = cartSummary.items.length > 0
      ? cartSummary.items.reduce((acc, item) => {
        acc[item.category] = (acc[item.category] || 0) + 1
        return acc
      }, {})
      : {}

    const topCategory = Object.entries(favoriteCategory)
      .sort(([, a], [, b]) => b - a)[0]?.[0] || 'No preference'

    return {
      totalSpent: orderSummary.items.reduce((sum, order) => sum + (order.amount || 0), 0),
      averageOrderValue: orderSummary.count > 0 ? orderSummary.items.reduce((sum, order) => sum + (order.amount || 0), 0) / orderSummary.count : 0,
      favoriteCategory: topCategory,
      cartTotal: cartSummary.total,
      wishlistCount: wishlistSummary.count,
      orderCount: orderSummary.count
    }
  }

  const trackPriceChanges = (productId) => {
    const productsArray = productsData?.products || []
  const product = productsArray.find(p => p._id === productId)
    const wishlistItem = getWishlistSummary().items.find(w => w.productId === productId)

    if (product && wishlistItem) {
      const priceChange = product.price - wishlistItem.price
      const percentageChange = (priceChange / wishlistItem.price) * 100

      return {
        productName: product.name,
        oldPrice: wishlistItem.price,
        newPrice: product.price,
        priceChange,
        percentageChange,
        isDecrease: priceChange < 0
      }
    }
    return null
  }

  const checkInventory = async (productId) => {
    try {
      
      const productResponse = await fetch(`${getFullApiUrl()}/product/${productId}`)
      const productData = await productResponse.json()

      let product
      if (productData.success && productData.product) {
        product = productData.product
      } else {
        
        product = productsData?.products?.find(p => p._id === productId)
      }

      if (product) {
        return {
          productId: product._id,
          name: product.name,
          stock: product.stock || 0,
          available: product.stock > 0,
          seller: product.seller || '',
          category: product.category || '',
          price: product.price || 0,
          lastUpdated: new Date().toLocaleDateString(),
          status: product.stock > 0 ? 'In Stock' : 'Out of Stock',
          lowStock: product.stock > 0 && product.stock <= 5 ? 'Low Stock Alert' : null,
          availability: (product.stock || 0) > 10 ? 'In Stock' : (product.stock || 0) > 0 ? 'Low Stock' : 'Out of Stock'
        }
      }
      return null
    } catch (error) {
      
      return null
    }
  }

  const calculateCartAmount = (items) => {
    return items.reduce((sum, item) => {
      const quantity = item.quantity || item.qty || 1
      const price = item.price || 0
      return sum + (price * quantity)
    }, 0)
  }

  const handlePendingAction = async (action) => {
    switch (action.type) {
      case 'add_to_cart':
        
        let product = currentSearchResults.find(p => p.name.toLowerCase() === action.productName.toLowerCase())

        if (!product) {
          product = currentSearchResults.find(p => p.name.toLowerCase().includes(action.productName.toLowerCase()))
        }

        if (!product) {
          product = currentSearchResults.find(p => action.productName.toLowerCase().includes(p.name.toLowerCase()))
        }

        if (product) {
          return `🛒 To add ${action.quantity || 1} "${product.name}" to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nPrice: ₹${product.price}\n\nI can help you:\n• Navigate to cart page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}". Would you like me to search for similar products?`

      case 'remove_from_cart':
        const removeCartItems = getCartSummary().items
        let cartItem = removeCartItems.find(item => item.name.toLowerCase() === action.productName.toLowerCase())

        if (!cartItem) {
          cartItem = removeCartItems.find(item => item.name.toLowerCase().includes(action.productName.toLowerCase()))
        }

        if (!cartItem) {
          cartItem = removeCartItems.find(item => action.productName.toLowerCase().includes(item.name.toLowerCase()))
        }

        if (cartItem) {
          return `🛒 To remove "${cartItem.name}" from your cart, please navigate to the cart page where you can manage your items.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}" in your cart. Would you like me to show your current cart items?`

      case 'add_to_wishlist':
        const wishlistProduct = currentSearchResults.find(p => p.name.toLowerCase().includes(action.productName.toLowerCase()))
        if (wishlistProduct) {
          return `💖 To add "${wishlistProduct.name}" to your wishlist, please navigate to the product page and use the "Add to Wishlist" button.\n\nPrice: ₹${wishlistProduct.price}\nCategory: ${wishlistProduct.category}\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}". Would you like me to search for similar products?`

      case 'remove_from_wishlist':
        const wishlistItem = getWishlistSummary().items.find(item => item.name.toLowerCase().includes(action.productName.toLowerCase()))
        if (wishlistItem) {
          return `💖 To remove "${wishlistItem.name}" from your wishlist, please navigate to the wishlist page where you can manage your saved items.\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}" in your wishlist. Would you like me to show your current wishlist items?`

      case 'search_with_filters':
        const results = await advancedSearch(action.filters)
        return `🔍 Search Results with Filters\n\nI found ${results.length} products matching your criteria:\n\n${results.products.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category}\n`
        ).join('')}\n\nWould you like me to:\n• Show more results\n• Apply different filters\n• Add items to cart\n• Get recommendations`

      case 'checkout':
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          return `🛒 Checkout Summary\n\nTotal Items: ${cartSummary.count}\nTotal Amount: ₹${cartSummary.total}\n\nI can help you:\n• Review your cart\n• Apply discounts\n• Choose payment method\n• Complete purchase\n• Save for later`
        } else {
          return `Your cart is empty. Would you like me to:\n• Show trending products\n• Search for items\n• Show recommendations`
        }

      case 'cancel_order':
        if (action.orderId) {
          
          return `✅ Order #${action.orderId.slice(-6)} has been cancelled successfully!\n\nRefund will be processed within 5-7 business days.\n\nWould you like to:\n• Check other orders\n• Browse products\n• Contact support`
        }
        return `Order cancellation completed. Would you like to:\n• Check your order history\n• Browse products\n• Contact support`

      case 'clear_cart':
        return `🛒 To clear your cart, please navigate to the cart page where you can remove all items.\n\nI can help you:\n• Navigate to cart page\n• Browse products\n• Search for items\n• View recommendations`

      case 'track_order':
        if (action.orderId) {
          const orderDetails = getOrderDetails(action.orderId)
          if (orderDetails) {
            return `📦 Order #${action.orderId.slice(-6)} Details:\n\nStatus: ${orderDetails.status}\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            return `❌ Order #${action.orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
        }
        return `Please provide your order number to track it.`

      case 'payment_issue':
        return `⚠️ Payment Issue Support\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nPlease describe your specific issue, and I'll guide you through the resolution process.`

      case 'search_by_price':
        
        const pricePatterns = [
          
          { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
          
          { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
          
          { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
        ]

        let minPrice = 0
        let maxPrice = 0
        let priceRangeFound = false

        for (const { pattern, type } of pricePatterns) {
          const match = action.userMessage.match(pattern)
          if (match) {
            priceRangeFound = true

            if (type === 'range') {
              minPrice = parseInt(match[1])
              maxPrice = parseInt(match[2])
            } else if (type === 'under') {
              minPrice = 0
              maxPrice = parseInt(match[1])
            } else if (type === 'above') {
              minPrice = parseInt(match[1])
              maxPrice = Infinity
            }
            break
          }
        }

        if (priceRangeFound) {
          const results = await searchProducts('', { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            return `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
          } else {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            return `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`
          }
        }

        return `💰 Please specify your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n• "Between 1000 and 2000"\n\nWhat's your budget range?`

      case 'product_availability':
        
        const productName = action.productName || action.userMessage.replace(/(?:check|availability|stock|available|in stock|out of stock)/gi, '').trim()
        if (productName) {
          const results = await searchProducts(productName)
          if (results.products && results.products.length > 0) {
            const product = results[0]
            const availability = await checkInventory(product._id)

            if (availability) {
              return `📦 Stock Availability for "${product.name}":\n\n• Status: ${availability.status}\n• Stock Level: ${availability.stock} units\n• Seller: ${availability.seller}\n• Category: ${availability.category}\n• Price: ₹${availability.price}\n• Last Updated: ${availability.lastUpdated}\n${availability.lowStock ? `• ⚠️ ${availability.lowStock}\n` : ''}\n\nWould you like to:\n• Add to cart\n• Check similar products\n• Get price alerts\n• View full details`
            } else {
              return `❌ Sorry, I couldn't check the availability for "${product.name}".\n\nWould you like to:\n• Search for similar products\n• Browse the category\n• Get recommendations`
            }
          } else {
            return `❌ Product "${productName}" not found.\n\nWould you like to:\n• Search for similar products\n• Browse categories\n• Get recommendations`
          }
        }

        return `📦 Please specify which product you'd like me to check for availability!\n\nExamples:\n• "Check iPhone stock"\n• "Is laptop available"\n• "Shoe availability"\n\nWhat product should I check?`

      case 'search_by_category':
        
        const category = action.userMessage?.trim() || ''
        if (category) {
          const categoryProducts = await getCategoryProducts(category)

          if (categoryProducts.length > 0) {
            return `📦 Great choice! Here are ${categoryProducts.length} products in the ${category} category:\n\n${categoryProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nI can help you:\n• Add any to cart\n• See more ${category} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks\n• Browse other categories`
          } else {
            const availableCategories = await getAvailableCategories()
            const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
            return `📦 No products found in the ${category} category.\n\nAvailable categories:\n${categoryList}\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items\n• Get recommendations`
          }
        }

        const availableCategories = await getAvailableCategories()
        const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
        return `📦 Please specify which category you'd like to browse!\n\nAvailable categories:\n${categoryList}\n\nExamples:\n• "Electronics"\n• "Fashion"\n• "Toys"\n• "Sports"\n\nWhat category interests you?`

      case 'technical_issue':
        return `🔧 Technical Support\n\nI can help you with:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nPlease describe your specific technical issue, and I'll guide you through the resolution process.`

      default:
        return "I'm not sure what action to take. Could you please clarify?"
    }
  }

  const [conversationMemory, setConversationMemory] = useState([])
  const [aiPersonality, setAiPersonality] = useState({
    name: 'MKCart Assistant',
    expertise: ['e-commerce', 'shopping', 'product recommendations', 'customer service'],
    tone: 'helpful and knowledgeable',
    capabilities: ['search', 'recommendations', 'order management', 'payment assistance']
  })

  const analyzeUserIntent = (message) => {
    const lowerMessage = message.toLowerCase()

    const intents = {
      search: /search|find|look for|browse|explore|discover/i,
      purchase: /buy|purchase|order|checkout|pay|add to cart/i,
      information: /what|how|when|where|why|tell me|explain|describe/i,
      comparison: /compare|vs|versus|difference|better|best/i,
      recommendation: /recommend|suggest|advise|what should|help me choose/i,
      complaint: /problem|issue|error|wrong|broken|not working/i,
      gratitude: /thank|thanks|appreciate|grateful/i,
      greeting: /hello|hi|hey|good morning|good afternoon|good evening/i,
      farewell: /bye|goodbye|see you|farewell/i,
      urgency: /urgent|asap|quickly|fast|immediately/i
    }

    for (const [intent, pattern] of Object.entries(intents)) {
      if (pattern.test(lowerMessage)) {
        return intent
      }
    }

    return 'general'
  }

  const analyzeSentiment = (message) => {
    const lowerMessage = message.toLowerCase()

    const positiveWords = ['good', 'great', 'excellent', 'amazing', 'wonderful', 'perfect', 'love', 'like', 'happy', 'satisfied']
    const negativeWords = ['bad', 'terrible', 'awful', 'hate', 'dislike', 'angry', 'frustrated', 'disappointed', 'upset']

    let positiveCount = 0
    let negativeCount = 0

    positiveWords.forEach(word => {
      if (lowerMessage.includes(word)) positiveCount++
    })

    negativeWords.forEach(word => {
      if (lowerMessage.includes(word)) negativeCount++
    })

    if (positiveCount > negativeCount) return 'positive'
    if (negativeCount > positiveCount) return 'negative'
    return 'neutral'
  }

  const extractEntities = (message) => {
    const entities = {
      products: [],
      categories: [],
      prices: [],
      quantities: [],
      brands: [],
      actions: []
    }

    const productPatterns = [
      /iPhone|iPad|MacBook|Samsung|Nike|Adidas|Sony|Dell|HP|Lenovo/gi,
      /laptop|phone|shoes|shirt|pants|headphones|camera|watch/gi
    ]

    productPatterns.forEach(pattern => {
      const matches = message.match(pattern)
      if (matches) {
        entities.products.push(...matches)
      }
    })

    const categoryPatterns = [
      /electronics|fashion|sports|books|beauty|home|automotive|toys/gi
    ]

    categoryPatterns.forEach(pattern => {
      const matches = message.match(pattern)
      if (matches) {
        entities.categories.push(...matches)
      }
    })

    const priceMatches = message.match(/₹?\d+(?:,\d+)*(?:\.\d{2})?/g)
    if (priceMatches) {
      entities.prices.push(...priceMatches)
    }

    const quantityMatches = message.match(/\d+\s*(?:piece|item|unit|quantity|qty)/gi)
    if (quantityMatches) {
      entities.quantities.push(...quantityMatches)
    }

    return entities
  }

  const responseLibraries = {
    greetings: {
      morning: [
        "Good morning! ☀️ I'm your MKCart AI assistant, ready to help you with your shopping needs. How can I assist you today?",
        "Rise and shine! 🌅 Welcome to MKCart. I'm here to make your shopping experience delightful. What can I help you find?",
        "Good morning! 🌞 I hope you're having a wonderful start to your day. I'm ready to help you discover amazing products.",
        "Morning! ☀️ Your personal shopping assistant is here and ready to serve. What's on your shopping list today?"
      ],
      afternoon: [
        "Good afternoon! 🌤️ Welcome to MKCart. I'm your AI shopping companion, ready to help you find exactly what you need.",
        "Afternoon! 🌅 I hope your day is going great. I'm here to assist you with all your shopping questions and needs.",
        "Good afternoon! 🌤️ Your MKCart assistant is ready to help you discover amazing products and deals.",
        "Hello there! 🌅 I'm your shopping buddy for the afternoon. What can I help you find today?"
      ],
      evening: [
        "Good evening! 🌙 Welcome to MKCart. I'm here to help you with your evening shopping needs.",
        "Evening! 🌆 I hope you've had a great day. I'm ready to assist you with finding the perfect products.",
        "Good evening! 🌙 Your MKCart assistant is here to help you wind down with some great shopping.",
        "Hello! 🌆 Evening shopping is my specialty. What can I help you discover today?"
      ],
      general: [
        "Hello! 👋 I'm your MKCart AI assistant, your personal shopping companion. How can I help you today?",
        "Hi there! 🛍️ Welcome to MKCart. I'm here to make your shopping experience amazing. What can I assist you with?",
        "Greetings! 🎉 I'm your AI shopping assistant, ready to help you find the perfect products. What's on your mind?",
        "Hey! 👋 Your MKCart assistant is here and ready to help. What would you like to explore today?"
      ]
    },

    gratitude: {
      positive: [
        "You're absolutely welcome! 😊 It's my pleasure to help you have the best shopping experience possible.",
        "Thank you for choosing MKCart! 🙏 I'm here whenever you need assistance with your shopping journey.",
        "You're very welcome! 💫 I love helping customers find exactly what they're looking for.",
        "It's my pleasure! 🌟 I'm committed to making your shopping experience smooth and enjoyable.",
        "Anytime! 😄 I'm your shopping assistant, and I'm here to help you succeed."
      ],
      neutral: [
        "You're welcome! I'm here to help with all your shopping needs.",
        "No problem at all! Let me know if you need anything else.",
        "Glad I could help! Feel free to ask if you have more questions.",
        "You're welcome! I'm always here when you need assistance."
      ]
    },

    farewell: [
      "Goodbye! 👋 Thank you for shopping with MKCart. Have a wonderful day!",
      "See you later! 🛍️ I'll be here when you return. Happy shopping!",
      "Take care! 😊 I hope you found everything you were looking for.",
      "Farewell! 🌟 Thank you for choosing MKCart. Come back anytime!",
      "Bye for now! 👋 I'm always here to help with your next shopping adventure."
    ],

    confusion: [
      "I'm not quite sure I understood that. Could you please rephrase or tell me more specifically what you're looking for?",
      "Let me make sure I understand correctly. Could you clarify what you'd like help with?",
      "I want to help you best, but I need a bit more clarity. What exactly are you looking for?",
      "I'm here to help, but I need to understand better. Could you explain what you need?"
    ],

    recommendations: {
      general: [
        "Based on what I know about your preferences, here are some products you might love:",
        "I think you'll really enjoy these recommendations I've picked just for you:",
        "Here are some amazing products that match your style and preferences:",
        "I've curated these recommendations especially for you:"
      ],
      trending: [
        "These are the hottest products everyone's talking about right now:",
        "Here are the trending items that are flying off our virtual shelves:",
        "These products are trending and getting amazing reviews:",
        "Check out what's popular and in-demand right now:"
      ],
      personalized: [
        "Based on your shopping history and preferences, I think you'll love:",
        "I've analyzed your style and here are some perfect matches:",
        "These recommendations are tailored specifically to your taste:",
        "Here are some products that align perfectly with your preferences:"
      ]
    },

    search: {
      product: [
        "I'll help you find the perfect {product}. Let me search our extensive collection for you.",
        "Searching for {product}... I'll show you the best options available.",
        "Let me find the best {product} options for you from our curated selection.",
        "I'm on it! Searching for {product} across all our categories."
      ],
      category: [
        "Great choice! Let me show you the best {category} products we have.",
        "I'll browse through our {category} collection to find you the perfect items.",
        "Let me explore our {category} section for you.",
        "I'm searching our {category} inventory for the best options."
      ]
    },

    help: {
      general: [
        "I'm here to help! I can assist you with searching products, managing your cart, tracking orders, and much more.",
        "I can help you find products, compare prices, track orders, manage your wishlist, and answer any shopping questions.",
        "I'm your shopping assistant! I can search, recommend, help with orders, and make your shopping experience better.",
        "I'm here to make your shopping easier! I can search, compare, track, and help with any shopping needs."
      ],
      specific: [
        "I can help you with that! Just tell me more about what you're looking for.",
        "Absolutely! I'm here to assist you with that. What specific details can you provide?",
        "I'd love to help! Let me know more about what you need assistance with.",
        "I'm ready to help! Please share more details so I can assist you better."
      ]
    },

    emotions: {
      excited: [
        "That's fantastic! 🎉 I'm excited to help you with that!",
        "Wonderful! ✨ I can't wait to assist you with this!",
        "Amazing! 🌟 Let's make this happen together!",
        "Excellent choice! 🚀 I'm here to help you succeed!"
      ],
      frustrated: [
        "I understand this can be frustrating. Let me help you resolve this quickly.",
        "I'm here to help make this easier for you. Let's work through this together.",
        "I can see this is bothering you. Let me assist you in finding a solution.",
        "Don't worry, I'm here to help you get this sorted out."
      ],
      confused: [
        "No worries! Let me break this down for you in a simpler way.",
        "I understand this might be confusing. Let me explain it clearly.",
        "Let me help you understand this better. I'll guide you through it step by step.",
        "I'm here to clarify things for you. What specific part would you like me to explain?"
      ],
      satisfied: [
        "I'm so glad I could help! 😊 Is there anything else you'd like assistance with?",
        "Perfect! I'm happy we could resolve this together. What's next?",
        "Excellent! I'm here whenever you need more help.",
        "Great! I'm always ready to assist you with your next shopping adventure."
      ]
    },

    urgency: {
      high: [
        "I understand this is urgent! Let me help you quickly.",
        "I'll prioritize this for you right away.",
        "Let me get this sorted out immediately for you.",
        "I'm on it! This will be handled as a priority."
      ],
      medium: [
        "I'll help you with this promptly.",
        "Let me assist you with this right away.",
        "I'll get this done for you quickly.",
        "I'm here to help you resolve this efficiently."
      ],
      low: [
        "I'll help you with this at your convenience.",
        "Take your time, I'm here to assist you.",
        "I'll guide you through this step by step.",
        "I'm here whenever you're ready to proceed."
      ]
    },

    personality: {
      formal: [
        "I understand your request. Allow me to assist you with that matter.",
        "I appreciate your inquiry. Let me provide you with the necessary information.",
        "Thank you for your question. I'll be happy to help you with this.",
        "I acknowledge your request. Let me address this for you."
      ],
      casual: [
        "Hey! I got you covered on that!",
        "No problem at all! Let me help you out.",
        "Sure thing! I'm here to make this easy for you.",
        "Absolutely! Let's get this sorted together."
      ],
      friendly: [
        "Of course! I'd love to help you with that! 😊",
        "You bet! I'm here to make your day easier!",
        "Absolutely! Let's make this happen together!",
        "Sure thing! I'm excited to help you out!"
      ]
    },

    context: {
      firstTime: [
        "Welcome to MKCart! I'm here to make your first shopping experience amazing!",
        "First time here? Let me show you around and help you get started!",
        "Welcome! I'm your personal shopping assistant. Let me help you discover our amazing products!",
        "New to MKCart? I'm here to guide you through everything we have to offer!"
      ],
      returning: [
        "Welcome back! I'm glad to see you again!",
        "Great to have you back! How can I help you today?",
        "Welcome back! I'm here to continue helping you with your shopping needs!",
        "It's wonderful to see you again! What can I assist you with today?"
      ],
      frequent: [
        "Welcome back, valued customer! I'm here to help you with your shopping!",
        "Great to see you again! I'm ready to assist you with your shopping needs!",
        "Welcome back! I'm here to make your shopping experience even better!",
        "It's always a pleasure to help you! What can I do for you today?"
      ]
    },

    payment: {
      methods: [
        "We accept multiple payment methods for your convenience:\n\n💳 Credit/Debit Cards (Visa, MasterCard, American Express)\n📱 UPI (Google Pay, PhonePe, Paytm)\n🏦 Net Banking (All major banks)\n📲 Digital Wallets (Paytm, Amazon Pay)\n💳 EMI Options (3, 6, 9, 12 months)\n💰 Cash on Delivery\n\nAll payments are secured with bank-level encryption!",
        "Here are our secure payment options:\n\n💳 Cards: Visa, MasterCard, Amex\n📱 UPI: Instant transfers\n🏦 Net Banking: Direct bank transfers\n📲 Wallets: Paytm, Amazon Pay, Google Pay\n💳 EMI: No-cost EMI available\n💰 COD: Pay when you receive\n\nYour payment security is our top priority!",
        "Choose from our wide range of payment methods:\n\n💳 Credit/Debit Cards\n📱 UPI Payments\n🏦 Internet Banking\n📲 Mobile Wallets\n💳 Easy EMI Plans\n💰 Cash on Delivery\n\nAll transactions are 100% secure and encrypted!"
      ],
      security: [
        "Your payment security is guaranteed with:\n\n🔒 SSL Encryption (256-bit)\n🛡️ PCI DSS Compliance\n🔐 3D Secure Authentication\n🛡️ Fraud Protection\n🔒 Secure Payment Gateway\n\nWe never store your payment details!",
        "We use industry-leading security measures:\n\n🔒 Bank-level encryption\n🛡️ PCI DSS certified\n🔐 Two-factor authentication\n🛡️ Real-time fraud detection\n🔒 Secure payment processing\n\nYour financial information is completely safe!",
        "Rest assured with our security features:\n\n🔒 Military-grade encryption\n🛡️ Payment card industry standards\n🔐 Secure authentication\n🛡️ Anti-fraud systems\n🔒 Protected transactions\n\nWe prioritize your payment safety!"
      ],
      issues: [
        "I understand payment issues can be frustrating. Let me help you:\n\n🔍 Check payment status\n💳 Verify card details\n📱 Confirm UPI ID\n🏦 Validate bank information\n📞 Contact payment support\n\nWhat specific payment issue are you facing?",
        "Let's resolve your payment problem together:\n\n🔍 Review transaction details\n💳 Check card validity\n📱 Verify UPI credentials\n🏦 Confirm bank details\n📞 Get expert assistance\n\nPlease share more details about the issue.",
        "I'm here to help with your payment concern:\n\n🔍 Investigate the problem\n💳 Validate payment method\n📱 Check UPI status\n🏦 Verify bank information\n📞 Connect with support team\n\nWhat exactly happened with your payment?"
      ],
      emi: [
        "EMI options available for your convenience:\n\n💳 3 months EMI - No extra cost\n💳 6 months EMI - 0% interest\n💳 9 months EMI - Low processing fee\n💳 12 months EMI - Competitive rates\n\nEligible on orders above ₹1,000!",
        "Make your purchase easier with EMI:\n\n💳 3, 6, 9, 12 month plans\n💳 No-cost EMI available\n💳 Instant approval\n💳 All major banks accepted\n💳 No hidden charges\n\nCheck eligibility at checkout!",
        "Flexible EMI plans for you:\n\n💳 Multiple tenure options\n💳 Zero interest on select plans\n💳 Quick approval process\n💳 Wide bank coverage\n💳 Transparent pricing\n\nSplit your payment into easy installments!"
      ]
    },

    product: {
      details: [
        "Here are the complete product details:\n\n📦 Brand: {brand}\n💰 Price: {price}\n⭐ Rating: {rating}/5 ({reviews} reviews)\n📏 Dimensions: {dimension}\n⚖️ Weight: {weight}\n🏭 Material: {material}\n🛡️ Warranty: {warranty}\n\nKey Features:\n{features}\n\nWould you like to know more about any specific aspect?",
        "Product specifications for you:\n\n🏷️ Brand: {brand}\n💵 Price: {price}\n⭐ Customer Rating: {rating}⭐\n📐 Size: {dimension}\n⚖️ Weight: {weight}\n🏭 Build Material: {material}\n🛡️ Warranty Period: {warranty}\n\nHighlighted Features:\n{features}\n\nNeed any clarification on these details?",
        "Complete product information:\n\n🏷️ Manufacturer: {brand}\n💰 Cost: {price}\n⭐ User Rating: {rating}/5\n📏 Measurements: {dimension}\n⚖️ Product Weight: {weight}\n🏭 Construction: {material}\n🛡️ Guarantee: {warranty}\n\nSpecial Features:\n{features}\n\nWhat would you like to know more about?"
      ],
      comparison: [
        "Let me compare these products for you:\n\n📊 Price Comparison:\n• Product A: ₹{priceA}\n• Product B: ₹{priceB}\n\n⭐ Rating Comparison:\n• Product A: {ratingA}⭐\n• Product B: {ratingB}⭐\n\n🔍 Feature Comparison:\n• Product A: {featuresA}\n• Product B: {featuresB}\n\nWhich aspects are most important to you?",
        "Here's a detailed comparison:\n\n💰 Price Analysis:\n• Option 1: ₹{priceA}\n• Option 2: ₹{priceB}\n\n⭐ Customer Ratings:\n• Option 1: {ratingA}⭐\n• Option 2: {ratingB}⭐\n\n✨ Key Differences:\n• Option 1: {featuresA}\n• Option 2: {featuresB}\n\nWhat factors matter most in your decision?",
        "Product comparison breakdown:\n\n💵 Cost Comparison:\n• Item A: ₹{priceA}\n• Item B: ₹{priceB}\n\n⭐ Quality Ratings:\n• Item A: {ratingA}⭐\n• Item B: {ratingB}⭐\n\n🔍 Feature Analysis:\n• Item A: {featuresA}\n• Item B: {featuresB}\n\nWhich product better fits your needs?"
      ],
      availability: [
        "Stock status for this product:\n\n✅ In Stock: {quantity} units available\n🚚 Delivery: {deliveryTime}\n📍 Location: {location}\n🔄 Restock: {restockDate}\n\nWould you like me to check availability in other locations?",
        "Current availability information:\n\n✅ Available: {quantity} pieces in stock\n🚚 Shipping: {deliveryTime}\n📍 Warehouse: {location}\n🔄 Next Stock: {restockDate}\n\nShould I check alternative locations for you?",
        "Product availability details:\n\n✅ Stock: {quantity} units ready\n🚚 Delivery Time: {deliveryTime}\n📍 Storage: {location}\n🔄 Replenishment: {restockDate}\n\nWould you like me to search nearby warehouses?"
      ]
    },

    recommendations: {
      personalized: [
        "Based on your preferences, here are personalized recommendations:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nThese match your style and budget perfectly!",
        "Curated just for you:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nSelected based on your shopping history!",
        "Personal picks for you:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nTailored to your taste and preferences!"
      ],
      trending: [
        "Hot trending products right now:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nEveryone's talking about these!",
        "Currently trending items:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nFlying off our shelves!",
        "Trending products this week:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nHighly popular choices!"
      ],
      category: [
        "Best picks in {category}:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nTop-rated in this category!",
        "Leading {category} products:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nCustomer favorites!",
        "Premium {category} selection:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nHighest quality options!"
      ]
    },

    search: {
      results: [
        "🔍 Search Results for '{query}':\n\nFound {count} products matching your search\n\n{products}\n\n💡 Tips:\n• Use filters to narrow results\n• Sort by price, rating, or popularity\n• Save items to wishlist for later\n• Compare similar products\n\nWould you like to refine your search?",
        "📋 Search Results for '{query}':\n\n{count} products found\n\n{products}\n\n✨ Suggestions:\n• Apply price range filters\n• Sort by customer ratings\n• Check product reviews\n• Add favorites to wishlist\n\nNeed help finding something specific?",
        "🎯 Search Results for '{query}':\n\n{count} matching products\n\n{products}\n\n🔧 Options:\n• Filter by category or brand\n• Sort by newest arrivals\n• View detailed specifications\n• Read customer reviews\n\nLooking for something else?"
      ],
      noResults: [
        "😔 No products found for '{query}'\n\n💡 Suggestions:\n• Check spelling and try again\n• Try different keywords\n• Browse similar categories\n• Use broader search terms\n• Check our trending products\n\nWould you like me to suggest alternatives?",
        "🔍 No results for '{query}'\n\n✨ Try these alternatives:\n• Use simpler search terms\n• Check for typos\n• Browse related categories\n• Look at popular items\n• Try synonyms\n\nLet me help you find what you're looking for!",
        "📭 No products match '{query}'\n\n🎯 Suggestions:\n• Double-check your spelling\n• Try related keywords\n• Explore similar categories\n• Check trending products\n• Use category filters\n\nI can help you discover great alternatives!"
      ],
      suggestions: [
        "💡 Search Suggestions:\n\n• Try: '{suggestion1}', '{suggestion2}', '{suggestion3}'\n• Popular searches: '{popular1}', '{popular2}'\n• Related categories: '{category1}', '{category2}'\n\nWould you like to try one of these searches?",
        "🔍 Did you mean:\n\n• '{suggestion1}' (most popular)\n• '{suggestion2}' (trending)\n• '{suggestion3}' (similar)\n• Popular: '{popular1}', '{popular2}'\n• Categories: '{category1}', '{category2}'\n\nWhich would you like to explore?",
        "✨ Search Alternatives:\n\n• Similar terms: '{suggestion1}', '{suggestion2}'\n• Trending searches: '{popular1}', '{popular2}'\n• Related categories: '{category1}', '{category2}'\n• Popular products in this area\n\nLet me know which interests you!"
      ],
      filters: [
        "🔧 Search Filters Available:\n\n💰 Price Range: ₹100 - ₹50,000+\n⭐ Rating: 1-5 stars\n🏷️ Brand: All major brands\n📦 Category: All categories\n🚚 Delivery: Free/Express\n\nApply filters to find exactly what you need!",
        "⚙️ Filter Options:\n\n💰 Price: Set your budget range\n⭐ Rating: Filter by customer ratings\n🏷️ Brand: Choose specific brands\n📦 Category: Select product categories\n🚚 Shipping: Free delivery options\n\nCustomize your search for better results!",
        "🎛️ Search Filters:\n\n💰 Price Range: Customize budget\n⭐ Customer Rating: 1-5 stars\n🏷️ Brand Selection: All available brands\n📦 Category Filter: All product types\n🚚 Delivery Options: Free/Paid shipping\n\nUse filters to narrow down your search!"
      ]
    },

    tracking: {
      found: [
        "📦 Order Tracking Results:\n\nOrder: #{orderNumber}\nStatus: {status}\nEstimated Delivery: {deliveryDate}\nCurrent Location: {location}\n\n📋 Order Details:\n{items}\n\n💰 Total: {total}\n🚚 Shipping: {shipping}\n\nWould you like to track another order?",
        "🚚 Order Status Update:\n\nOrder Number: #{orderNumber}\nCurrent Status: {status}\nExpected Delivery: {deliveryDate}\nLast Update: {location}\n\n📦 Items Ordered:\n{items}\n\n💵 Order Total: {total}\n📮 Shipping Method: {shipping}\n\nNeed help with this order?",
        "📋 Order Information:\n\nOrder ID: #{orderNumber}\nStatus: {status}\nDelivery Date: {deliveryDate}\nCurrent Location: {location}\n\n🛍️ Products:\n{items}\n\n💰 Total Amount: {total}\n🚚 Delivery: {shipping}\n\nAny questions about this order?"
      ],
      notFound: [
        "🔍 Order #{orderNumber} not found\n\nPossible reasons:\n• Order number might be incorrect\n• Order might be from a different account\n• Order might be older than 2 years\n• Check spelling and try again\n\nNeed help finding your order?",
        "📭 Order #{orderNumber} not located\n\n💡 Suggestions:\n• Verify the order number\n• Check if you're logged into the right account\n• Orders older than 2 years may not be available\n• Contact support for assistance\n\nWould you like me to help you search?",
        "❌ Order #{orderNumber} not found\n\n🔍 Troubleshooting:\n• Double-check the order number\n• Ensure you're using the correct account\n• Recent orders are more likely to be found\n• Older orders may have limited information\n\nLet me help you locate your order!"
      ],
      multiple: [
        "📦 Multiple Orders Found:\n\n{orders}\n\n💡 Tips:\n• Click on any order for detailed tracking\n• Orders are sorted by date (newest first)\n• Track multiple orders simultaneously\n• Get delivery notifications\n\nWhich order would you like to track in detail?",
        "📋 Your Recent Orders:\n\n{orders}\n\n✨ Features:\n• Real-time tracking updates\n• Delivery notifications\n• Order history access\n• Return/refund status\n\nSelect an order for detailed information!",
        "🚚 Order Summary:\n\n{orders}\n\n🔧 Options:\n• View detailed tracking\n• Check delivery status\n• Monitor shipping progress\n• Access order history\n\nChoose an order to get more details!"
      ]
    },

    cart: {
      items: [
        "🛒 Your Shopping Cart:\n\n{items}\n\n💰 Subtotal: {subtotal}\n🚚 Shipping: {shipping}\n💳 Tax: {tax}\n💵 Total: {total}\n\n✨ Cart Features:\n• Save for later\n• Update quantities\n• Remove items\n• Apply coupon codes\n• Proceed to checkout\n\nReady to complete your purchase?",
        "📦 Cart Contents:\n\n{items}\n\n💳 Price Breakdown:\n• Subtotal: {subtotal}\n• Shipping: {shipping}\n• Tax: {tax}\n• Total: {total}\n\n🔧 Cart Options:\n• Modify quantities\n• Remove products\n• Save to wishlist\n• Add coupon\n• Checkout now\n\nWhat would you like to do?",
        "🛍️ Your Cart Summary:\n\n{items}\n\n💰 Cost Summary:\n• Items Total: {subtotal}\n• Delivery Fee: {shipping}\n• Taxes: {tax}\n• Grand Total: {total}\n\n⚙️ Available Actions:\n• Edit quantities\n• Delete items\n• Move to wishlist\n• Apply discounts\n• Place order\n\nReady to proceed?"
      ],
      empty: [
        "🛒 Your cart is empty\n\n💡 Suggestions:\n• Browse our trending products\n• Check out personalized recommendations\n• Explore new arrivals\n• View your wishlist items\n• Discover daily deals\n\nLet me help you find something amazing!",
        "📭 Shopping cart is empty\n\n✨ What's new:\n• Latest product arrivals\n• Trending items this week\n• Personalized picks for you\n• Special offers and deals\n• Customer favorites\n\nWould you like to explore our collection?",
        "🛍️ No items in your cart\n\n🎯 Discover:\n• Hot selling products\n• Recommended for you\n• New arrivals\n• Limited time offers\n• Best sellers\n\nReady to start shopping? Let me show you some great options!"
      ],
      recommendations: [
        "💡 Cart Recommendations:\n\nBased on your cart, you might also like:\n\n{recommendations}\n\n🔥 Add these to save more:\n• Bundle deals available\n• Free shipping on orders above ₹999\n• Extra discounts on multiple items\n\nWould you like to add any of these?",
        "✨ Suggested Additions:\n\nPerfect with your current items:\n\n{recommendations}\n\n💎 Benefits:\n• Complete your look\n• Save with bundles\n• Free delivery eligible\n• Extra savings available\n\nInterested in any of these?",
        "🎯 Recommended for You:\n\nGreat additions to your cart:\n\n{recommendations}\n\n🚀 Advantages:\n• Enhance your purchase\n• Bundle savings\n• Free shipping threshold\n• Additional discounts\n\nWant to add any of these items?"
      ]
    },

    wishlist: {
      items: [
        "❤️ Your Wishlist:\n\n{items}\n\n💡 Wishlist Features:\n• Move items to cart\n• Remove from wishlist\n• Share wishlist\n• Get price drop alerts\n• Compare items\n\nWould you like to move any items to your cart?",
        "📋 Wishlist Contents:\n\n{items}\n\n✨ Options Available:\n• Add to cart\n• Remove items\n• Share with friends\n• Price notifications\n• Item comparison\n\nReady to purchase any of these?",
        "💝 Your Saved Items:\n\n{items}\n\n🔧 Wishlist Tools:\n• Purchase items\n• Delete from list\n• Share wishlist\n• Price alerts\n• Compare products\n\nWhich items would you like to buy?"
      ],
      empty: [
        "❤️ Your wishlist is empty\n\n💡 Start building your wishlist:\n• Browse trending products\n• Save items you love\n• Get price drop notifications\n• Share with friends\n• Compare products\n\nLet me show you some amazing products!",
        "📭 No items in wishlist\n\n✨ Benefits of wishlisting:\n• Save items for later\n• Price drop alerts\n• Easy comparison\n• Share with family\n• Quick access\n\nWould you like to explore and save some items?",
        "💝 Wishlist is empty\n\n🎯 Why create a wishlist:\n• Never lose track of items\n• Get notified of sales\n• Compare prices easily\n• Share with loved ones\n• Quick reordering\n\nReady to discover and save some favorites?"
      ],
      priceAlerts: [
        "💰 Price Drop Alert!\n\nThese items in your wishlist have price drops:\n\n{priceDrops}\n\n⚡ Limited time offers\n🔥 Don't miss out on savings\n💳 Secure payment options\n\nWould you like to purchase any of these?",
        "📉 Price Reduced!\n\nGreat news! Prices dropped on:\n\n{priceDrops}\n\n🎯 Special offers available\n🚀 Quick checkout process\n💎 Premium customer service\n\nReady to grab these deals?",
        "💸 Savings Alert!\n\nPrice reductions on your wishlist:\n\n{priceDrops}\n\n🔥 Limited time only\n⚡ Fast delivery available\n💳 Multiple payment options\n\nDon't wait - these deals won't last!"
      ]
    },

    support: {
      general: [
        "I'm here to help with any questions or issues:\n\n📞 Live Chat: Available 24/7\n📧 Email: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Response Time: Within 2 hours\n\nWhat can I assist you with today?",
        "Customer support at your service:\n\n📞 Chat Support: 24/7 available\n📧 Email Support: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Quick Response: Under 2 hours\n\nHow can I help you today?",
        "Need help? I'm here for you:\n\n📞 24/7 Live Chat\n📧 Email: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Fast Response: 2 hours max\n\nWhat's your concern today?"
      ],
      order: [
        "Order support assistance:\n\n📦 Track your order\n🔄 Check order status\n❌ Cancel order\n🔄 Return/Refund\n📞 Order support\n\nPlease provide your order number for quick assistance.",
        "I can help with your order:\n\n📦 Order tracking\n🔄 Status updates\n❌ Order cancellation\n🔄 Returns & refunds\n📞 Direct support\n\nShare your order number for immediate help.",
        "Order-related help available:\n\n📦 Track delivery\n🔄 Check status\n❌ Cancel if needed\n🔄 Return process\n📞 Get support\n\nYour order number will help me assist you faster."
      ],
      technical: [
        "Technical support is here to help:\n\n🔧 Website issues\n📱 App problems\n💳 Payment errors\n🔐 Account issues\n📞 Tech support\n\nDescribe the technical problem you're facing.",
        "Technical assistance available:\n\n🔧 Site problems\n📱 App issues\n💳 Payment troubles\n🔐 Account problems\n📞 Expert help\n\nPlease explain the technical issue you're experiencing.",
        "I can help with technical issues:\n\n🔧 Website problems\n📱 App difficulties\n💳 Payment issues\n🔐 Account troubles\n📞 Technical support\n\nWhat technical problem are you encountering?"
      ],
      refund: [
        "Refund and return assistance:\n\n🔄 Return policy: 30 days\n💰 Refund time: 5-7 days\n📦 Free return shipping\n📞 Refund support\n\nI'll guide you through the return process.",
        "Return and refund help:\n\n🔄 30-day return window\n💰 5-7 day refund time\n📦 No-cost returns\n📞 Refund assistance\n\nLet me help you with the return process.",
        "Refund support available:\n\n🔄 30-day returns\n💰 Quick refunds (5-7 days)\n📦 Free return shipping\n📞 Refund help\n\nI'll assist you with the return and refund process."
      ]
    }
  }

  const getRandomResponse = (library, category = null) => {
    if (category && library[category]) {
      const responses = library[category]
      return responses[Math.floor(Math.random() * responses.length)]
    } else if (Array.isArray(library)) {
      return library[Math.floor(Math.random() * library.length)]
    }
    return "I'm here to help! How can I assist you today?"
  }

  const comprehensiveNLU = (userMessage) => {
    const lowerMessage = userMessage.toLowerCase()
    const analysis = {
      intent: null,
      sentiment: null,
      entities: {},
      emotions: [],
      urgency: 'low',
      personality: 'friendly',
      context: 'general',
      confidence: 0,
      suggestions: [],
      responseType: 'general'
    }

    const intentPatterns = {
      search: {
        patterns: [
          /search|find|look for|where can i get|i need|i want|show me|display|browse/i,
          /buy|purchase|get|acquire|obtain/i,
          /product|item|thing|stuff/i
        ],
        confidence: 0.9
      },
      recommendation: {
        patterns: [
          /recommend|suggest|advise|what should|help me choose|best|top|popular/i,
          /similar|like this|same as|alternative/i
        ],
        confidence: 0.85
      },
      cart: {
        patterns: [
          /cart|basket|add to cart|remove from cart|checkout|buy now/i,
          /quantity|how many|update|change/i
        ],
        confidence: 0.9
      },
      wishlist: {
        patterns: [
          /wishlist|favorites|save|wish|favorite|saved items/i,
          /save for later|remember this/i
        ],
        confidence: 0.85
      },
      order: {
        patterns: [
          /order|track|delivery|shipping|status|tracking|package|parcel/i,
          /when will|where is|arrive|delivered/i
        ],
        confidence: 0.9
      },
      complaint: {
        patterns: [
          /problem|issue|error|wrong|broken|not working|complaint/i,
          /refund|return|cancel|disappointed|angry/i
        ],
        confidence: 0.8
      },
      gratitude: {
        patterns: [
          /thank|thanks|appreciate|grateful|awesome|great job/i
        ],
        confidence: 0.95
      },
      greeting: {
        patterns: [
          /hello|hi|hey|good morning|good afternoon|good evening|greetings/i
        ],
        confidence: 0.95
      },
      farewell: {
        patterns: [
          /bye|goodbye|see you|farewell|take care|later/i
        ],
        confidence: 0.9
      },
      help: {
        patterns: [
          /help|support|assist|how do i|what can you|capabilities/i
        ],
        confidence: 0.85
      }
    }

    let maxConfidence = 0
    for (const [intent, data] of Object.entries(intentPatterns)) {
      const matches = data.patterns.filter(pattern => pattern.test(userMessage))
      if (matches.length > 0) {
        const confidence = data.confidence * (matches.length / data.patterns.length)
        if (confidence > maxConfidence) {
          maxConfidence = confidence
          analysis.intent = intent
        }
      }
    }
    analysis.confidence = maxConfidence

    const sentimentWords = {
      positive: [
        'good', 'great', 'excellent', 'amazing', 'wonderful', 'perfect', 'love', 'like', 'happy', 'satisfied',
        'awesome', 'fantastic', 'brilliant', 'outstanding', 'superb', 'terrific', 'fabulous', 'incredible'
      ],
      negative: [
        'bad', 'terrible', 'awful', 'hate', 'dislike', 'angry', 'frustrated', 'disappointed', 'upset',
        'horrible', 'dreadful', 'miserable', 'annoyed', 'irritated', 'mad', 'furious', 'livid'
      ],
      neutral: [
        'okay', 'fine', 'alright', 'normal', 'usual', 'standard', 'regular', 'typical'
      ]
    }

    let positiveScore = 0
    let negativeScore = 0
    let neutralScore = 0

    Object.entries(sentimentWords).forEach(([sentiment, words]) => {
      words.forEach(word => {
        const regex = new RegExp(`\\b${word}\\b`, 'gi')
        const matches = userMessage.match(regex)
        if (matches) {
          if (sentiment === 'positive') positiveScore += matches.length
          else if (sentiment === 'negative') negativeScore += matches.length
          else neutralScore += matches.length
        }
      })
    })

    if (positiveScore > negativeScore && positiveScore > neutralScore) {
      analysis.sentiment = 'positive'
    } else if (negativeScore > positiveScore && negativeScore > neutralScore) {
      analysis.sentiment = 'negative'
    } else {
      analysis.sentiment = 'neutral'
    }

    const emotionPatterns = {
      excited: [/excited|thrilled|can't wait|eager|enthusiastic/i],
      frustrated: [/frustrated|annoyed|irritated|fed up|tired of/i],
      confused: [/confused|don't understand|unclear|not sure|puzzled/i],
      satisfied: [/satisfied|happy|pleased|content|fulfilled/i],
      worried: [/worried|concerned|anxious|nervous|stressed/i]
    }

    Object.entries(emotionPatterns).forEach(([emotion, patterns]) => {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.emotions.push(emotion)
      }
    })

    const urgencyPatterns = {
      high: [/urgent|asap|immediately|right now|quickly|emergency/i],
      medium: [/soon|shortly|promptly|efficiently/i],
      low: [/whenever|no rush|take your time|convenient/i]
    }

    for (const [level, patterns] of Object.entries(urgencyPatterns)) {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.urgency = level
        break
      }
    }

    const personalityPatterns = {
      formal: [/please|kindly|would you|could you|may i/i],
      casual: [/hey|yo|what's up|cool|awesome/i],
      friendly: [/thanks|appreciate|love|great|wonderful/i]
    }

    for (const [style, patterns] of Object.entries(personalityPatterns)) {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.personality = style
        break
      }
    }

    if (conversationMemory.length === 0) {
      analysis.context = 'firstTime'
    } else if (conversationMemory.length > 10) {
      analysis.context = 'frequent'
    } else {
      analysis.context = 'returning'
    }

    analysis.entities = extractEntities(userMessage)

    if (analysis.intent === 'search' && analysis.entities.products.length > 0) {
      analysis.suggestions.push('Compare similar products', 'Check reviews', 'Find deals')
    } else if (analysis.intent === 'cart') {
      analysis.suggestions.push('View cart', 'Proceed to checkout', 'Add more items')
    } else if (analysis.intent === 'recommendation') {
      analysis.suggestions.push('Personalized picks', 'Trending items', 'Category browse')
    }

    if (analysis.confidence > 0.8) {
      analysis.responseType = 'specific'
    } else if (analysis.confidence > 0.5) {
      analysis.responseType = 'contextual'
    } else {
      analysis.responseType = 'general'
    }

    return analysis
  }

  const generateRandomData = {
    
    products: () => {
      const products = [
        { name: "Wireless Bluetooth Headphones", price: "₹1,299", category: "Electronics", rating: 4.5, reviews: 1247, brand: "Sony", features: ["Noise Cancellation", "40hr Battery", "Quick Charge"] },
        { name: "Premium Cotton T-Shirt", price: "₹599", category: "Fashion", rating: 4.3, reviews: 892, brand: "Nike", features: ["100% Cotton", "Breathable", "Multiple Colors"] },
        { name: "Smart Fitness Watch", price: "₹2,499", category: "Electronics", rating: 4.7, reviews: 2156, brand: "Fitbit", features: ["Heart Rate Monitor", "GPS", "Water Resistant"] },
        { name: "Organic Face Cream", price: "₹899", category: "Beauty", rating: 4.4, reviews: 567, brand: "The Body Shop", features: ["Natural Ingredients", "Anti-aging", "Suitable for all skin types"] },
        { name: "Stainless Steel Water Bottle", price: "₹399", category: "Home", rating: 4.6, reviews: 1234, brand: "Hydro Flask", features: ["24hr Cold", "12hr Hot", "BPA Free"] },
        { name: "Gaming Mouse", price: "₹1,799", category: "Electronics", rating: 4.8, reviews: 1890, brand: "Logitech", features: ["RGB Lighting", "Programmable Buttons", "High DPI"] },
        { name: "Yoga Mat", price: "₹299", category: "Sports", rating: 4.2, reviews: 445, brand: "Lululemon", features: ["Non-slip", "Eco-friendly", "6mm Thick"] },
        { name: "LED Desk Lamp", price: "₹699", category: "Home", rating: 4.5, reviews: 678, brand: "Philips", features: ["Adjustable Brightness", "Color Temperature", "Touch Control"] },
        { name: "Wireless Charger", price: "₹1,199", category: "Electronics", rating: 4.6, reviews: 945, brand: "Samsung", features: ["Fast Charging", "Universal Compatibility", "LED Indicator"] },
        { name: "Running Shoes", price: "₹3,999", category: "Sports", rating: 4.9, reviews: 2341, brand: "Adidas", features: ["Cushioned Sole", "Breathable Mesh", "Lightweight"] }
      ]
      return products[Math.floor(Math.random() * products.length)]
    },

    deals: () => {
      const deals = [
        { type: "Flash Sale", discount: "50% OFF", category: "Electronics", validUntil: "2 hours", code: "FLASH50" },
        { type: "Weekend Special", discount: "30% OFF", category: "Fashion", validUntil: "Sunday", code: "WEEKEND30" },
        { type: "New User Offer", discount: "₹500 OFF", category: "All Products", validUntil: "24 hours", code: "NEW500" },
        { type: "Bundle Deal", discount: "Buy 2 Get 1 Free", category: "Beauty", validUntil: "3 days", code: "BUNDLE3" },
        { type: "Clearance Sale", discount: "Up to 70% OFF", category: "Home", validUntil: "1 week", code: "CLEAR70" },
        { type: "Student Discount", discount: "20% OFF", category: "All Products", validUntil: "Always", code: "STUDENT20" },
        { type: "First Order", discount: "₹200 OFF", category: "All Products", validUntil: "First Purchase", code: "FIRST200" },
        { type: "Loyalty Reward", discount: "15% OFF", category: "All Products", validUntil: "7 days", code: "LOYAL15" }
      ]
      return deals[Math.floor(Math.random() * deals.length)]
    },

    trends: () => {
      const trends = [
        "Sustainable Fashion",
        "Smart Home Devices",
        "Fitness & Wellness",
        "Organic Beauty Products",
        "Gaming Accessories",
        "Kitchen Gadgets",
        "Travel Essentials",
        "Pet Care Products",
        "Work From Home Setup",
        "Outdoor Adventure Gear",
        "Digital Art Supplies",
        "Plant Care Essentials"
      ]
      return trends[Math.floor(Math.random() * trends.length)]
    },

    reviews: () => {
      const reviews = [
        { text: "Amazing quality! Highly recommended.", rating: 5, author: "Priya S.", verified: true },
        { text: "Great value for money. Will buy again!", rating: 4, author: "Rahul M.", verified: true },
        { text: "Fast delivery and excellent product.", rating: 5, author: "Anjali K.", verified: true },
        { text: "Good product but could be better.", rating: 3, author: "Vikram P.", verified: false },
        { text: "Perfect for my needs. Love it!", rating: 5, author: "Sneha R.", verified: true },
        { text: "Exceeded my expectations!", rating: 5, author: "Arjun K.", verified: true },
        { text: "Good quality for the price.", rating: 4, author: "Meera P.", verified: true },
        { text: "Fast shipping and great packaging.", rating: 5, author: "Karan S.", verified: true }
      ]
      return reviews[Math.floor(Math.random() * reviews.length)]
    },

    shipping: () => {
      const options = [
        { method: "Standard Delivery", time: "3-5 business days", cost: "₹99", tracking: true },
        { method: "Express Delivery", time: "1-2 business days", cost: "₹199", tracking: true },
        { method: "Same Day Delivery", time: "Today", cost: "₹299", tracking: true },
        { method: "Free Delivery", time: "5-7 business days", cost: "Free", tracking: true },
        { method: "Premium Delivery", time: "Next Day", cost: "₹399", tracking: true }
      ]
      return options[Math.floor(Math.random() * options.length)]
    },

    payments: () => {
      const methods = [
        { name: "Credit/Debit Card", icon: "💳", security: "SSL Encrypted", processing: "Instant" },
        { name: "UPI", icon: "📱", security: "Bank Level", processing: "Instant" },
        { name: "Net Banking", icon: "🏦", security: "Bank Level", processing: "Instant" },
        { name: "Digital Wallets", icon: "📲", security: "SSL Encrypted", processing: "Instant" },
        { name: "EMI", icon: "💳", security: "SSL Encrypted", processing: "Instant" },
        { name: "Cash on Delivery", icon: "💰", security: "Pay on Delivery", processing: "On Delivery" }
      ]
      return methods[Math.floor(Math.random() * methods.length)]
    },

    categories: () => {
      const categories = [
        { name: "Electronics", icon: "📱", count: "15,000+ products", trending: true },
        { name: "Fashion", icon: "👗", count: "25,000+ products", trending: true },
        { name: "Home & Garden", icon: "🏠", count: "12,000+ products", trending: false },
        { name: "Sports & Fitness", icon: "🏃‍♂️", count: "8,000+ products", trending: true },
        { name: "Beauty & Personal Care", icon: "💄", count: "10,000+ products", trending: true },
        { name: "Books & Media", icon: "📚", count: "20,000+ products", trending: false },
        { name: "Toys & Games", icon: "🎮", count: "6,000+ products", trending: false },
        { name: "Automotive", icon: "🚗", count: "4,000+ products", trending: false }
      ]
      return categories[Math.floor(Math.random() * categories.length)]
    },

    support: () => {
      const topics = [
        { issue: "Order Tracking", priority: "High", response: "I can help you track your order. Please provide your order number." },
        { issue: "Payment Issues", priority: "High", response: "I understand payment problems can be frustrating. Let me help you resolve this." },
        { issue: "Returns & Refunds", priority: "Medium", response: "I'll guide you through our return and refund process." },
        { issue: "Product Quality", priority: "Medium", response: "I'm here to help with any product quality concerns." },
        { issue: "Delivery Problems", priority: "High", response: "I can help you resolve delivery issues quickly." },
        { issue: "Account Issues", priority: "Medium", response: "Let me help you with your account-related questions." }
      ]
      return topics[Math.floor(Math.random() * topics.length)]
    },

    specifications: () => {
      const specs = [
        { dimension: "10 x 5 x 2 cm", weight: "150g", material: "Premium Plastic", warranty: "1 Year" },
        { dimension: "15 x 8 x 3 cm", weight: "250g", material: "Aluminum", warranty: "2 Years" },
        { dimension: "20 x 12 x 4 cm", weight: "400g", material: "Stainless Steel", warranty: "3 Years" },
        { dimension: "8 x 6 x 1.5 cm", weight: "100g", material: "Silicone", warranty: "6 Months" },
        { dimension: "25 x 18 x 5 cm", weight: "600g", material: "Wood", warranty: "1 Year" }
      ]
      return specs[Math.floor(Math.random() * specs.length)]
    }
  }

  const learnFromUserBehavior = (userMessage, intent, sentiment, entities) => {
    
    if (entities.categories.length > 0) {
      setUserPreferences(prev => ({
        ...prev,
        favoriteCategories: [...new Set([...prev.favoriteCategories, ...entities.categories])]
      }))
    }

    if (entities.brands.length > 0) {
      setUserPreferences(prev => ({
        ...prev,
        preferredBrands: [...new Set([...prev.preferredBrands, ...entities.brands])]
      }))
    }

    if (sentiment === 'positive') {
      setAiPersonality(prev => ({
        ...prev,
        tone: 'enthusiastic and helpful'
      }))
    } else if (sentiment === 'negative') {
      setAiPersonality(prev => ({
        ...prev,
        tone: 'empathetic and supportive'
      }))
    }
  }

  const generateAdaptiveSuggestions = () => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const userInsights = getUserInsights()

    const suggestions = []

    if (cartSummary.count > 0) {
      suggestions.push('View your cart', 'Proceed to checkout', 'Add more items')
    } else {
      suggestions.push('Browse trending products', 'Search for items', 'Get recommendations')
    }

    if (wishlistSummary.count > 0) {
      suggestions.push('View your wishlist', 'Add wishlist items to cart')
    }

    if (userPreferences.favoriteCategories.length > 0) {
      suggestions.push(`Browse ${userPreferences.favoriteCategories[0]} products`)
    }

    const hour = new Date().getHours()
    if (hour < 12) {
      suggestions.push('Start your day with great deals')
    } else if (hour < 17) {
      suggestions.push('Afternoon shopping session')
    } else {
      suggestions.push('Evening shopping deals')
    }

    return suggestions.slice(0, 5)
  }

  const generatePersonalizedGreeting = () => {
    const timeOfDay = new Date().getHours()
    const userInsights = getUserInsights()
    const cartSummary = getCartSummary()

    let greeting = ''

    if (timeOfDay < 12) {
      greeting = getRandomResponse(responseLibraries.greetings, 'morning')
    } else if (timeOfDay < 17) {
      greeting = getRandomResponse(responseLibraries.greetings, 'afternoon')
    } else {
      greeting = getRandomResponse(responseLibraries.greetings, 'evening')
    }

    let personalization = ''

    if (userInsights.favoriteCategory !== 'No preference') {
      personalization = `I noticed you love ${userInsights.favoriteCategory} products! `
    }

    if (cartSummary.count > 0) {
      personalization += `You have ${cartSummary.count} items in your cart ready for checkout. `
    }

    return `${greeting}! ${personalization}I'm here to help you with all your shopping needs.`
  }

  const analyzeConversationPattern = () => {
    if (conversationMemory.length < 3) return null

    const recentMessages = conversationMemory.slice(-5)
    const intents = recentMessages.map(msg => msg.intent)
    const sentiments = recentMessages.map(msg => msg.sentiment)

    const patterns = {
      frequentSearch: intents.filter(i => i === 'search').length > 2,
      priceConscious: recentMessages.some(msg => msg.entities.prices.length > 0),
      brandLoyal: recentMessages.some(msg => msg.entities.brands.length > 0),
      comparisonFocused: intents.filter(i => i === 'comparison').length > 1,
      issueProne: intents.filter(i => i === 'complaint').length > 0
    }

    return patterns
  }

  const generateContextualResponse = (userMessage, intent, sentiment, entities) => {
    const lowerMessage = userMessage.toLowerCase()

    learnFromUserBehavior(userMessage, intent, sentiment, entities)

    const patterns = analyzeConversationPattern()

    if (intent === 'greeting') {
      return generatePersonalizedGreeting()
    }

    if (intent === 'gratitude') {
      return getRandomResponse(responseLibraries.gratitude, sentiment === 'positive' ? 'positive' : 'neutral')
    }

    if (intent === 'farewell') {
      return getRandomResponse(responseLibraries.farewell)
    }

    if (intent === 'search') {
      if (entities.products.length > 0) {
        const product = entities.products[0]
        let response = getRandomResponse(responseLibraries.search, 'product').replace('{product}', product)

        if (patterns?.priceConscious) {
          response += `\n\n💰 I'll also show you the best prices and any current deals.`
        }

        if (patterns?.comparisonFocused) {
          response += `\n\n📊 I can also help you compare ${product} with similar products.`
        }

        response += `\n\nI can also help you:\n• Compare similar products\n• Check availability and pricing\n• Read customer reviews\n• Find related accessories\n\nWhat specific features are you looking for in ${product}?`
        return response
      }

      if (entities.categories.length > 0) {
        const category = entities.categories[0]
        return getRandomResponse(responseLibraries.search, 'category').replace('{category}', category) +
          `\n\nI can help you:\n• Filter by price range\n• Sort by popularity or rating\n• Find trending items\n• Get personalized picks\n\nWhat's your budget for ${category} items?`
      }

      return getRandomResponse(responseLibraries.help, 'general') +
        `\n\nI can search by:\n• Product name or brand\n• Category (electronics, fashion, etc.)\n• Price range\n• Features or specifications\n\nJust tell me what you're interested in!`
    }

    if (intent === 'recommendation') {
      const userInsights = getUserInsights()
      const adaptiveSuggestions = generateAdaptiveSuggestions()

      if (userInsights.favoriteCategory !== 'No preference') {
        const randomProduct = generateRandomData.products()
        const randomDeal = generateRandomData.deals()

        return getRandomResponse(responseLibraries.recommendations, 'personalized') +
          `\n\n⭐ ${randomProduct.name} - ${randomProduct.price} (${randomProduct.rating}⭐)\n🔥 ${randomDeal.type}: ${randomDeal.discount} on ${randomDeal.category}\n\nI can also suggest:\n• Trending items in your favorite categories\n• Best deals and discounts\n• New arrivals you might like\n• Products similar to your recent purchases\n\nWould you like to see more recommendations?`
      }

      const randomProduct = generateRandomData.products()
      const trendingTopic = generateRandomData.trends()

      return getRandomResponse(responseLibraries.recommendations, 'trending') +
        `\n\n🔥 Trending: ${trendingTopic}\n⭐ ${randomProduct.name} - ${randomProduct.price} (${randomProduct.rating}⭐)\n\nI can also suggest:\n• Show trending products\n• Recommend based on popular categories\n• Find deals and discounts\n• Suggest based on your interests\n\nWhat type of products are you interested in?`
    }

    if (intent === 'complaint') {
      let response = `I understand you're experiencing an issue, and I'm here to help resolve it quickly.\n\n🔧 Let me assist you with:\n\n• Order problems\n• Payment issues\n• Website/app problems\n• Product concerns\n• Delivery issues\n\n`

      if (sentiment === 'negative') {
        response += `I apologize for any inconvenience. Please describe the specific problem you're facing, and I'll guide you through the resolution process.`
      } else {
        response += `Please describe the specific problem you're facing, and I'll guide you through the resolution process.`
      }

      return response
    }

    if (intent === 'comparison') {
      if (entities.products.length >= 2) {
        const product1 = entities.products[0]
        const product2 = entities.products[1]
        return `I'll help you compare ${product1} and ${product2}!\n\n📊 Comparison Analysis:\n\nI can compare:\n• Price and value\n• Features and specifications\n• Customer reviews and ratings\n• Availability and delivery\n• Warranty and support\n\nWould you like me to show you a detailed comparison?`
      }

      return `I'd be happy to help you compare products! Please tell me which products you'd like to compare, and I'll provide a detailed analysis.\n\nYou can compare:\n• Similar products\n• Different brands\n• Different price ranges\n• Different categories`
    }

    if (lowerMessage.includes('fashion') || lowerMessage.includes('clothing') || lowerMessage.includes('dress')) {
      const randomProduct = generateRandomData.products()
      return `👗 Fashion & Style!\n\nI can help you discover amazing fashion items:\n\n• Trendy clothing and accessories\n• Shoes, bags, and jewelry\n• Seasonal collections\n• Size and fit guidance\n• Style recommendations\n\n🔥 Trending: ${randomProduct.name} - ${randomProduct.price}\n\nWould you like me to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized style picks`
    }

    if (lowerMessage.includes('electronics') || lowerMessage.includes('phone') || lowerMessage.includes('laptop')) {
      const randomProduct = generateRandomData.products()
      return `📱 Electronics & Tech!\n\nI can help you find the latest gadgets:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\n🔥 Hot Deal: ${randomProduct.name} - ${randomProduct.price}\n\nWould you like me to:\n• Show trending electronics\n• Search for specific devices\n• Compare tech products\n• Get tech recommendations`
    }

    if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
      const randomDeal = generateRandomData.deals()
      return `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\n🔥 Special Offer: ${randomDeal.type} - ${randomDeal.discount}\n\nWould you like me to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
    }

    if (lowerMessage.includes('delivery') || lowerMessage.includes('shipping') || lowerMessage.includes('when')) {
      const shippingOption = generateRandomData.shipping()
      return `🚚 Delivery & Shipping Info!\n\n${shippingOption.method}: ${shippingOption.time}\nCost: ${shippingOption.cost}\n\nI can help you with:\n• Track your order\n• Check delivery status\n• Change delivery address\n• Schedule delivery\n• Express shipping options\n\nWould you like to check your order status?`
    }

    if (lowerMessage.includes('review') || lowerMessage.includes('rating') || lowerMessage.includes('feedback')) {
      const randomReview = generateRandomData.reviews()
      return `⭐ Reviews & Ratings!\n\nHere's what customers are saying:\n\n"${randomReview.text}" - ${randomReview.author} (${randomReview.rating}⭐)\n\nI can help you with:\n• Read product reviews\n• Check ratings\n• Compare customer feedback\n• Find highly-rated products\n• Write your own review\n\nWould you like to see more reviews?`
    }

    if (lowerMessage.includes('deal') || lowerMessage.includes('offer') || lowerMessage.includes('discount')) {
      const randomDeal = generateRandomData.deals()
      const randomProduct = generateRandomData.products()
      return `🎉 Deals & Offers!\n\n🔥 ${randomDeal.type}: ${randomDeal.discount} on ${randomDeal.category}\n⏰ Valid until: ${randomDeal.validUntil}\n\nFeatured Deal: ${randomProduct.name} - ${randomProduct.price}\n\nI can help you with:\n• Find more deals\n• Apply discount codes\n• Flash sales\n• Bundle offers\n• Loyalty rewards\n\nWould you like to see all current offers?`
    }

    return generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
  }

  const generateIntelligentDefaultResponse = (userMessage, intent, sentiment, entities) => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const orderSummary = getOrderSummary()

    const userInsights = getUserInsights()
    const randomProduct = generateRandomData.products()
    const randomDeal = generateRandomData.deals()
    const trendingTopic = generateRandomData.trends()

    let response = getRandomResponse(responseLibraries.help, 'specific') + '\n\n'

    if (cartSummary.count > 0) {
      response += `🛒 I notice you have ${cartSummary.count} items in your cart (₹${cartSummary.total}).\n`
    }

    if (wishlistSummary.count > 0) {
      response += `💖 You have ${wishlistSummary.count} items in your wishlist.\n`
    }

    if (orderSummary.count > 0) {
      response += `📦 You have ${orderSummary.count} recent orders.\n`
    }

    if (userInsights.favoriteCategory !== 'No preference') {
      response += `\n⭐ Since you love ${userInsights.favoriteCategory}, check out: ${randomProduct.name} - ${randomProduct.price}\n`
    }

    response += `\n🔥 Trending: ${trendingTopic}\n🎉 Special: ${randomDeal.type} - ${randomDeal.discount}\n\n`

    response += `I can help you with:\n\n`

    if (entities.products.length > 0) {
      response += `• Search for ${entities.products[0]}\n`
      response += `• Compare ${entities.products[0]} with similar products\n`
      response += `• Check availability and pricing\n`
    }

    if (entities.categories.length > 0) {
      response += `• Browse ${entities.categories[0]} products\n`
      response += `• Find deals in ${entities.categories[0]}\n`
    }

    response += `• Manage your cart and wishlist\n`
    response += `• Track orders and payments\n`
    response += `• Get personalized recommendations\n`
    response += `• Find deals and offers\n`
    response += `• Resolve any issues\n`

    response += `\nWhat would you like to do?`

    return response
  }

  const updateConversationMemory = (userMessage, aiResponse, context) => {
    const memoryEntry = {
      timestamp: new Date(),
      userMessage,
      aiResponse,
      context,
      intent: analyzeUserIntent(userMessage),
      sentiment: analyzeSentiment(userMessage),
      entities: extractEntities(userMessage)
    }

    setConversationMemory(prev => {
      const updated = [...prev, memoryEntry]
      
      return updated.slice(-10)
    })
  }

  const formatAIResponse = (response) => {
    
    let formattedResponse = response

    formattedResponse = formattedResponse.replace(/🛒 Shopping:/g, '<div class="ai-section-header">🛒 Shopping</div>')
    formattedResponse = formattedResponse.replace(/📊 Your Account:/g, '<div class="ai-section-header">📊 Your Account</div>')
    formattedResponse = formattedResponse.replace(/📊 Account:/g, '<div class="ai-section-header">📊 Account</div>')
    formattedResponse = formattedResponse.replace(/🔍 Search:/g, '<div class="ai-section-header">🔍 Search</div>')
    formattedResponse = formattedResponse.replace(/🔍 Quick Actions:/g, '<div class="ai-section-header">🔍 Quick Actions</div>')
    formattedResponse = formattedResponse.replace(/💬 Support:/g, '<div class="ai-section-header">💬 Support</div>')
    formattedResponse = formattedResponse.replace(/⭐ Personalized Recommendations:/g, '<div class="ai-section-header">⭐ Personalized Recommendations</div>')
    formattedResponse = formattedResponse.replace(/📊 Comparison Analysis:/g, '<div class="ai-section-header">📊 Comparison Analysis</div>')
    formattedResponse = formattedResponse.replace(/🔧 Let me assist you with:/g, '<div class="ai-section-header">🔧 Let me assist you with</div>')

    formattedResponse = formattedResponse.replace(/I can help you with:/g, '<div class="ai-subsection-header">I can help you with:</div>')
    formattedResponse = formattedResponse.replace(/I can also help you:/g, '<div class="ai-subsection-header">I can also help you:</div>')
    formattedResponse = formattedResponse.replace(/I can also suggest:/g, '<div class="ai-subsection-header">I can also suggest:</div>')
    formattedResponse = formattedResponse.replace(/I can compare:/g, '<div class="ai-subsection-header">I can compare:</div>')
    formattedResponse = formattedResponse.replace(/You can compare:/g, '<div class="ai-subsection-header">You can compare:</div>')
    formattedResponse = formattedResponse.replace(/Would you like to:/g, '<div class="ai-subsection-header">Would you like to:</div>')
    formattedResponse = formattedResponse.replace(/What would you like to do?/g, '<div class="ai-subsection-header">What would you like to do?</div>')

    formattedResponse = formattedResponse.replace(/Cart: (\d+) items \(₹([\d,]+)\)/g, '<span class="ai-text-accent">Cart: $1 items (₹$2)</span>')
    formattedResponse = formattedResponse.replace(/Wishlist: (\d+) items/g, '<span class="ai-text-accent">Wishlist: $1 items</span>')
    formattedResponse = formattedResponse.replace(/Orders: (\d+) orders/g, '<span class="ai-text-accent">Orders: $1 orders</span>')

    formattedResponse = formattedResponse.replace(/✅/g, '<span class="ai-text-success">✅</span>')
    formattedResponse = formattedResponse.replace(/❌/g, '<span class="ai-text-error">❌</span>')
    formattedResponse = formattedResponse.replace(/⚠️/g, '<span class="ai-text-warning">⚠️</span>')

    formattedResponse = formattedResponse.replace(/\n\n/g, '<div class="ai-message-spacing"></div>')
    formattedResponse = formattedResponse.replace(/\n/g, '<br>')

    return formattedResponse
  }

  const extractProductName = (message) => {
    
    if (!message || typeof message !== 'string') {
      return ''
    }

    const lowerMessage = message.toLowerCase()

    const cleanedMessage = lowerMessage
      .replace(/(add|remove|delete|update|change|to|cart|wishlist|quantity|qty|number|count|from|in|the|a|an)/g, '')
      .replace(/\s+/g, ' ')
      .trim()

    if (!cleanedMessage) {
      const words = message.split(' ')
      const productWords = words.filter(word =>
        word.length > 2 &&
        !['the', 'and', 'or', 'but', 'for', 'with', 'from', 'to', 'in', 'on', 'at', 'by', 'add', 'remove', 'update', 'change', 'cart', 'wishlist', 'quantity', 'qty'].includes(word.toLowerCase())
      )
      return productWords.join(' ') || message
    }

    return cleanedMessage || message
  }

  const extractCategory = (message) => {
    
    const categoryMap = {
      'electronics': ['electronics', 'electronic', 'tech', 'technology', 'gadgets', 'devices', 'phone', 'laptop', 'computer', 'smartphone', 'tablet'],
      'fashion': ['fashion', 'clothing', 'apparel', 'wear', 'dress', 'style', 'outfit', 'shirt', 'pants', 'shoes', 'accessories'],
      'home': ['home', 'house', 'kitchen', 'furniture', 'decor', 'garden', 'outdoor', 'living', 'bedroom', 'bathroom'],
      'sports': ['sports', 'fitness', 'exercise', 'athletic', 'gym', 'workout', 'running', 'training', 'equipment'],
      'books': ['books', 'book', 'reading', 'literature', 'novel', 'textbook', 'magazine', 'journal'],
      'beauty': ['beauty', 'cosmetics', 'makeup', 'skincare', 'personal care', 'perfume', 'cosmetic'],
      'automotive': ['automotive', 'car', 'vehicle', 'auto', 'automobile', 'motorcycle', 'bike'],
      'toys': ['toys', 'toy', 'games', 'play', 'children', 'kids', 'game', 'entertainment']
    }

    const lowerMessage = message.toLowerCase()

    for (const [category, variations] of Object.entries(categoryMap)) {
      if (variations.some(v => lowerMessage.includes(v))) {
        return category
      }
    }

    for (const [category, variations] of Object.entries(categoryMap)) {
      for (const variation of variations) {
        if (lowerMessage.includes(variation)) {
          return category
        }
      }
    }

    return message.trim()
  }

  const extractBrand = (message) => {
   
    const brands = [
      'samsung', 'apple', 'nike', 'adidas', 'sony', 'dell', 'hp', 'lenovo', 'lg', 'panasonic', 'canon', 'nikon', 'puma', 'reebok', 'under armour',
      'asus', 'acer', 'msi', 'gigabyte', 'corsair', 'logitech', 'razer', 'steelseries', 'hyperx', 'jbl', 'bose', 'beats', 'skullcandy', 'sennheiser',
      'philips', 'sharp', 'toshiba', 'hitachi', 'mitsubishi', 'fujitsu', 'vaio', 'alienware', 'roccat', 'cooler master', 'thermaltake', 'antec',
      'new balance', 'converse', 'vans', 'timberland', 'dr martens', 'clarks', 'crocs', 'skechers', 'reebok', 'fila', 'umbro', 'kappa', 'lotto',
      'motorola', 'oneplus', 'xiaomi', 'oppo', 'vivo', 'realme', 'honor', 'huawei', 'google', 'blackberry', 'htc', 'nokia', 'lg', 'zte',
      'gopro', 'dji', 'fujifilm', 'olympus', 'pentax', 'leica', 'sigma', 'tamron', 'tokina', 'rokinon', 'samyang', 'laowa', 'venus optics',
      'coca cola', 'pepsi', 'nestle', 'unilever', 'procter & gamble', 'johnson & johnson', 'colgate', 'unilever', 'nestle', 'kraft', 'kellogg',
      'ikea', 'walmart', 'target', 'costco', 'best buy', 'home depot', 'lowes', 'macy', 'nordstrom', 'gap', 'h&m', 'zara', 'uniqlo', 'forever 21'
    ]
    
    const lowerMessage = message.toLowerCase().trim()

    for (const brand of brands) {
      if (lowerMessage === brand || lowerMessage.includes(brand)) {
        return brand
      }
    }

    const brandPatterns = [
      /(?:brand|make|manufacturer|company)\s+(?:is\s+)?([a-zA-Z0-9\s&]+)/i,
      /(?:looking\s+for|search\s+for|find)\s+([a-zA-Z0-9\s&]+)\s+(?:brand|products?)/i,
      /([a-zA-Z0-9\s&]+)\s+(?:brand|products?|items?)/i
    ]
    
    for (const pattern of brandPatterns) {
      const match = lowerMessage.match(pattern)
      if (match && match[1]) {
        const extractedBrand = match[1].trim()
        if (extractedBrand.length > 1 && extractedBrand.length < 50) {
          return extractedBrand
        }
      }
    }

    return lowerMessage.replace(/^(search|find|look|show|get|i want|i need|give me)\s+/i, '').trim()
  }

  const extractQuantity = (message) => {
    
    const quantityPatterns = [
      
      /(\d+)\s*(piece|item|unit|quantity|qty|number|count)/i,
      
      /add\s+(\d+)\s+(?:of|pieces?|items?|units?)/i,
      
      /quantity\s+(\d+)/i,
      
      /to\s+(\d+)/i,
      
      /(\d+)\s+quantity/i,
      
      /add\s+(\d+)\s+[a-zA-Z]/i
    ]

    for (const pattern of quantityPatterns) {
      const match = message.match(pattern)
      if (match) {
        const quantity = parseInt(match[1])
        if (quantity > 0 && quantity <= 100) {
          return quantity
        }
      }
    }

    const numbers = message.match(/(\d+)/g)
    if (numbers && numbers.length > 0) {
      
      const validQuantities = numbers.filter(num => {
        const numInt = parseInt(num)
        return numInt <= 100 && numInt > 0
      })
      if (validQuantities.length > 0) {
        return parseInt(validQuantities[0])
      }
    }

    return 1 
  }

  const extractOrderId = (message) => {
    
    const orderMatch = message.match(/(?:order|order id|order number|track order)\s*(?:#|number)?\s*([a-zA-Z0-9]+)/i)
    if (orderMatch) {
      return orderMatch[1]
    }

    const idMatch = message.match(/([a-zA-Z0-9]{6,})/)
    if (idMatch) {
      return idMatch[1]
    }

    return message.trim()
  }

  const extractPaymentMethod = (message) => {
    const paymentMethods = ['credit card', 'debit card', 'paypal', 'cash', 'bank transfer', 'upi', 'gpay', 'phonepe', 'amazon pay']
    const lowerMessage = message.toLowerCase()

    for (const method of paymentMethods) {
      if (lowerMessage.includes(method)) {
        return method
      }
    }

    return 'credit card' 
  }

  const extractIssueType = (message) => {
    const issues = {
      'order': ['order', 'delivery', 'shipping', 'tracking'],
      'payment': ['payment', 'billing', 'charge', 'refund', 'money'],
      'product': ['product', 'item', 'quality', 'defective', 'broken'],
      'website': ['website', 'app', 'login', 'account', 'technical'],
      'delivery': ['delivery', 'shipping', 'address', 'location']
    }

    const lowerMessage = message.toLowerCase()

    for (const [issueType, keywords] of Object.entries(issues)) {
      for (const keyword of keywords) {
        if (lowerMessage.includes(keyword)) {
          return issueType
        }
      }
    }

    return 'general' 
  }

  const processIntelligentKeywords = (userMessage) => {
    const lowerMessage = userMessage.toLowerCase()

    const keywordMap = {
      
      'fashion': {
        keywords: ['fashion', 'clothing', 'dress', 'shirt', 'pants', 'shoes', 'accessories', 'style', 'outfit', 'wear', 'apparel'],
        response: `👗 Fashion & Style!\n\nI can help you discover amazing fashion items:\n\n• Trendy clothing and accessories\n• Shoes, bags, and jewelry\n• Seasonal collections\n• Size and fit guidance\n• Style recommendations\n\nWould you like to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized style picks`
      },

      'electronics': {
        keywords: ['electronics', 'phone', 'laptop', 'computer', 'smartphone', 'tablet', 'gadget', 'tech', 'technology', 'device', 'mobile'],
        response: `📱 Electronics & Tech!\n\nI can help you find the latest gadgets:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\nWould you like to:\n• Show trending electronics\n• Search for specific devices\n• Compare tech products\n• Get tech recommendations`
      },

      'home': {
        keywords: ['home', 'house', 'kitchen', 'furniture', 'decor', 'garden', 'outdoor', 'living', 'bedroom', 'bathroom', 'appliance'],
        response: `🏠 Home & Garden!\n\nI can help you find perfect home items:\n\n• Furniture and decor\n• Kitchen appliances\n• Garden tools and plants\n• Home improvement\n• Smart home devices\n\nWould you like to:\n• Show trending home products\n• Search for specific items\n• Browse home categories\n• Get home recommendations`
      },

      'sports': {
        keywords: ['sports', 'fitness', 'exercise', 'gym', 'workout', 'running', 'training', 'athletic', 'equipment', 'sportswear'],
        response: `🏃‍♂️ Sports & Fitness!\n\nI can help you find sports equipment:\n\n• Workout gear and clothing\n• Sports equipment\n• Fitness accessories\n• Athletic shoes\n• Training gear\n\nWould you like to:\n• Show trending sports items\n• Search for specific equipment\n• Browse sports categories\n• Get fitness recommendations`
      },

      'books': {
        keywords: ['books', 'book', 'reading', 'education', 'study', 'textbook', 'novel', 'literature', 'learning', 'academic'],
        response: `📚 Books & Education!\n\nI can help you find great books:\n\n• Fiction and non-fiction\n• Textbooks and academic\n• Self-help and business\n• Children's books\n• Digital books\n\nWould you like to:\n• Show trending books\n• Search for specific titles\n• Browse book categories\n• Get reading recommendations`
      },

      'beauty': {
        keywords: ['beauty', 'cosmetics', 'makeup', 'skincare', 'personal care', 'perfume', 'cosmetic', 'beauty product'],
        response: `💄 Beauty & Personal Care!\n\nI can help you find beauty products:\n\n• Makeup and cosmetics\n• Skincare products\n• Fragrances and perfumes\n• Hair care products\n• Personal hygiene\n\nWould you like to:\n• Show trending beauty items\n• Search for specific products\n• Browse beauty categories\n• Get beauty recommendations`
      },

      'automotive': {
        keywords: ['car', 'vehicle', 'auto', 'automotive', 'automobile', 'motorcycle', 'bike', 'accessories', 'parts'],
        response: `🚗 Automotive!\n\nI can help you find automotive products:\n\n• Car accessories and parts\n• Motorcycle gear\n• Vehicle maintenance\n• Auto electronics\n• Safety equipment\n\nWould you like to:\n• Show trending auto items\n• Search for specific parts\n• Browse automotive categories\n• Get auto recommendations`
      },

      'toys': {
        keywords: ['toys', 'toy', 'games', 'game', 'play', 'children', 'kids', 'entertainment', 'fun'],
        response: `🎮 Toys & Games!\n\nI can help you find fun products:\n\n• Children's toys\n• Board games and puzzles\n• Video games\n• Educational toys\n• Outdoor play equipment\n\nWould you like to:\n• Show trending toys\n• Search for specific games\n• Browse toy categories\n• Get game recommendations`
      },

      'pricing': {
        keywords: ['price', 'cost', 'expensive', 'cheap', 'budget', 'affordable', 'deal', 'discount', 'sale', 'offer'],
        response: () => {
          const randomDeal = generateRandomData.deals()
          return `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\n🔥 Current Offer: ${randomDeal.type} - ${randomDeal.discount}\nUse Code: ${randomDeal.code}\n\nWould you like to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
        }
      },

      'payment': {
        keywords: ['payment', 'pay', 'card', 'upi', 'emi', 'cash', 'wallet', 'bank', 'credit', 'debit', 'money', 'transaction', 'billing'],
        response: () => {
          const paymentMethod = generateRandomData.payments()
          return getRandomResponse(responseLibraries.payment, 'methods') +
            `\n\n${paymentMethod.icon} ${paymentMethod.name}\n🔒 ${paymentMethod.security}\n⚡ ${paymentMethod.processing}\n\nWould you like to:\n• Learn about payment security\n• Get EMI options\n• Resolve payment issues\n• Check payment status`
        }
      },

      'product_details': {
        keywords: ['details', 'specifications', 'specs', 'features', 'information', 'description', 'what is', 'tell me about', 'product info'],
        response: () => {
          const product = generateRandomData.products()
          const specs = generateRandomData.specifications()
          const review = generateRandomData.reviews()

          let response = getRandomResponse(responseLibraries.product, 'details')
            .replace('{brand}', product.brand)
            .replace('{price}', product.price)
            .replace('{rating}', product.rating)
            .replace('{reviews}', product.reviews)
            .replace('{dimension}', specs.dimension)
            .replace('{weight}', specs.weight)
            .replace('{material}', specs.material)
            .replace('{warranty}', specs.warranty)
            .replace('{features}', product.features.map(f => `• ${f}`).join('\n'))

          response += `\n\n💬 Customer Review:\n"${review.text}" - ${review.author} (${review.rating}⭐)`

          return response
        }
      },

      'recommendations': {
        keywords: ['recommend', 'suggestion', 'advise', 'what should', 'help me choose', 'best', 'top', 'popular', 'trending'],
        response: () => {
          const product1 = generateRandomData.products()
          const product2 = generateRandomData.products()
          const product3 = generateRandomData.products()
          const category = generateRandomData.categories()

          let response = getRandomResponse(responseLibraries.recommendations, 'personalized')
            .replace('{product1.name}', product1.name)
            .replace('{product1.price}', product1.price)
            .replace('{product1.rating}', product1.rating)
            .replace('{product2.name}', product2.name)
            .replace('{product2.price}', product2.price)
            .replace('{product2.rating}', product2.rating)
            .replace('{product3.name}', product3.name)
            .replace('{product3.price}', product3.price)
            .replace('{product3.rating}', product3.rating)

          response += `\n\n${category.icon} Trending in ${category.name}: ${category.count} products available!`

          return response
        }
      },

      'customer_support': {
        keywords: ['support', 'help', 'assist', 'problem', 'issue', 'trouble', 'complaint', 'contact', 'service', 'customer care'],
        response: () => {
          const supportTopic = generateRandomData.support()
          return getRandomResponse(responseLibraries.support, 'general') +
            `\n\n🔧 ${supportTopic.issue} (${supportTopic.priority} Priority)\n${supportTopic.response}\n\nWould you like to:\n• Get order support\n• Technical assistance\n• Return/refund help\n• Contact live agent`
        }
      },

      'help': {
        keywords: ['help', 'support', 'assist', 'problem', 'issue', 'trouble', 'question', 'how', 'what', 'why'],
        response: () => {
          const category = generateRandomData.categories()
          return `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 Search & Discovery\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 Shopping Experience\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 Payment & Orders\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 Customer Support\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\n${category.icon} Popular Category: ${category.name} (${category.count})\n\nWhat specific help do you need?`
        }
      },

      'cart': {
        keywords: ['cart', 'shopping cart', 'basket', 'add to cart', 'remove from cart', 'checkout', 'buy', 'purchase'],
        response: `🛒 Cart Management!\n\nI can help you with your cart:\n\n• View your current cart\n• Add items to cart\n• Remove items from cart\n• Update quantities\n• Proceed to checkout\n\nWould you like to:\n• View your cart\n• Add items to cart\n• Remove items\n• Checkout now`
      },

      'wishlist': {
        keywords: ['wishlist', 'favorites', 'save', 'wish', 'favorite', 'saved items'],
        response: `💖 Wishlist Management!\n\nI can help you with your wishlist:\n\n• View your wishlist\n• Add items to wishlist\n• Remove items from wishlist\n• Share your wishlist\n• Get price alerts\n\nWould you like to:\n• View your wishlist\n• Add items to wishlist\n• Remove items\n• Share wishlist`
      },

      'orders': {
        keywords: ['order', 'track', 'delivery', 'shipping', 'status', 'tracking', 'package', 'parcel'],
        response: `📦 Order Tracking!\n\nI can help you track your orders:\n\n• View all your orders\n• Track specific order\n• Check delivery status\n• Cancel orders\n• Return items\n\nWould you like to:\n• View your orders\n• Track specific order\n• Check delivery status\n• Cancel order`
      },

      'recommendations': {
        keywords: ['recommend', 'suggestion', 'advise', 'what should', 'help me choose', 'best', 'top', 'popular'],
        response: `⭐ Recommendations!\n\nI can provide smart recommendations:\n\n• Personalized picks\n• Trending products\n• Category recommendations\n• Price-based suggestions\n• Similar products\n\nWould you like to:\n• Get personalized picks\n• See trending items\n• Browse by category\n• Find similar products`
      }
    }

    for (const [category, data] of Object.entries(keywordMap)) {
      if (data.keywords.some(keyword => lowerMessage.includes(keyword))) {
        return {
          response: typeof data.response === 'function' ? data.response() : data.response,
          contextUpdate: { currentTopic: category, lastAction: `${category}_inquiry` }
        }
      }
    }

    if (lowerMessage.includes('what can you do') || lowerMessage.includes('your capabilities') || lowerMessage.includes('what do you do')) {
      const category = generateRandomData.categories()
      const deal = generateRandomData.deals()
      return {
        response: `I'm your AI shopping assistant! Here's what I can do:\n\n🛍️ Shopping:\n• Search products by name, category, or brand\n• Compare products and prices\n• Find deals and discounts\n• Manage your cart and wishlist\n\n📦 Orders:\n• Track your orders\n• Check delivery status\n• Manage returns and cancellations\n\n💡 Recommendations:\n• Personalized product suggestions\n• Trending items\n• Price alerts\n• Style recommendations\n\n💬 Support:\n• Answer questions\n• Resolve issues\n• Provide guidance\n\n${category.icon} Popular: ${category.name} (${category.count})\n🔥 Current: ${deal.type} - ${deal.discount}\n\nI'm here to make your shopping experience amazing! What would you like to do?`,
        contextUpdate: { currentTopic: 'capabilities', lastAction: 'capabilities_inquiry' }
      }
    }

    if (lowerMessage.includes('emi') || lowerMessage.includes('installment')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'emi'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'emi_inquiry' }
      }
    }

    if (lowerMessage.includes('security') || lowerMessage.includes('safe') || lowerMessage.includes('secure')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'security'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'security_inquiry' }
      }
    }

    if (lowerMessage.includes('payment problem') || lowerMessage.includes('payment issue') || lowerMessage.includes('payment error')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'issues'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'payment_issue' }
      }
    }

    if (lowerMessage.includes('compare') || lowerMessage.includes('vs') || lowerMessage.includes('difference')) {
      const product1 = generateRandomData.products()
      const product2 = generateRandomData.products()
      let response = getRandomResponse(responseLibraries.product, 'comparison')
        .replace('{priceA}', product1.price)
        .replace('{priceB}', product2.price)
        .replace('{ratingA}', product1.rating)
        .replace('{ratingB}', product2.rating)
        .replace('{featuresA}', product1.features.slice(0, 2).join(', '))
        .replace('{featuresB}', product2.features.slice(0, 2).join(', '))

      return {
        response: response,
        contextUpdate: { currentTopic: 'product', lastAction: 'comparison_inquiry' }
      }
    }

    if (lowerMessage.includes('stock') || lowerMessage.includes('available') || lowerMessage.includes('in stock')) {
      const product = generateRandomData.products()
      const shipping = generateRandomData.shipping()
      let response = getRandomResponse(responseLibraries.product, 'availability')
        .replace('{quantity}', Math.floor(Math.random() * 50) + 10)
        .replace('{deliveryTime}', shipping.time)
        .replace('{location}', 'Mumbai Warehouse')
        .replace('{restockDate}', 'Next week')

      return {
        response: response,
        contextUpdate: { currentTopic: 'product', lastAction: 'availability_inquiry' }
      }
    }

    if (lowerMessage.includes('order problem') || lowerMessage.includes('order issue') || lowerMessage.includes('delivery problem')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'order'),
        contextUpdate: { currentTopic: 'support', lastAction: 'order_issue' }
      }
    }

    if (lowerMessage.includes('technical') || lowerMessage.includes('website problem') || lowerMessage.includes('app issue')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'technical'),
        contextUpdate: { currentTopic: 'support', lastAction: 'technical_issue' }
      }
    }

    if (lowerMessage.includes('refund') || lowerMessage.includes('return') || lowerMessage.includes('money back')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'refund'),
        contextUpdate: { currentTopic: 'support', lastAction: 'refund_inquiry' }
      }
    }

    if (lowerMessage.includes('how are you') || lowerMessage.includes('how do you feel')) {
      return {
        response: "I'm doing great, thank you for asking! 😊 I'm always excited to help you with your shopping needs. How can I assist you today?",
        contextUpdate: { currentTopic: 'wellbeing', lastAction: 'wellbeing_inquiry' }
      }
    }

    if (lowerMessage.includes('joke') || lowerMessage.includes('funny') || lowerMessage.includes('humor')) {
      const jokes = [
        "Why did the shopping cart go to therapy? Because it had too many issues to carry! 😄",
        "What do you call a shopping assistant who's always late? A procrasti-buyer! 🛍️",
        "Why did the customer bring a ladder to the store? To reach the high-end products! 📈",
        "What's a shopper's favorite type of music? Sale music! 🎵"
      ]
      return {
        response: jokes[Math.floor(Math.random() * jokes.length)],
        contextUpdate: { currentTopic: 'humor', lastAction: 'humor_request' }
      }
    }

    if (lowerMessage.includes('weather') || lowerMessage.includes('temperature')) {
      return {
        response: "I'm focused on shopping, but I can help you find weather-appropriate clothing and accessories! 🌤️ Would you like me to show you seasonal items?",
        contextUpdate: { currentTopic: 'weather', lastAction: 'weather_inquiry' }
      }
    }

    if (lowerMessage.includes('time') || lowerMessage.includes('clock')) {
      const now = new Date()
      const timeString = now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: true
      })
      return {
        response: `It's currently ${timeString}. Perfect time for some shopping! 🛍️ What can I help you find?`,
        contextUpdate: { currentTopic: 'time', lastAction: 'time_inquiry' }
      }
    }

    return null 
  }

  const getSubActions = (actionType) => {
    const mainAction = quickActions.find(qa => qa.action === actionType)
    return mainAction ? mainAction.subActions || [] : []
  }

  return (
    <>
      {}
      <AnimatePresence>
        {!isOpen && (
          <motion.div
            className="ai-chat-toggle-container"
            style={style}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
          >
            <motion.button
              className="ai-chat-toggle-btn"
              onClick={openChat}
              onMouseEnter={handleMouseEnter}
              onMouseLeave={handleMouseLeave}
              whileHover={{ scale: 1.1, rotate: 5 }}
              whileTap={{ scale: 0.9 }}
            >
              <motion.div
                className="ai-avatar"
                animate={{
                  rotate: [0, 360],
                  scale: [1, 1.1, 1],
                }}
                transition={{
                  rotate: { duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" },
                  scale: { duration: 2, repeat: Number.POSITIVE_INFINITY, ease: "easeInOut" },
                }}
              >
                <Bot size={24} />
              </motion.div>

              {}
              {[...Array(6)].map((_, i) => (
                <motion.div
                  key={i}
                  className="ai-particle"
                  style={{
                    position: "absolute",
                    width: "4px",
                    height: "4px",
                    background: "linear-gradient(45deg, #667eea, #764ba2)",
                    borderRadius: "50%",
                    left: "50%",
                    top: "50%",
                  }}
                  animate={{
                    x: [0, Math.cos((i * 60) * Math.PI / 180) * 30],
                    y: [0, Math.sin((i * 60) * Math.PI / 180) * 30],
                    rotate: [0, 360],
                    scale: [0, 1, 0],
                    opacity: [0, 1, 0],
                  }}
                  transition={{
                    duration: 2.5,
                    repeat: Number.POSITIVE_INFINITY,
                    delay: i * 0.3,
                  }}
                />
              ))}

              {}
              <AnimatePresence>
                {showTooltip && (
                  <motion.div
                    className="ai-welcome-tooltip"
                    initial={{ opacity: 0, x: 20, scale: 0.8 }}
                    animate={{ opacity: 1, x: 0, scale: 1 }}
                    exit={{ opacity: 0, x: 20, scale: 0.8 }}
                    transition={{ duration: 0.3 }}
                  >
                    <div className="tooltip-content">
                      <Zap size={16} />
                      <span>AI Assistant ready to help!</span>
                    </div>
                    <div className="tooltip-arrow" />
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.button>
          </motion.div>
        )}
      </AnimatePresence>

      {}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            className={`ai-chat-window ${isFullScreen ? 'fullscreen' : ''}`}
            style={style}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
          >
            {}
            <div className="ai-chat-header">
              <div className="ai-header-content">
                <div className="ai-agent-info">
                  <div className="ai-agent-avatar">
                    <motion.div
                      animate={{ rotate: [0, 360] }}
                      transition={{ duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" }}
                    >
                      <Bot size={24} />
                    </motion.div>
                    <div className="ai-status-indicator online" />
                  </div>

                  <div className="ai-agent-details">
                    <h4 className="ai-agent-name">MKCart AI Assistant</h4>
                    <p className="ai-agent-role">
                      {isTyping ? "Thinking..." : isListening ? "Listening..." : "Online & Ready"}
                    </p>
                  </div>
                </div>

                <div className="ai-header-actions">
                  <motion.button
                    className="ai-header-btn"
                    onClick={() => setVoiceEnabled(!voiceEnabled)}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                    data-active={voiceEnabled}
                  >
                    {voiceEnabled ? <Volume2 size={16} /> : <VolumeX size={16} />}
                  </motion.button>

                  <motion.button
                    className="ai-header-btn"
                    onClick={clearChat}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <RotateCcw size={16} />
                  </motion.button>

                  <motion.button
                    className="ai-header-btn"
                    onClick={closeChat}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <X size={16} />
                  </motion.button>
                </div>
              </div>
            </div>

            {}
            <div className="ai-chat-messages">
              {messages.map((message) => (
                <div key={message.id} className={`ai-message ${message.type}`}>
                  <div className="ai-message-avatar">
                    {message.type === "ai" ? (
                      <motion.div
                        animate={{ rotate: [0, 360] }}
                        transition={{ duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" }}
                      >
                        <Bot size={20} />
                      </motion.div>
                    ) : (
                      <User size={20} />
                    )}
                  </div>

                  <div className="ai-message-bubble">
                    <div className="ai-message-content" dangerouslySetInnerHTML={{ __html: message.type === 'ai' ? formatAIResponse(message.message) : message.message.replace(/\n/g, '<br>') }} />
                    <div className="ai-message-actions">
                      <motion.button
                        className="ai-message-action"
                        onClick={() => copyMessage(message)}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        <Copy size={14} />
                      </motion.button>
                      <motion.button
                        className="ai-message-action"
                        onClick={() => shareMessage(message)}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        <Share2 size={14} />
                      </motion.button>
                      {message.type === "ai" && (
                        <>
                          <motion.button
                            className="ai-message-action"
                            onClick={() => rateMessage(message.id, "up")}
                            whileHover={{ scale: 1.1 }}
                            whileTap={{ scale: 0.9 }}
                          >
                            <ThumbsUp size={14} />
                          </motion.button>
                          <motion.button
                            className="ai-message-action"
                            onClick={() => rateMessage(message.id, "down")}
                            whileHover={{ scale: 1.1 }}
                            whileTap={{ scale: 0.9 }}
                          >
                            <ThumbsDown size={14} />
                          </motion.button>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              ))}

              {}
              {isTyping && (
                <div className="ai-processing-indicator">
                  <div className="ai-processing-spinner" />
                  <div className="ai-processing-text">{currentTask}</div>
                </div>
              )}

              {}
              <div ref={messagesEndRef} />

            </div>

            {}
            <div className="ai-quick-actions">
              <div className="ai-quick-actions-grid">
                {currentSubActions ? (
                  
                  <>
                    {}
                    {subActionHistory.length > 0 && (
                      <div className="ai-sub-action-breadcrumb">
                        {subActionHistory.map((item, index) => (
                          <span key={index} className="ai-breadcrumb-item">
                            {item.label}
                            {index < subActionHistory.length - 1 && <span className="ai-breadcrumb-separator"></span>}
                          </span>
                        ))}
                      </div>
                    )}

                    {}
                    {currentSubActions.map((subAction) => (
                      <motion.button
                        key={subAction.action}
                        className="ai-quick-action-btn"
                        onClick={() => handleQuickAction(subAction.action)}
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        disabled={isTyping}
                        style={{
                          background: `linear-gradient(135deg, ${subAction.color}20, ${subAction.color}10)`,
                          border: `1px solid ${subAction.color}30`
                        }}
                      >
                        <div className="ai-quick-action-icon">
                          <subAction.icon size={16} />
                        </div>
                        <span className="ai-quick-action-text">{subAction.label}</span>
                      </motion.button>
                    ))}
                  </>
                ) : (
                  quickActions.map((actionObj) => (
                    <motion.button
                      key={actionObj.action}
                      className="ai-quick-action-btn"
                      onClick={() => handleQuickAction(actionObj.action)}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                      disabled={isTyping}
                      style={{
                        background: `linear-gradient(135deg, ${actionObj.color}20, ${actionObj.color}10)`,
                        border: `1px solid ${actionObj.color}30`
                      }}
                    >
                      <div className="ai-quick-action-icon">
                        <actionObj.icon size={16} />
                      </div>
                      <span className="ai-quick-action-text">{actionObj.label}</span>
                    </motion.button>
                  ))
                )}
              </div>
            </div>

            {}
            <div className="ai-chat-input-container">
              <div className="ai-input-wrapper">
                <motion.button
                  className="ai-input-action-btn"
                  onClick={handleFileUpload}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                >
                  <Paperclip size={16} />
                </motion.button>

                <motion.button
                  className="ai-input-action-btn"
                  onClick={isListening ? stopListening : startListening}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                  data-active={isListening}
                >
                  {isListening ? <MicOff size={16} /> : <Mic size={16} />}
                </motion.button>

                <textarea
                  className="ai-chat-input"
                  value={inputMessage}
                  onChange={(e) => setInputMessage(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="Type your message here..."
                  disabled={isTyping}
                  rows={1}
                />

                <motion.button
                  className="ai-send-btn"
                  onClick={handleSendMessage}
                  disabled={!inputMessage.trim() || isTyping}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Send size={16} />
                </motion.button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}

export default AIChatAssistant