File size: 210,061 Bytes
03bc196
 
 
 
 
 
 
 
 
17b02e0
03bc196
 
 
 
 
 
17b02e0
 
0133950
17b02e0
 
 
03bc196
840e7f3
 
03bc196
840e7f3
03bc196
17b02e0
 
840e7f3
03bc196
17b02e0
03bc196
8c3aa0b
03bc196
840e7f3
17b02e0
840e7f3
 
 
03bc196
 
17b02e0
 
03bc196
17b02e0
 
 
 
03bc196
17b02e0
 
 
 
 
 
 
 
 
03bc196
 
 
 
840e7f3
03bc196
 
8c3aa0b
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
03bc196
17b02e0
 
03bc196
17b02e0
840e7f3
 
 
 
17b02e0
03bc196
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
 
17b02e0
 
 
 
 
 
 
 
 
 
03bc196
8c3aa0b
03bc196
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
8c3aa0b
17b02e0
840e7f3
03bc196
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
8c3aa0b
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
8c3aa0b
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
17b02e0
03bc196
8c3aa0b
 
03bc196
 
17b02e0
 
03bc196
17b02e0
840e7f3
 
03bc196
 
8c3aa0b
17b02e0
03bc196
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
 
 
17b02e0
03bc196
 
17b02e0
 
 
 
 
03bc196
 
 
17b02e0
03bc196
 
17b02e0
 
 
 
 
03bc196
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
03bc196
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bc196
840e7f3
17b02e0
03bc196
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
03bc196
840e7f3
17b02e0
03bc196
17b02e0
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
03bc196
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
 
 
03bc196
 
17b02e0
 
 
840e7f3
17b02e0
840e7f3
 
17b02e0
840e7f3
 
17b02e0
 
 
 
840e7f3
 
17b02e0
840e7f3
17b02e0
 
840e7f3
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
840e7f3
 
 
 
 
17b02e0
840e7f3
 
 
 
17b02e0
 
 
 
 
840e7f3
 
 
17b02e0
840e7f3
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
840e7f3
17b02e0
 
 
840e7f3
 
 
 
 
 
17b02e0
840e7f3
 
 
17b02e0
840e7f3
 
 
 
 
 
17b02e0
840e7f3
17b02e0
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
17b02e0
 
840e7f3
17b02e0
 
840e7f3
 
17b02e0
 
 
840e7f3
 
17b02e0
840e7f3
17b02e0
840e7f3
17b02e0
 
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
17b02e0
840e7f3
 
 
 
 
 
17b02e0
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
840e7f3
 
8c3aa0b
840e7f3
 
 
 
17b02e0
840e7f3
 
17b02e0
840e7f3
 
 
 
 
17b02e0
840e7f3
 
 
17b02e0
840e7f3
 
 
8c3aa0b
840e7f3
 
17b02e0
 
840e7f3
 
 
8c3aa0b
840e7f3
 
 
 
 
 
 
 
 
8c3aa0b
840e7f3
8c3aa0b
 
17b02e0
 
 
 
840e7f3
17b02e0
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
840e7f3
 
17b02e0
840e7f3
17b02e0
 
840e7f3
 
 
 
 
 
 
 
8c3aa0b
 
840e7f3
 
 
 
 
 
 
 
17b02e0
840e7f3
17b02e0
 
 
 
840e7f3
 
 
8c3aa0b
 
840e7f3
 
 
 
 
 
8c3aa0b
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
 
 
 
840e7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
17b02e0
 
 
840e7f3
 
 
17b02e0
 
840e7f3
17b02e0
840e7f3
 
 
 
 
17b02e0
840e7f3
17b02e0
840e7f3
 
 
17b02e0
8c3aa0b
17b02e0
840e7f3
 
 
 
8c3aa0b
840e7f3
 
 
 
 
 
 
 
 
 
17b02e0
 
840e7f3
 
 
 
 
 
 
17b02e0
840e7f3
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
17b02e0
840e7f3
 
 
17b02e0
840e7f3
 
 
 
 
 
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
8c3aa0b
840e7f3
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
17b02e0
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
8c3aa0b
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
840e7f3
17b02e0
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
17b02e0
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
840e7f3
17b02e0
 
840e7f3
17b02e0
 
 
 
 
 
 
8c3aa0b
840e7f3
17b02e0
 
840e7f3
17b02e0
 
840e7f3
17b02e0
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
840e7f3
17b02e0
840e7f3
17b02e0
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
840e7f3
8c3aa0b
17b02e0
 
 
 
 
 
 
 
8c3aa0b
 
17b02e0
 
 
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
8c3aa0b
17b02e0
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
840e7f3
17b02e0
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
840e7f3
 
 
17b02e0
 
8c3aa0b
 
17b02e0
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
8c3aa0b
 
17b02e0
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
8c3aa0b
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
8c3aa0b
17b02e0
 
840e7f3
17b02e0
 
 
 
 
 
 
 
840e7f3
17b02e0
 
840e7f3
 
17b02e0
 
840e7f3
 
 
17b02e0
 
 
8c3aa0b
17b02e0
840e7f3
17b02e0
 
 
840e7f3
 
17b02e0
 
 
840e7f3
17b02e0
840e7f3
 
 
 
17b02e0
 
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
17b02e0
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
840e7f3
 
17b02e0
 
840e7f3
 
 
 
17b02e0
840e7f3
17b02e0
840e7f3
 
17b02e0
840e7f3
 
17b02e0
840e7f3
 
 
17b02e0
840e7f3
17b02e0
 
840e7f3
17b02e0
 
840e7f3
 
17b02e0
 
840e7f3
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
 
17b02e0
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
 
 
17b02e0
840e7f3
 
17b02e0
8c3aa0b
17b02e0
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
840e7f3
17b02e0
 
840e7f3
 
 
17b02e0
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
840e7f3
 
 
17b02e0
 
 
840e7f3
 
 
 
 
17b02e0
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
840e7f3
 
 
17b02e0
840e7f3
 
17b02e0
840e7f3
 
17b02e0
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
840e7f3
17b02e0
840e7f3
8c3aa0b
 
17b02e0
 
840e7f3
17b02e0
840e7f3
17b02e0
840e7f3
 
 
17b02e0
 
840e7f3
17b02e0
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
 
17b02e0
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
840e7f3
 
 
 
 
 
17b02e0
 
 
840e7f3
 
 
17b02e0
840e7f3
17b02e0
840e7f3
 
 
17b02e0
 
840e7f3
 
17b02e0
 
 
 
840e7f3
 
 
17b02e0
 
 
 
 
840e7f3
17b02e0
 
 
 
 
840e7f3
17b02e0
 
 
 
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
17b02e0
840e7f3
 
 
 
 
 
 
17b02e0
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
03bc196
8c3aa0b
03bc196
 
17b02e0
840e7f3
17b02e0
 
 
 
 
03bc196
17b02e0
 
 
 
 
 
 
 
 
03bc196
840e7f3
17b02e0
840e7f3
03bc196
17b02e0
 
 
 
 
840e7f3
 
 
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
840e7f3
 
 
17b02e0
840e7f3
 
17b02e0
840e7f3
 
17b02e0
 
 
 
840e7f3
 
17b02e0
 
 
 
 
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
17b02e0
 
 
 
 
 
840e7f3
 
17b02e0
840e7f3
 
17b02e0
840e7f3
17b02e0
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
 
17b02e0
 
 
 
 
840e7f3
 
 
 
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
 
17b02e0
 
 
 
 
 
 
 
 
 
840e7f3
03bc196
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
840e7f3
17b02e0
840e7f3
 
 
17b02e0
 
840e7f3
17b02e0
 
840e7f3
17b02e0
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
840e7f3
 
 
 
 
 
 
 
 
 
17b02e0
 
840e7f3
 
 
 
 
 
17b02e0
 
 
 
 
 
 
 
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
 
 
17b02e0
 
 
 
840e7f3
 
 
 
17b02e0
 
 
 
 
 
 
 
840e7f3
 
 
 
 
 
17b02e0
840e7f3
17b02e0
 
840e7f3
8c3aa0b
 
840e7f3
17b02e0
840e7f3
8c3aa0b
840e7f3
 
 
 
 
17b02e0
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
840e7f3
 
 
 
 
 
17b02e0
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
840e7f3
 
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
8c3aa0b
840e7f3
 
 
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c3aa0b
17b02e0
 
 
 
8c3aa0b
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
 
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
17b02e0
 
 
840e7f3
17b02e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840e7f3
 
17b02e0
 
840e7f3
 
17b02e0
840e7f3
 
 
 
03bc196
8c3aa0b
 
17b02e0
840e7f3
 
 
 
 
 
 
17b02e0
 
840e7f3
17b02e0
 
 
840e7f3
03bc196
17b02e0
03bc196
 
 
 
17b02e0
840e7f3
 
 
 
 
 
03bc196
17b02e0
 
 
 
03bc196
 
17b02e0
 
03bc196
 
 
17b02e0
 
 
 
 
 
03bc196
 
 
840e7f3
17b02e0
840e7f3
03bc196
17b02e0
840e7f3
 
 
 
 
 
03bc196
17b02e0
 
 
 
 
 
 
 
 
03bc196
 
 
840e7f3
 
03bc196
 
17b02e0
03bc196
840e7f3
 
03bc196
17b02e0
840e7f3
17b02e0
840e7f3
 
03bc196
840e7f3
17b02e0
840e7f3
 
17b02e0
 
 
03bc196
 
 
840e7f3
 
03bc196
 
17b02e0
03bc196
840e7f3
 
17b02e0
 
840e7f3
17b02e0
840e7f3
 
17b02e0
 
 
 
 
 
03bc196
 
 
17b02e0
840e7f3
 
03bc196
840e7f3
17b02e0
840e7f3
 
17b02e0
 
 
 
840e7f3
 
03bc196
17b02e0
 
 
 
 
03bc196
 
8c3aa0b
 
03bc196
17b02e0
 
 
 
 
 
 
03bc196
17b02e0
 
 
 
 
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


from flask import Flask, render_template_string, request, redirect, url_for, jsonify, session
import json
import os
import logging
import threading
import time
from datetime import datetime, timedelta, timezone
import pytz # Keep pytz if needed elsewhere, but timezone is now preferred for basic UTC handling
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
# SECURITY: Ensure this key is strong and loaded from environment in production
app.secret_key = os.getenv("FLASK_SECRET_KEY", "a_much_stronger_default_secret_key_please_change_v3") # Changed secret key significantly
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
app.config['SESSION_COOKIE_SECURE'] = True # Keep secure cookies
# Set session lifetime (e.g., 30 days)
app.permanent_session_lifetime = timedelta(days=30)

DATA_FILE = 'data_ultra_flowers.json' # Changed filename
USER_DATA_FILE = 'data_ultra_flowerusers.json' # Changed filename

REPO_ID = "Kgshop/Testbasebase" # <<< UPDATED REPOSITORY ID
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") # Use the same token if read/write access is the same
# Placeholder for a new logo if available, otherwise keep the old one or remove
LOGO_URL = "https://huggingface.co/spaces/shopflo0/flowerbase/resolve/main/Gemini_Generated_Image_ebfuonebfuonebfu.jpg" # Placeholder logo

logging.basicConfig(level=logging.INFO) # Changed level to INFO for less verbosity in production

# --- Helper Function & Jinja Filter ---
def format_iso_datetime_filter(iso_str):
    """
    Parses an ISO 8601 datetime string (handling 'Z' for UTC)
    and returns a timezone-aware datetime object (UTC).
    Returns None if parsing fails.
    """
    if not iso_str: return None
    try:
        # Check if it's already a datetime object (e.g., from previous processing)
        if isinstance(iso_str, datetime):
            dt = iso_str
            # Ensure it's timezone-aware (assume UTC if naive)
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            return dt
        else:
            # Process string format
            expiry_dt_str = str(iso_str) # Ensure it's a string
            if 'Z' in expiry_dt_str:
               expiry_dt_str = expiry_dt_str.replace('Z', '+00:00')
            # Handle potential missing timezone info by assuming UTC
            dt = datetime.fromisoformat(expiry_dt_str)
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            return dt
    except (ValueError, TypeError) as e:
        logging.warning(f"Could not parse date string: {iso_str}. Error: {e}")
        return None

# Register the function as a Jinja2 filter
app.template_filter('format_iso_datetime')(format_iso_datetime_filter)


# --- Data Loading/Saving Functions ---
def load_data():
    try:
        # Attempt to download only if tokens are set, otherwise use local
        if HF_TOKEN_READ:
            try:
                download_db_from_hf()
            except RepositoryNotFoundError:
                logging.warning(f"Репозиторий HF {REPO_ID} не найден. Попытка использовать локальный файл {DATA_FILE}.")
            except Exception as download_err:
                logging.error(f"Ошибка загрузки {DATA_FILE} с HF: {download_err}. Попытка использовать локальный файл.")

        if not os.path.exists(DATA_FILE):
            logging.warning(f"Локальный файл базы данных '{DATA_FILE}' не найден. Создается пустая база данных.")
            return {'products': [], 'categories': [], 'news': []}

        with open(DATA_FILE, 'r', encoding='utf-8') as file:
            data = json.load(file)
            logging.info(f"Данные магазина цветов успешно загружены из '{DATA_FILE}'")
            if not isinstance(data, dict):
                 logging.warning("Структура JSON некорректна, создается структура по умолчанию.")
                 return {'products': [], 'categories': [], 'news': []}

            # Ensure essential keys exist
            data.setdefault('products', [])
            data.setdefault('categories', [])
            data.setdefault('news', [])

            # News expiry check
            current_time_utc = datetime.now(timezone.utc)
            updated_news = []
            news_list = data.get('news', [])
            if not isinstance(news_list, list): # Handle case where 'news' might not be a list
                logging.warning("Ключ 'news' в JSON не является списком. Новости будут проигнорированы.")
                news_list = []

            for news_item in news_list:
                 if not isinstance(news_item, dict): # Skip non-dict items
                     logging.warning(f"Найден несловарный элемент в списке новостей: {news_item}")
                     continue

                 expiry_str = news_item.get('expiry')
                 if expiry_str:
                     expiry_datetime = format_iso_datetime_filter(expiry_str) # Use the filter function for parsing
                     if expiry_datetime:
                         # Compare timezone-aware datetimes
                         if expiry_datetime > current_time_utc:
                             updated_news.append(news_item)
                         else:
                             logging.info(f"Новость '{news_item.get('title', 'N/A')}' истекла и удалена.")
                     else:
                         # Keep news if date format is wrong, but log error
                         logging.error(f"Ошибка парсинга даты истечения для новости '{news_item.get('title', 'N/A')}'. Новость сохранена.")
                         updated_news.append(news_item)
                 else:
                     updated_news.append(news_item) # Keep news without expiry
            data['news'] = updated_news

            return data
    except FileNotFoundError:
        # This case is now handled by the check after download attempt
        logging.warning(f"Локальный файл базы данных '{DATA_FILE}' не найден и не удалось скачать. Создается пустая база данных.")
        return {'products': [], 'categories': [], 'news': []}
    except json.JSONDecodeError:
        logging.error(f"Ошибка: Невозможно декодировать JSON-файл '{DATA_FILE}'. Создается пустая база данных.")
        return {'products': [], 'categories': [], 'news': []}
    except Exception as e:
        logging.error(f"Неожиданная ошибка при загрузке данных магазина цветов: {e}", exc_info=True)
        return {'products': [], 'categories': [], 'news': []}


def save_data(data):
    try:
        data_to_save = data.copy()
        # Ensure datetime objects are converted to ISO format strings before saving
        if 'news' in data_to_save and isinstance(data_to_save['news'], list):
            for news_item in data_to_save['news']:
                 if not isinstance(news_item, dict): continue # Skip non-dict items
                 # Ensure timestamp and expiry are strings
                 if 'timestamp' in news_item and isinstance(news_item['timestamp'], datetime):
                     # Ensure UTC before formatting
                     ts_dt = news_item['timestamp']
                     if ts_dt.tzinfo is None:
                         ts_dt = ts_dt.replace(tzinfo=timezone.utc)
                     else:
                         ts_dt = ts_dt.astimezone(timezone.utc)
                     news_item['timestamp'] = ts_dt.isoformat()

                 if 'expiry' in news_item and isinstance(news_item['expiry'], datetime):
                     exp_dt = news_item['expiry']
                     if exp_dt.tzinfo is None:
                         exp_dt = exp_dt.replace(tzinfo=timezone.utc)
                     else:
                         exp_dt = exp_dt.astimezone(timezone.utc)
                     news_item['expiry'] = exp_dt.isoformat()

        with open(DATA_FILE, 'w', encoding='utf-8') as file:
            json.dump(data_to_save, file, ensure_ascii=False, indent=4)
        logging.info(f"Данные магазина цветов успешно сохранены в '{DATA_FILE}'")
        # Attempt to upload only if write token is set
        if HF_TOKEN_WRITE:
            upload_db_to_hf()
    except Exception as e:
        logging.error(f"Ошибка при сохранении данных магазина цветов: {e}", exc_info=True)
        # Decide if you want to raise the exception or just log it
        # raise

def upload_db_to_hf():
    if not HF_TOKEN_WRITE:
        logging.info("HF_TOKEN_WRITE не установлен, загрузка на Hugging Face пропущена.")
        return
    if not os.path.exists(DATA_FILE):
        logging.warning(f"Файл {DATA_FILE} не найден для загрузки на HF.")
        return
    try:
        api = HfApi()
        api.upload_file(
            path_or_fileobj=DATA_FILE,
            path_in_repo=DATA_FILE,
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN_WRITE,
            commit_message=f"Автоматическое резервное копирование базы данных цветов {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        logging.info(f"Резервная копия JSON-базы данных цветов загружена в {REPO_ID}.")
    except Exception as e:
        logging.error(f"Ошибка при загрузке резервной копии базы данных цветов {DATA_FILE}: {e}")

def download_db_from_hf():
    if not HF_TOKEN_READ:
        logging.info("HF_TOKEN_READ не установлен, загрузка с Hugging Face пропущена.")
        return # Don't raise error, just skip download attempt
    try:
        logging.info(f"Попытка загрузки {DATA_FILE} из {REPO_ID}...")
        hf_hub_download(
            repo_id=REPO_ID,
            filename=DATA_FILE,
            repo_type="dataset",
            token=HF_TOKEN_READ,
            local_dir=".",
            force_filename=DATA_FILE, # Ensure it overwrites with the correct name
            local_dir_use_symlinks=False # Recommended for compatibility
        )
        logging.info(f"JSON-база данных цветов '{DATA_FILE}' успешно загружена из {REPO_ID}.")
    except RepositoryNotFoundError as e:
        logging.warning(f"Репозиторий {REPO_ID} не найден на Hugging Face: {e}.")
        raise # Re-raise to be caught in load_data
    except Exception as e:
        # Log other potential download errors (network issues, permissions, file not found on remote)
        logging.error(f"Ошибка при загрузке JSON-базы данных цветов '{DATA_FILE}' с Hugging Face: {e}")
        # Check if it's specifically a file not found error (often HTTP 404)
        if "404" in str(e):
             logging.warning(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}.")
        raise # Re-raise to be caught in load_data


# --- User Data Functions (Similar adjustments) ---

def load_user_data():
    try:
        if HF_TOKEN_READ:
            try:
                download_user_db_from_hf()
            except RepositoryNotFoundError:
                logging.warning(f"Репозиторий HF {REPO_ID} для пользователей не найден. Попытка использовать локальный файл {USER_DATA_FILE}.")
            except Exception as download_err:
                 logging.error(f"Ошибка загрузки {USER_DATA_FILE} с HF: {download_err}. Попытка использовать локальный файл.")


        if not os.path.exists(USER_DATA_FILE):
             logging.warning(f"Локальный файл базы данных пользователей '{USER_DATA_FILE}' не найден. Создается пустая база данных.")
             return {'users': []}

        with open(USER_DATA_FILE, 'r', encoding='utf-8') as file:
            user_data = json.load(file)
            logging.info(f"Данные пользователей успешно загружены из '{USER_DATA_FILE}'")
            if not isinstance(user_data, dict):
                 logging.warning("Структура JSON пользователей некорректна, создается структура по умолчанию.")
                 return {'users': []}

            user_data.setdefault('users', [])
            # Add basic validation for users list if needed
            if not isinstance(user_data['users'], list):
                 logging.warning("Ключ 'users' в JSON пользователей не является списком. Создается пустой список.")
                 user_data['users'] = []
            return user_data
    except FileNotFoundError:
        # Handled by os.path.exists check now
        logging.warning(f"Локальный файл базы данных пользователей '{USER_DATA_FILE}' не найден и не удалось скачать. Создается пустая база данных.")
        return {'users': []}
    except json.JSONDecodeError:
        logging.error(f"Ошибка: Невозможно декодировать JSON-файл пользователей '{USER_DATA_FILE}'.")
        return {'users': []}
    except Exception as e:
        logging.error(f"Неожиданная ошибка при загрузке данных пользователей: {e}", exc_info=True)
        return {'users': []}


def save_user_data(user_data):
    try:
        # Ensure datetime objects in order history are strings (in UTC ISO format)
        for user in user_data.get('users', []):
            if 'order_history' in user and isinstance(user['order_history'], list):
                for order in user['order_history']:
                     if not isinstance(order, dict): continue # Skip non-dict items
                     if 'timestamp' in order and isinstance(order['timestamp'], datetime):
                         ts_dt = order['timestamp']
                         if ts_dt.tzinfo is None:
                             ts_dt = ts_dt.replace(tzinfo=timezone.utc)
                         else:
                             ts_dt = ts_dt.astimezone(timezone.utc)
                         order['timestamp'] = ts_dt.isoformat()

        with open(USER_DATA_FILE, 'w', encoding='utf-8') as file:
            json.dump(user_data, file, ensure_ascii=False, indent=4)
        logging.info(f"Данные пользователей успешно сохранены в '{USER_DATA_FILE}'")
        if HF_TOKEN_WRITE:
            upload_user_db_to_hf()
    except Exception as e:
        logging.error(f"Ошибка при сохранении данных пользователей: {e}", exc_info=True)
        # raise

def upload_user_db_to_hf():
    if not HF_TOKEN_WRITE:
        logging.info("HF_TOKEN_WRITE не установлен, загрузка пользовательской базы на Hugging Face пропущена.")
        return
    if not os.path.exists(USER_DATA_FILE):
        logging.warning(f"Файл {USER_DATA_FILE} не найден для загрузки на HF.")
        return
    try:
        api = HfApi()
        api.upload_file(
            path_or_fileobj=USER_DATA_FILE,
            path_in_repo=USER_DATA_FILE,
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN_WRITE,
            commit_message=f"Автоматическое резервное копирование базы данных пользователей {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        logging.info(f"Резервная копия JSON-базы данных пользователей загружена в {REPO_ID}.")
    except Exception as e:
        logging.error(f"Ошибка при загрузке резервной копии базы данных пользователей {USER_DATA_FILE}: {e}")

def download_user_db_from_hf():
    if not HF_TOKEN_READ:
        logging.info("HF_TOKEN_READ не установлен, загрузка пользовательской базы с Hugging Face пропущена.")
        return # Don't raise error
    try:
        logging.info(f"Попытка загрузки {USER_DATA_FILE} из {REPO_ID}...")
        hf_hub_download(
            repo_id=REPO_ID,
            filename=USER_DATA_FILE,
            repo_type="dataset",
            token=HF_TOKEN_READ,
            local_dir=".",
            force_filename=USER_DATA_FILE, # Ensure it overwrites with the correct name
            local_dir_use_symlinks=False
        )
        logging.info(f"JSON-база данных пользователей '{USER_DATA_FILE}' успешно загружена из {REPO_ID}.")
    except RepositoryNotFoundError as e:
        logging.warning(f"Репозиторий {REPO_ID} (для пользователей) не найден на Hugging Face: {e}.")
        raise # Re-raise
    except Exception as e:
        logging.error(f"Ошибка при загрузке JSON-базы данных пользователей '{USER_DATA_FILE}' с Hugging Face: {e}")
        if "404" in str(e):
             logging.warning(f"Файл {USER_DATA_FILE} не найден в репозитории {REPO_ID}.")
        raise # Re-raise

# --- Background Backup Thread ---
# Global lock for saving data to prevent race conditions between request threads and backup thread
data_lock = threading.Lock()
user_data_lock = threading.Lock()

def periodic_backup():
    while True:
        time.sleep(900) # Backup every 15 minutes
        logging.info("Запуск периодического резервного копирования...")
        try:
            # No need to reload data here if save functions acquire lock
            # Just trigger the save which handles upload internally
             with data_lock:
                 current_data = load_data() # Load latest state inside lock just before saving
                 save_data(current_data) # save_data now includes upload if token exists
             with user_data_lock:
                 current_user_data = load_user_data() # Load latest state inside lock
                 save_user_data(current_user_data) # save_user_data includes upload if token exists

             logging.info("Периодическое резервное копирование завершено.")
        except Exception as e:
            logging.error(f"Ошибка во время периодического резервного копирования: {e}", exc_info=True)


# --- Helper Functions ---
def get_category_counts(products):
    counts = {}
    if not isinstance(products, list): # Add type check
        return counts
    for product in products:
        if isinstance(product, dict): # Check if product is a dict
            category = product.get('category', 'Без категории')
            counts[category] = counts.get(category, 0) + 1
    return counts

# --- User Management Functions ---
# Wrap data saving in locks to ensure thread safety
def register_user(login, password, phone, address):
    with user_data_lock:
        user_data_dict = load_user_data() # Load latest data inside lock
        users = user_data_dict.get('users', [])
        if any(user.get('login') == login for user in users if isinstance(user, dict)):
            return False, "Логин уже занят."
        if len(password) < 6: # Basic password length check
             return False, "Пароль должен быть не менее 6 символов."
        hashed_password = generate_password_hash(password)
        new_user = {
            'login': login,
            'password': hashed_password,
            'phone': phone,
            'address': address,
            'points': 0,
            'order_history': []
        }
        # Ensure users is a list before appending
        if not isinstance(users, list):
            users = []
        users.append(new_user)
        user_data_dict['users'] = users
        save_user_data(user_data_dict) # Save data inside lock
    return True, "Регистрация прошла успешно."

def authenticate_user(login, password):
    # No lock needed for read-only operations usually, but load_user_data handles potential downloads
    user_data_dict = load_user_data()
    users = user_data_dict.get('users', [])
    if not isinstance(users, list): return None # Safety check
    for user in users:
        if isinstance(user, dict) and user.get('login') == login:
            if check_password_hash(user.get('password', ''), password):
                return user # Return the user dictionary
    return None

def get_user_profile(login):
    # Read-only, no lock needed unless concerned about reads during backup write
    user_data_dict = load_user_data()
    users = user_data_dict.get('users', [])
    if not isinstance(users, list): return None # Safety check
    for user in users:
         if isinstance(user, dict) and user.get('login') == login:
             return user
    return None

def update_user_profile(login, phone, address):
    user_found = False
    with user_data_lock:
        user_data_dict = load_user_data()
        users = user_data_dict.get('users', [])
        if not isinstance(users, list):
             save_user_data(user_data_dict) # Save even if structure was bad
             return False, "Ошибка структуры данных пользователей."

        for user in users:
            if isinstance(user, dict) and user.get('login') == login:
                user['phone'] = phone
                user['address'] = address
                user_found = True
                break
        if user_found:
             user_data_dict['users'] = users # Ensure the modified list is assigned back
             save_user_data(user_data_dict) # Save updated data
             return True, "Профиль обновлен."
        else:
             # Save data even if user not found, in case load fixed something
             save_user_data(user_data_dict)
             return False, "Пользователь не найден."


def add_points_to_user(login, points):
    user_found = False
    with user_data_lock:
        user_data_dict = load_user_data()
        users = user_data_dict.get('users', [])
        if not isinstance(users, list):
             save_user_data(user_data_dict)
             return False # Indicate failure

        for user in users:
            if isinstance(user, dict) and user.get('login') == login:
                user['points'] = user.get('points', 0) + points
                user_found = True
                break
        if user_found:
            user_data_dict['users'] = users
            save_user_data(user_data_dict)
            return True
        else:
             save_user_data(user_data_dict)
             return False # User not found


def redeem_points_from_user(login, points_to_redeem):
    user_found = False
    success = False
    message = "Пользователь не найден."
    with user_data_lock:
        user_data_dict = load_user_data()
        users = user_data_dict.get('users', [])
        if not isinstance(users, list):
            save_user_data(user_data_dict)
            return False, "Ошибка структуры данных пользователей."

        for user in users:
            if isinstance(user, dict) and user.get('login') == login:
                user_found = True
                current_points = user.get('points', 0)
                if current_points >= points_to_redeem:
                    user['points'] = current_points - points_to_redeem
                    success = True
                    message = "Баллы успешно списаны"
                else:
                    message = "Недостаточно баллов для списания."
                break

        if user_found and success:
            user_data_dict['users'] = users
            save_user_data(user_data_dict)
            return True, message
        else:
            # Save even on failure if load fixed something or if user was found but points insufficient
            save_user_data(user_data_dict)
            return False, message


def save_order_to_history(login, order_details):
    user_found = False
    # Use UTC for storage consistency
    timestamp_utc = datetime.now(timezone.utc)

    with user_data_lock:
        user_data_dict = load_user_data()
        users = user_data_dict.get('users', [])
        if not isinstance(users, list):
            save_user_data(user_data_dict)
            return False, "Ошибка структуры данных пользователей."

        for user in users:
            if isinstance(user, dict) and user.get('login') == login:
                if 'order_history' not in user or not isinstance(user['order_history'], list):
                    user['order_history'] = [] # Ensure it exists and is a list

                # Add timestamp as ISO string (UTC)
                order_details_copy = order_details.copy() # Avoid modifying original dict if passed by reference
                order_details_copy['timestamp'] = timestamp_utc.isoformat()
                user['order_history'].append(order_details_copy)
                user_found = True
                break

        if user_found:
            user_data_dict['users'] = users
            save_user_data(user_data_dict)
            return True, "Заказ сохранен в истории."
        else:
            save_user_data(user_data_dict)
            return False, "Пользователь не найден."


def get_order_history(login):
    # Read-only, lock might be overkill but load_user_data handles potential downloads
    user_data_dict = load_user_data()
    users = user_data_dict.get('users', [])
    if not isinstance(users, list): return []
    user = next((user for user in users if isinstance(user, dict) and user.get('login') == login), None)
    if user:
        # Return history, newest first
        # Sort using the datetime filter function for robustness
        history = user.get('order_history', [])
        if not isinstance(history, list): return [] # Safety check

        # Default datetime for sorting if timestamp is missing or invalid
        min_utc_dt = datetime.min.replace(tzinfo=timezone.utc)

        sorted_history = sorted(
            [item for item in history if isinstance(item, dict)], # Filter out non-dict items
            key=lambda x: format_iso_datetime_filter(x.get('timestamp')) or min_utc_dt,
            reverse=True
        )
        return sorted_history
    return []

# --- Flask Routes ---

@app.route('/')
def menu():
    # Use lock for loading main data as it might involve download/initial creation
    with data_lock:
        data = load_data()
    products = data.get('products', [])
    categories = data.get('categories', [])
    news_list = data.get('news', [])

    # User data loading is handled within called functions (get_user_profile)
    logged_in = 'user_login' in session
    user_login = session.get('user_login')
    user_profile = get_user_profile(user_login) if logged_in else None
    user_points = user_profile.get('points', 0) if user_profile else 0

    category_counts = get_category_counts(products)

    # Sort news by timestamp (creation time) descending, most recent first
    min_utc_dt = datetime.min.replace(tzinfo=timezone.utc)
    news_for_template = sorted(
        [item for item in news_list if isinstance(item, dict)], # Filter non-dict news
        key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt,
        reverse=True
    )

    # HTML Template (incorporating fixes for header and logo animation)
    menu_html = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Ultra Flowers - Магазин Цветов</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <!-- Updated Fonts -->
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
        <style>
            :root {
                /* New Modern Palette */
                --primary-color: #D8BFD8;       /* Thistle */
                --secondary-color: #B0E0E6;     /* Powder Blue */
                --accent-color: #FFB6C1;        /* Light Pink accent */
                --background-light: #FAF0E6;    /* Linen */
                --background-card: #FFFFFF;     /* White */
                --text-dark: #36454F;         /* Charcoal */
                --text-medium: #708090;       /* Slate Gray */
                --text-light: #FFFFFF;
                --shadow-color: rgba(112, 128, 144, 0.15); /* Slate Gray shadow */
                --border-color: #E0E0E0;       /* Light Gray Border */

                --font-primary: 'Poppins', sans-serif;
                --font-headings: 'Playfair Display', serif;
                --header-height: 180px; /* Approximate header height for padding calculation */
            }

            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html {
                scroll-behavior: smooth;
            }
            body {
                font-family: var(--font-primary);
                background-color: var(--background-light);
                color: var(--text-dark);
                line-height: 1.7;
                overflow-x: hidden;
                font-weight: 300; /* Lighter default font weight */
                 /* FIX 2: Add padding top to body to prevent sticky header overlap */
                 padding-top: var(--header-height);
                 padding-bottom: 100px; /* Space for the fixed navigation bar */
            }
            .container {
                max-width: 1300px; /* Slightly wider container */
                margin: 0 auto;
                padding: 0 20px; /* Padding only left/right */
                /* Removed padding-bottom here, moved to body */
            }

            /* --- Header --- */
            .header {
                text-align: center;
                padding: 25px 20px; /* Adjusted padding */
                background-color: rgba(255, 255, 255, 0.85); /* Slightly less transparent white */
                backdrop-filter: blur(10px);
                /* FIX 2: Make header fixed instead of sticky for simpler non-overlap */
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                z-index: 999;
                box-shadow: 0 2px 10px var(--shadow-color);
                border-bottom: 1px solid var(--border-color);
                height: var(--header-height); /* Give header explicit height */
                display: flex; /* Use flexbox for centering */
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }
            .header-logo {
                width: 80px; /* Slightly smaller logo */
                height: 80px;
                border-radius: 50%;
                object-fit: cover;
                border: none; /* Removed border */
                box-shadow: 0 4px 15px var(--shadow-color);
                margin-bottom: 10px; /* Adjusted margin */
                transition: transform 0.5s ease-in-out; /* FIX 3: Animation transition */
                cursor: pointer; /* Add pointer cursor for clickable logo */
            }
            /* FIX 3: Add rotating class for animation */
            .header-logo.rotating {
                 transform: rotate(360deg) scale(1.05); /* Combine rotation with slight scale */
            }
            .header h1 {
                font-family: var(--font-headings);
                font-size: 2.5rem; /* Adjusted size */
                font-weight: 700;
                color: var(--text-dark);
                margin: 0 0 5px 0; /* Adjusted margin */
                letter-spacing: 1px;
            }
            .motto {
                font-size: 0.9rem; /* Adjusted size */
                color: var(--text-medium);
                font-style: italic;
                font-weight: 400;
            }

            /* --- Filters & Search --- */
            /* Adjust margins/padding now that header is fixed */
            .filters-section {
                 /* Removed padding-top as body now has padding */
                 padding-bottom: 30px;
                 margin-bottom: 30px;
            }
            .filters-container {
                display: flex;
                flex-wrap: wrap;
                gap: 12px; /* Slightly increased gap */
                justify-content: center;
                margin-bottom: 30px; /* Space before search */
            }
            #allCategoriesButton { /* Style for the fixed button */
                display: none;
                position: fixed;
                bottom: 95px; /* Above nav bar */
                left: 20px;
                z-index: 998; /* Below header/modals */
                box-shadow: 0 4px 15px var(--shadow-color);
            }
            .search-container {
                text-align: center;
            }
            #search-input {
                width: 100%;
                max-width: 550px;
                padding: 14px 25px; /* Increased padding */
                font-size: 1rem;
                border: 1px solid var(--border-color);
                border-radius: 30px;
                background: var(--background-card);
                color: var(--text-dark);
                transition: all 0.3s ease;
                box-shadow: 0 2px 8px var(--shadow-color);
            }
            #search-input::placeholder {
                color: var(--text-medium);
                font-style: italic;
            }
            #search-input:focus {
                border-color: var(--primary-color);
                box-shadow: 0 4px 12px rgba(216, 191, 216, 0.4); /* Primary color shadow */
                outline: none;
            }
            .category-filter {
                padding: 10px 22px;
                border: 1px solid var(--border-color);
                border-radius: 25px;
                background-color: var(--background-card);
                color: var(--text-medium);
                cursor: pointer;
                transition: all 0.3s ease;
                font-weight: 400; /* Regular weight */
                font-size: 0.9rem;
                white-space: nowrap;
                box-shadow: 0 1px 4px var(--shadow-color);
            }
            .category-filter.active, .category-filter:hover {
                background-color: var(--primary-color);
                color: var(--text-dark);
                border-color: var(--primary-color);
                transform: translateY(-2px);
                box-shadow: 0 4px 10px rgba(216, 191, 216, 0.3);
            }

            /* --- Product Grid --- */
            .products-grid {
                display: grid;
                /* Responsive grid columns */
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 30px; /* Increased gap */
                padding: 20px 0;
            }
            .product {
                background: var(--background-card);
                border-radius: 12px; /* Slightly less rounded */
                padding: 0; /* Padding handled internally now */
                box-shadow: 0 5px 20px var(--shadow-color);
                transition: all 0.4s ease;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                display: flex;
                flex-direction: column;
            }
            .product:hover {
                transform: translateY(-6px);
                box-shadow: 0 10px 25px rgba(112, 128, 144, 0.2); /* Darker shadow on hover */
            }
            .product-image {
                width: 100%;
                aspect-ratio: 1 / 1; /* Maintain square aspect ratio */
                background: var(--background-light); /* Light background for image area */
                overflow: hidden;
                display: flex;
                justify-content: center;
                align-items: center;
                transition: all 0.3s ease;
                border-radius: 12px 12px 0 0; /* Rounded top corners */
            }
            .product-image img {
                width: 100%;
                height: 100%;
                object-fit: cover; /* Cover the area */
                transition: transform 0.5s ease, filter 0.3s ease;
            }
            .product:hover .product-image img {
                transform: scale(1.05);
                filter: brightness(1.03);
            }
            .product-info {
                padding: 20px;
                text-align: center;
                flex-grow: 1; /* Allow info to take remaining space */
                display: flex;
                flex-direction: column;
                justify-content: space-between; /* Push button to bottom */
            }
            .product h2 {
                font-family: var(--font-headings);
                font-size: 1.3rem; /* Slightly smaller heading */
                font-weight: 600;
                color: var(--text-dark);
                margin: 0 0 5px 0;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .product-price {
                font-size: 1.2rem;
                color: var(--primary-color); /* Use primary color for price */
                font-weight: 700;
                margin-bottom: 10px;
            }
            .product-description {
                font-size: 0.85rem;
                color: var(--text-medium);
                margin-bottom: 15px;
                line-height: 1.5;
                /* Allow description to wrap for 2 lines */
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                min-height: calc(1.5em * 2); /* Reserve space for 2 lines */
            }
            .product-interaction {
                 margin-top: auto; /* Push to bottom */
                 padding-top: 15px;
            }
            .quantity-control {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 15px; /* Increased gap */
            }
            .quantity-button {
                background: transparent;
                border: 1px solid var(--border-color);
                color: var(--text-medium);
                border-radius: 50%;
                width: 32px; /* Fixed size */
                height: 32px;
                font-size: 1rem;
                cursor: pointer;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 0;
            }
            .quantity-button:hover {
                background-color: var(--background-light);
                border-color: var(--primary-color);
                color: var(--primary-color);
            }
            .quantity {
                font-size: 1.1rem;
                font-weight: 600;
                min-width: 25px;
                text-align: center;
                color: var(--text-dark);
            }
            .login-prompt { /* Style for the login link */
                font-size: 0.85rem;
                text-align: center;
            }
            .login-prompt a {
                color: var(--primary-color);
                text-decoration: underline;
                font-weight: 600;
            }
            .login-prompt a:hover {
                color: var(--secondary-color);
            }

            /* --- Modals --- */
            .modal {
                display: none;
                position: fixed;
                z-index: 1001;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background: rgba(54, 69, 79, 0.7); /* Darker backdrop */
                backdrop-filter: blur(8px);
                overflow-y: auto;
                padding-top: 5vh; /* Space from top */
                padding-bottom: 5vh;
            }
            .modal-content {
                background: var(--background-card);
                margin: 0 auto;
                padding: 30px 35px; /* Increased padding */
                border-radius: 16px; /* More rounded */
                width: 90%;
                max-width: 650px; /* Slightly smaller max-width */
                box-shadow: 0 10px 40px rgba(54, 69, 79, 0.3);
                border: none; /* Remove border */
                position: relative; /* For close button */
                animation: slideInUp 0.5s ease-out;
            }
            @keyframes slideInUp {
                from { transform: translateY(50px); opacity: 0; }
                to { transform: translateY(0); opacity: 1; }
            }
            .close {
                position: absolute;
                top: 15px;
                right: 20px;
                font-size: 2rem;
                font-weight: 300;
                color: var(--text-medium);
                cursor: pointer;
                transition: all 0.3s ease;
                line-height: 1;
            }
            .close:hover {
                color: var(--text-dark);
                transform: rotate(90deg);
            }
            .modal-content h2 {
                font-family: var(--font-headings);
                font-size: 1.8rem;
                font-weight: 600;
                color: var(--text-dark);
                margin-bottom: 25px;
                text-align: center;
            }

            /* --- Cart Specific Styles --- */
            .cart-item {
                display: flex;
                gap: 15px;
                align-items: center;
                padding: 15px 0;
                border-bottom: 1px solid var(--border-color);
            }
            .cart-item:last-child {
                border-bottom: none;
            }
            .cart-item img {
                width: 80px;
                height: 80px;
                object-fit: cover;
                border-radius: 8px;
                flex-shrink: 0;
            }
            .cart-item-details {
                flex-grow: 1;
            }
            .cart-item-details strong {
                font-size: 1rem;
                font-weight: 600;
                color: var(--text-dark);
                display: block;
                margin-bottom: 5px;
            }
            .cart-item-details p {
                font-size: 0.85rem;
                color: var(--text-medium);
                line-height: 1.5;
                margin-bottom: 3px;
            }
             .cart-item-price {
                font-size: 1rem;
                font-weight: 600;
                color: var(--primary-color);
                white-space: nowrap;
             }
            .cart-total {
                font-size: 1.4rem;
                font-weight: 700;
                color: var(--text-dark);
                margin: 30px 0 20px 0;
                text-align: right;
                border-top: 1px solid var(--border-color);
                padding-top: 20px;
            }
            .cart-total span {
                color: var(--primary-color);
            }
            #redeemPointsSection {
                margin: 15px 0;
                padding: 15px;
                background-color: rgba(216, 191, 216, 0.1); /* Light primary background */
                border-radius: 8px;
                display: flex;
                align-items: center;
                gap: 10px;
                font-size: 0.9rem;
            }
             #redeemPointsSection label {
                color: var(--text-medium);
             }
             #redeemPointsCheckbox {
                width: auto; /* Reset width */
                margin: 0;
                accent-color: var(--primary-color);
             }
             #pointsToRedeemInput {
                width: 80px;
                padding: 8px 12px;
                font-size: 0.9rem;
                border-radius: 20px;
                text-align: center;
                border: 1px solid var(--border-color); /* Added border */
             }
            .cart-actions {
                margin-top: 25px;
                display: flex;
                justify-content: space-between;
                gap: 15px;
            }

            /* --- General Button Styles --- */
            .button { /* Base button style */
                padding: 12px 25px;
                border: 1px solid var(--primary-color);
                border-radius: 30px;
                background-color: var(--primary-color);
                color: var(--text-dark);
                cursor: pointer;
                transition: all 0.3s ease;
                font-size: 0.9rem;
                font-weight: 600;
                text-align: center;
                text-decoration: none;
                display: inline-block; /* Allow inline behavior */
            }
            .button:hover {
                background-color: var(--secondary-color);
                border-color: var(--secondary-color);
                transform: translateY(-2px);
                box-shadow: 0 6px 15px rgba(176, 224, 230, 0.4);
            }
            .button-secondary { /* Outline style */
                background-color: transparent;
                border-color: var(--border-color);
                color: var(--text-medium);
            }
             .button-secondary:hover {
                background-color: var(--background-light);
                border-color: var(--text-medium);
                color: var(--text-dark);
                box-shadow: 0 4px 10px var(--shadow-color);
             }
             .button-danger {
                background-color: var(--accent-color);
                border-color: var(--accent-color);
                color: var(--text-dark);
             }
             .button-danger:hover {
                background-color: #f7a0ac;
                border-color: #f7a0ac;
                box-shadow: 0 6px 15px rgba(255, 182, 193, 0.4);
             }


            /* --- Auth & Profile Forms --- */
            .auth-form label, .profile-info p, #editProfileForm label {
                font-weight: 400;
                margin-bottom: 5px;
                color: var(--text-medium);
                font-size: 0.9rem;
                display: block;
            }
            .auth-form input, #editProfileForm input {
                width: 100%;
                padding: 12px 20px;
                margin-bottom: 15px;
                border: 1px solid var(--border-color);
                border-radius: 8px; /* Less rounded inputs */
                background: var(--background-light);
                color: var(--text-dark);
                transition: all 0.3s ease;
                font-size: 0.9rem;
            }
            .auth-form input:focus, #editProfileForm input:focus {
                 border-color: var(--primary-color);
                 background-color: var(--background-card);
                 box-shadow: 0 0 8px rgba(216, 191, 216, 0.3);
                 outline: none;
             }
            .auth-buttons {
                text-align: center;
                margin-top: 25px;
                display: flex;
                gap: 15px;
                justify-content: center;
            }
            .profile-info strong {
                font-weight: 600;
                color: var(--text-dark);
                margin-right: 8px;
            }
             .profile-info p {
                margin-bottom: 15px;
                font-size: 1rem;
                border-bottom: 1px solid var(--border-color);
                padding-bottom: 10px;
             }
             .profile-info p:last-of-type {
                 border-bottom: none;
             }
             .profile-actions {
                 margin-top: 20px;
                 display: flex;
                 gap: 15px;
             }
             #registerMessage, #loginMessage, #editProfileMessage {
                margin-top: 15px;
                text-align: center;
                font-size: 0.9rem;
                padding: 10px;
                border-radius: 8px;
                display: none; /* Hide initially */
             }
              #registerMessage:not(:empty), #loginMessage:not(:empty), #editProfileMessage:not(:empty) {
                 display: block; /* Show when content is added */
             }
             #registerMessage.success, #loginMessage.success, #editProfileMessage.success {
                 background-color: rgba(176, 224, 230, 0.2); /* Light secondary background */
                 color: var(--secondary-color);
              }
              #registerMessage.error, #loginMessage.error, #editProfileMessage.error {
                  background-color: rgba(255, 182, 193, 0.2); /* Light accent background */
                  color: var(--accent-color);
               }

            /* --- Bottom Navigation --- */
            .bottom-nav {
                position: fixed;
                bottom: 0;
                left: 0;
                width: 100%;
                background: rgba(255, 255, 255, 0.9);
                display: flex;
                justify-content: space-around;
                padding: 10px 0;
                border-top: 1px solid var(--border-color);
                box-shadow: 0 -4px 15px var(--shadow-color);
                backdrop-filter: blur(10px);
                z-index: 1000;
            }
            .bottom-nav .nav-item {
                color: var(--text-medium);
                text-align: center;
                cursor: pointer;
                background: none;
                border: none;
                font-size: 0.7rem; /* Smaller text */
                transition: color 0.3s ease;
                flex: 1; /* Equal width */
                padding: 5px 0;
                text-decoration: none; /* Added for link */
                display: flex; /* Align icon and text */
                flex-direction: column;
                align-items: center;
            }
            .bottom-nav .nav-item i {
                font-size: 1.5rem; /* Slightly smaller icons */
                display: block;
                margin-bottom: 5px;
            }
            .bottom-nav .nav-item:hover, .bottom-nav .nav-item.active { /* Add active state if needed */
                color: var(--primary-color);
            }

             /* --- Cart Button --- */
            #cart-button {
                position: fixed;
                bottom: 85px; /* Above nav bar */
                right: 20px;
                background-color: var(--primary-color);
                color: var(--text-dark);
                border: none;
                border-radius: 50%;
                width: 55px; /* Slightly smaller */
                height: 55px;
                font-size: 1.6rem;
                cursor: pointer;
                box-shadow: 0 6px 20px rgba(216, 191, 216, 0.5);
                transition: all 0.3s ease;
                z-index: 1000;
                display: none; /* Hidden by default */
                align-items: center;
                justify-content: center;
            }
            #cart-button:hover {
                transform: scale(1.1) rotate(10deg);
                box-shadow: 0 8px 25px rgba(216, 191, 216, 0.7);
            }
            #cart-count { /* Optional: Add a badge */
               position: absolute;
               top: -5px;
               right: -5px;
               background-color: var(--accent-color);
               color: var(--text-dark);
               border-radius: 50%;
               padding: 2px 6px;
               font-size: 0.7rem;
               font-weight: bold;
            }

            /* --- News Modal --- */
            #newsContent {
                margin-top: 20px;
                max-height: 70vh; /* Limit height */
                overflow-y: auto; /* Add scroll if content overflows */
            }
            .news-item {
                padding: 20px;
                margin-bottom: 20px;
                border: 1px solid var(--border-color);
                background: var(--background-light); /* Use light background */
                border-radius: 12px;
            }
            .news-item h3 {
                font-family: var(--font-headings);
                color: var(--primary-color);
                margin-top: 0;
                margin-bottom: 10px;
                font-size: 1.4rem;
            }
            .news-item p {
                margin: 5px 0;
                font-size: 0.9rem;
                color: var(--text-medium);
            }
             .news-item img {
                max-width: 100%;
                height: auto;
                border-radius: 8px;
                margin: 15px 0; /* Space around image */
             }
             .news-item .timestamp-date, .news-item .expiry-date {
                 font-size: 0.8rem;
                 color: var(--text-medium);
                 margin-top: 10px;
                 font-style: italic;
             }


            /* --- Options Modal Specific --- */
            #optionsModal label {
                font-weight: 600;
                margin-top: 15px;
                margin-bottom: 8px;
                color: var(--text-dark);
                display: block;
            }
             #optionsModal .quantity-input-container {
                 margin-bottom: 20px;
                 display: flex; /* Make it flex */
                 justify-content: center;
                 align-items: center; /* Align items vertically */
                 gap: 10px; /* Add gap between elements */
             }
             /* Style the number input specifically */
             #quantityInput {
                 width: 60px;
                 text-align: center;
                 border: 1px solid var(--border-color);
                 border-radius: 5px;
                 padding: 5px;
                 font-size: 1rem;
                 font-weight: 600;
                 /* Remove default arrows in some browsers */
                 -moz-appearance: textfield;
                 appearance: textfield;
             }
              #quantityInput::-webkit-outer-spin-button,
              #quantityInput::-webkit-inner-spin-button {
                -webkit-appearance: none;
                margin: 0;
              }

             #optionsModal textarea#orderComment {
                 width: 100%;
                 min-height: 80px;
                 padding: 12px 15px;
                 border: 1px solid var(--border-color);
                 border-radius: 8px;
                 font-size: 0.9rem;
                 background: var(--background-light);
                 color: var(--text-dark);
                 resize: vertical;
                 margin-bottom: 20px;
             }
             #optionsModal select#deliveryTime {
                  width: 100%;
                  padding: 12px 15px;
                  border: 1px solid var(--border-color);
                  border-radius: 8px;
                  background: var(--background-light);
                  color: var(--text-dark);
                  font-size: 0.9rem;
                  margin-bottom: 20px;
             }
             #optionsList {
                 margin-bottom: 25px;
             }
             .options-checkbox {
                 display: flex; /* Use flex for alignment */
                 align-items: center;
                 margin-bottom: 10px;
                 padding: 10px;
                 background-color: rgba(216, 191, 216, 0.05);
                 border-radius: 8px;
             }
             .options-checkbox input[type="checkbox"] {
                 margin-right: 10px;
                 width: auto; /* Reset width */
                 accent-color: var(--primary-color);
                 flex-shrink: 0; /* Prevent shrinking */
             }
             .options-checkbox label { /* Label text within */
                 margin: 0;
                 font-weight: 400;
                 color: var(--text-dark);
                 flex-grow: 1;
                 cursor: pointer; /* Make label clickable */
             }
            #optionsModal .button { /* Add to Cart button */
                display: block; /* Make it full width */
                width: 100%;
                margin-top: 10px;
            }

            /* --- Product Detail Modal (Swiper) --- */
            #productModal .swiper-container {
                 width: 100%;
                 max-width: 450px; /* Limit image size */
                 margin: 0 auto 30px;
                 border-radius: 12px;
                 overflow: hidden;
                 box-shadow: 0 5px 15px var(--shadow-color);
            }
            #productModal .swiper-slide {
                 background: var(--background-light);
                 display: flex;
                 justify-content: center;
                 align-items: center;
                 aspect-ratio: 1 / 1;
            }
            #productModal .swiper-slide img {
                 max-width: 90%;
                 max-height: 90%;
                 object-fit: contain;
            }
            #productModal .swiper-pagination-bullet-active {
                background-color: var(--primary-color);
            }
            #productModal .swiper-button-next,
            #productModal .swiper-button-prev {
                color: var(--primary-color);
                transition: transform 0.3s ease;
                --swiper-navigation-size: 30px; /* Adjust size */
            }
             #productModal .swiper-button-next:hover,
             #productModal .swiper-button-prev:hover {
                 transform: scale(1.1);
             }
            #modalContent h2 { /* Product Name */
                font-size: 2.2rem;
                margin-bottom: 15px;
            }
            #modalContent p { /* Product details text */
                font-size: 1rem;
                color: var(--text-medium);
                margin-bottom: 12px;
                line-height: 1.6;
            }
             #modalContent p strong {
                 font-weight: 600;
                 color: var(--text-dark);
             }
             #modalContent .product-price-modal { /* Price in modal */
                 font-size: 1.8rem;
                 color: var(--primary-color);
                 font-weight: 700;
                 margin-bottom: 20px;
                 text-align: center;
             }


            /* Footer Info */
            .footer-info {
                text-align: center;
                margin-top: 50px;
                padding: 20px;
                color: var(--text-medium);
                font-size: 0.85rem;
                border-top: 1px solid var(--border-color);
            }

             /* Utility class for temporary feedback */
            .temp-feedback {
                 position: fixed;
                 bottom: 90px; /* Above nav */
                 left: 50%;
                 transform: translateX(-50%);
                 background-color: var(--secondary-color);
                 color: var(--text-dark);
                 padding: 10px 20px;
                 border-radius: 20px;
                 z-index: 1002; /* Above modals */
                 box-shadow: 0 4px 10px var(--shadow-color);
                 opacity: 0; /* Start hidden */
                 transition: opacity 0.5s ease-out;
                 pointer-events: none; /* Don't block clicks */
             }
             .temp-feedback.show {
                 opacity: 1;
             }


            /* Responsive Adjustments */
            @media (max-width: 768px) {
                :root { --header-height: 160px; } /* Adjust header height */
                body { padding-top: var(--header-height); }
                .header h1 { font-size: 2.0rem; }
                .header-logo { width: 70px; height: 70px;}
                .product { border-radius: 10px; }
                .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }
                .modal-content { width: 95%; padding: 25px 20px; }
                #productModal .swiper-container { max-width: 90%; }
                .cart-actions { flex-direction: column; }
                .bottom-nav i { font-size: 1.4rem; }
                .bottom-nav span { font-size: 0.7rem; }
                #cart-button { width: 50px; height: 50px; font-size: 1.4rem; bottom: 75px; right: 15px; }
                #allCategoriesButton { bottom: 75px; left: 15px; padding: 8px 15px; font-size: 0.8rem; }
            }
             @media (max-width: 480px) {
                 :root { --header-height: 150px; } /* Adjust header height */
                 body { padding-top: var(--header-height); }
                 .header { padding: 20px 15px; }
                 .header h1 { font-size: 1.8rem; }
                 .header-logo { width: 60px; height: 60px;}
                 .motto { font-size: 0.8rem; }
                 .filters-container { gap: 8px; }
                 .category-filter { padding: 8px 15px; font-size: 0.8rem; }
                 #search-input { padding: 12px 20px; font-size: 0.9rem; }
                 .products-grid { grid-template-columns: 1fr; gap: 20px; } /* Single column */
                 .product h2 { font-size: 1.1rem; }
                 .product-price { font-size: 1.1rem; }
                 .product-description { font-size: 0.8rem; }
                 .modal-content { padding: 20px 15px; }
                 .modal-content h2 { font-size: 1.5rem; }
                 .cart-item { flex-direction: column; align-items: flex-start; gap: 10px; }
                 .cart-item img { width: 60px; height: 60px; }
             }

        </style>
    </head>
    <body>
         <!-- Temporary feedback message container -->
         <div id="tempFeedback" class="temp-feedback"></div>

        <div class="container">
            <header class="header">
                <img src="{{ LOGO_URL }}" alt="Логотип Ultra Flowers" class="header-logo" id="headerLogo">
                <h1>Ultra Flowers</h1>
                <p class="motto">Создаем красоту для каждого момента.</p>
            </header>

            <section class="filters-section">
                <div class="filters-container">
                    <button class="category-filter active" data-category="all">Все Цветы ({{ products|length }})</button>
                    {% for category in categories %}
                    <button class="category-filter" data-category="{{ category }}">{{ category }} ({{ category_counts.get(category, 0) }})</button> {# Use .get for safety #}
                    {% endfor %}
                    <button id="allCategoriesButton" class="category-filter" onclick="showAllCategories()">Все Категории</button>
                </div>
                <div class="search-container">
                    <input type="text" id="search-input" placeholder="Найти букеты, композиции...">
                </div>
            </section>

            <main class="products-grid" id="products-grid">
                {% for product in products %}
                {% if product is mapping %} {# Check if product is a dictionary-like object #}
                <div class="product"
                     onclick="openModal({{ loop.index0 }})"
                     data-name="{{ product.get('name', '')|lower }}"
                     data-description="{{ product.get('description', '')|lower }}"
                     data-category="{{ product.get('category', 'Без категории') }}"
                     data-id="{{ loop.index0 }}">
                    <div class="product-image">
                        {% set photos = product.get('photos', []) %}
                        {% if photos and photos is iterable and photos|length > 0 %}
                            <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photos[0] }}"
                                 alt="{{ product.get('name', 'Фото товара') }}"
                                 loading="lazy"
                                 onerror="this.onerror=null; this.src='https://via.placeholder.com/300/E0E0E0/BDBDBD?text=Фото+ошибка';"> {# Added onerror handler #}
                        {% else %}
                             <img src="https://via.placeholder.com/300/E0E0E0/BDBDBD?text=Нет+фото" alt="Нет фото">
                        {% endif %}
                    </div>
                    <div class="product-info">
                        <div> <!-- Wrapper for top info -->
                            <h2>{{ product.get('name', 'Без названия') }}</h2>
                            <div class="product-price">{{ product.get('price', 0)|int }} ₸</div> {# Format price #}
                            <p class="product-description">{{ product.get('description', 'Описание отсутствует.') }}</p>
                        </div>
                         <div class="product-interaction">
                            {% if logged_in %}
                                <div class="quantity-control">
                                    <button class="quantity-button" onclick="changeProductQuantity(event, {{ loop.index0 }}, -1)" aria-label="Уменьшить количество">-</button>
                                    <span class="quantity" id="quantity-{{ loop.index0 }}">0</span>
                                    <button class="quantity-button" onclick="changeProductQuantity(event, {{ loop.index0 }}, 1)" aria-label="Увеличить количество">+</button>
                                </div>
                            {% else %}
                                <p class="login-prompt">
                                    <a href="#" onclick="openProfileModal(); return false;">Войдите</a>, чтобы заказать и получить кэшбэк!
                                </p>
                            {% endif %}
                         </div>
                    </div>
                </div>
                {% else %}
                 <!-- Optionally log or display a message for invalid product data -->
                 <!-- <p>Ошибка: Некорректные данные товара</p> -->
                {% endif %}
                {% endfor %}
                {% if not products %}
                  <p style="grid-column: 1 / -1; text-align: center; color: var(--text-medium); font-size: 1.1rem; padding: 40px 0;">Извините, в данный момент нет доступных букетов.</p>
                {% endif %}
            </main>

            <footer class="footer-info">
                © {{ current_year }} Ultra Flowers. Доставка цветов с любовью.
            </footer>
        </div>

        <!-- Product Detail Modal -->
        <div id="productModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
                <div id="modalContent">
                    <!-- Product details will be loaded here -->
                </div>
            </div>
        </div>

        <!-- Options Modal -->
        <div id="optionsModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('optionsModal')" aria-label="Закрыть">×</span>
                <h2>Параметры заказа</h2>
                <label for="quantityInput" style="text-align: center;">Количество:</label>
                <div class="quantity-input-container">
                    <button class="quantity-button" onclick="changeQuantity(-1)" aria-label="Уменьшить">-</button>
                    <input type="number" id="quantityInput" min="1" value="1" style="width: 60px; text-align:center;"> {# Simpler input style #}
                    <button class="quantity-button" onclick="changeQuantity(1)" aria-label="Увеличить">+</button>
                </div>

                <div id="optionsList">
                     <!-- Dynamic options checkboxes will appear here -->
                </div>

                <label for="orderComment">Комментарий:</label>
                <textarea id="orderComment" rows="3" placeholder="Особые пожелания к заказу (например, открытка, цвет ленты)..."></textarea>

                <label for="deliveryTime">Время доставки:</label>
                <select id="deliveryTime">
                    <option value="now">Как можно скорее</option>
                    {% for i in range(1, 9) %} {# Adjusted range for more realistic delivery slots #}
                    <option value="{{ i * 60 }}">~ {{ i }} час(а/ов)</option> {# More descriptive text #}
                    {% endfor %}
                     <option value="specify">Указать время (в комментарии)</option>
                </select>

                <button class="button" onclick="confirmAddToCart()" style="width: 100%; margin-top: 20px;">Добавить в корзину</button>
            </div>
        </div>

        <!-- Cart Modal -->
        <div id="cartModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
                <h2>Ваша корзина</h2>
                <div id="cartContent">
                   <!-- Cart items will be loaded here -->
                   <p style="text-align: center; color: var(--text-medium);">Ваша корзина пуста.</p>
                </div>
                <div id="cartTotalsSection" style="display: none;"> {# Hide totals if cart is empty #}
                    {% if logged_in %}
                    <div id="redeemPointsSection" style="display: {% if user_points > 0 %}flex{% else %}none{% endif %};"> {# Control visibility based on points #}
                        <input type="checkbox" id="redeemPointsCheckbox" onchange="togglePointsRedeemInput()">
                        <label for="redeemPointsCheckbox">Списать <span id="availablePoints">{{ user_points }}</span> баллов:</label>
                        <input type="number" id="pointsToRedeemInput" min="0" value="0" style="display:none;" max="{{ user_points }}"> {# Added max attribute #}
                    </div>
                    {% endif %}
                    <div class="cart-total">
                        <strong>Итого: <span id="cartTotal">0</span> ₸</strong>
                    </div>
                    <div class="cart-actions">
                        <button class="button button-secondary" onclick="clearCart()">Очистить корзину</button>
                        <button class="button" onclick="orderViaWhatsApp()">Оформить заказ в WhatsApp</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Profile/Auth Modals -->
        <div id="profileModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('profileModal')" aria-label="Закрыть">×</span>
                <h2>Профиль</h2>
                {% if logged_in %}
                <div id="profileContent" class="profile-info">
                     <p><strong>Логин:</strong> {{ user_login }}</p>
                     <p><strong>Баллы:</strong> <span id="profilePoints">{{ user_points }}</span></p>
                     <p><strong>Телефон:</strong> <span id="profilePhone">{{ user_profile.get('phone', 'Не указан') }}</span></p> {# Use .get for safety #}
                     <p><strong>Адрес:</strong> <span id="profileAddress">{{ user_profile.get('address', 'Не указан') }}</span></p> {# Use .get for safety #}
                    <div class="profile-actions">
                        <button class="button button-secondary" onclick="openEditProfileModal()">Редактировать</button>
                        <button class="button button-danger" onclick="logout()">Выйти</button>
                    </div>
                </div>
                {% else %}
                <div id="authContent">
                    <p style="text-align: center; margin-bottom: 25px; color: var(--text-medium);">Войдите или зарегистрируйтесь, чтобы управлять заказами и копить баллы.</p>
                    <div class="auth-buttons">
                        <button class="button" onclick="openLoginModal()">Войти</button>
                        <button class="button button-secondary" onclick="openRegisterModal()">Регистрация</button>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        <div id="registerModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('registerModal')" aria-label="Закрыть">×</span>
                <h2>Регистрация</h2>
                <form id="registerForm" class="auth-form">
                    <label for="registerLogin">Логин:</label>
                    <input type="text" id="registerLogin" name="registerLogin" required>
                    <label for="registerPassword">Пароль (мин. 6 символов):</label>
                    <input type="password" id="registerPassword" name="registerPassword" required minlength="6">
                    <label for="registerPhone">Телефон:</label>
                    <input type="tel" id="registerPhone" name="registerPhone" placeholder="+7 (___) ___-__-__" required>
                    <label for="registerAddress">Адрес доставки:</label>
                    <input type="text" id="registerAddress" name="registerAddress" placeholder="Город, улица, дом, квартира" required>
                    <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Зарегистрироваться</button>
                    <div id="registerMessage"></div>
                </form>
            </div>
        </div>

        <div id="loginModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('loginModal')" aria-label="Закрыть">×</span>
                <h2>Вход</h2>
                <form id="loginForm" class="auth-form">
                    <label for="loginUsername">Логин:</label>
                    <input type="text" id="loginUsername" name="loginUsername" required>
                    <label for="loginPassword">Пароль:</label>
                    <input type="password" id="loginPassword" name="loginPassword" required>
                    <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Войти</button>
                    <div id="loginMessage"></div>
                </form>
            </div>
        </div>

        <div id="editProfileModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('editProfileModal')" aria-label="Закрыть">×</span>
                <h2>Редактировать профиль</h2>
                <form id="editProfileForm" class="auth-form">
                     <label for="editPhone">Телефон:</label>
                     <input type="tel" id="editPhone" name="editPhone" required value="{{ user_profile.get('phone', '') if user_profile else '' }}"> {# Pre-fill value #}
                     <label for="editAddress">Адрес доставки:</label>
                     <input type="text" id="editAddress" name="editAddress" required value="{{ user_profile.get('address', '') if user_profile else '' }}"> {# Pre-fill value #}
                    <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Сохранить</button>
                    <div id="editProfileMessage"></div>
                </form>
            </div>
        </div>

         <!-- News Modal -->
        <div id="newsModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('newsModal')" aria-label="Закрыть">×</span>
                <h2>Новости и Акции</h2>
                <div id="newsContent">
                {% if news_for_template %}
                    {% for news_item in news_for_template %}
                     {% if news_item is mapping %} {# Check if news_item is a dictionary #}
                        <div class="news-item">
                            {% set photo = news_item.get('photo') %}
                            {% if photo %}
                               <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
                                    alt="{{ news_item.get('title', 'Фото новости') }}"
                                    onerror="this.style.display='none'"> {# Hide image on error #}
                            {% endif %}
                            <h3>{{ news_item.get('title', 'Без заголовка') }}</h3>
                            <p>{{ news_item.get('text', '') | safe }}</p> {# Allow basic HTML in news text #}
                            {# --- UPDATED DATE FORMATTING using the registered filter --- #}
                            {% set timestamp_dt = news_item.timestamp | format_iso_datetime %}
                            {% if timestamp_dt %}
                                <p class="timestamp-date">Опубликовано: {{ timestamp_dt.strftime('%d.%m.%Y %H:%M') }} UTC</p>
                            {% endif %}
                            {% set expiry = news_item.get('expiry') %}
                            {% if expiry %}
                               {% set expiry_dt = expiry | format_iso_datetime %}
                               {% if expiry_dt %}
                                  <p class="expiry-date">Актуально до: {{ expiry_dt.strftime('%d.%m.%Y %H:%M') }} UTC</p>
                               {% else %}
                                  <!-- Optional: Show 'Invalid date' if needed -->
                                  <!-- <p class="expiry-date">Актуально до: Неверная дата</p> -->
                               {% endif %}
                            {% endif %}
                            {# --- END UPDATED DATE FORMATTING --- #}
                        </div>
                     {% endif %} {# End check if news_item is mapping #}
                    {% endfor %}
                {% else %}
                    <p style="text-align: center; color: var(--text-medium);">Пока нет новостей.</p>
                {% endif %}
                </div>
            </div>
        </div>

         <!-- Cashback Info Modal -->
         <div id="cashbackModal" class="modal">
             <div class="modal-content">
                 <span class="close" onclick="closeModal('cashbackModal')" aria-label="Закрыть">×</span>
                 <h2>Программа лояльности</h2>
                 {% if logged_in %}
                 <p>Вы получаете <strong>5% кэшбэка</strong> баллами с каждого оплаченного заказа.</p>
                 <p>Ваш текущий баланс: <strong id="cashbackPoints">{{ user_points }}</strong> баллов.</p>
                 <p>Баллами можно оплатить часть следующих заказов (до полной суммы минус 1 ₸).</p>
                 {% else %}
                 <p><a href="#" onclick="openProfileModal();closeModal('cashbackModal'); return false;" style="color: var(--primary-color); font-weight: 600;">Авторизуйтесь</a>, чтобы копить баллы и узнавать о специальных предложениях!</p>
                 <p>Зарегистрированные пользователи получают 5% кэшбэка баллами с каждого заказа.</p>
                 {% endif %}
             </div>
         </div>


        <!-- Floating Cart Button -->
        <button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину"> {# <<< FIXED: Calls openCartModal now #}
             <i class="fas fa-shopping-bag"></i>
             <span id="cart-count" style="display: none;">0</span> {# Cart count badge #}
        </button>

        <!-- Bottom Navigation Bar -->
        <nav class="bottom-nav">
            <a href="tel:+77077777777" class="nav-item"> {# Replace with actual phone #}
                <i class="fas fa-phone-alt"></i>
                <span>Звонок</span>
            </a>
            <button type="button" class="nav-item" onclick="openCashbackModal()">
                <i class="fas fa-gift"></i>
                <span>Кэшбэк</span>
            </button>
            <button type="button" class="nav-item" onclick="openProfileModal()">
                <i class="fas fa-user-circle"></i>
                <span>Профиль</span>
            </button>
            <button type="button" class="nav-item" onclick="openNewsModal()">
                <i class="fas fa-newspaper"></i>
                <span>Новости</span>
            </button>
        </nav>


        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> {# Updated jQuery version #}
        {# <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script> #} {# Popper not strictly needed for current setup #}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
        <script>
             // Wrap all JS code in a ready function to ensure DOM is loaded
             $(document).ready(function() {

                const products = {{ products|tojson }};
                let selectedProductIndex = null;
                let currentOptionsQuantity = 1; // Quantity specifically for the options modal
                let availablePoints = {{ user_points }};
                let productQuantities = {}; // Stores quantity { productIndex: quantity } for display on cards
                const repoId = "{{ repo_id }}";
                 // Ensure userProfile is a valid object or null
                 let userProfile = {{ user_profile|tojson if user_profile else 'null' }};
                 if (typeof userProfile !== 'object' || userProfile === null) {
                     userProfile = null;
                 }


                // --- Modal Management ---
                window.openModal = function(modalIdOrIndex) { // Make functions global for inline onclick
                     // Check if it's an index (number) or modal ID (string)
                     if (typeof modalIdOrIndex === 'number') {
                        // It's a product index
                        if (modalIdOrIndex >= 0 && modalIdOrIndex < products.length) {
                             loadProductDetails(modalIdOrIndex);
                             $('#productModal').fadeIn(200); // Use fadeIn for smoother opening
                             $('body').css('overflow', 'hidden'); // Prevent background scroll
                        } else {
                             console.error("Invalid product index:", modalIdOrIndex);
                             showTemporaryFeedback("Ошибка: Товар не найден.", true);
                        }
                     } else if (typeof modalIdOrIndex === 'string') {
                        // It's a modal ID
                        const modal = $('#' + modalIdOrIndex);
                        if (modal.length) {
                            modal.fadeIn(200);
                            $('body').css('overflow', 'hidden'); // Prevent background scroll
                            // If opening cart, refresh its content
                            if (modalIdOrIndex === 'cartModal') {
                                 renderCart();
                            }
                            // If opening edit profile, pre-fill if not already done by template
                            if (modalIdOrIndex === 'editProfileModal' && userProfile) {
                                $('#editPhone').val(userProfile.phone || '');
                                $('#editAddress').val(userProfile.address || '');
                            }

                        } else {
                             console.error("Modal with ID not found:", modalIdOrIndex);
                        }
                     }
                }

                window.closeModal = function(modalId) {
                    const modal = $('#' + modalId);
                    if(modal.length) {
                         modal.fadeOut(200); // Use fadeOut
                    }
                    // Restore background scroll only if no other modals are visible
                    // Use timeout to allow fadeOut animation to complete before check
                     setTimeout(() => {
                         if ($('.modal:visible').length === 0) {
                             $('body').css('overflow', 'auto');
                         }
                     }, 250);

                    // Reset specific modal states if needed
                    if (modalId === 'optionsModal') {
                        currentOptionsQuantity = 1;
                        $('#quantityInput').val(1);
                        $('#orderComment').val('');
                        $('#optionsList').html(''); // Clear options
                    }
                     // Clear messages in auth modals
                    if (['registerModal', 'loginModal', 'editProfileModal'].includes(modalId)) {
                         const messageDivId = '#' + modalId.replace('Modal', 'Message');
                         $(messageDivId).text('').removeClass('success error').hide(); // Hide message div
                    }
                }

                // Close modal if clicking outside the content area
                 $('.modal').on('click', function(event) {
                    if ($(event.target).is('.modal')) { // Check if the click is directly on the modal background
                         closeModal(this.id);
                    }
                 });
                  // Close modal on Escape key press
                 $(document).on('keydown', function(event) {
                     if (event.key === "Escape") {
                         $('.modal:visible').each(function() { // Close all visible modals
                             closeModal(this.id);
                         });
                     }
                 });


                // --- Product Details ---
                function loadProductDetails(index) {
                     if (index < 0 || index >= products.length || typeof products[index] !== 'object' || products[index] === null) {
                         $('#modalContent').html('<p>Ошибка: Товар не найден или данные некорректны.</p>');
                         return;
                     }
                     const product = products[index];
                     let photosHtml = '';
                     const photos = product.photos || [];

                     if (photos.length > 0) {
                         photos.forEach(photo => {
                             const photoUrl = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${photo}`;
                             photosHtml += `
                                 <div class="swiper-slide">
                                     <div class="swiper-zoom-container">
                                         <img src="${photoUrl}" alt="${product.name || 'Фото товара'}" onerror="this.onerror=null; this.src='https://via.placeholder.com/450/E0E0E0/BDBDBD?text=Фото+ошибка';">
                                     </div>
                                 </div>`;
                         });
                     } else {
                         photosHtml = `<div class="swiper-slide"><img src="https://via.placeholder.com/450/E0E0E0/BDBDBD?text=Нет+фото" alt="Нет фото"></div>`;
                     }

                     let optionsText = 'Нет';
                     const options = product.options || [];
                      if (options.length > 0) {
                          optionsText = options.map(opt => `${opt.name || '?'} (+${opt.price || 0} ₸)`).join(', ');
                      }


                     const detailHtml = `
                         <h2>${product.name || 'Без названия'}</h2>
                         <div class="swiper-container product-swiper">
                             <div class="swiper-wrapper">${photosHtml}</div>
                             <div class="swiper-pagination"></div>
                             <div class="swiper-button-next"></div>
                             <div class="swiper-button-prev"></div>
                         </div>
                         <p class="product-price-modal">${(product.price || 0)} ₸</p>
                         <p><strong>Категория:</strong> ${product.category || 'Без категории'}</p>
                         <p><strong>Описание:</strong> ${product.description || 'Описание отсутствует.'}</p>
                         <p><strong>Доступные опции:</strong> ${optionsText}</p>
                         {# Add Add-to-cart button directly in product modal? Maybe better to keep it separate #}
                     `;
                     $('#modalContent').html(detailHtml);
                     initializeSwiper('#productModal .product-swiper'); // Pass specific selector
                 }

                 function initializeSwiper(selector) {
                     // Destroy previous instance if exists
                     if (window.productSwiperInstance) {
                         window.productSwiperInstance.destroy(true, true);
                         window.productSwiperInstance = null;
                     }
                     // Ensure container exists before initializing
                      const swiperContainer = $(selector);
                      if (swiperContainer.length > 0) {
                         const slides = swiperContainer.find('.swiper-slide');
                         window.productSwiperInstance = new Swiper(swiperContainer[0], { // Get DOM element
                             slidesPerView: 1,
                             spaceBetween: 10,
                             loop: slides.length > 1, // Loop only if more than 1 slide
                             grabCursor: true,
                             pagination: { el: swiperContainer.find('.swiper-pagination')[0], clickable: true },
                             navigation: { nextEl: swiperContainer.find('.swiper-button-next')[0], prevEl: swiperContainer.find('.swiper-button-prev')[0] },
                             zoom: { maxRatio: 3, toggle: true }, // Enable zoom
                             keyboard: true, // Enable keyboard navigation
                         });
                     }
                 }


                // --- Options Modal Logic ---
                function openOptionsModal(index) {
                     if (!{{ logged_in|lower }}) {
                          // Close product modal if open before showing login
                          closeModal('productModal');
                          openModal('profileModal'); // Redirect to login/register if not logged in
                          return;
                     }
                     if (index < 0 || index >= products.length || typeof products[index] !== 'object' || products[index] === null) {
                          showTemporaryFeedback("Ошибка: Не удалось загрузить опции товара.", true);
                          return;
                     }

                     selectedProductIndex = index;
                     const product = products[index];
                     const optionsList = $('#optionsList');
                     optionsList.html(''); // Clear previous options

                     const options = product.options || [];
                     if (options.length > 0) {
                          optionsList.append('<label>Дополнительные опции:</label>'); // Use append
                          options.forEach((option, i) => {
                             // Check if option is valid
                             if (typeof option === 'object' && option !== null && 'name' in option && 'price' in option) {
                                 optionsList.append(`
                                     <div class="options-checkbox">
                                         <input type="checkbox" class="option-checkbox" id="option-${index}-${i}" data-name="${option.name}" data-price="${option.price || 0}">
                                         <label for="option-${index}-${i}">${option.name} (+${option.price || 0} ₸)</label> {# Label associated with input #}
                                     </div>
                                 `);
                             }
                         });
                      } else {
                          optionsList.append('<p style="font-size: 0.9em; color: var(--text-medium);">Дополнительные опции не доступны.</p>');
                      }

                     // Reset quantity input for this modal instance
                      // Use the quantity from the card if > 0, otherwise default to 1
                      currentOptionsQuantity = productQuantities[index] > 0 ? productQuantities[index] : 1;
                      $('#quantityInput').val(currentOptionsQuantity);
                      $('#orderComment').val(''); // Clear comment
                      $('#deliveryTime').val('now'); // Reset delivery time

                     // Close product modal before opening options modal
                      closeModal('productModal');
                      openModal('optionsModal');
                 }
                window.openOptionsModal = openOptionsModal; // Make global

                  window.changeQuantity = function(change) { // Make global
                     const quantityInput = $('#quantityInput');
                     let currentValue = parseInt(quantityInput.val()) || 1;
                     currentOptionsQuantity = Math.max(1, currentValue + change); // Ensure quantity is at least 1
                     quantityInput.val(currentOptionsQuantity);
                  }

                // --- Cart Logic ---
                 function getCart() {
                     try {
                         const cartData = localStorage.getItem('cart');
                         const cart = JSON.parse(cartData || '[]');
                         // Basic validation: ensure it's an array
                         return Array.isArray(cart) ? cart : [];
                     } catch (e) {
                         console.error("Error parsing cart from localStorage:", e);
                         return []; // Return empty array on error
                     }
                 }

                 function saveCart(cart) {
                     try {
                          // Ensure cart is an array before saving
                          if (!Array.isArray(cart)) {
                              console.error("Attempted to save non-array as cart:", cart);
                              cart = []; // Reset to empty array
                          }
                         localStorage.setItem('cart', JSON.stringify(cart));
                         updateCartButton(); // Update count and visibility
                         if ($('#cartModal').is(':visible')) { // Only re-render cart modal if it's currently open
                            renderCart();
                         }
                     } catch (e) {
                         console.error("Error saving cart to localStorage:", e);
                         showTemporaryFeedback("Ошибка сохранения корзины", true);
                     }
                 }

                window.confirmAddToCart = function() { // Make global
                    if (selectedProductIndex === null) return;
                     if (selectedProductIndex < 0 || selectedProductIndex >= products.length || typeof products[selectedProductIndex] !== 'object') {
                         showTemporaryFeedback("Ошибка: Выбранный товар недействителен.", true);
                         return;
                     }

                    const quantity = parseInt($('#quantityInput').val()) || 1;
                    if (quantity <= 0) {
                        showTemporaryFeedback("Укажите количество больше 0", true);
                        return;
                    }

                    let cart = getCart();
                    const product = products[selectedProductIndex];

                    // --- Get selected options ---
                    const selectedOptions = [];
                     $('#optionsList .option-checkbox:checked').each(function() {
                         selectedOptions.push({
                            name: $(this).data('name'),
                            price: parseFloat($(this).data('price')) || 0
                         });
                     });

                    const comment = $('#orderComment').val().trim();
                    const deliveryTime = $('#deliveryTime').val();

                    // Create a unique ID for this specific cart item instance (allows same product with different options/comments)
                     const cartItemId = `${selectedProductIndex}-${Date.now()}`; // Use index + timestamp

                     // Basic check for product validity before adding
                     if (!product || typeof product.name === 'undefined' || typeof product.price === 'undefined') {
                          showTemporaryFeedback("Ошибка: Не удалось добавить товар (некорректные данные).", true);
                          return;
                     }

                    cart.push({
                        id: cartItemId,
                        productIndex: selectedProductIndex, // Store original product index
                        name: product.name,
                        basePrice: parseFloat(product.price) || 0, // Ensure basePrice is a number
                        photo: (product.photos && product.photos.length > 0) ? product.photos[0] : '',
                        quantity: quantity,
                        options: selectedOptions,
                        comment: comment,
                        deliveryTime: deliveryTime
                    });

                    saveCart(cart);
                    closeModal('optionsModal');
                    // Update quantity on the product card visually
                    productQuantities[selectedProductIndex] = quantity; // Update visual quantity tracker
                     updateProductCardQuantity(selectedProductIndex, quantity);

                     // Briefly show feedback (e.g., item added)
                     showTemporaryFeedback("Добавлено в корзину!");
                }

                 function showTemporaryFeedback(message, isError = false) {
                     const feedbackDiv = $('#tempFeedback');
                     feedbackDiv.text(message);
                     feedbackDiv.removeClass('show error success'); // Remove previous classes

                     if (isError) {
                         feedbackDiv.addClass('error'); // You might want to style .error differently
                         feedbackDiv.css('background-color', 'var(--accent-color)'); // Example error style
                     } else {
                         feedbackDiv.addClass('success');
                         feedbackDiv.css('background-color', 'var(--secondary-color)'); // Default success style
                     }

                     feedbackDiv.addClass('show');

                     // Clear previous timeouts if any
                     if (window.feedbackTimeout) {
                         clearTimeout(window.feedbackTimeout);
                     }
                     if (window.feedbackRemoveTimeout) {
                          clearTimeout(window.feedbackRemoveTimeout);
                     }

                     window.feedbackTimeout = setTimeout(() => {
                         feedbackDiv.removeClass('show');
                     }, 2500); // Show for 2.5 seconds
                 }


                 function updateCartButton() {
                     const cart = getCart();
                     const cartButton = $('#cart-button');
                     const cartCountBadge = $('#cart-count');
                     let totalItems = 0;
                     // Ensure each item has a valid quantity
                     cart.forEach(item => {
                         totalItems += parseInt(item.quantity) || 0;
                     });


                     if (totalItems > 0) {
                         cartButton.css('display', 'flex'); // Show button using jQuery
                         cartCountBadge.text(totalItems).show(); // Show badge
                     } else {
                         cartButton.hide(); // Hide button
                         cartCountBadge.hide(); // Hide badge
                     }
                 }


                function renderCart() {
                    const cart = getCart();
                    const cartContent = $('#cartContent');
                    const cartTotalsSection = $('#cartTotalsSection');
                    let total = 0;
                    let cartHtml = '';

                    if (cart.length === 0) {
                        cartHtml = '<p style="text-align: center; color: var(--text-medium);">Ваша корзина пуста.</p>';
                        cartTotalsSection.hide(); // Hide totals
                    } else {
                        cart.forEach(item => {
                             // Ensure item structure is valid
                             if (typeof item !== 'object' || item === null || !item.id) {
                                 console.warn("Skipping invalid cart item:", item);
                                 return; // Skip this item
                             }

                             const basePrice = parseFloat(item.basePrice) || 0;
                             const quantity = parseInt(item.quantity) || 0;
                             const options = Array.isArray(item.options) ? item.options : [];

                             const optionsTotal = options.reduce((sum, opt) => sum + (parseFloat(opt.price) || 0), 0);
                             const itemTotal = (basePrice + optionsTotal) * quantity;
                             total += itemTotal;

                             let optionsText = '';
                             if (options.length > 0) {
                                 optionsText = '<p>Опции: ' + options.map(o => `${o.name || '?'} (+${o.price || 0} ₸)`).join(', ') + '</p>';
                             }
                             let commentText = item.comment ? `<p>Комментарий: ${$('<div/>').text(item.comment).html()}</p>` : ''; // Basic HTML escaping for comment
                             let deliveryValue = item.deliveryTime || 'now';
                             let deliveryDisplay = 'Как можно скорее';
                             if(deliveryValue === 'specify') {
                                 deliveryDisplay = 'Указано в комментарии';
                             } else if (deliveryValue !== 'now') {
                                 const hours = parseInt(deliveryValue) / 60;
                                 deliveryDisplay = `~ ${hours} час(а/ов)`;
                             }
                             let deliveryText = `<p>Доставка: ${deliveryDisplay}</p>`;
                             const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/80/E0E0E0/BDBDBD?text=Нет+фото';


                             cartHtml += `
                                <div class="cart-item" data-item-id="${item.id}">
                                    <img src="${photoUrl}" alt="${item.name || 'Фото товара'}" onerror="this.onerror=null; this.src='https://via.placeholder.com/80/E0E0E0/BDBDBD?text=Ошибка'; this.style.width='80px'; this.style.height='80px';">
                                    <div class="cart-item-details">
                                        <strong>${item.name || 'Без названия'}</strong>
                                        <p>Цена: ${basePrice} ₸ x ${quantity}</p>
                                        ${optionsText}
                                        ${commentText}
                                        ${deliveryText}
                                    </div>
                                    <span class="cart-item-price">${itemTotal.toFixed(0)} ₸</span>
                                    <button onclick="removeFromCart('${item.id}')" class="button-secondary" style="padding: 5px 10px; font-size: 0.8rem; border-radius: 50%; line-height: 1; margin-left: 10px;" aria-label="Удалить товар">×</button>
                                </div>
                            `;
                        });
                        cartTotalsSection.show(); // Show totals
                    }

                    cartContent.html(cartHtml);
                    $('#cartTotal').text(total.toFixed(0)); // Show total price

                    // Update available points display if logged in
                    if ({{ logged_in|lower }}) {
                         $('#availablePoints').text(availablePoints);
                         const redeemSection = $('#redeemPointsSection');
                          if (availablePoints > 0) {
                              redeemSection.css('display', 'flex'); // Show if points > 0
                          } else {
                              redeemSection.hide(); // Hide if no points
                          }
                         // Update max value for points input
                         $('#pointsToRedeemInput').attr('max', availablePoints);
                    } else {
                        $('#redeemPointsSection').hide(); // Hide for non-logged in users
                    }

                    // Reset redeem checkbox and input state each time cart is rendered
                     const redeemCheckbox = $('#redeemPointsCheckbox');
                     const pointsInput = $('#pointsToRedeemInput');
                     redeemCheckbox.prop('checked', false); // Uncheck checkbox
                     pointsInput.val(0).hide(); // Reset value and hide input

                }
                window.renderCart = renderCart; // Make global

                 window.removeFromCart = function(itemId) { // Make global
                     let cart = getCart();
                     const initialLength = cart.length;
                     cart = cart.filter(item => item.id !== itemId);
                     if (cart.length < initialLength) {
                         // Find which product index this cart item corresponded to
                         // This is tricky if multiple items can be from the same product index
                         // Simple approach: Assume removing from cart doesn't reset card quantity display for now
                         saveCart(cart); // This will re-render the cart
                         showTemporaryFeedback("Товар удален из корзины");
                     }
                 }

                window.clearCart = function() { // Make global
                    if (confirm("Вы уверены, что хотите очистить корзину?")) {
                        localStorage.removeItem('cart');
                        productQuantities = {}; // Reset card quantities tracker
                         updateAllProductCardQuantities(); // Update visuals on cards
                        saveCart([]); // Save empty cart and re-render cart modal
                        closeModal('cartModal');
                        showTemporaryFeedback("Корзина очищена");
                    }
                }

                 function updateAllProductCardQuantities() {
                     $('.product').each(function() {
                         const index = parseInt($(this).data('id'));
                         if (!isNaN(index)) {
                              updateProductCardQuantity(index, productQuantities[index] || 0);
                         }
                     });
                 }


                window.togglePointsRedeemInput = function() { // Make global
                    const redeemCheckbox = $('#redeemPointsCheckbox');
                    const pointsInput = $('#pointsToRedeemInput');
                    if (redeemCheckbox.is(':checked')) {
                        pointsInput.val(availablePoints).show(); // Default to max available points? Or 0? Let's default to max.
                    } else {
                        pointsInput.val(0).hide(); // Reset value and hide
                    }
                    pointsInput.attr('max', availablePoints); // Ensure max is updated
                }

                window.orderViaWhatsApp = function() { // Make global
                    const cart = getCart();
                    if (cart.length === 0) {
                        showTemporaryFeedback("Ваша корзина пуста!", true);
                        return;
                    }
                     if (!userProfile) {
                         showTemporaryFeedback("Пожалуйста, войдите, чтобы оформить заказ.", true);
                          closeModal('cartModal');
                         openModal('profileModal');
                         return;
                     }

                    let total = 0;
                    let orderText = "🌷 *Новый Заказ - Ultra Flowers* 🌷%0A%0A";
                    let orderItemsForHistory = [];

                    cart.forEach((item, index) => {
                         const basePrice = parseFloat(item.basePrice) || 0;
                         const quantity = parseInt(item.quantity) || 0;
                         const options = Array.isArray(item.options) ? item.options : [];

                         const optionsTotal = options.reduce((sum, opt) => sum + (parseFloat(opt.price) || 0), 0);
                         const itemTotal = (basePrice + optionsTotal) * quantity;
                         total += itemTotal;

                         orderText += `*${index + 1}. ${item.name || 'Без названия'}* (${basePrice} ₸) x ${quantity}`;
                         if (options.length > 0) {
                              orderText += "%0A   Опции: " + options.map(o => `${o.name || '?'} (+${o.price || 0} ₸)`).join(', ');
                         }
                         if (item.comment) {
                              orderText += `%0A   Комментарий: ${encodeURIComponent(item.comment)}`; // Encode comment
                         }
                         let deliveryValue = item.deliveryTime || 'now';
                         let deliveryDisplay = 'Как можно скорее';
                         if(deliveryValue === 'specify') {
                             deliveryDisplay = 'Указано в комментарии';
                         } else if (deliveryValue !== 'now') {
                             const hours = parseInt(deliveryValue) / 60;
                             deliveryDisplay = `~ ${hours} час(а/ов)`;
                         }
                         orderText += `%0A   Доставка: ${deliveryDisplay}`;
                         orderText += `%0A   *Сумма по позиции:* ${itemTotal.toFixed(0)} ₸%0A%0A`; // Item subtotal

                         orderItemsForHistory.push({
                             name: item.name || 'Без названия',
                             quantity: quantity,
                             basePrice: basePrice,
                             options: options,
                             comment: item.comment,
                             deliveryTime: deliveryValue,
                             itemTotal: itemTotal
                         });
                    });


                    let redeemedPoints = 0;
                     const redeemCheckbox = $('#redeemPointsCheckbox');
                     if (redeemCheckbox.is(':checked')) {
                        redeemedPoints = parseInt($('#pointsToRedeemInput').val()) || 0;

                        if (redeemedPoints <= 0) {
                             // Don't redeem if points are zero or negative
                             redeemedPoints = 0;
                             finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, redeemedPoints);
                             return;
                        }

                        if (redeemedPoints > availablePoints) {
                            showTemporaryFeedback(`Недостаточно баллов! Доступно: ${availablePoints}`, true);
                            $('#pointsToRedeemInput').val(availablePoints); // Correct input
                            return;
                        }
                        // Allow redeeming points up to total amount - 1 (leave 1 KZT to pay)
                         const maxRedeemable = total > 1 ? Math.floor(total - 1) : 0;
                         if (redeemedPoints > maxRedeemable) {
                             const correctedRedeem = Math.min(availablePoints, maxRedeemable);
                             showTemporaryFeedback(`Максимальное списание: ${correctedRedeem} ₸. Скорректировано.`, true);
                             $('#pointsToRedeemInput').val(correctedRedeem);
                             redeemedPoints = correctedRedeem;
                             if (redeemedPoints <= 0) {
                                 finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, 0); // Finalize without redemption
                                 return;
                             }
                         }

                        // Proceed with redeeming points via AJAX
                        $.post('/redeem_points', { points: redeemedPoints })
                             .done(function(response) {
                                if (response.status === 'success') {
                                    availablePoints -= redeemedPoints; // Update client-side count
                                    $('#availablePoints').text(availablePoints);
                                    $('#profilePoints').text(availablePoints); // Update profile modal too
                                     // Update total after successful redemption
                                     const finalTotal = Math.max(0, total - redeemedPoints);
                                     showTemporaryFeedback(`${redeemedPoints} баллов списано!`);
                                     finalizeOrderWhatsApp(orderText, orderItemsForHistory, finalTotal, redeemedPoints);
                                } else {
                                    showTemporaryFeedback("Ошибка списания баллов: " + response.message, true);
                                    // Don't proceed with order if points couldn't be redeemed
                                }
                             })
                             .fail(function() {
                                  showTemporaryFeedback("Ошибка сети при списании баллов. Попробуйте еще раз.", true);
                             });
                         // Don't call finalizeOrderWhatsApp here, wait for AJAX response.
                         return; // Exit this function, wait for AJAX callback
                    } else {
                        // If not redeeming points, finalize immediately
                         finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, 0); // Pass 0 redeemed points
                    }
                }

             function finalizeOrderWhatsApp(orderText, orderItemsForHistory, finalTotal, redeemedPoints) {
                 // Calculate earned points based on the final amount paid (after redemption)
                 const pointsEarned = Math.floor(Math.max(0, finalTotal) * 0.05); // 5% cashback

                 orderText += `Списано баллов: ${redeemedPoints} ₸%0A`;
                 orderText += `*Итого к оплате:* ${Math.max(0, finalTotal).toFixed(0)} ₸%0A`;
                  if (pointsEarned > 0) {
                     orderText += `Будет начислено баллов: ${pointsEarned}%0A`;
                 }
                 orderText += `%0A`;

                 // Add customer info
                 orderText += `*Клиент:*%0A`;
                 orderText += `Логин: ${userProfile.login}%0A`;
                 orderText += `Телефон: ${encodeURIComponent(userProfile.phone || 'Не указан')}%0A`;
                 orderText += `Адрес: ${encodeURIComponent(userProfile.address || 'Не указан')}`;

                 // --- Send updates to backend ---
                 // 1. Add earned points (only if earned > 0)
                 if (pointsEarned > 0) {
                     $.post('/add_points', { points: pointsEarned })
                          .done(function(response) {
                             if (response.status === 'success') {
                                 availablePoints += pointsEarned; // Update client-side count
                                 $('#availablePoints').text(availablePoints);
                                 $('#profilePoints').text(availablePoints);
                                 console.log(`${pointsEarned} баллов начислено.`);
                             } else {
                                 console.error("Ошибка начисления баллов:", response.message);
                                 // Non-critical, proceed with order anyway
                             }
                          })
                          .fail(function() {
                             console.error("Сетевая ошибка при начислении баллов.");
                          });
                 }

                 // 2. Save order to history
                 const orderDetails = {
                     items: orderItemsForHistory,
                     total_amount: Math.max(0, finalTotal), // Amount actually paid
                     redeemed_points: redeemedPoints,
                     earned_points: pointsEarned,
                     // Customer info is linked via session login, no need to store redundantly unless required
                     // timestamp will be added by backend
                 };
                  $.ajax({
                        url: '/save_order_history',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(orderDetails),
                        success: function(historyResponse) {
                           if (historyResponse.status === 'success') {
                               console.log("История заказа успешно сохранена.")
                           } else {
                               console.error("Ошибка сохранения истории заказов:", historyResponse.message);
                               // Non-critical, proceed with order anyway
                           }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                           console.error("Сетевая ошибка при сохранении истории заказов:", textStatus, errorThrown);
                        }
                    });

                 // 3. Open WhatsApp
                 const whatsappNumber = "+77077777777"; // Replace with actual phone number
                 const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${orderText}`;
                 window.open(whatsappUrl, '_blank');

                 // 4. Clear cart and close modals after a short delay
                 setTimeout(() => {
                    clearCart(); // Clears local storage, updates button, re-renders cart (which will be empty)
                    closeModal('cartModal');
                    showTemporaryFeedback("Заказ отправлен! Корзина очищена.");
                 }, 500); // Small delay
             }


            // --- Filtering Logic ---
            $('#search-input').on('input', filterProducts);
            $('.category-filter').on('click', function() {
                $('.category-filter').removeClass('active');
                $(this).addClass('active');
                filterProducts();
                // Show/hide the 'All Categories' button
                 $('#allCategoriesButton').css('display', ($(this).data('category') !== 'all') ? 'block' : 'none');
            });

             window.showAllCategories = function() { // Make global
                 $('.category-filter').removeClass('active');
                 $('.category-filter[data-category="all"]').addClass('active');
                 filterProducts();
                 $('#allCategoriesButton').hide();
             }

            function filterProducts() {
                const searchTerm = $('#search-input').val().toLowerCase().trim();
                const activeCategory = $('.category-filter.active').data('category');
                let hasVisibleProducts = false;
                const $grid = $('#products-grid');
                const $noMatchMsg = $grid.find('.no-match-message');

                $grid.find('.product').each(function() {
                    const $productCard = $(this);
                    const name = $productCard.data('name') || '';
                    const description = $productCard.data('description') || '';
                    const category = $productCard.data('category') || 'Без категории';

                    const matchesSearch = searchTerm === '' || name.includes(searchTerm) || description.includes(searchTerm);
                    const matchesCategory = activeCategory === 'all' || category === activeCategory;

                    if (matchesSearch && matchesCategory) {
                         $productCard.css('display', 'flex'); // Use flex display
                         hasVisibleProducts = true;
                    } else {
                         $productCard.hide();
                    }
                });

                 // Optional: Show a message if no products match
                 if (!hasVisibleProducts && products.length > 0) {
                     if ($noMatchMsg.length === 0) {
                          $grid.append('<p class="no-match-message" style="grid-column: 1 / -1; text-align: center; color: var(--text-medium); padding: 40px 0;">Букеты не найдены по вашему запросу.</p>');
                     } else {
                         $noMatchMsg.show();
                     }
                 } else {
                     $noMatchMsg.hide();
                 }
            }

             // Initialize card quantities based on saved cart (if any) - This is complex if cart items are unique instances
             // Simple approach: Just initialize display quantities to 0
              function initializeCardQuantities() {
                   if (Array.isArray(products)) {
                      products.forEach((_, index) => {
                           productQuantities[index] = 0; // Start all at 0
                           updateProductCardQuantity(index, 0);
                      });
                  }
                  // Potential future enhancement: If cart logic changes to update existing items,
                  // you could try to load quantities from the cart here based on productIndex.
                  // But since cart items are unique instances now, this is less direct.
              }

             function updateProductCardQuantity(index, quantity) {
                 const quantitySpan = $(`#quantity-${index}`);
                 if (quantitySpan.length) {
                     quantitySpan.text(quantity);
                 }
             }


            // --- Auth & Profile Logic ---
            window.openProfileModal = function() { openModal('profileModal'); }
            window.openRegisterModal = function() { closeModal('profileModal'); openModal('registerModal'); }
            window.openLoginModal = function() { closeModal('profileModal'); openModal('loginModal'); }
            window.openEditProfileModal = function() {
                // Pre-filling is now handled in openModal and template
                closeModal('profileModal');
                openModal('editProfileModal');
            }
            window.openNewsModal = function() { openModal('newsModal'); }
            window.openCashbackModal = function() { openModal('cashbackModal'); }
            window.openCartModal = function() { openModal('cartModal'); }

            window.logout = function() {
                window.location.href = '/logout';
            }

            // --- Product Card Quantity Buttons ---
            window.changeProductQuantity = function(event, index, change) { // Make global
                event.stopPropagation(); // Prevent product modal from opening

                 if (!{{ logged_in|lower }}) {
                     openModal('profileModal'); // Prompt login if not logged in
                     return;
                 }

                 // Find the product card element
                 const productCard = $(`.product[data-id='${index}']`);
                 if (!productCard.length) {
                     console.error("Could not find product card for index:", index);
                     return;
                 }

                 let currentCardQuantity = productQuantities[index] || 0;
                 let newQuantity = Math.max(0, currentCardQuantity + change);

                 if (newQuantity > 0) {
                     // If increasing or setting > 0, open options modal to confirm/customize
                     // Pass the *new* quantity to the options modal logic
                     currentOptionsQuantity = newQuantity; // Set global quantity for the modal
                     openOptionsModal(index);
                     // The options modal itself will handle adding to cart and updating the final card quantity
                 } else { // newQuantity is 0 (likely due to clicking '-')
                     // Update visual display on card to 0 immediately
                     productQuantities[index] = 0;
                     updateProductCardQuantity(index, 0);

                     // If quantity becomes 0 by clicking '-', remove corresponding items from cart
                     let cart = getCart();
                     const initialLength = cart.length;
                     // Remove ALL items in cart matching this productIndex
                     cart = cart.filter(item => item.productIndex !== index);
                     if (cart.length < initialLength) {
                         saveCart(cart); // Update cart if items were removed
                         showTemporaryFeedback("Удалено из корзины");
                     }
                 }
            }


            // --- AJAX Form Submissions ---
            function handleFormSubmit(formId, url, successCallback) {
                $('#' + formId).on('submit', function(event) {
                    event.preventDefault();
                    const $form = $(this);
                    const $messageDiv = $('#' + formId.replace('Form', 'Message')); // e.g., #registerMessage
                    const $submitButton = $form.find('button[type="submit"]');
                    const originalButtonText = $submitButton.text();

                    $submitButton.prop('disabled', true).text('Обработка...'); // Disable button
                    $messageDiv.text('').removeClass('success error').hide(); // Clear previous messages

                    $.post(url, $form.serialize())
                        .done(function(response) {
                             if (response.status === 'success') {
                                 $messageDiv.text(response.message || 'Успешно!').removeClass('error').addClass('success').show();
                                 if (successCallback) {
                                     successCallback(response);
                                 }
                             } else {
                                 $messageDiv.text(response.message || 'Произошла ошибка.').removeClass('success').addClass('error').show();
                             }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                             let errorMsg = 'Ошибка сети. Пожалуйста, попробуйте еще раз.';
                              // Try to get more specific error from server response if available
                              if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                                  errorMsg = jqXHR.responseJSON.message;
                              } else if (jqXHR.responseText) {
                                  // Fallback for non-JSON errors
                                  try {
                                      const errorData = JSON.parse(jqXHR.responseText);
                                      if (errorData.message) errorMsg = errorData.message;
                                  } catch(e) { /* Ignore parsing error */ }
                              }
                             $messageDiv.text(errorMsg).removeClass('success').addClass('error').show();
                        })
                        .always(function() {
                             // Re-enable button
                             $submitButton.prop('disabled', false).text(originalButtonText);
                        });
                });
            }

            handleFormSubmit('registerForm', '/register', function(response) {
                 $('#registerForm')[0].reset(); // Clear the form
                 showTemporaryFeedback("Регистрация успешна! Теперь вы можете войти.");
                 setTimeout(() => { closeModal('registerModal'); openModal('loginModal'); }, 1500); // Close after delay & open login
            });

            handleFormSubmit('loginForm', '/login', function(response) {
                // Reload the page on successful login to update user state everywhere
                 showTemporaryFeedback("Вход выполнен успешно! Перезагрузка...");
                 setTimeout(() => { window.location.reload(); }, 1000);
            });

            handleFormSubmit('editProfileForm', '/update_profile', function(response) {
                 // Update userProfile variable and profile modal display
                 if (response.status === 'success' && userProfile) {
                     userProfile.phone = $('#editPhone').val();
                     userProfile.address = $('#editAddress').val();
                     $('#profilePhone').text(userProfile.phone);
                     $('#profileAddress').text(userProfile.address);
                     showTemporaryFeedback("Профиль успешно обновлен!");
                     setTimeout(() => { closeModal('editProfileModal'); /* Don't reopen profile automatically */ }, 1000);
                 }
            });

            // --- FIX 3: Logo Animation ---
             $('#headerLogo').on('click', function() {
                 const $logo = $(this);
                 if (!$logo.hasClass('rotating')) { // Prevent re-triggering during animation
                     $logo.addClass('rotating');
                     setTimeout(() => {
                         $logo.removeClass('rotating');
                     }, 500); // Match CSS transition duration (0.5s)
                 }
             });


            // --- Initial Setup ---
             updateCartButton(); // Initialize cart button state
             initializeCardQuantities(); // Set initial card quantities to 0 (or load from cart if logic changes)
             filterProducts(); // Apply initial filter (show all)

             // Add a small delay before rendering cart on load if needed, e.g., if points update slowly
             // setTimeout(renderCart, 100); // Example: render cart after 100ms

          }); // End of $(document).ready()
        </script>
    </body>
    </html>
    '''
    current_year = datetime.now().year

    # Pass necessary variables to the template
    return render_template_string(
        menu_html,
        products=products,
        categories=categories,
        category_counts=category_counts,
        repo_id=REPO_ID,
        LOGO_URL=LOGO_URL,
        logged_in=logged_in,
        user_login=user_login,
        user_points=user_points,
        user_profile=user_profile,
        news_for_template=news_for_template,
        current_year=current_year
    )


@app.route('/product/<int:index>')
def product_detail(index):
     # This route *could* load product details specifically for the modal via AJAX,
     # but the current implementation loads all product data initially and uses JS.
     # Keeping this route might be useful for direct linking or future enhancements.
     # For now, let's make it return the data needed by the JS `loadProductDetails` if called directly.

    with data_lock: # Use lock for reading main data
        data = load_data()
    products = data.get('products', [])

    if 0 <= index < len(products) and isinstance(products[index], dict):
        product = products[index]
        # Return JSON data for the specific product
        return jsonify(product)
    else:
        return jsonify({'error': 'Товар не найден или данные некорректны'}), 404


@app.route('/admin', methods=['GET', 'POST'])
def admin():
    # Basic Auth - Consider a more robust system for production
    auth = request.authorization
    # Load credentials securely from environment variables
    ADMIN_USERNAME = os.getenv("ADMIN_USER", "admin") # Default only for dev
    ADMIN_PASSWORD = os.getenv("ADMIN_PASS", "secret") # Default only for dev

    # Check if credentials are provided and valid
    if not auth or not (auth.username == ADMIN_USERNAME and auth.password == ADMIN_PASSWORD):
        # Log failed attempt, potentially rate-limit
        logging.warning(f"Failed admin login attempt for user: {auth.username if auth else 'None'} from IP: {request.remote_addr}")
        # Return 401 Unauthorized with WWW-Authenticate header to prompt login
        return ('Доступ запрещен. Требуется авторизация.', 401, {'WWW-Authenticate': 'Basic realm="Admin Login Required"'})

    # --- If authenticated, proceed ---
    # Use locks for loading/saving data
    with data_lock:
        data = load_data()

    products = data.get('products', [])
    categories = data.get('categories', [])
    news_list = data.get('news', [])

     # Ensure data structures are lists
    if not isinstance(products, list): products = []
    if not isinstance(categories, list): categories = []
    if not isinstance(news_list, list): news_list = []

    if request.method == 'POST':
        action = request.form.get('action')
        try:
            # --- Category Management ---
            if action == 'add_category':
                 category_name = request.form.get('category_name', '').strip()
                 if category_name and category_name not in categories:
                     with data_lock:
                         data = load_data() # Reload fresh data inside lock
                         categories = data.get('categories', [])
                         if not isinstance(categories, list): categories = [] # Ensure list
                         if category_name not in categories: # Double check
                             categories.append(category_name)
                             data['categories'] = categories
                             save_data(data) # Save inside lock
                         else:
                              logging.warning(f"Категория '{category_name}' уже существует (обнаружена при добавлении).")
                 elif not category_name:
                      logging.warning("Попытка добавить пустую категорию.")
                 else:
                      logging.warning(f"Категория '{category_name}' уже существует.")
                 return redirect(url_for('admin'))

            elif action == 'delete_category':
                 category_index_str = request.form.get('category_index')
                 if category_index_str is not None:
                     category_index = int(category_index_str)
                     with data_lock:
                         data = load_data()
                         categories = data.get('categories', [])
                         products = data.get('products', [])
                         if not isinstance(categories, list): categories = []
                         if not isinstance(products, list): products = []

                         if 0 <= category_index < len(categories):
                             category_to_delete = categories.pop(category_index)
                             # Update products using this category
                             updated_products = []
                             for product in products:
                                 if isinstance(product, dict) and product.get('category') == category_to_delete:
                                     product['category'] = 'Без категории'
                                 updated_products.append(product)

                             data['categories'] = categories
                             data['products'] = updated_products
                             save_data(data)
                             logging.info(f"Категория '{category_to_delete}' удалена.")
                         else:
                              logging.warning(f"Попытка удаления категории с неверным индексом: {category_index}")
                 else:
                      logging.warning("Индекс категории не предоставлен для удаления.")
                 return redirect(url_for('admin'))

            # --- Product Management ---
            elif action == 'add':
                name = request.form.get('name', '').strip()
                price_str = request.form.get('price', '0').replace(',', '.').strip()
                price = float(price_str) if price_str else 0.0
                description = request.form.get('description', '').strip()
                category = request.form.get('category', 'Без категории')
                photos_files = request.files.getlist('photos')
                option_names = request.form.getlist('option_names')
                option_prices = request.form.getlist('option_prices')
                photos_list = []
                options_list = []

                # Basic validation
                if not name or price < 0:
                     logging.error("Ошибка добавления: Название и неотрицательная цена обязательны.")
                     # Add flash message for user feedback here if desired
                     return redirect(url_for('admin'))

                # Upload photos to HF
                if HF_TOKEN_WRITE:
                    api = HfApi()
                    uploads_dir = 'uploads_temp'
                    os.makedirs(uploads_dir, exist_ok=True)
                    for photo in photos_files[:10]: # Limit photos
                        if photo and photo.filename:
                            # Sanitize filename and make unique
                            base, ext = os.path.splitext(photo.filename)
                            safe_base = secure_filename(base)
                            photo_filename = f"{safe_base}_{int(time.time())}{ext}"
                            temp_path = os.path.join(uploads_dir, photo_filename)
                            try:
                                photo.save(temp_path)
                                api.upload_file(
                                    path_or_fileobj=temp_path,
                                    path_in_repo=f"photos/{photo_filename}",
                                    repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
                                    commit_message=f"Добавлено фото для товара {name}"
                                )
                                photos_list.append(photo_filename)
                                logging.info(f"Загружено фото {photo_filename} на HF.")
                            except Exception as upload_err:
                                logging.error(f"Ошибка загрузки фото {photo_filename} на HF: {upload_err}")
                            finally:
                                if os.path.exists(temp_path):
                                     try:
                                         os.remove(temp_path)
                                     except OSError as rm_err:
                                          logging.error(f"Не удалось удалить временный файл {temp_path}: {rm_err}")
                    # Clean up temp dir
                    try:
                        if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                             os.rmdir(uploads_dir)
                    except OSError as e:
                         logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}")
                elif photos_files and any(p.filename for p in photos_files):
                    logging.warning("HF_TOKEN_WRITE не установлен, загрузка фото пропущена.")

                # Process options
                for opt_name, opt_price_str in zip(option_names, option_prices):
                    opt_name = opt_name.strip()
                    opt_price_str = opt_price_str.replace(',', '.').strip()
                    if opt_name and opt_price_str is not None: # Ensure price string exists
                        try:
                            options_list.append({
                                'name': opt_name,
                                'price': float(opt_price_str)
                            })
                        except ValueError:
                            logging.warning(f"Неверный формат цены для опции '{opt_name}': '{opt_price_str}'. Опция пропущена.")

                new_product = {
                    'name': name, 'price': price, 'description': description,
                    'category': category if category in categories else 'Без категории',
                    'photos': photos_list, 'options': options_list
                }
                with data_lock:
                    data = load_data()
                    products = data.get('products', [])
                    if not isinstance(products, list): products = []
                    products.append(new_product)
                    data['products'] = products
                    save_data(data)
                logging.info(f"Добавлен товар: {name}")
                return redirect(url_for('admin'))

            elif action == 'edit':
                product_index_str = request.form.get('product_index')
                if product_index_str is not None:
                    product_index = int(product_index_str)
                    with data_lock:
                        data = load_data()
                        products = data.get('products', [])
                        categories = data.get('categories', []) # Load categories too for validation
                        if not isinstance(products, list): products = []
                        if not isinstance(categories, list): categories = []

                        if 0 <= product_index < len(products) and isinstance(products[product_index], dict):
                            product = products[product_index] # Get the product dict

                            # Update fields similar to 'add' action
                            new_name = request.form.get('name', product.get('name', '')).strip()
                            price_str = request.form.get('price', str(product.get('price', 0))).replace(',', '.')
                            new_price = float(price_str) if price_str else product.get('price', 0)
                            new_description = request.form.get('description', product.get('description', '')).strip()
                            new_category = request.form.get('category', product.get('category', 'Без категории'))

                            # Basic validation
                            if not new_name or new_price < 0:
                                 logging.error("Ошибка редактирования: Название и неотрицательная цена обязательны.")
                                 # Add flash message
                                 return redirect(url_for('admin'))


                            product['name'] = new_name
                            product['price'] = new_price
                            product['description'] = new_description
                            product['category'] = new_category if new_category in categories else 'Без категории'

                            # Handle photos: keep existing + add new
                            existing_photos_to_keep = request.form.getlist('existing_photos')
                            new_photos_files = request.files.getlist('photos')
                             # Filter out any empty strings or invalid values from existing_photos_to_keep
                            current_photos = [p for p in existing_photos_to_keep if p and isinstance(p, str)]


                            # Upload new photos
                            if HF_TOKEN_WRITE and new_photos_files:
                                api = HfApi()
                                uploads_dir = 'uploads_temp'
                                os.makedirs(uploads_dir, exist_ok=True)
                                photo_limit = 10
                                for photo in new_photos_files:
                                    if len(current_photos) >= photo_limit:
                                        logging.warning(f"Достигнут лимит фото ({photo_limit}) для товара {product['name']}. Остальные фото пропущены.")
                                        break
                                    if photo and photo.filename:
                                         base, ext = os.path.splitext(photo.filename)
                                         safe_base = secure_filename(base)
                                         photo_filename = f"{safe_base}_{int(time.time())}{ext}"
                                         temp_path = os.path.join(uploads_dir, photo_filename)
                                         try:
                                             photo.save(temp_path)
                                             api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
                                                             repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
                                                             commit_message=f"Обновлено фото для товара {product['name']}")
                                             current_photos.append(photo_filename)
                                             logging.info(f"Загружено новое фото {photo_filename} при редактировании.")
                                         except Exception as upload_err:
                                              logging.error(f"Ошибка загрузки фото {photo_filename} на HF при редактировании: {upload_err}")
                                         finally:
                                              if os.path.exists(temp_path):
                                                  try: os.remove(temp_path)
                                                  except OSError as rm_err: logging.error(f"Не удалось удалить {temp_path}: {rm_err}")
                                # Clean up temp dir
                                try:
                                    if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                                         os.rmdir(uploads_dir)
                                except OSError as e:
                                    logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}")
                            elif new_photos_files and any(p.filename for p in new_photos_files):
                                 logging.warning("HF_TOKEN_WRITE не установлен, загрузка новых фото при редактировании пропущена.")

                            product['photos'] = current_photos

                            # Update options (replace all existing with new list from form)
                            option_names = request.form.getlist('option_names')
                            option_prices = request.form.getlist('option_prices')
                            options_list = []
                            for opt_name, opt_price_str in zip(option_names, option_prices):
                                 opt_name = opt_name.strip()
                                 opt_price_str = opt_price_str.replace(',', '.').strip()
                                 if opt_name and opt_price_str is not None:
                                     try:
                                         options_list.append({'name': opt_name, 'price': float(opt_price_str)})
                                     except ValueError:
                                         logging.warning(f"Неверный формат цены для опции '{opt_name}': '{opt_price_str}' при редактировании. Опция пропущена.")
                            product['options'] = options_list

                            # products[product_index] = product # Update the list (already modified by reference)
                            data['products'] = products # Assign back just in case
                            save_data(data) # Save changes
                            logging.info(f"Товар '{product['name']}' (индекс {product_index}) обновлен.")
                        else:
                             logging.warning(f"Попытка редактирования товара с неверным индексом или неверными данными: {product_index}")
                else:
                     logging.warning("Индекс товара не предоставлен для редактирования.")
                return redirect(url_for('admin'))

            elif action == 'delete':
                product_index_str = request.form.get('product_index')
                if product_index_str is not None:
                    product_index = int(product_index_str)
                    deleted_product_name = "N/A"
                    photos_to_delete = []
                    with data_lock:
                         data = load_data()
                         products = data.get('products', [])
                         if not isinstance(products, list): products = []

                         if 0 <= product_index < len(products):
                             # Optionally: Delete associated photos from HF? Risky.
                             # For now, just remove the product entry.
                             deleted_product = products.pop(product_index)
                             deleted_product_name = deleted_product.get('name', 'N/A')
                             photos_to_delete = deleted_product.get('photos', []) # Get photos for potential later deletion
                             data['products'] = products
                             save_data(data)
                             logging.info(f"Удален товар: {deleted_product_name} (индекс {product_index})")
                             # Add logic here later to delete photos_to_delete from HF if desired
                         else:
                             logging.warning(f"Попытка удаления товара с неверным индексом: {product_index}")
                else:
                     logging.warning("Индекс товара не предоставлен для удаления.")
                return redirect(url_for('admin'))

            # --- News Management ---
            elif action == 'add_news':
                 news_title = request.form.get('news_title', '').strip()
                 news_text = request.form.get('news_text', '').strip() # Consider sanitizing HTML
                 news_photo_file = request.files.get('news_photo')
                 # Get expiry values safely, default to 0
                 expiry_days = int(request.form.get('expiry_days') or 0)
                 expiry_hours = int(request.form.get('expiry_hours') or 0)
                 expiry_minutes = int(request.form.get('expiry_minutes') or 0)

                 if not news_title or not news_text:
                     logging.error("Ошибка добавления новости: Заголовок и текст обязательны.")
                     # Add flash message
                     return redirect(url_for('admin'))


                 news_photo_filename = None
                 if HF_TOKEN_WRITE and news_photo_file and news_photo_file.filename:
                      base, ext = os.path.splitext(news_photo_file.filename)
                      safe_base = secure_filename(base)
                      news_photo_filename = f"news_{safe_base}_{int(time.time())}{ext}"
                      uploads_dir = 'uploads_temp'
                      os.makedirs(uploads_dir, exist_ok=True)
                      temp_path = os.path.join(uploads_dir, news_photo_filename)
                      try:
                          news_photo_file.save(temp_path)
                          api = HfApi()
                          api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{news_photo_filename}",
                                          repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
                                          commit_message=f"Добавлено фото для новости {news_title}")
                          logging.info(f"Загружено фото новости {news_photo_filename} на HF.")
                      except Exception as upload_err:
                          logging.error(f"Ошибка загрузки фото новости {news_photo_filename} на HF: {upload_err}")
                          news_photo_filename = None # Reset filename if upload failed
                      finally:
                           if os.path.exists(temp_path):
                                try: os.remove(temp_path)
                                except OSError as rm_err: logging.error(f"Не удалось удалить {temp_path}: {rm_err}")
                           try:
                               if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                                  os.rmdir(uploads_dir)
                           except OSError as e:
                               logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}")
                 elif news_photo_file and news_photo_file.filename:
                      logging.warning("HF_TOKEN_WRITE не установлен, загрузка фото новости пропущена.")

                 expiry_time = None
                 total_delta = timedelta(days=expiry_days, hours=expiry_hours, minutes=expiry_minutes)
                 if total_delta > timedelta(0):
                     # Store expiry in UTC
                     expiry_time = datetime.now(timezone.utc) + total_delta

                 new_news_item = {
                     'title': news_title,
                     'text': news_text, # Be careful with HTML injection if not sanitized
                     'photo': news_photo_filename,
                      # Store as ISO string (UTC) or None
                     'expiry': expiry_time.isoformat() if expiry_time else None,
                     'timestamp': datetime.now(timezone.utc).isoformat() # Add creation timestamp (UTC ISO)
                 }
                 with data_lock:
                     data = load_data()
                     news_list = data.get('news', [])
                     if not isinstance(news_list, list): news_list = []
                     news_list.append(new_news_item)
                     data['news'] = news_list
                     save_data(data)
                 logging.info(f"Добавлена новость: {news_title}")
                 return redirect(url_for('admin'))

            elif action == 'delete_news':
                 news_index_str = request.form.get('news_index') # This index refers to the sorted list in the admin view
                 if news_index_str is not None:
                     news_index_view = int(news_index_str)
                     with data_lock:
                         data = load_data()
                         all_news_raw = data.get('news', [])
                         if not isinstance(all_news_raw, list): all_news_raw = []

                         # Re-sort raw news like in admin view to find the correct item
                         min_utc_dt = datetime.min.replace(tzinfo=timezone.utc)
                         sorted_news_for_admin = sorted(
                              [item for item in all_news_raw if isinstance(item, dict)],
                              key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt,
                              reverse=True
                         )

                         if 0 <= news_index_view < len(sorted_news_for_admin):
                             item_to_delete = sorted_news_for_admin[news_index_view]
                             # Find the item in the original raw list to remove it
                             # This assumes timestamps or titles are unique enough, might need a unique ID later
                             original_index_to_delete = -1
                             for i, item in enumerate(all_news_raw):
                                 if item == item_to_delete: # Compare dictionaries
                                      original_index_to_delete = i
                                      break

                             if original_index_to_delete != -1:
                                 deleted_news = all_news_raw.pop(original_index_to_delete)
                                 logging.info(f"Удалена новость: {deleted_news.get('title', 'N/A')}")
                                 # Consider deleting photo from HF here if needed
                                 data['news'] = all_news_raw # Update the main data dictionary
                                 save_data(data)
                             else:
                                 logging.error(f"Не удалось найти новость для удаления в исходном списке (индекс вида {news_index_view}).")

                         else:
                              logging.warning(f"Попытка удаления новости с неверным индексом вида: {news_index_view}")
                 else:
                      logging.warning("Индекс новости не предоставлен для удаления.")
                 return redirect(url_for('admin'))

        except ValueError as ve:
             logging.error(f"Ошибка преобразования значения в админке (action={action}): {ve}")
             # Optionally: add flash message to show user
        except Exception as e:
             logging.error(f"Непредвиденная ошибка в админке (action={action}): {e}", exc_info=True)
             # Optionally: add flash message

        # Redirect even on error for simplicity, consider flash messages
        return redirect(url_for('admin'))

    # --- Admin Panel HTML ---
    # Sort news list for display in admin panel (use the same sorting as main page)
    min_utc_dt = datetime.min.replace(tzinfo=timezone.utc)
    admin_news_list = sorted(
         [item for item in news_list if isinstance(item, dict)], # Filter non-dicts
         key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt,
         reverse=True
    )
    # Sort products alphabetically for admin view
    admin_products_list = sorted(
        [p for p in products if isinstance(p, dict)], # Filter non-dicts
        key=lambda p: p.get('name', '').lower()
    )

    admin_html = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Админ-панель - Ultra Flowers</title>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet">
        <style>
            /* --- Reusing styles from main CSS for consistency --- */
             :root {
                --primary-color: #D8BFD8; --secondary-color: #B0E0E6; --accent-color: #FFB6C1;
                --background-light: #FAF0E6; --background-card: #FFFFFF; --text-dark: #36454F;
                --text-medium: #708090; --text-light: #FFFFFF; --shadow-color: rgba(112, 128, 144, 0.15);
                --border-color: #E0E0E0; --font-primary: 'Poppins', sans-serif; --font-headings: 'Playfair Display', serif;
                --danger-color: #E57373; --danger-bg: rgba(229, 115, 115, 0.1);
                --success-color: #81C784; --success-bg: rgba(129, 199, 132, 0.1);
            }
            body { font-family: var(--font-primary); background-color: var(--background-light); color: var(--text-dark); padding: 25px; font-weight: 300; }
            .container { max-width: 1000px; margin: 0 auto; }
            h1, h2 { font-family: var(--font-headings); font-weight: 700; color: var(--text-dark); margin-bottom: 25px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
            h1 { font-size: 2rem; } h2 { font-size: 1.5rem; margin-top: 30px; }
            .section { background: var(--background-card); padding: 25px; border-radius: 12px; box-shadow: 0 5px 20px var(--shadow-color); margin-bottom: 30px; }
            label { display: block; margin: 15px 0 5px; color: var(--text-medium); font-size: 0.9rem; font-weight: 600; }
            input[type="text"], input[type="number"], input[type="file"], select, textarea {
                width: 100%; padding: 12px 15px; border: 1px solid var(--border-color); border-radius: 8px;
                background: var(--background-light); color: var(--text-dark); font-size: 0.9rem; transition: all 0.3s ease; margin-bottom: 10px;
                box-sizing: border-box; /* Include padding and border in the element's total width and height */
            }
             input[type="file"] { background: var(--background-card); border: none; padding: 10px 0; } /* Style file input differently */
             input[type=number]::-webkit-outer-spin-button,
             input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
             input[type=number] { -moz-appearance: textfield; } /* Firefox */

            input:focus, select:focus, textarea:focus { border-color: var(--primary-color); background-color: var(--background-card); box-shadow: 0 0 8px rgba(216, 191, 216, 0.3); outline: none; }
            textarea { min-height: 80px; resize: vertical; }
            button, .button {
                padding: 10px 20px; border: 1px solid var(--primary-color); border-radius: 25px; background-color: var(--primary-color);
                color: var(--text-dark); cursor: pointer; margin: 10px 5px 0 0; transition: all 0.3s ease;
                font-size: 0.9rem; font-weight: 600; text-decoration: none; display: inline-block; vertical-align: middle; /* Align buttons nicely */
            }
            button:hover, .button:hover { background-color: var(--secondary-color); border-color: var(--secondary-color); transform: translateY(-1px); box-shadow: 0 4px 10px rgba(176, 224, 230, 0.4); }
            .button-danger { background-color: var(--accent-color); border-color: var(--accent-color); color: var(--text-dark); }
            .button-danger:hover { background-color: #f7a0ac; border-color: #f7a0ac; box-shadow: 0 4px 10px rgba(255, 182, 193, 0.4); }
            .button-secondary { background-color: transparent; border-color: var(--border-color); color: var(--text-medium); }
            .button-secondary:hover { background-color: var(--background-light); border-color: var(--text-medium); color: var(--text-dark); box-shadow: 0 2px 8px var(--shadow-color); }

            .list-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap;}
            .list-item:last-child { border-bottom: none; }
            .list-item .item-info { flex-grow: 1; min-width: 200px; } /* Allow wrapping */
            .list-item .item-info span { display: block; margin-bottom: 3px; } /* Ensure block display for wrapping */
             .list-item .item-info span small { color: var(--text-medium); font-size: 0.85em;}
            .list-item img.item-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 4px; flex-shrink: 0; border: 1px solid var(--border-color); }
            .list-item .actions { display: flex; gap: 8px; flex-shrink: 0; align-items: center; flex-wrap: wrap; /* Allow actions to wrap */ }
            .list-item .actions form { margin: 0; padding: 0; display: inline;} /* Fix form layout issue */
            .list-item .actions button, .list-item .actions .button { margin: 0; padding: 6px 12px; font-size: 0.8rem; }

            .options-list .option-item, .photos-list .photo-item { display: flex; gap: 10px; margin-bottom: 8px; align-items: center; flex-wrap: wrap; }
            .options-list input { width: calc(50% - 30px); min-width: 120px; margin-bottom: 0; } /* Adjust width */
             .options-list .remove-option-btn { margin-left: auto; padding: 4px 8px; font-size: 0.7rem; border-radius: 50%; line-height: 1; background-color: var(--danger-bg); border: 1px solid var(--danger-color); color: var(--danger-color);}
             .options-list .remove-option-btn:hover { background-color: var(--danger-color); color: white; }

            .photos-list img { height: 40px; width: auto; margin-right: 5px; border-radius: 3px; border: 1px solid var(--border-color); }
            .photos-list span { font-size: 0.8rem; word-break: break-all; flex-grow: 1; margin-right: 5px; color: var(--text-medium);}
             .photos-list .button-danger { padding: 4px 8px; font-size: 0.7rem; margin-left: auto; border-radius: 50%; line-height: 1;}

            .add-option-button { background-color: var(--success-bg); border-color: var(--success-color); color: var(--success-color); }
            .add-option-button:hover { background-color: var(--success-color); border-color: var(--success-color); color: white; box-shadow: 0 4px 10px rgba(129, 199, 132, 0.4); }

            /* Edit Modal Styles */
            .modal { display:none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(54, 69, 79, 0.7); backdrop-filter: blur(8px); overflow-y: auto; padding: 5vh 20px; }
            .modal-content { background: var(--background-card); margin: 0 auto; padding: 30px; border-radius: 12px; width: 95%; max-width: 700px; box-shadow: 0 10px 40px rgba(54, 69, 79, 0.3); position: relative; animation: slideInAdmin 0.4s ease-out; }
             @keyframes slideInAdmin { from { transform: translateY(30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
            .modal-content h2 { margin-top: 0; }
            .close-modal { position: absolute; top: 15px; right: 20px; font-size: 2rem; font-weight: 300; color: var(--text-medium); cursor: pointer; transition: all 0.3s ease; line-height: 1; text-decoration: none; border: none; background: none;}
            .close-modal:hover { color: var(--text-dark); transform: rotate(90deg); }
            .expiry-inputs div { display: inline-block; margin-right: 10px; }
             .expiry-inputs label { display: inline-block; margin-right: 5px; font-weight: normal; font-size: 0.85rem;}
             .expiry-inputs input { width: 70px; display: inline-block; padding: 8px 10px; font-size: 0.85rem;}

             /* Admin specific helpers */
             .form-section { margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px dashed var(--border-color); }
             .form-section:last-child { border-bottom: none; }
             .field-hint { font-size: 0.8em; color: var(--text-medium); margin-top: -5px; margin-bottom: 10px; display: block; }

        </style>
    </head>
    <body>
        <div class="container">
            <h1>Админ-панель Ultra Flowers</h1>
             <!-- Console Message for Debugging -->
             <p style="background: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 10px; border-radius: 5px; font-size: 0.9em;">
                 ℹ️ Если кнопки "Редактировать", "Удалить" или "+ Добавить опцию" не работают, проверьте консоль разработчика в браузере (обычно клавиша F12) на наличие ошибок JavaScript.
             </p>

            <!-- Управление категориями -->
            <div class="section">
                <h2>Управление категориями</h2>
                <div class="form-section">
                    <form method="POST" action="{{ url_for('admin') }}"> {# Explicit action URL #}
                        <input type="hidden" name="action" value="add_category">
                        <label for="category_name">Название новой категории:</label>
                        <input type="text" name="category_name" id="category_name" required>
                        <button type="submit">Добавить категорию</button>
                    </form>
                </div>
                <div class="category-list">
                    <h3>Существующие категории:</h3>
                    {% for category in categories %}
                    <div class="list-item">
                        <div class="item-info"><span>{{ category }}</span></div>
                        <div class="actions">
                             <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #}
                                <input type="hidden" name="action" value="delete_category">
                                <input type="hidden" name="category_index" value="{{ loop.index0 }}">
                                <button type="submit" class="button-danger" onclick="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');">Удалить</button>
                            </form>
                        </div>
                    </div>
                    {% else %}
                    <p>Нет категорий.</p>
                    {% endfor %}
                </div>
            </div>

            <!-- Добавление товара -->
            <div class="section">
                <h2>Добавить Товар (Букет/Композицию)</h2>
                <form method="POST" enctype="multipart/form-data" action="{{ url_for('admin') }}"> {# Explicit action URL #}
                    <input type="hidden" name="action" value="add">
                    <div class="form-section">
                        <label for="name">Название:</label>
                        <input type="text" name="name" id="name" required>
                        <label for="price">Цена (₸):</label>
                        <input type="number" step="0.01" min="0" name="price" id="price" placeholder="Например, 15000" required>
                        <label for="description">Описание:</label>
                        <textarea name="description" id="description" rows="4" placeholder="Состав букета, размер, особенности..."></textarea>
                        <label for="category">Категория:</label>
                        <select name="category" id="category">
                            <option value="Без категории">Без категории</option>
                            {% for category in categories %}
                            <option value="{{ category }}">{{ category }}</option>
                            {% endfor %}
                        </select>
                        <label for="photos">Фотографии (до 10):</label>
                        <input type="file" name="photos" id="photos" multiple accept="image/*">
                         <span class="field-hint">Можно выбрать несколько файлов.</span>
                    </div>

                    <div class="form-section">
                        <div class="options-list" id="options-list-add">
                            <label>Опции (необязательно):</label>
                            <!-- Options added dynamically -->
                        </div>
                        <button type="button" class="button-secondary add-option-button" onclick="addOptionField('add')">+ Добавить опцию</button>
                    </div>

                    <button type="submit" style="margin-top: 20px;">Добавить Товар</button>
                </form>
            </div>

            <!-- Список товаров -->
            <div class="section">
                <h2>Список Товаров ({{ admin_products_list|length }})</h2>
                <div class="product-list">
                     {% for product in admin_products_list %} {# Using sorted list #}
                     {% if product is mapping %} {# Check if product is dict #}
                     <div class="list-item">
                          {% set photos = product.get('photos', []) %}
                          {% if photos and photos is iterable and photos|length > 0 %}
                          <img class="item-thumb" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photos[0] }}" alt="{{ product.get('name', '') }}" onerror="this.style.display='none'">
                          {% else %}
                          <div style="width: 50px; height: 50px; background-color: #eee; flex-shrink: 0; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 0.7em; color: var(--text-medium);">Нет фото</div>
                          {% endif %}
                         <div class="item-info">
                             <span><strong>{{ product.get('name', 'Без названия') }}</strong> ({{ product.get('category', 'Без категории') }}) - {{ product.get('price', 0) }} ₸</span>
                             <span><small>{{ product.get('description', '')[:100] }}{% if product.get('description', '')|length > 100 %}...{% endif %}</small></span>
                              {% set options = product.get('options', []) %}
                              {% if options and options is iterable and options|length > 0 %}
                                 <span><small>Опции: {{ options|map(attribute='name')|join(', ') }}</small></span>
                              {% endif %}
                         </div>
                         <div class="actions">
                             {# FIX 1: Ensure onclick calls openEditModal with the correct ORIGINAL index #}
                              <button type="button" class="button-secondary" onclick="openEditModal({{ products.index(product) }})">Редакт.</button> {# Find original index #}
                              <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #}
                                 <input type="hidden" name="action" value="delete">
                                 {# FIX 1: Use the ORIGINAL index for deletion #}
                                 <input type="hidden" name="product_index" value="{{ products.index(product) }}"> {# Find original index #}
                                 <button type="submit" class="button-danger" onclick="return confirm('Вы уверены, что хотите удалить товар \'{{ product.get('name', '') }}\'?');">Удалить</button>
                             </form>
                         </div>
                     </div>
                     {% endif %} {# End check if product is mapping #}
                     {% else %}
                      <p>Нет добавленных товаров.</p>
                     {% endfor %}
                 </div>
             </div>

             <!-- Управление новостями -->
            <div class="section">
                <h2>Управление Новостями и Акциями</h2>
                <div class="form-section">
                    <form method="POST" enctype="multipart/form-data" action="{{ url_for('admin') }}"> {# Explicit action URL #}
                        <input type="hidden" name="action" value="add_news">
                        <label for="news_title">Заголовок новости:</label>
                        <input type="text" name="news_title" id="news_title" required>
                        <label for="news_text">Текст новости (можно использовать базовый HTML):</label>
                        <textarea name="news_text" id="news_text" rows="4" required></textarea>
                        <label for="news_photo">Фото для новости (необязательно):</label>
                         <input type="file" name="news_photo" id="news_photo" accept="image/*">
                        <label>Срок действия новости (оставьте 0, если бессрочно):</label>
                        <div class="expiry-inputs">
                            <div><label for="expiry_days">Дни:</label><input type="number" name="expiry_days" id="expiry_days" value="0" min="0"></div>
                            <div><label for="expiry_hours">Часы:</label><input type="number" name="expiry_hours" id="expiry_hours" value="0" min="0" max="23"></div>
                            <div><label for="expiry_minutes">Мин:</label><input type="number" name="expiry_minutes" id="expiry_minutes" value="0" min="0" max="59"></div>
                        </div>
                        <button type="submit" style="margin-top: 20px;">Добавить новость</button>
                    </form>
                 </div>

                 <div class="news-list" style="margin-top: 30px;">
                      <h3>Существующие новости ({{ admin_news_list|length }}):</h3>
                     {% for news_item in admin_news_list %} {# Using sorted list for display #}
                     {% if news_item is mapping %} {# Check if item is dict #}
                     <div class="list-item">
                          {% set photo = news_item.get('photo') %}
                          {% if photo %}
                          <img class="item-thumb" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ news_item.get('title', '') }}" onerror="this.style.display='none'">
                          {% else %}
                          <div style="width: 50px; height: 50px; background-color: #eee; flex-shrink: 0; border-radius: 4px;"></div>
                          {% endif %}
                         <div class="item-info">
                             <span><strong>{{ news_item.get('title', 'Без заголовка') }}</strong></span>
                             <span><small>{{ news_item.get('text', '')[:150] | safe }}{% if news_item.get('text', '')|length > 150 %}...{% endif %}</small></span>
                             {# --- UPDATED DATE FORMATTING using the registered filter --- #}
                             {% set ts_dt = news_item.timestamp | format_iso_datetime %}
                             <span><small style="color: var(--text-medium);">Добавлено: {{ ts_dt.strftime('%d.%m.%Y %H:%M') if ts_dt else 'N/A' }} UTC</small></span>
                              {% set expiry = news_item.get('expiry') %}
                              {% if expiry %}
                                 {% set expiry_dt = expiry | format_iso_datetime %}
                                 {% if expiry_dt %}
                                     <span ><small style="color: var(--accent-color);">Актуально до: {{ expiry_dt.strftime('%d.%m.%Y %H:%M') }} UTC</small></span>
                                 {% endif %}
                              {% endif %}
                              {# --- END UPDATED DATE FORMATTING --- #}
                         </div>
                          <div class="actions">
                              <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #}
                                 <input type="hidden" name="action" value="delete_news">
                                  {# Pass the index FROM THE SORTED LIST VIEW #}
                                 <input type="hidden" name="news_index" value="{{ loop.index0 }}">
                                 <button type="submit" class="button-danger" onclick="return confirm('Удалить новость \'{{ news_item.get('title', '') }}\'?');">Удалить</button>
                             </form>
                         </div>
                     </div>
                     {% endif %} {# End check if item is mapping #}
                     {% else %}
                     <p>Нет добавленных новостей.</p>
                     {% endfor %}
                 </div>
             </div>


         </div>

        <!-- Модальное окно редактирования товара -->
        <div id="editModal" class="modal">
            <div class="modal-content">
                 <button type="button" class="close-modal" onclick="closeEditModal()" aria-label="Закрыть">×</button>
                 <h2>Редактировать Товар</h2>
                 {# Ensure form targets the correct endpoint #}
                 <form method="POST" enctype="multipart/form-data" id="editForm" action="{{ url_for('admin') }}">
                     <input type="hidden" name="action" value="edit">
                     <input type="hidden" name="product_index" id="editProductIndex">

                     <div class="form-section">
                         <label for="editName">Название:</label>
                         <input type="text" name="name" id="editName" required>
                         <label for="editPrice">Цена (₸):</label>
                         <input type="number" step="0.01" min="0" name="price" id="editPrice" required>
                         <label for="editDescription">Описание:</label>
                         <textarea name="description" id="editDescription" rows="4"></textarea>
                         <label for="editCategory">Категория:</label>
                         <select name="category" id="editCategory">
                             {# Options populated by JS #}
                         </select>
                     </div>

                     <div class="form-section">
                         <label>Текущие фотографии (нажмите <span style="color: var(--danger-color); font-weight: bold;">X</span>, чтобы убрать):</label>
                         <div id="editPhotosList" class="photos-list">
                             <!-- Photos will be populated by JS -->
                         </div>
                         <label for="editPhotos">Добавить новые фотографии (до 10 всего):</label>
                          <input type="file" name="photos" id="editPhotos" multiple accept="image/*">
                          <span class="field-hint">Новые фото будут добавлены к существующим (если не удалены).</span>
                      </div>

                      <div class="form-section">
                         <div class="options-list" id="options-list-edit">
                             <label>Опции:</label>
                              <!-- Options will be populated by JS -->
                         </div>
                         <button type="button" class="button-secondary add-option-button" onclick="addOptionField('edit')">+ Добавить опцию</button>
                      </div>

                     <button type="submit" style="margin-top: 20px;">Сохранить изменения</button>
                 </form>
            </div>
        </div>

        <script>
             // Ensure script runs after DOM is loaded
             document.addEventListener('DOMContentLoaded', function() {

                 // Use the raw products list from Flask for indexing in edit/delete
                 const allProductsDataAdmin = {{ products|tojson }};
                 const allCategoriesAdmin = {{ categories|tojson }};
                 const repoIdAdmin = "{{ repo_id }}";

                 // --- FIX 1: Make functions globally accessible ---
                 window.addOptionField = function(context) {
                     const optionsList = document.getElementById(`options-list-${context}`);
                     if (!optionsList) {
                          console.error(`Element not found: options-list-${context}`);
                          return; // Exit if target list doesn't exist
                     }
                     const optionDiv = document.createElement('div');
                     optionDiv.className = 'option-item';
                     optionDiv.innerHTML = `
                         <input type="text" name="option_names" placeholder="Название опции (нпр, Ваза)" required> {# Added required #}
                         <input type="number" step="0.01" min="0" name="option_prices" placeholder="Доп. цена (₸)" required> {# Added required + min #}
                         <button type="button" class="button-danger remove-option-btn" onclick="removeParentElement(this)" aria-label="Удалить опцию">X</button>
                     `;
                     optionsList.appendChild(optionDiv);
                 }

                 // Helper to remove parent element (used for options and photos)
                 window.removeParentElement = function(buttonElement) {
                     buttonElement.parentElement.remove();
                 }


                 window.openEditModal = function(index) {
                      console.log("Attempting to open edit modal for index:", index); // Debug log
                      if (index < 0 || index >= allProductsDataAdmin.length || typeof allProductsDataAdmin[index] !== 'object') {
                           alert("Ошибка: Неверный индекс товара для редактирования.");
                           console.error("Invalid index or product data for edit:", index, allProductsDataAdmin[index]);
                           return;
                      }
                      const product = allProductsDataAdmin[index];
                      console.log("Editing product:", product); // Debug log

                     // --- Populate basic fields ---
                     document.getElementById('editProductIndex').value = index;
                     document.getElementById('editName').value = product.name || '';
                     document.getElementById('editPrice').value = product.price || 0;
                     document.getElementById('editDescription').value = product.description || '';

                     // --- Populate category select ---
                     const categorySelect = document.getElementById('editCategory');
                     categorySelect.innerHTML = '<option value="Без категории">Без категории</option>'; // Reset options
                     if (Array.isArray(allCategoriesAdmin)) {
                         allCategoriesAdmin.forEach(cat => {
                             const option = document.createElement('option');
                             option.value = cat;
                             option.textContent = cat;
                             if (product.category === cat) {
                                 option.selected = true; // Select current category
                             }
                             categorySelect.appendChild(option);
                         });
                     }
                      // Fallback if product category isn't in the list
                     if (!categorySelect.value) {
                          categorySelect.value = 'Без категории';
                     }


                     // --- Populate photos ---
                     const photosListDiv = document.getElementById('editPhotosList');
                     photosListDiv.innerHTML = ''; // Clear previous
                     const photos = product.photos || [];
                      if (Array.isArray(photos) && photos.length > 0) {
                         photos.forEach((photo) => {
                             if (typeof photo === 'string' && photo) { // Ensure photo is a non-empty string
                                 const photoUrl = `https://huggingface.co/datasets/${repoIdAdmin}/resolve/main/photos/${photo}`;
                                 const photoDiv = document.createElement('div');
                                 photoDiv.className = 'photo-item';
                                 // Use hidden input to track photos to keep. Remove div + input on delete click.
                                 photoDiv.innerHTML = `
                                     <input type="hidden" name="existing_photos" value="${photo}">
                                     <img src="${photoUrl}" alt="Текущее фото" style="height: 40px; width: auto;" onerror="this.style.display='none'">
                                     <span>${photo}</span>
                                     <button type="button" class="button-danger" onclick="removeParentElement(this)" aria-label="Удалить фото">X</button>
                                 `;
                                 photosListDiv.appendChild(photoDiv);
                              }
                          });
                      } else {
                         photosListDiv.innerHTML = '<p style="font-size: 0.9em; color: var(--text-medium);">Нет текущих фото.</p>';
                      }


                     // --- Populate options ---
                     const optionsListDiv = document.getElementById('options-list-edit');
                      // Clear previous options but keep the label if it exists or add one
                     optionsListDiv.innerHTML = '<label>Опции:</label>';
                     const options = product.options || [];
                      if (Array.isArray(options) && options.length > 0) {
                         options.forEach(option => {
                             // Ensure option is valid before adding
                             if (typeof option === 'object' && option !== null) {
                                 const optionDiv = document.createElement('div');
                                 optionDiv.className = 'option-item';
                                 optionDiv.innerHTML = `
                                     <input type="text" name="option_names" value="${option.name || ''}" placeholder="Название опции" required>
                                     <input type="number" step="0.01" min="0" name="option_prices" value="${option.price || 0}" placeholder="Доп. цена (₸)" required>
                                     <button type="button" class="button-danger remove-option-btn" onclick="removeParentElement(this)" aria-label="Удалить опцию">X</button>
                                 `;
                                  optionsListDiv.appendChild(optionDiv);
                             }
                         });
                      }

                     // Clear file input for new photos
                      const editPhotosInput = document.getElementById('editPhotos');
                      if (editPhotosInput) { editPhotosInput.value = ''; }


                      // Show the modal
                      const editModal = document.getElementById('editModal');
                      if(editModal) {
                          editModal.style.display = 'block';
                          document.body.style.overflow = 'hidden'; // Prevent background scroll
                          console.log("Edit modal should be visible now."); // Debug log
                      } else {
                          console.error("Edit modal element not found!");
                      }
                 }

                  window.closeEditModal = function() {
                     const editModal = document.getElementById('editModal');
                     if(editModal) {
                          editModal.style.display = 'none';
                     }
                      // Restore scroll only if no other modals are open
                     if (document.querySelectorAll('.modal[style*="display: block"]').length === 0) {
                          document.body.style.overflow = 'auto';
                     }
                      // Optional: Reset form, but might be better to keep data if user reopens
                      // document.getElementById('editForm').reset();
                      // Clear dynamic lists
                      const photosListDiv = document.getElementById('editPhotosList');
                      const optionsListDiv = document.getElementById('options-list-edit');
                      if(photosListDiv) photosListDiv.innerHTML = '';
                      if(optionsListDiv) optionsListDiv.innerHTML = '<label>Опции:</label>'; // Keep label

                 }

                  // Close modal on Escape key
                  document.addEventListener('keydown', function(event) {
                      if (event.key === "Escape") {
                          const editModal = document.getElementById('editModal');
                          if (editModal && editModal.style.display === 'block') {
                              closeEditModal();
                          }
                      }
                  });
                  // Close modal on outside click (specific to edit modal)
                  const editModalElement = document.getElementById('editModal');
                  if(editModalElement) {
                      editModalElement.addEventListener('click', function(event) {
                         if (event.target === editModalElement) { // Check if click is on the background
                              closeEditModal();
                          }
                      });
                   }

             }); // End DOMContentLoaded
         </script>
     </body>
     </html>
     '''
    return render_template_string(
        admin_html,
        products=products, # Pass original list for index finding
        admin_products_list=admin_products_list, # Pass sorted list for display
        categories=categories,
        repo_id=REPO_ID,
        admin_news_list=admin_news_list # Pass sorted news list
    )


# --- API Routes (Login, Register, Profile, Points, History) ---

@app.route('/register', methods=['POST'])
def register():
    # Simplified data extraction
    login = request.form.get('registerLogin')
    password = request.form.get('registerPassword')
    phone = request.form.get('registerPhone')
    address = request.form.get('registerAddress')

    if not all([login, password, phone, address]):
        return jsonify({'status': 'error', 'message': 'Все поля обязательны для заполнения.'}), 400

    # Input validation (basic)
    if len(password) < 6:
        return jsonify({'status': 'error', 'message': 'Пароль должен быть не менее 6 символов.'}), 400
    if len(login) < 3:
         return jsonify({'status': 'error', 'message': 'Логин должен быть не менее 3 символов.'}), 400

    success, message = register_user(login, password, phone, address)
    status_code = 201 if success else 409 # Use 409 Conflict if user exists
    return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code

@app.route('/login', methods=['POST'])
def login():
    # Simplified data extraction
    login_username = request.form.get('loginUsername')
    login_password = request.form.get('loginPassword')

    if not login_username or not login_password:
         return jsonify({'status': 'error', 'message': 'Логин и пароль обязательны.'}), 400

    user = authenticate_user(login_username, login_password)
    if user:
        session.permanent = True # Make session persistent (uses app.permanent_session_lifetime)
        session['user_login'] = user['login'] # Store login in session AFTER setting permanent
        logging.info(f"Пользователь '{user['login']}' успешно вошел в систему. Session ID: {session.sid if hasattr(session, 'sid') else 'N/A'}")
        return jsonify({'status': 'success', 'message': 'Вход выполнен успешно.'})
    else:
        logging.warning(f"Неудачная попытка входа для пользователя '{login_username}'.")
        return jsonify({'status': 'error', 'message': 'Неверный логин или пароль.'}), 401

@app.route('/logout')
def logout():
    user = session.pop('user_login', None)
    session.clear() # Clear entire session for good measure
    if user:
         logging.info(f"Пользователь '{user}' вышел из системы.")
    # Redirect to main page after logout
    return redirect(url_for('menu'))

@app.route('/update_profile', methods=['POST'])
def update_profile():
    if 'user_login' not in session:
        return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401

    login = session['user_login']
    # Simplified data extraction
    phone = request.form.get('editPhone')
    address = request.form.get('editAddress')

    if not phone or not address:
         return jsonify({'status': 'error', 'message': 'Телефон и адрес обязательны.'}), 400

    success, message = update_user_profile(login, phone, address)
    if success:
        logging.info(f"Профиль пользователя {login} обновлен.")
        return jsonify({'status': 'success', 'message': message}), 200
    else:
         # Log failure reason if possible (e.g., user not found, save error)
         logging.warning(f"Не удалось обновить профиль для {login}: {message}")
         # Determine appropriate status code (404 if not found, 500 if save failed)
         status_code = 404 if "не найден" in message else 500
         return jsonify({'status': 'error', 'message': message}), status_code

@app.route('/add_points', methods=['POST'])
def add_points():
    if 'user_login' not in session:
        return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401
    login = session['user_login']
    try:
        # Assume form data from finalizeOrderWhatsApp AJAX call
        points_str = request.form.get('points')
        if points_str is None:
             return jsonify({'status': 'error', 'message': 'Параметр points отсутствует.'}), 400
        points = int(points_str)
        if points < 0: # Allow 0 points (e.g., if order total was 0 after redemption)
             return jsonify({'status': 'error', 'message': 'Нельзя начислить отрицательные баллы.'}), 400
    except ValueError:
        return jsonify({'status': 'error', 'message': 'Неверное количество баллов.'}), 400

    success = add_points_to_user(login, points)
    if success:
        logging.info(f"Начислено {points} баллов пользователю {login}")
        return jsonify({'status': 'success', 'message': f'{points} баллов начислено.'})
    else:
        # This case should ideally not happen if user is logged in, means data inconsistency
        logging.error(f"Ошибка начисления баллов: пользователь {login} не найден при попытке добавления.")
        return jsonify({'status': 'error', 'message': 'Ошибка начисления баллов: пользователь не найден.'}), 500

@app.route('/redeem_points', methods=['POST'])
def redeem_points():
    if 'user_login' not in session:
        return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401
    login = session['user_login']
    try:
        # Assume form data from orderViaWhatsApp AJAX call
        points_str = request.form.get('points')
        if points_str is None:
            return jsonify({'status': 'error', 'message': 'Параметр points отсутствует.'}), 400
        points = int(points_str)
        if points <= 0: # Must redeem a positive amount
            return jsonify({'status': 'error', 'message': 'Количество списываемых баллов должно быть положительным.'}), 400
    except ValueError:
        return jsonify({'status': 'error', 'message': 'Неверное количество баллов.'}), 400

    success, message = redeem_points_from_user(login, points)
    status_code = 200 if success else 400 # 400 for insufficient points or user error
    if success:
        logging.info(f"Списано {points} баллов у пользователя {login}")
    else:
        logging.warning(f"Ошибка списания {points} баллов у пользователя {login}: {message}")
    return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code

@app.route('/save_order_history', methods=['POST'])
def save_order_history_route(): # Renamed route function slightly
    if 'user_login' not in session:
        return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401
    login = session['user_login']
    if not request.is_json:
        logging.warning(f"Получен не-JSON запрос на /save_order_history от {login}")
        return jsonify({'status': 'error', 'message': 'Запрос должен быть в формате JSON.'}), 400

    order_details = request.get_json()
    # Validate basic structure
    if not isinstance(order_details, dict) or not isinstance(order_details.get('items'), list) or not isinstance(order_details.get('total_amount'), (int, float)):
         logging.warning(f"Получены неполные или некорректные данные заказа для сохранения в историю от {login}: {order_details}")
         return jsonify({'status': 'error', 'message': 'Неполные или некорректные данные заказа.'}), 400

    success, message = save_order_to_history(login, order_details)
    status_code = 201 if success else 500 # 500 if save failed unexpectedly
    if success:
        logging.info(f"Заказ сохранен в историю для пользователя {login}")
    else:
        logging.error(f"Ошибка сохранения заказа в историю для пользователя {login}: {message}")
    return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code


# --- App Initialization ---
if __name__ == '__main__':
    # Start background backup thread only if HF tokens are set for writing
    if HF_TOKEN_WRITE:
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
        logging.info("Поток периодического резервного копирования запущен.")
    else:
        logging.info("HF_TOKEN_WRITE не установлен, резервное копирование на HF отключено.")

    # Use Waitress or Gunicorn for production instead of Flask's built-in server
    # For development:
    port = int(os.environ.get("PORT", 7860)) # Use environment variable for port
    # Set debug=False for production/semi-production, host='0.0.0.0' for external access
    app.run(debug=False, host='0.0.0.0', port=port)