File size: 109,045 Bytes
c05c6b5
 
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db8b34
87ab168
 
 
84d66d7
 
 
 
 
87ab168
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87ab168
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
c05c6b5
87ab168
84d66d7
 
cd63945
87ab168
 
 
cd63945
 
84d66d7
 
 
 
 
 
87ab168
 
6ca5846
cd63945
6ca5846
 
84d66d7
 
6ca5846
87ab168
84d66d7
87ab168
84d66d7
 
cd63945
84d66d7
87ab168
c05c6b5
 
 
 
84d66d7
 
 
87ab168
84d66d7
 
cd63945
87ab168
c05c6b5
 
87ab168
c05c6b5
 
 
87ab168
84d66d7
 
87ab168
84d66d7
cd63945
87ab168
6ca5846
84d66d7
 
 
 
 
 
6ca5846
84d66d7
87ab168
cd63945
 
84d66d7
 
cd63945
84d66d7
 
 
87ab168
84d66d7
 
 
87ab168
84d66d7
 
87ab168
84d66d7
87ab168
84d66d7
87ab168
84d66d7
 
 
 
 
 
87ab168
84d66d7
 
 
 
 
 
 
 
87ab168
cd63945
84d66d7
 
cd63945
6ca5846
84d66d7
 
 
 
6ca5846
84d66d7
 
87ab168
 
 
 
84d66d7
 
 
c05c6b5
 
 
 
 
87ab168
84d66d7
 
 
c05c6b5
84d66d7
 
 
87ab168
 
 
 
c05c6b5
87ab168
 
c05c6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87ab168
 
c05c6b5
84d66d7
87ab168
 
 
 
c05c6b5
 
87ab168
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
6ca5846
 
c05c6b5
6ca5846
 
 
 
87ab168
 
84d66d7
c05c6b5
87ab168
 
 
 
 
c05c6b5
87ab168
84d66d7
87ab168
 
 
 
84d66d7
c05c6b5
87ab168
 
 
 
 
84d66d7
c05c6b5
 
6ca5846
 
c05c6b5
87ab168
 
c05c6b5
87ab168
 
 
 
 
84d66d7
c05c6b5
 
87ab168
c05c6b5
87ab168
 
 
c05c6b5
87ab168
 
c05c6b5
87ab168
 
 
 
 
84d66d7
87ab168
 
 
 
84d66d7
6ca5846
 
 
 
 
 
 
 
 
 
 
87ab168
 
 
 
 
 
 
 
6ca5846
c05c6b5
 
87ab168
 
 
6ca5846
 
87ab168
 
 
6ca5846
 
 
87ab168
6ca5846
 
 
 
 
 
87ab168
 
 
 
c05c6b5
 
6ca5846
87ab168
 
 
 
 
 
c05c6b5
87ab168
 
 
 
6ca5846
 
84d66d7
6ca5846
 
c05c6b5
6ca5846
87ab168
 
6ca5846
 
87ab168
6ca5846
 
87ab168
6ca5846
 
87ab168
 
 
 
 
 
 
 
 
 
 
6ca5846
87ab168
6ca5846
87ab168
6ca5846
 
87ab168
 
 
 
 
6ca5846
 
 
 
 
 
87ab168
 
6ca5846
 
87ab168
6ca5846
 
87ab168
6ca5846
87ab168
6ca5846
 
87ab168
6ca5846
 
87ab168
 
 
6ca5846
87ab168
6ca5846
 
87ab168
6ca5846
87ab168
 
 
6ca5846
87ab168
 
c05c6b5
87ab168
 
 
 
 
6ca5846
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
84d66d7
87ab168
 
 
 
 
6ca5846
c05c6b5
87ab168
 
84d66d7
c05c6b5
6ca5846
87ab168
 
 
6ca5846
 
87ab168
 
 
 
6ca5846
87ab168
 
 
 
 
c05c6b5
87ab168
6ca5846
87ab168
 
 
 
 
 
 
c05c6b5
87ab168
 
6ca5846
c05c6b5
87ab168
 
 
 
6ca5846
87ab168
6ca5846
87ab168
 
6ca5846
87ab168
 
 
c05c6b5
87ab168
6ca5846
87ab168
 
 
 
 
6ca5846
87ab168
 
 
 
 
6ca5846
c05c6b5
 
87ab168
 
 
 
 
 
 
6ca5846
 
 
c05c6b5
87ab168
 
 
c05c6b5
87ab168
c05c6b5
87ab168
 
 
 
 
 
 
 
6ca5846
 
c05c6b5
6ca5846
87ab168
 
 
 
6ca5846
 
87ab168
6ca5846
87ab168
 
 
 
c05c6b5
 
 
 
 
 
 
87ab168
 
 
6ca5846
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca5846
87ab168
 
 
 
 
6ca5846
 
 
 
 
87ab168
 
 
 
6ca5846
 
87ab168
 
 
 
 
 
 
 
 
 
84d66d7
 
87ab168
 
 
6ca5846
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
84d66d7
87ab168
 
 
 
 
84d66d7
c05c6b5
 
6ca5846
84d66d7
c05c6b5
6ca5846
c05c6b5
84d66d7
6ca5846
84d66d7
 
 
 
6ca5846
 
87ab168
c05c6b5
87ab168
84d66d7
 
c05c6b5
87ab168
 
 
 
 
 
 
c05c6b5
87ab168
 
 
c05c6b5
84d66d7
 
cd63945
87ab168
 
 
cd63945
 
84d66d7
 
 
 
 
87ab168
cd63945
84d66d7
 
 
 
 
 
87ab168
84d66d7
 
 
 
 
 
 
cd63945
84d66d7
 
 
 
 
 
 
 
87ab168
 
 
 
 
c05c6b5
 
87ab168
c05c6b5
87ab168
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
c05c6b5
87ab168
 
 
c05c6b5
 
 
87ab168
 
 
c05c6b5
87ab168
 
c05c6b5
87ab168
 
 
 
 
6ca5846
87ab168
c05c6b5
 
 
 
87ab168
 
 
 
 
 
 
c05c6b5
 
 
87ab168
 
 
 
 
 
 
 
 
 
 
 
6ca5846
84d66d7
 
cd63945
87ab168
 
 
cd63945
 
84d66d7
 
 
 
 
6ca5846
 
 
 
 
 
87ab168
cd63945
6ca5846
84d66d7
 
 
 
 
 
87ab168
84d66d7
 
cd63945
84d66d7
6ca5846
84d66d7
87ab168
cd63945
84d66d7
 
6ca5846
87ab168
 
84d66d7
 
 
 
 
 
87ab168
 
 
84d66d7
 
 
6ca5846
84d66d7
6ca5846
 
 
84d66d7
6ca5846
 
 
 
 
87ab168
84d66d7
87ab168
 
84d66d7
87ab168
 
 
c05c6b5
 
87ab168
 
 
 
 
84d66d7
 
87ab168
 
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca5846
87ab168
84d66d7
87ab168
 
 
 
 
84d66d7
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d66d7
c05c6b5
87ab168
 
 
 
 
 
 
 
 
 
 
 
 
 
84d66d7
87ab168
 
6ca5846
87ab168
 
 
 
6ca5846
87ab168
 
 
 
 
 
 
 
6ca5846
84d66d7
87ab168
 
84d66d7
87ab168
 
 
 
 
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87ab168
 
 
 
 
84d66d7
87ab168
 
6ca5846
87ab168
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
 
87ab168
 
 
6ca5846
 
87ab168
6ca5846
 
87ab168
 
 
6ca5846
87ab168
 
 
6ca5846
87ab168
 
84d66d7
87ab168
 
 
 
 
 
 
 
 
 
6ca5846
 
 
87ab168
 
 
 
 
 
 
 
 
84d66d7
87ab168
84d66d7
c05c6b5
87ab168
 
 
 
 
6ca5846
87ab168
 
 
 
 
 
6ca5846
 
87ab168
 
 
 
 
 
 
c05c6b5
87ab168
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
84d66d7
 
 
 
87ab168
84d66d7
 
 
 
87ab168
84d66d7
 
 
 
 
 
 
87ab168
6ca5846
 
 
 
 
 
 
 
 
87ab168
6ca5846
87ab168
 
 
6ca5846
87ab168
 
84d66d7
87ab168
 
 
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
 
 
87ab168
 
 
 
6ca5846
 
87ab168
 
6ca5846
87ab168
6ca5846
 
 
 
 
 
 
 
87ab168
 
 
 
6ca5846
 
87ab168
6ca5846
 
87ab168
 
 
 
 
 
 
 
c05c6b5
 
 
 
 
 
 
 
87ab168
 
c05c6b5
 
 
 
 
87ab168
 
 
c05c6b5
87ab168
84d66d7
6ca5846
 
 
 
87ab168
 
 
 
 
 
c05c6b5
87ab168
84d66d7
c05c6b5
 
 
87ab168
 
c05c6b5
 
87ab168
 
84d66d7
6ca5846
 
 
 
87ab168
 
 
 
 
6ca5846
87ab168
 
 
 
6ca5846
87ab168
c05c6b5
 
 
87ab168
 
 
 
 
 
6ca5846
87ab168
 
 
 
6ca5846
 
 
 
87ab168
6ca5846
 
 
 
 
 
87ab168
 
 
6ca5846
 
87ab168
 
 
 
 
 
 
 
6ca5846
87ab168
 
 
6ca5846
 
87ab168
6ca5846
 
87ab168
6ca5846
87ab168
 
6ca5846
87ab168
 
 
 
 
 
 
 
 
 
6ca5846
 
87ab168
c05c6b5
 
87ab168
 
c05c6b5
 
87ab168
 
 
 
6ca5846
 
87ab168
6ca5846
 
 
87ab168
 
 
 
 
 
 
 
 
 
c05c6b5
6ca5846
 
 
87ab168
6ca5846
87ab168
 
 
6ca5846
 
87ab168
6ca5846
87ab168
6ca5846
87ab168
 
 
6ca5846
 
 
87ab168
 
 
6ca5846
87ab168
6ca5846
87ab168
c05c6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca5846
87ab168
6ca5846
 
87ab168
 
6ca5846
 
 
 
 
 
 
 
87ab168
6ca5846
 
 
 
87ab168
6ca5846
87ab168
 
6ca5846
 
 
 
c05c6b5
6ca5846
 
 
87ab168
84d66d7
87ab168
6ca5846
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d66d7
6ca5846
 
 
 
 
 
 
84d66d7
6ca5846
 
 
c05c6b5
6ca5846
 
 
84d66d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca5846
 
 
 
 
 
87ab168
 
 
 
6ca5846
87ab168
6ca5846
87ab168
 
 
6ca5846
 
 
87ab168
 
6ca5846
 
87ab168
6ca5846
87ab168
6ca5846
87ab168
 
 
 
6ca5846
87ab168
 
 
 
 
6ca5846
 
c05c6b5
6ca5846
c05c6b5
87ab168
84d66d7
87ab168
 
 
 
 
6ca5846
87ab168
 
 
6ca5846
87ab168
c05c6b5
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

from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify, g
import json
import os
import logging
import threading
import time
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
from werkzeug.utils import secure_filename
from dotenv import load_dotenv
import requests
import uuid

load_dotenv()

app = Flask(__name__)
app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login'
DATA_FILE = 'data.json'


SYNC_FILES = [DATA_FILE]

REPO_ID = "Kgshop/shaik"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")

STORE_ADDRESSES = [
    "ТЦ Новый Ялян: 2 этаж, сектор D, бутик 53-55",
    "Рынок Ялян: ряд G, бутик 46"
]


CURRENCY_CODE = 'KZT'
CURRENCY_NAME = 'Казахстанский тенге'

DOWNLOAD_RETRIES = 3
DOWNLOAD_DELAY = 5

STATUS_MAPS = {
    'ru': {
        "new": "Новый",
        "accepted": "Принят",
        "prepared": "Собран",
        "shipped": "Отправлен"
    },
    'kz': {
        "new": "Жаңа",
        "accepted": "Қабылданды",
        "prepared": "Жиналды",
        "shipped": "Жөнелтілді"
    }
}

translations = {
    'ru': {
        'page_title': "SHAIK парфюм оптом и в розницу - Каталог",
        'header_title': "SHAIK Parfum",
        'our_addresses': "Наши адреса в г. Алматы",
        'search_placeholder': "Поиск по названию или описанию...",
        'all_filter': "Все",
        'top_product': "Топ",
        'add_to_cart_button': "В корзину",
        'from_price': "от",
        'no_products_yet': "Товары пока не добавлены.",
        'loading': "Загрузка...",
        'product_load_error': "Не удалось загрузить информацию о товаре.",
        'specify_details': "Укажите детали",
        'variant_label': "Вариант:",
        'quantity_label': "Количество:",
        'confirm_add_to_cart': "Добавить в корзину",
        'your_cart': "Ваша корзина",
        'cart_is_empty': "Ваша корзина пуста.",
        'total': "Итого:",
        'clear_cart_button': "Очистить",
        'formulate_order_button': "Оформить заказ",
        'cart_item_variant': "Вариант",
        'remove_item_title': "Удалить товар",
        'clear_cart_confirm': "Вы уверены, что хотите очистить корзину?",
        'cart_is_empty_alert': "Корзина пуста!",
        'formulating_order': "Формируем заказ...",
        'add_to_cart_notification': "добавлен в корзину!",
        'no_products_found': "По вашему запросу товары не найдены.",
        'category': "Категория",
        'brand': "Бренд",
        'no_category': "Без категории",
        'no_brand': "Без бренда",
        'available_variants': "Доступные варианты:",
        'description': "Описание:",
        'no_description': "Описание отсутствует.",
        'order_page_title': "Заказ №",
        'order_created_at': "Дата создания:",
        'order_items': "Товары в заказе",
        'order_total_price': "Общая сумма товаров:",
        'order_status_and_confirmation': "Статус и подтверждение",
        'order_current_status': "Текущий статус:",
        'order_whatsapp_prompt': "Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения заказа и уточнения деталей доставки и оплаты.",
        'order_contact_us_button': "Связаться с нами",
        'return_to_catalog': "Вернуться в каталог",
        'order_not_found_error': "Ошибка",
        'order_not_found_message': "Заказ с таким ID не найден.",
        'whatsapp_confirm_message_1': "Здравствуйте! Хочу подтвердить свой заказ на SHAIK парфюм:",
        'whatsapp_confirm_message_2': "Номер заказа:",
        'whatsapp_confirm_message_3': "Ссылка на заказ:",
        'whatsapp_confirm_message_4': "Пожалуйста, свяжитесь со мной для уточнения деталей.",
    },
    'kz': {
        'page_title': "SHAIK парфюмериясы көтерме және бөлшек саудада - Каталог",
        'header_title': "SHAIK Parfum",
        'our_addresses': "Алматы қаласындағы мекенжайларымыз",
        'search_placeholder': "Аты немесе сипаттамасы бойынша іздеу...",
        'all_filter': "Барлығы",
        'top_product': "Топ",
        'add_to_cart_button': "Себетке салу",
        'from_price': "-ден бастап",
        'no_products_yet': "Тауарлар әлі қосылмаған.",
        'loading': "Жүктелуде...",
        'product_load_error': "Тауар туралы ақпаратты жүктеу мүмкін болмады.",
        'specify_details': "Мәліметтерді көрсетіңіз",
        'variant_label': "Нұсқа:",
        'quantity_label': "Саны:",
        'confirm_add_to_cart': "Себетке қосу",
        'your_cart': "Сіздің себетіңіз",
        'cart_is_empty': "Сіздің себетіңіз бос.",
        'total': "Жиыны:",
        'clear_cart_button': "Тазарту",
        'formulate_order_button': "Тапсырыс беру",
        'cart_item_variant': "Нұсқа",
        'remove_item_title': "Тауарды жою",
        'clear_cart_confirm': "Себетті тазалағыңыз келетініне сенімдісіз бе?",
        'cart_is_empty_alert': "Себет бос!",
        'formulating_order': "Тапсырыс қалыптастырылуда...",
        'add_to_cart_notification': "себетке қосылды!",
        'no_products_found': "Сіздің сұранысыңыз бойынша тауарлар табылмады.",
        'category': "Санат",
        'brand': "Бренд",
        'no_category': "Санатсыз",
        'no_brand': "Брендсіз",
        'available_variants': "Қолжетімді нұсқалар:",
        'description': "Сипаттама:",
        'no_description': "Сипаттама жоқ.",
        'order_page_title': "Тапсырыс №",
        'order_created_at': "Құрылған күні:",
        'order_items': "Тапсырыстағы тауарлар",
        'order_total_price': "Тауарлардың жалпы сомасы:",
        'order_status_and_confirmation': "Мәртебесі және растау",
        'order_current_status': "Ағымдағы мәртебе:",
        'order_whatsapp_prompt': "Тапсырысты растау және жеткізу мен төлем туралы мәліметтерді нақтылау үшін WhatsApp арқылы бізбен хабарласыңыз.",
        'order_contact_us_button': "Бізбен байланысу",
        'return_to_catalog': "Каталогқа оралу",
        'order_not_found_error': "Қате",
        'order_not_found_message': "Мұндай ID-мен тапсырыс табылмады.",
        'whatsapp_confirm_message_1': "Сәлеметсіз бе! SHAIK парфюмериясына берген тапсырысымды растағым келеді:",
        'whatsapp_confirm_message_2': "Тапсырыс нөмірі:",
        'whatsapp_confirm_message_3': "Тапсырысқа сілтеме:",
        'whatsapp_confirm_message_4': "Мәліметтерді нақтылау үшін менімен хабарласуыңызды сұраймын.",
    }
}


logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')



def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
    if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
        logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")

    token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE

    files_to_download = [specific_file] if specific_file else SYNC_FILES
    logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...")
    all_successful = True

    for file_name in files_to_download:
        success = False
        for attempt in range(retries + 1):
            try:
                logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
                local_path = hf_hub_download(
                    repo_id=REPO_ID,
                    filename=file_name,
                    repo_type="dataset",
                    token=token_to_use,
                    local_dir=".",
                    local_dir_use_symlinks=False,
                    force_download=True,
                    resume_download=False
                )
                logging.info(f"Successfully downloaded {file_name} to {local_path}.")
                success = True
                break
            except RepositoryNotFoundError:
                 logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.")
                 return False
            except HfHubHTTPError as e:
                if e.response.status_code == 404:
                    logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.")
                    if attempt == 0 and not os.path.exists(file_name):
                        try:
                            if file_name == DATA_FILE:
                                with open(file_name, 'w', encoding='utf-8') as f:
                                    json.dump({'products': [], 'categories': [], 'brands': [], 'orders': {}}, f)
                                logging.info(f"Created empty local file {file_name} because it was not found on HF.")
                        except Exception as create_e:
                            logging.error(f"Failed to create empty local file {file_name}: {create_e}")
                    success = False
                    break
                else:
                    logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
            except requests.exceptions.RequestException as e:
                 logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
            except Exception as e:
                 logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True)

            if attempt < retries:
                time.sleep(delay)

        if not success:
            logging.error(f"Failed to download {file_name} after {retries + 1} attempts.")
            all_successful = False

    logging.info(f"Download process finished. Overall success: {all_successful}")
    return all_successful

def upload_db_to_hf(specific_file=None):
    if not HF_TOKEN_WRITE:
        logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.")
        return
    try:
        api = HfApi()
        files_to_upload = [specific_file] if specific_file else SYNC_FILES
        logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")

        for file_name in files_to_upload:
            if os.path.exists(file_name):
                try:
                    api.upload_file(
                        path_or_fileobj=file_name,
                        path_in_repo=file_name,
                        repo_id=REPO_ID,
                        repo_type="dataset",
                        token=HF_TOKEN_WRITE,
                        commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                    )
                    logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
                except Exception as e:
                     logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
            else:
                logging.warning(f"File {file_name} not found locally, skipping upload.")
        logging.info("Finished uploading files to HF.")
    except Exception as e:
        logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)

def periodic_backup():
    backup_interval = 1800
    logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
    while True:
        time.sleep(backup_interval)
        logging.info("Starting periodic backup...")
        upload_db_to_hf()
        logging.info("Periodic backup finished.")



def load_data():
    default_data = {'products': [], 'categories': [], 'brands': [], 'orders': {}}
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as file:
            data = json.load(file)
        logging.info(f"Local data loaded successfully from {DATA_FILE}")
        if not isinstance(data, dict):
             logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
             raise FileNotFoundError
        if 'products' not in data: data['products'] = []
        if 'categories' not in data: data['categories'] = []
        if 'brands' not in data: data['brands'] = []
        if 'orders' not in data: data['orders'] = {}
        return data
    except FileNotFoundError:
        logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")
    except json.JSONDecodeError:
        logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.")

    if download_db_from_hf(specific_file=DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as file:
                data = json.load(file)
            logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
            if not isinstance(data, dict):
                 logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
                 return default_data
            if 'products' not in data: data['products'] = []
            if 'categories' not in data: data['categories'] = []
            if 'brands' not in data: data['brands'] = []
            if 'orders' not in data: data['orders'] = {}
            return data
        except FileNotFoundError:
             logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")
             return default_data
        except json.JSONDecodeError:
            logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.")
            return default_data
        except Exception as e:
            logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True)
            return default_data
    else:
        logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")
        if not os.path.exists(DATA_FILE):
            try:
                with open(DATA_FILE, 'w', encoding='utf-8') as f:
                    json.dump(default_data, f)
                logging.info(f"Created empty local file {DATA_FILE} after failed download.")
            except Exception as create_e:
                logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}")
        return default_data

def save_data(data):
    try:
        if not isinstance(data, dict):
            logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
            return
        if 'products' not in data: data['products'] = []
        if 'categories' not in data: data['categories'] = []
        if 'brands' not in data: data['brands'] = []
        if 'orders' not in data: data['orders'] = {}

        with open(DATA_FILE, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
        logging.info(f"Data successfully saved to {DATA_FILE}")
        upload_db_to_hf(specific_file=DATA_FILE)
    except Exception as e:
        logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)



CATALOG_TEMPLATE = '''
    <!DOCTYPE html>
    <html lang="{{ lang_code }}">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ _['page_title'] }}</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <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=Cormorant+Garamond:wght@400;600;700&family=Georgia&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
        <style>
            :root {
                --primary-color: #FF3B30; 
                --primary-dark: #D9322A;
                --surface-color: #1A1A1A;
                --background-color: #121212;
                --text-color: #F5F5F5;
                --text-color-muted: #999;
                --border-color: #333333;
                --success-color: #28a745;
            }
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { 
                font-family: 'Georgia', serif; 
                background: var(--background-color); 
                color: var(--text-color); 
                line-height: 1.6; 
                transition: background-color 0.3s; 
            }
            .container { max-width: 100%; margin: 0 auto; padding: 0; }
            .content-area { padding: 20px; }

            .header { display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; background: rgba(18, 18, 18, 0.8); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border-color); position: sticky; top: 0; z-index: 1000; }
            .logo-title-container { display: flex; align-items: center; gap: 15px; }
            .logo-title-container img { height: 45px; width: 45px; border-radius: 50%; object-fit: cover; box-shadow: 0 0 10px rgba(255, 59, 48, 0.5); }
            .header h1 { font-family: 'Cormorant Garamond', serif; font-size: 1.8rem; font-weight: 700; color: var(--text-color); }
            
            .lang-switcher { display: flex; gap: 5px; background-color: var(--surface-color); padding: 5px; border-radius: 50px; }
            .lang-switcher a { color: var(--text-color-muted); text-decoration: none; font-size: 0.9rem; padding: 5px 10px; border-radius: 50px; transition: all 0.3s; }
            .lang-switcher a.active { background-color: var(--primary-color); color: white; font-weight: bold; }
            
            .store-addresses { padding: 20px; text-align: center; background-color: var(--surface-color); border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.5); font-size: 0.95rem; color: var(--text-color-muted); margin: 20px; }
            .store-addresses h3 { font-family: 'Cormorant Garamond', serif; color: var(--primary-color); font-size: 1.3rem; margin-bottom: 10px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 8px; }
            .store-addresses p { margin: 5px 0; }

            .search-container { padding: 0 20px 20px; }
            #search-input { width: 100%; padding: 12px 20px; font-size: 1rem; border: 1px solid var(--border-color); border-radius: 50px; outline: none; transition: all 0.3s; background-color: var(--surface-color); color: var(--text-color); }
            #search-input:focus { border-color: var(--primary-color); box-shadow: 0 0 0 4px rgba(255, 59, 48, 0.2); }
            
            .filters-wrapper { margin: 0 20px 20px; display: flex; flex-direction: column; gap: 15px; }
            .filters-container { display: flex; overflow-x: auto; gap: 10px; padding-bottom: 10px; scrollbar-width: none; -ms-overflow-style: none; }
            .filters-container::-webkit-scrollbar { display: none; }
            .filter-label { font-size: 0.9rem; color: var(--text-color-muted); margin-left: 5px; }
            .category-filter, .brand-filter { padding: 8px 18px; border: 1px solid var(--border-color); border-radius: 50px; background-color: transparent; cursor: pointer; transition: all 0.3s ease; font-size: 0.9rem; font-weight: 400; color: var(--text-color-muted); white-space: nowrap; }
            .category-filter.active, .brand-filter.active, .category-filter:hover, .brand-filter:hover { background-color: var(--primary-color); color: #fff; border-color: var(--primary-color); font-weight: 500; box-shadow: 0 2px 8px rgba(255, 59, 48, 0.3); transform: translateY(-2px); }

            .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; padding: 0 20px 120px; }
            @media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 20px; } }

            .product { background: var(--surface-color); border-radius: 16px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4); transition: all 0.3s ease; overflow: hidden; display: flex; flex-direction: column; height: 100%; position: relative; border: 1px solid var(--border-color); }
            .product:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(255, 59, 48, 0.15); border-color: var(--primary-color); }
            
            .product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #000; display: flex; justify-content: center; align-items: center; padding: 10px; }
            .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; }
            .product:hover .product-image img { transform: scale(1.05); }
            .product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; text-align: center; }
            .product h2 { font-family: 'Cormorant Garamond', serif; font-size: 1.2rem; font-weight: 600; margin: 0 0 8px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-color); }
            .product-price { font-size: 1.2rem; color: var(--primary-color); font-weight: 700; margin: 5px 0; }
            .product-price .from-text { font-size: 0.8rem; color: var(--text-color-muted); font-weight: 400; }
            .product-description { display: none; }
            .product-actions { padding: 0 15px 15px; }
            
            .product-button { display: inline-flex; align-items: center; justify-content: center; width: 100%; padding: 10px; border: none; border-radius: 50px; background-color: var(--primary-color); color: #fff; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s ease; text-decoration: none; text-transform: uppercase; letter-spacing: 0.5px; }
            .product-button:hover { background-color: var(--primary-dark); box-shadow: 0 4px 10px rgba(255, 59, 48, 0.4); }
            .product-button i { margin-right: 8px; }

            .fab { position: fixed; background-color: var(--primary-color); color: #fff; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(255, 59, 48, 0.4); z-index: 1000; transition: transform 0.2s ease; }
            .fab:hover { transform: scale(1.1); }
            #cart-button { bottom: 20px; right: 20px; display: none; }
            #cart-button span { position: absolute; top: -2px; right: -2px; background-color: #dc3545; color: white; border-radius: 50%; padding: 3px 7px; font-size: 0.75rem; font-weight: bold; min-width: 22px; text-align: center; }
            
            .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.85); backdrop-filter: blur(8px); overflow-y: auto; }
            .modal-content { background: var(--surface-color); margin: 5% auto; padding: 25px; border-radius: 16px; width: 95%; max-width: 600px; box-shadow: 0 10px 40px rgba(0,0,0,0.7); animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94); position: relative; border: 1px solid var(--border-color); }
            @keyframes slideIn { from { transform: translateY(-40px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
            
            .close { position: absolute; top: 15px; right: 20px; font-size: 2rem; color: var(--text-color-muted); cursor: pointer; transition: color 0.3s, transform 0.3s; line-height: 1; }
            .close:hover { color: var(--primary-color); transform: rotate(90deg); }
            
            .modal-content h2 { font-family: 'Cormorant Garamond', serif; margin-top: 0; margin-bottom: 25px; color: var(--primary-color); font-size: 1.8rem; display: flex; align-items: center; gap: 12px;}
            
            .cart-item { display: grid; grid-template-columns: 65px 1fr auto 25px; 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: 65px; height: 65px; object-fit: contain; border-radius: 8px; background-color: #000; padding: 5px; }
            .cart-item-details strong { display: block; margin-bottom: 4px; font-size: 1.05rem; }
            .cart-item-price { font-size: 0.9rem; color: var(--text-color-muted); }
            .cart-item-total { font-weight: bold; text-align: right; font-size: 1rem; color: var(--primary-color); }
            .cart-item-remove { background:none; border:none; color:#FF453A; cursor:pointer; font-size: 1.5rem; line-height: 1; transition: color 0.2s; }
            .cart-item-remove:hover { color: #ff0000; }
            
            .quantity-input, .variant-select { width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; margin-top: 8px; margin-bottom: 20px; box-sizing: border-box; background-color: var(--background-color); color: var(--text-color); }

            .cart-summary { margin-top: 25px; text-align: right; border-top: 1px solid var(--border-color); padding-top: 20px; }
            .cart-summary strong { font-size: 1.4rem; color: var(--primary-color); }
            .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 12px; }
            .cart-actions .product-button { flex-grow: 1; }
            .clear-cart { background: #444; color: var(--text-color); }
            .clear-cart:hover { background: #555; }
            
            .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: var(--primary-color); color: #fff; padding: 12px 25px; border-radius: 50px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); z-index: 1002; opacity: 0; transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94); font-size: 0.95rem; font-weight: 500; }
            .notification.show { opacity: 1; bottom: 90px; }
            .no-results-message { grid-column: 1 / -1; text-align: center; padding: 50px; font-size: 1.2rem; color: var(--text-color-muted); }
            .top-product-indicator { position: absolute; top: 10px; right: 10px; background: linear-gradient(135deg, #FF3B30, #D9322A); color: #fff; padding: 3px 8px; font-size: 0.7rem; border-radius: 50px; font-weight: bold; z-index: 10; display: flex; align-items: center; gap: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.5); }
            
            #whatsapp-fab { bottom: 20px; left: 20px; background-color: #25D366; color: white; }
            #whatsapp-modal { display: none; position: fixed; bottom: 85px; left: 20px; background-color: var(--surface-color); border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.6); z-index: 1001; overflow: hidden; border: 1px solid var(--border-color); animation: fadeIn 0.3s; }
            @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
            #whatsapp-modal a { display: flex; align-items: center; gap: 15px; padding: 15px 20px; text-decoration: none; color: var(--text-color); transition: background-color 0.2s; }
            #whatsapp-modal a:first-child { border-bottom: 1px solid var(--border-color); }
            #whatsapp-modal a:hover { background-color: rgba(255,255,255,0.05); }
            #whatsapp-modal i { color: #25D366; font-size: 1.6rem; }
        </style>
    </head>
    <body>
        <div class="container">
             <header class="header">
                 <div class="logo-title-container">
                    <img src="https://huggingface.co/spaces/Shaik-parfume/app/resolve/main/icon.png" alt="SHAIK Logo">
                    <h1>{{ _['header_title'] }}</h1>
                </div>
                <div class="lang-switcher">
                    <a href="/ru{{ request.path.replace('/kz', '') }}" class="{{ 'active' if lang_code == 'ru' else '' }}">RU</a>
                    <a href="/kz{{ request.path.replace('/ru', '') }}" class="{{ 'active' if lang_code == 'kz' else '' }}">KZ</a>
                </div>
            </header>

            <div class="store-addresses">
                <h3><i class="fas fa-map-marker-alt"></i> {{ _['our_addresses'] }}</h3>
                {% for address in store_addresses %}
                    <p>{{ address }}</p>
                {% endfor %}
            </div>


            <div class="search-container">
                <input type="text" id="search-input" placeholder="{{ _['search_placeholder'] }}">
            </div>

            <div class="filters-wrapper">
                <div>
                    <span class="filter-label">{{ _['category'] }}:</span>
                    <div class="filters-container">
                        <button class="category-filter active" data-category="all">{{ _['all_filter'] }}</button>
                        {% for category in categories %}
                        <button class="category-filter" data-category="{{ category }}">{{ category }}</button>
                        {% endfor %}
                    </div>
                </div>
                {% if brands %}
                <div>
                    <span class="filter-label">{{ _['brand'] }}:</span>
                    <div class="filters-container">
                        <button class="brand-filter active" data-brand="all">{{ _['all_filter'] }}</button>
                        {% for brand in brands %}
                        <button class="brand-filter" data-brand="{{ brand }}">{{ brand }}</button>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>


            <main class="products-grid" id="products-grid">
                {% for product in products %}
                <div class="product"
                     data-name="{{ product['name']|lower }}"
                     data-description="{{ product.get('description', '')|lower }}"
                     data-category="{{ product.get('category', _['no_category']) }}"
                     data-brand="{{ product.get('brand', _['no_brand']) }}">
                     {% if product.get('is_top', False) %}
                        <span class="top-product-indicator"><i class="fas fa-star fa-xs"></i> {{ _['top_product'] }}</span>
                     {% endif %}
                    <div class="product-image" onclick="openModal({{ loop.index0 }})" style="cursor: pointer;">
                        {% if product.get('photos') and product['photos']|length > 0 %}
                            <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
                                 alt="{{ product['name'] }}"
                                 loading="lazy">
                        {% else %}
                            <img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy">
                        {% endif %}
                    </div>
                    <div class="product-info">
                        <h2>{{ product['name'] }}</h2>
                        <div class="product-price">
                           {% if product.get('variants') and product.variants|length > 0 %}
                               <span class="from-text">{{ _['from_price'] }}</span> {{ "%.2f"|format(product.variants|map(attribute='price')|min) }} {{ currency_code }}
                           {% else %}
                               -
                           {% endif %}
                        </div>
                    </div>
                    <div class="product-actions">
                        <button class="product-button" onclick="openQuantityModal({{ loop.index0 }})">
                           <i class="fas fa-shopping-bag"></i> {{ _['add_to_cart_button'] }}
                        </button>
                    </div>
                </div>
                {% endfor %}
                 {% if not products %}
                 <p class="no-results-message">{{ _['no_products_yet'] }}</p>
                 {% endif %}
            </main>
        </div>

        <div id="productModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">&times;</span>
                <div id="modalContent">{{ _['loading'] }}</div>
            </div>
        </div>

        <div id="quantityModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">&times;</span>
                <h2>{{ _['specify_details'] }}</h2>
                <label for="variantSelect">{{ _['variant_label'] }}</label>
                <select id="variantSelect" class="variant-select"></select>

                <label for="quantityInput">{{ _['quantity_label'] }}</label>
                <input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
                
                <button class="product-button" onclick="confirmAddToCart()"><i class="fas fa-check"></i> {{ _['confirm_add_to_cart'] }}</button>
            </div>
        </div>

        <div id="cartModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">&times;</span>
                <h2><i class="fas fa-shopping-cart"></i> {{ _['your_cart'] }}</h2>
                <div id="cartContent"><p style="text-align: center; padding: 20px 0;">{{ _['cart_is_empty'] }}</p></div>
                <div class="cart-summary">
                    <strong>{{ _['total'] }} <span id="cartTotal">0.00</span> {{ currency_code }}</strong>
                </div>
                <div class="cart-actions">
                    <button class="product-button clear-cart" onclick="clearCart()">
                       <i class="fas fa-trash"></i> {{ _['clear_cart_button'] }}
                    </button>
                    <button class="product-button formulate-order-button" onclick="formulateOrder()">
                       <i class="fas fa-file-alt"></i> {{ _['formulate_order_button'] }}
                    </button>
                </div>
            </div>
        </div>

        <button id="cart-button" class="fab" onclick="openCartModal()" aria-label="Открыть корзину">
           <i class="fas fa-shopping-cart"></i>
           <span id="cart-count">0</span>
        </button>

        <button id="whatsapp-fab" class="fab" onclick="toggleWhatsAppModal()"><i class="fab fa-whatsapp"></i></button>
        <div id="whatsapp-modal">
            <a href="https://api.whatsapp.com/send?phone=77762021169" target="_blank" rel="noopener noreferrer">
                <i class="fab fa-whatsapp"></i>
                <span>WhatsApp 1</span>
            </a>
            <a href="https://api.whatsapp.com/send?phone=77711094111" target="_blank" rel="noopener noreferrer">
                <i class="fab fa-whatsapp"></i>
                <span>WhatsApp 2</span>
            </a>
        </div>

        <div id="notification-placeholder"></div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
        <script>
            const products = {{ products|tojson }};
            const repoId = '{{ repo_id }}';
            const currencyCode = '{{ currency_code }}';
            let selectedProductIndex = null;
            let cart = JSON.parse(localStorage.getItem('shaikCart') || '[]');
            const langCode = '{{ lang_code }}';
            const translations = {{ _|tojson }};

            function openModal(index) {
                loadProductDetails(index);
                document.getElementById('productModal').style.display = "block";
                document.body.style.overflow = 'hidden';
            }

            function closeModal(modalId) {
                document.getElementById(modalId).style.display = "none";
                const anyModalOpen = document.querySelector('.modal[style*="display: block"]');
                if (!anyModalOpen) {
                    document.body.style.overflow = 'auto';
                }
            }
            
            function toggleWhatsAppModal() {
                const modal = document.getElementById('whatsapp-modal');
                modal.style.display = modal.style.display === 'block' ? 'none' : 'block';
            }

            function loadProductDetails(index) {
                const modalContent = document.getElementById('modalContent');
                modalContent.innerHTML = `<p style="text-align:center; padding: 40px;">${translations['loading']}</p>`;
                fetch(`/${langCode}/product/${index}`)
                    .then(response => response.text())
                    .then(data => {
                        modalContent.innerHTML = data;
                        initializeSwiper();
                    })
                    .catch(error => {
                        console.error('Ошибка загрузки деталей продукта:', error);
                        modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">${translations['product_load_error']}</p>`;
                    });
            }

            function initializeSwiper() {
                new Swiper('#productModal .swiper-container', {
                    slidesPerView: 1, spaceBetween: 20, loop: true, grabCursor: true,
                    pagination: { el: '.swiper-pagination', clickable: true, dynamicBullets: true },
                    navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
                    zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' },
                    autoplay: { delay: 4000, disableOnInteraction: true },
                });
            }

            function setupVariantSelect(variants) {
                const select = document.getElementById('variantSelect');
                select.innerHTML = '';
                if (variants && variants.length > 0) {
                    variants.forEach((variant, index) => {
                         const option = document.createElement('option');
                         option.value = index;
                         option.text = `${variant.name} - ${variant.price.toFixed(2)} ${currencyCode}`;
                         select.appendChild(option);
                    });
                    select.style.display = 'block';
                } else {
                    select.style.display = 'none';
                }
            }

            function openQuantityModal(index) {
                selectedProductIndex = index;
                const product = products[index];
                if (!product) return;

                setupVariantSelect(product.variants);
                document.getElementById('quantityInput').value = 1;
                document.getElementById('quantityModal').style.display = 'block';
                document.body.style.overflow = 'hidden';
            }

            function confirmAddToCart() {
                if (selectedProductIndex === null) return;

                const quantity = parseInt(document.getElementById('quantityInput').value);
                const variantIndex = document.getElementById('variantSelect').value;
                const product = products[selectedProductIndex];
                
                if (!product || !product.variants || product.variants.length === 0) {
                    alert("Ошибка: Варианты для этого товара не найдены.");
                    return;
                }
                
                const selectedVariant = product.variants[variantIndex];

                if (isNaN(quantity) || quantity <= 0) {
                    alert("Пожалуйста, укажите корректное количество.");
                    return;
                }

                const cartItemId = `${product.id}-${selectedVariant.name}`;
                const existingItem = cart.find(item => item.id === cartItemId);

                if (existingItem) {
                    existingItem.quantity += quantity;
                } else {
                    cart.push({
                        id: cartItemId,
                        productId: product.id,
                        name: product.name,
                        price: selectedVariant.price,
                        variantName: selectedVariant.name,
                        photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,
                        quantity: quantity
                    });
                }

                localStorage.setItem('shaikCart', JSON.stringify(cart));
                closeModal('quantityModal');
                updateCartButton();
                showNotification(`${product.name} (${selectedVariant.name}) ${translations['add_to_cart_notification']}`);
            }

            function updateCartButton() {
                 const cartCountElement = document.getElementById('cart-count');
                 const cartButton = document.getElementById('cart-button');
                 const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);

                 if (totalItems > 0) {
                     cartCountElement.textContent = totalItems;
                     cartButton.style.display = 'flex';
                 } else {
                     cartButton.style.display = 'none';
                 }
            }

            function openCartModal() {
                const cartContent = document.getElementById('cartContent');
                const cartTotalElement = document.getElementById('cartTotal');
                let total = 0;

                if (cart.length === 0) {
                    cartContent.innerHTML = `<p style="text-align: center; padding: 20px 0;">${translations['cart_is_empty']}</p>`;
                    cartTotalElement.textContent = '0.00';
                } else {
                    cartContent.innerHTML = cart.map(item => {
                        const itemTotal = item.price * item.quantity;
                        total += itemTotal;
                        const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/65x65.png?text=N/A';
                        
                        return `
                            <div class="cart-item">
                                <img src="${photoUrl}" alt="${item.name}">
                                <div class="cart-item-details">
                                    <strong>${item.name}</strong>
                                    <p class="cart-item-price">${translations['cart_item_variant']}: ${item.variantName}</p>
                                    <p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}</p>
                                </div>
                                <span class="cart-item-total">${itemTotal.toFixed(2)}</span>
                                <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="${translations['remove_item_title']}">&times;</button>
                            </div>`;
                    }).join('');
                    cartTotalElement.textContent = total.toFixed(2);
                }
                document.getElementById('cartModal').style.display = 'block';
                document.body.style.overflow = 'hidden';
            }

             function removeFromCart(itemId) {
                cart = cart.filter(item => item.id !== itemId);
                localStorage.setItem('shaikCart', JSON.stringify(cart));
                openCartModal();
                updateCartButton();
             }

            function clearCart() {
                if (confirm(translations['clear_cart_confirm'])) {
                    cart = [];
                    localStorage.removeItem('shaikCart');
                    openCartModal();
                    updateCartButton();
                }
            }

            function formulateOrder() {
                if (cart.length === 0) {
                    alert(translations['cart_is_empty_alert']);
                    return;
                }
                document.querySelector('.formulate-order-button').disabled = true;
                showNotification(translations['formulating_order'], 5000);

                fetch('/create_order', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ cart: cart })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.order_id) {
                        localStorage.removeItem('shaikCart');
                        cart = [];
                        updateCartButton();
                        closeModal('cartModal');
                        window.location.href = `/${langCode}/order/${data.order_id}`;
                    } else {
                        throw new Error(data.error || 'Не получен ID заказа от сервера.');
                    }
                })
                .catch(error => {
                    console.error('Ошибка при формировании заказа:', error);
                    alert(`Ошибка: ${error.message}`);
                    document.querySelector('.formulate-order-button').disabled = false;
                });
            }

            function filterProducts() {
                const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
                const activeCategory = document.querySelector('.category-filter.active').dataset.category;
                const activeBrandEl = document.querySelector('.brand-filter.active');
                const activeBrand = activeBrandEl ? activeBrandEl.dataset.brand : 'all';
                const grid = document.getElementById('products-grid');
                let visibleProducts = 0;

                const existingNoResults = grid.querySelector('.no-results-message');
                if (existingNoResults) existingNoResults.remove();
                
                document.querySelectorAll('.products-grid .product').forEach(productElement => {
                    const name = productElement.dataset.name;
                    const description = productElement.dataset.description;
                    const category = productElement.dataset.category;
                    const brand = productElement.dataset.brand;

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

                    if (matchesSearch && matchesCategory && matchesBrand) {
                        productElement.style.display = 'flex';
                        visibleProducts++;
                    } else {
                        productElement.style.display = 'none';
                    }
                });

                 if (visibleProducts === 0) {
                    const msg = document.createElement('p');
                    msg.className = 'no-results-message';
                    msg.textContent = products.length > 0 ? translations['no_products_found'] : translations['no_products_yet'];
                    grid.appendChild(msg);
                 }
            }

             function setupFilters() {
                 document.getElementById('search-input').addEventListener('input', filterProducts);
                 document.querySelectorAll('.category-filter').forEach(filter => {
                     filter.addEventListener('click', function() {
                         document.querySelector('.category-filter.active').classList.remove('active');
                         this.classList.add('active');
                         filterProducts();
                     });
                 });
                 document.querySelectorAll('.brand-filter').forEach(filter => {
                     filter.addEventListener('click', function() {
                         document.querySelector('.brand-filter.active').classList.remove('active');
                         this.classList.add('active');
                         filterProducts();
                     });
                 });
             }

             function showNotification(message, duration = 3000) {
                const placeholder = document.getElementById('notification-placeholder');
                const notification = document.createElement('div');
                notification.className = 'notification';
                notification.textContent = message;
                placeholder.appendChild(notification);
                void notification.offsetWidth;
                notification.classList.add('show');
                setTimeout(() => {
                    notification.classList.remove('show');
                    notification.addEventListener('transitionend', () => notification.remove());
                }, duration);
             }

            document.addEventListener('DOMContentLoaded', () => {
                updateCartButton();
                setupFilters();
                filterProducts();

                window.addEventListener('click', function(event) {
                    if (event.target.classList.contains('modal')) {
                        closeModal(event.target.id);
                    }
                    const waModal = document.getElementById('whatsapp-modal');
                    const waFab = document.getElementById('whatsapp-fab');
                    if (waModal.style.display === 'block' && !waModal.contains(event.target) && event.target !== waFab && !waFab.contains(event.target)) {
                        waModal.style.display = 'none';
                    }
                });

                window.addEventListener('keydown', function(event) {
                    if (event.key === 'Escape') {
                         document.querySelectorAll('.modal').forEach(modal => modal.style.display = 'none');
                         document.body.style.overflow = 'auto';
                    }
                });
            });
        </script>
    </body>
    </html>
'''

PRODUCT_DETAIL_TEMPLATE = '''
    <div style="padding: 10px;">
        <h2 style="font-family: 'Cormorant Garamond', serif; font-size: 2rem; font-weight: 700; margin-bottom: 20px; text-align: center; color: var(--primary-color);">{{ product['name'] }}</h2>
        <div class="swiper-container" style="max-width: 450px; margin: 0 auto 25px; border-radius: 12px; overflow: hidden; border: 1px solid var(--border-color);">
            <div class="swiper-wrapper">
                {% if product.get('photos') and product['photos']|length > 0 %}
                    {% for photo in product['photos'] %}
                    <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px; background-color: #000;">
                         <div class="swiper-zoom-container">
                             <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
                                  alt="{{ product['name'] }} - фото {{ loop.index }}"
                                  style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;">
                         </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;">
                         <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;">
                    </div>
                {% endif %}
            </div>
            {% if product.get('photos') and product['photos']|length > 1 %}
            <div class="swiper-pagination" style="position: relative; bottom: 5px; margin-top: 10px;"></div>
            <div class="swiper-button-next" style="color: var(--primary-color);"></div>
            <div class="swiper-button-prev" style="color: var(--primary-color);"></div>
            {% endif %}
        </div>

        <div style="font-size: 1rem; line-height: 1.7; padding: 0 10px;">
            <p><strong>{{ _['category'] }}:</strong> {{ product.get('category', _['no_category']) }}</p>
            <p><strong>{{ _['brand'] }}:</strong> {{ product.get('brand', _['no_brand']) }}</p>
            {% if product.get('variants') and product.variants|length > 0 %}
                <p style="font-size: 1.4rem; font-weight: bold; color: var(--primary-color); margin: 15px 0;">
                    {{ _['from_price'] }} {{ "%.2f"|format(product.variants|map(attribute='price')|min) }} {{ currency_code }}
                </p>
                <p><strong>{{ _['available_variants'] }}</strong></p>
                <ul style="list-style: none; padding-left: 0;">
                {% for variant in product.variants %}
                    <li style="padding: 5px 0; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between;">
                        <span>- {{ variant.name }}</span>
                        <strong>{{ "%.2f"|format(variant.price) }} {{ currency_code }}</strong>
                    </li>
                {% endfor %}
                </ul>
            {% endif %}
            <p style="margin-top: 20px;"><strong>{{ _['description'] }}:</strong><br> {{ product.get('description', _['no_description'])|replace('\\n', '<br>')|safe }}</p>
        </div>
        <div style="padding: 20px 10px 10px; text-align: center;">
            <button class="product-button" onclick="closeModal('productModal'); openQuantityModal({{ products_index }})" style="margin-top: 15px; padding: 12px 25px; font-size: 1rem;">
               <i class="fas fa-shopping-bag"></i> {{ _['add_to_cart_button'] }}
            </button>
        </div>
    </div>
'''

ORDER_TEMPLATE = '''
<!DOCTYPE html>
<html lang="{{ lang_code }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _['order_page_title'] }}{{ order.id }} - SHAIK парфюм</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=Cormorant+Garamond:wght@400;600;700&family=Georgia&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --primary-color: #FF3B30; 
            --primary-dark: #D9322A;
            --surface-color: #1A1A1A;
            --background-color: #121212;
            --text-color: #F5F5F5;
            --text-color-muted: #999;
            --border-color: #333333;
        }
        body { font-family: 'Georgia', serif; background: var(--background-color); color: var(--text-color); line-height: 1.6; padding: 15px; }
        .container { max-width: 800px; margin: 20px auto; padding: 30px; background: var(--surface-color); border-radius: 16px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6); border: 1px solid var(--border-color); }
        h1, h2 { font-family: 'Cormorant Garamond', serif; color: var(--primary-color); }
        h1 { text-align: center; margin-bottom: 25px; font-size: 2.2rem; font-weight: 700; }
        h2 { margin-top: 30px; margin-bottom: 15px; font-size: 1.6rem; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; display: flex; align-items: center; gap: 10px; }
        .order-meta { font-size: 0.9rem; color: var(--text-color-muted); margin-bottom: 20px; text-align: center; }
        .order-item { display: grid; grid-template-columns: 60px 1fr auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color); }
        .order-item:last-child { border-bottom: none; }
        .order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #000; padding: 5px; border: 1px solid #444;}
        .item-details strong { display: block; margin-bottom: 4px; font-size: 1.05rem; color: var(--text-color);}
        .item-details span { font-size: 0.9rem; color: var(--text-color-muted); display: block;}
        .item-total { font-weight: bold; text-align: right; font-size: 1.1rem; color: var(--primary-color);}
        .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid var(--primary-color); text-align: right; }
        .order-summary p { margin-bottom: 10px; font-size: 1.1rem; }
        .order-summary strong { font-size: 1.5rem; color: var(--primary-color); }
        .customer-info { margin-top: 30px; background-color: rgba(255, 59, 48, 0.05); padding: 20px; border-radius: 12px; border: 1px solid var(--primary-color);}
        .customer-info p { margin-bottom: 8px; font-size: 1rem; }
        .customer-info strong { color: var(--text-color); }
        .actions { margin-top: 30px; text-align: center; }
        .button { padding: 12px 25px; border: none; border-radius: 50px; background-color: #25D366; color: white; font-weight: 500; cursor: pointer; transition: all 0.3s ease; font-size: 1.1rem; display: inline-flex; align-items: center; gap: 10px; text-decoration: none; box-shadow: 0 4px 10px rgba(37, 211, 102, 0.3); }
        .button:hover { background-color: #1DA851; transform: translateY(-2px); }
        .catalog-link { display: block; text-align: center; margin-top: 25px; color: var(--primary-color); text-decoration: none; transition: color 0.2s; }
        .catalog-link:hover { color: var(--primary-dark); }
        .not-found { text-align: center; color: #ff453a; font-size: 1.2rem; padding: 40px 0;}
    </style>
</head>
<body>
    <div class="container">
        {% if order %}
            <h1><i class="fas fa-receipt"></i> {{ _['order_page_title'] }}{{ order.id }}</h1>
            <p class="order-meta">{{ _['order_created_at'] }} {{ order.created_at }}</p>

            <h2><i class="fas fa-shopping-bag"></i> {{ _['order_items'] }}</h2>
            <div id="orderItems">
                {% for item in order.cart %}
                    <div class="order-item">
                        <img src="{{ item.photo_url }}" alt="{{ item.name }}">
                        <div class="item-details">
                            <strong>{{ item.name }}</strong>
                            <span>{{ _['cart_item_variant'] }}: {{ item.variantName }}</span>
                            <span>{{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}</span>
                        </div>
                        <div class="item-total">
                            {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}
                        </div>
                    </div>
                {% endfor %}
            </div>

            <div class="order-summary">
                <p>{{ _['order_total_price'] }}: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
            </div>

            <div class="customer-info">
                 <h2><i class="fas fa-info-circle"></i> {{ _['order_status_and_confirmation'] }}</h2>
                 <p>{{ _['order_current_status'] }}: <strong>{{ status_map.get(order.status, order.status) }}</strong></p>
                 <p>{{ _['order_whatsapp_prompt'] }}</p>
            </div>

            <div class="actions">
                 <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> {{ _['order_contact_us_button'] }}</button>
            </div>

            <a href="{{ url_for('catalog', lang_code=lang_code) }}" class="catalog-link">&larr; {{ _['return_to_catalog'] }}</a>

            <script>
                function sendOrderViaWhatsApp() {
                    const orderId = '{{ order.id }}';
                    const orderUrl = `{{ request.url }}`;
                    const whatsappNumber = "77762021169";

                    let message = `{{ _['whatsapp_confirm_message_1'] }}%0A%0A`;
                    message += `*{{ _['whatsapp_confirm_message_2'] }}* ${orderId}%0A`;
                    message += `*{{ _['whatsapp_confirm_message_3'] }}* ${encodeURIComponent(orderUrl)}%0A%0A`;
                    message += `{{ _['whatsapp_confirm_message_4'] }}`;

                    const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;
                    window.open(whatsappUrl, '_blank');
                }
            </script>

        {% else %}
            <h1 style="color: #ff453a;"><i class="fas fa-exclamation-triangle"></i> {{ _['order_not_found_error'] }}</h1>
            <p class="not-found">{{ _['order_not_found_message'] }}</p>
            <a href="{{ url_for('catalog', lang_code=lang_code) }}" class="catalog-link">&larr; {{ _['return_to_catalog'] }}</a>
        {% endif %}
    </div>
</body>
</html>
'''

ADMIN_TEMPLATE = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Админ-панель - SHAIK парфюм</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=Cormorant+Garamond:wght@600&family=Georgia&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <style>
            :root {
                --primary-color: #FF3B30; 
                --primary-dark: #D9322A;
                --surface-color: #1A1A1A;
                --background-color: #121212;
                --text-color: #F5F5F5;
                --text-color-muted: #999;
                --border-color: #333333;
                --success-bg: #113d21;
                --success-text: #6ee791;
                --error-bg: #4d0a0a;
                --error-text: #ff8f8f;
                --warning-bg: #4a3a09;
                --warning-text: #ffd56b;
            }
            body { font-family: 'Georgia', serif; background-color: var(--background-color); color: var(--text-color); padding: 15px; line-height: 1.5; }
            .container { max-width: 1200px; margin: 0 auto; background-color: var(--surface-color); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); border: 1px solid var(--border-color); }
            .header { padding-bottom: 20px; margin-bottom: 25px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;}
            h1, h2, h3, h4 { font-family: 'Cormorant Garamond', serif; font-weight: 600; color: var(--primary-color); margin:0 0 15px 0;}
            h1 { font-size: 2rem; }
            h2 { font-size: 1.6rem; margin-top: 30px; display: flex; align-items: center; gap: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--border-color);}
            h3 { font-size: 1.2rem; color: var(--text-color); margin-top: 20px;}
            .section { margin-bottom: 30px; padding: 20px; background-color: #151515; border: 1px solid var(--border-color); border-radius: 8px; }
            
            label { font-weight: 500; margin-top: 12px; display: block; color: var(--text-color); font-size: 0.9rem;}
            input[type="text"], input[type="number"], input[type="password"], input[type="tel"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 6px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: var(--background-color); color: var(--text-color); }
            input:focus, textarea:focus, select:focus { border-color: var(--primary-color); outline: none; box-shadow: 0 0 0 3px rgba(255, 59, 48, 0.2); }
            textarea { min-height: 90px; resize: vertical; }
            input[type="file"] { padding: 8px; background-color: #222; cursor: pointer; border: 1px solid var(--border-color); border-radius: 6px; }
            input[type="checkbox"] { transform: scale(1.2); margin-right: 8px; vertical-align: middle; accent-color: var(--primary-color); }
            
            button, .button { padding: 9px 18px; border: none; border-radius: 50px; background-color: var(--primary-color); color: #fff; font-weight: 500; cursor: pointer; transition: all 0.2s ease; margin-top: 15px; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; line-height: 1.2; text-transform: uppercase; letter-spacing: 0.5px; }
            button:hover, .button:hover { background-color: var(--primary-dark); transform: translateY(-1px); }
            .delete-button { background-color: #8B0000; color: white; }
            .delete-button:hover { background-color: #6e0000; }
            
            .item-list { display: grid; gap: 15px; }
            .item { background: var(--surface-color); padding: 15px; border-radius: 8px; border: 1px solid var(--border-color); }
            .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
            .photo-preview img, .photo-edit-item img { width: 60px; height: 60px; border-radius: 6px; margin: 5px 5px 0 0; border: 1px solid var(--border-color); object-fit: cover;}
            .photo-preview-edit { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 5px; }
            .photo-edit-item { position: relative; }
            .photo-edit-item input[type="checkbox"] { position: absolute; top: 0px; right: 0px; transform: scale(1.3); accent-color: #ff453a; cursor: pointer; }
            
            .variant-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
            .variant-input-group input { flex-grow: 1; margin: 0; }
            .remove-variant-btn { background-color: #8B0000; color: white; padding: 6px 10px; font-size: 0.8rem; margin: 0; border-radius: 6px; }
            .add-variant-btn { background-color: #1c4532; color: var(--text-color); margin-top: 8px;}
            .add-variant-btn:hover { background-color: #22543d; }

            .message { padding: 12px 18px; border-radius: 8px; margin-bottom: 20px; font-size: 0.95rem; border: 1px solid;}
            .message.success { background-color: var(--success-bg); color: var(--success-text); border-color: var(--success-text);}
            .message.error { background-color: var(--error-bg); color: var(--error-text); border-color: var(--error-text);}
            .message.warning { background-color: var(--warning-bg); color: var(--warning-text); border-color: var(--warning-text); }
            .status-indicator { display: inline-block; padding: 3px 9px; border-radius: 50px; font-size: 0.75rem; font-weight: 500; margin-left: 5px; vertical-align: middle; }
            .status-indicator.top-product { background-color: #9c4221; color: #fff3c4; }
            .status-indicator.new { background-color: #e65100; color: #ffe0b2; }
            .status-indicator.accepted { background-color: #0277bd; color: #b3e5fc; }
            .status-indicator.prepared { background-color: #2f855a; color: #c6f6d5; }
            .status-indicator.shipped { background-color: #065f46; color: #a7f3d0; }
            
            details { background-color: #151515; border: 1px solid var(--border-color); border-radius: 8px; margin-bottom: 10px; }
            details > summary { cursor: pointer; font-weight: 500; color: var(--text-color); display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; list-style: none; position: relative; }
            details[open] > summary { border-bottom: 1px solid var(--border-color); }
            .order-details-content { padding: 15px 20px; }
            .order-status-form { display: flex; gap: 10px; align-items: center; margin-top: 15px; padding-top: 15px; border-top: 1px dashed var(--border-color); flex-wrap: wrap; }
            .order-status-form select { max-width: 180px; margin-top: 0; flex-grow: 1; }

            .flex-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
            .flex-item { min-width: 0; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;">
                    <img src="https://huggingface.co/spaces/Shaik-parfume/app/resolve/main/icon.png" alt="SHAIK Logo" style="height: 45px; width: 45px; border-radius: 50%;">
                    <h1><i class="fas fa-tools"></i> Админ-панель</h1>
                </div>
                <a href="{{ url_for('catalog', lang_code='ru') }}" class="button"><i class="fas fa-store"></i> Перейти в каталог</a>
            </div>


            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    {% for category, message in messages %}
                        <div class="message {{ category }}">{{ message }}</div>
                    {% endfor %}
                {% endif %}
            {% endwith %}

            <div class="section">
                <h2><i class="fas fa-history"></i> История заказов</h2>
                {% if orders %}
                    {% for order in orders | sort(attribute='created_at', reverse=true) %}
                        {% set current_status = order.get('status', 'new') %}
                        <details>
                            <summary>
                                <span>
                                    Заказ №{{ order.id }}
                                    <span class="status-indicator {{ current_status }}">{{ status_map_ru.get(current_status, current_status) }}</span>
                                </span>
                                <span style="font-size: 0.85rem; color: var(--text-color-muted); flex-shrink: 0; margin-left: 10px;">
                                    Дата: {{ order.created_at }} | Итого: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}
                                </span>
                            </summary>
                            <div class="order-details-content">
                                <h3>Состав заказа:</h3>
                                <div class="order-status-form">
                                    <form method="POST" style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                                        <input type="hidden" name="action" value="update_order_status">
                                        <input type="hidden" name="order_id" value="{{ order.id }}">
                                        <label for="status_{{ order.id }}" style="margin: 0; display: inline;">Статус:</label>
                                        <select name="new_status" id="status_{{ order.id }}">
                                            {% for status_key, status_value in status_map_ru.items() %}
                                                <option value="{{ status_key }}" {% if current_status == status_key %}selected{% endif %}>{{ status_value }}</option>
                                            {% endfor %}
                                        </select>
                                        <button type="submit" class="button" style="margin-top:0;"><i class="fas fa-check"></i> Сохранить</button>
                                         <a href="{{ url_for('view_order', lang_code='ru', order_id=order.id) }}" target="_blank" class="button" style="background-color: #444; color: white; margin-top:0;"><i class="fas fa-eye"></i> Просмотр</a>
                                    </form>
                                </div>
                            </div>
                        </details>
                    {% endfor %}
                {% else %}
                    <p>Активных заказов нет.</p>
                {% endif %}
            </div>


            <div class="flex-container">
                 <div class="flex-item">
                     <div class="section">
                         <h2><i class="fas fa-tags"></i> Категории</h2>
                          <details>
                              <summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary>
                              <div style="padding: 15px;">
                                  <form method="POST">
                                      <input type="hidden" name="action" value="add_category">
                                      <label for="add_category_name">Название новой категории:</label>
                                      <input type="text" id="add_category_name" name="category_name" required>
                                      <button type="submit"><i class="fas fa-plus"></i> Добавить</button>
                                  </form>
                              </div>
                          </details>
                         <h3>Существующие категории:</h3>
                         {% if categories %}
                         <div class="item-list">
                             {% for category in categories %}
                             <div class="item" style="display: flex; justify-content: space-between; align-items: center; padding: 10px;">
                                 <span>{{ category }}</span>
                                 <form method="POST" style="margin: 0;" onsubmit="return confirm('Удалить категорию \'{{ category }}\'?');">
                                     <input type="hidden" name="action" value="delete_category">
                                     <input type="hidden" name="category_name" value="{{ category }}">
                                     <button type="submit" class="delete-button" style="padding: 6px 12px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button>
                                 </form>
                             </div>
                             {% endfor %}
                         </div>
                         {% else %}
                         <p>Категорий пока нет.</p>
                         {% endif %}
                     </div>
                 </div>

                 <div class="flex-item">
                     <div class="section">
                         <h2><i class="fas fa-copyright"></i> Бренды</h2>
                          <details>
                              <summary><i class="fas fa-plus-circle"></i> Добавить новый бренд</summary>
                              <div style="padding: 15px;">
                                  <form method="POST">
                                      <input type="hidden" name="action" value="add_brand">
                                      <label for="add_brand_name">Название нового бренда:</label>
                                      <input type="text" id="add_brand_name" name="brand_name" required>
                                      <button type="submit"><i class="fas fa-plus"></i> Добавить</button>
                                  </form>
                              </div>
                          </details>
                         <h3>Существующие бренды:</h3>
                         {% if brands %}
                         <div class="item-list">
                             {% for brand in brands %}
                             <div class="item" style="display: flex; justify-content: space-between; align-items: center; padding: 10px;">
                                 <span>{{ brand }}</span>
                                 <form method="POST" style="margin: 0;" onsubmit="return confirm('Удалить бренд \'{{ brand }}\'?');">
                                     <input type="hidden" name="action" value="delete_brand">
                                     <input type="hidden" name="brand_name" value="{{ brand }}">
                                     <button type="submit" class="delete-button" style="padding: 6px 12px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button>
                                 </form>
                             </div>
                             {% endfor %}
                         </div>
                         {% else %}
                         <p>Брендов пока нет.</p>
                         {% endif %}
                     </div>
                 </div>
            </div>

            <div class="section">
                <h2><i class="fas fa-box-open"></i> Товары</h2>
                 <details>
                     <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary>
                     <div style="padding: 15px;">
                         <form method="POST" enctype="multipart/form-data">
                             <input type="hidden" name="action" value="add_product">
                             <label for="add_name">Название товара *:</label>
                             <input type="text" id="add_name" name="name" required>
                             <label for="add_description">Описание:</label>
                             <textarea id="add_description" name="description" rows="4"></textarea>
                             
                             <label for="add_category">Категория:</label>
                             <select id="add_category" name="category">
                                 <option value="Без категории">Без категории</option>
                                 {% for category in categories %}
                                 <option value="{{ category }}">{{ category }}</option>
                                 {% endfor %}
                             </select>
                             
                             <label for="add_brand">Бренд:</label>
                             <select id="add_brand" name="brand">
                                 <option value="Без бренда">Без бренда</option>
                                 {% for brand in brands %}
                                 <option value="{{ brand }}">{{ brand }}</option>
                                 {% endfor %}
                             </select>

                             <label for="add_photos">Фотографии (до 10 шт.):</label>
                             <input type="file" id="add_photos" name="photos" accept="image/*" multiple>
                             
                             <h4>Варианты и цены *:</h4>
                             <div id="add-variants-container">
                                 <div class="variant-input-group">
                                     <input type="text" name="variant_names" placeholder="Название варианта (напр. 100ml)" required>
                                     <input type="number" name="variant_prices" step="0.01" min="0" placeholder="Цена" required>
                                     <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button>
                                 </div>
                             </div>
                             <button type="button" class="button add-variant-btn" onclick="addVariantInput('add-variants-container')"><i class="fas fa-plus"></i> Добавить вариант</button>

                             <div style="margin-top: 20px;">
                                 <input type="checkbox" id="add_is_top" name="is_top">
                                 <label for="add_is_top">Топ товар</label>
                             </div>
                             <br>
                             <button type="submit"><i class="fas fa-save"></i> Добавить товар</button>
                         </form>
                     </div>
                </details>

                <h3>Список товаров:</h3>
                {% if products %}
                <div class="item-list">
                    {% for product in products %}
                    <div class="item">
                        <div style="display: flex; gap: 15px; align-items: flex-start;">
                             <div class="photo-preview">
                                {% if product.get('photos') and product.photos|length > 0 %}
                                <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank">
                                   <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото">
                                </a>
                                {% else %}
                                <img src="https://via.placeholder.com/60x60.png?text=N/A" alt="Нет фото">
                                {% endif %}
                            </div>
                            <div style="flex-grow: 1;">
                                <h3 style="margin-top: 0; margin-bottom: 5px;">
                                    {{ product['name'] }}
                                     {% if product.get('is_top', False) %}<span class="status-indicator top-product"><i class="fas fa-star fa-xs"></i> Топ</span>{% endif %}
                                </h3>
                                <p style="font-size: 0.9rem; color: var(--text-color-muted);"><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
                                <p style="font-size: 0.9rem; color: var(--text-color-muted);"><strong>Бренд:</strong> {{ product.get('brand', 'Без бренда') }}</p>
                            </div>
                        </div>

                        <div class="item-actions">
                             <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product.id }}')"><i class="fas fa-edit"></i> Редактировать</button>
                            <form method="POST" style="margin:0;" onsubmit="return confirm('Удалить товар \'{{ product['name'] }}\'?');">
                                <input type="hidden" name="action" value="delete_product">
                                <input type="hidden" name="product_id" value="{{ product.id }}">
                                <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
                            </form>
                        </div>

                        <div id="edit-form-{{ product.id }}" style="display: none; margin-top: 15px; border-top: 1px solid var(--border-color); padding-top: 15px;">
                            <h4><i class="fas fa-edit"></i> Редактирование</h4>
                            <form method="POST" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="edit_product">
                                <input type="hidden" name="product_id" value="{{ product.id }}">
                                <label>Название *:</label>
                                <input type="text" name="name" value="{{ product['name'] }}" required>
                                <label>Описание:</label>
                                <textarea name="description" rows="4">{{ product.get('description', '') }}</textarea>
                                
                                <label>Категория:</label>
                                <select name="category">
                                    <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
                                    {% for category in categories %}
                                    <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
                                    {% endfor %}
                                </select>

                                <label>Бренд:</label>
                                <select name="brand">
                                    <option value="Без бренда" {% if product.get('brand', 'Без бренда') == 'Без бренда' %}selected{% endif %}>Без бренда</option>
                                    {% for brand in brands %}
                                    <option value="{{ brand }}" {% if product.get('brand') == brand %}selected{% endif %}>{{ brand }}</option>
                                    {% endfor %}
                                </select>
                                
                                <label>Текущие фотографии (отметьте для удаления):</label>
                                <div class="photo-preview-edit">
                                    {% if product.get('photos') %}
                                        {% for photo in product['photos'] %}
                                        <div class="photo-edit-item">
                                            <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}">
                                            <input type="checkbox" name="delete_photos" value="{{ photo }}" title="Отметить для удаления">
                                        </div>
                                        {% endfor %}
                                    {% else %}
                                    <p style="font-size: 0.9rem; color: var(--text-color-muted);">Фотографий нет.</p>
                                    {% endif %}
                                </div>

                                <label>Добавить новые фотографии:</label>
                                <input type="file" name="photos" accept="image/*" multiple>

                                <h4>Варианты и цены *:</h4>
                                <div id="edit-variants-container-{{ product.id }}">
                                    {% for variant in product.get('variants', []) %}
                                    <div class="variant-input-group">
                                        <input type="text" name="variant_names" value="{{ variant.name }}" required>
                                        <input type="number" name="variant_prices" step="0.01" min="0" value="{{ variant.price }}" required>
                                        <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button>
                                    </div>
                                    {% endfor %}
                                </div>
                                <button type="button" class="button add-variant-btn" onclick="addVariantInput('edit-variants-container-{{ product.id }}')"><i class="fas fa-plus"></i> Добавить вариант</button>

                                <div style="margin-top: 20px;">
                                     <input type="checkbox" id="edit_is_top_{{ product.id }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
                                     <label for="edit_is_top_{{ product.id }}">Топ товар</label>
                                </div>
                                <br>
                                <button type="submit"><i class="fas fa-save"></i> Сохранить изменения</button>
                            </form>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <p>Товаров пока нет.</p>
                {% endif %}
            </div>
             <div class="section">
                 <h2><i class="fas fa-info-circle"></i> Инфо о магазине</h2>
                 <p><strong>Адреса в г. Алматы:</strong></p>
                 <ul style="padding-left: 20px;">
                    {% for address in store_addresses %}
                        <li>{{ address }}</li>
                    {% endfor %}
                 </ul>
                 <p style="margin-top: 10px;"><strong>Валюта:</strong> {{ currency_name }} ({{ currency_code }})</p>
             </div>
        </div>

        <script>
            function toggleEditForm(formId) {
                const form = document.getElementById(formId);
                form.style.display = form.style.display === 'none' ? 'block' : 'none';
            }

            function addVariantInput(containerId) {
                const container = document.getElementById(containerId);
                const newInputGroup = document.createElement('div');
                newInputGroup.className = 'variant-input-group';
                newInputGroup.innerHTML = `
                    <input type="text" name="variant_names" placeholder="Название варианта" required>
                    <input type="number" name="variant_prices" step="0.01" min="0" placeholder="Цена" required>
                    <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button>
                `;
                container.appendChild(newInputGroup);
            }

            function removeVariantInput(button) {
                const group = button.closest('.variant-input-group');
                const container = group.parentNode;
                if (container.children.length > 1) {
                    group.remove();
                } else {
                    alert("Должен быть хотя бы один вариант.");
                }
            }
        </script>
    </body>
    </html>
'''


@app.before_request
def before_request():
    path_parts = request.path.split('/')
    if len(path_parts) > 1 and path_parts[1] in translations:
        g.lang_code = path_parts[1]
    else:
        g.lang_code = 'ru'
    g.translations = translations.get(g.lang_code, translations['ru'])

@app.route('/')
def index():
    return redirect(url_for('catalog', lang_code='ru'))

@app.route('/<lang_code>/')
def catalog(lang_code):
    data = load_data()
    all_products = data.get('products', [])
    categories = sorted(data.get('categories', []))
    brands = sorted(data.get('brands', []))

    products_in_stock = [p for p in all_products if p.get('variants')]
    
    for p in products_in_stock:
        p['variants'] = sorted(p.get('variants', []), key=lambda v: v.get('price', 0))

    products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))

    return render_template_string(
        CATALOG_TEMPLATE,
        products=products_sorted,
        categories=categories,
        brands=brands,
        repo_id=REPO_ID,
        store_addresses=STORE_ADDRESSES,
        currency_code=CURRENCY_CODE,
        lang_code=g.lang_code,
        _=g.translations
    )

@app.route('/<lang_code>/product/<int:index>')
def product_detail(lang_code, index):
    data = load_data()
    all_products = data.get('products', [])
    products_in_stock = [p for p in all_products if p.get('variants')]
    
    for p in products_in_stock:
        p['variants'] = sorted(p.get('variants', []), key=lambda v: v.get('price', 0))
    
    products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))

    try:
        product = products_sorted[index]
    except IndexError:
        return "Товар не найден.", 404
    
    return render_template_string(
        PRODUCT_DETAIL_TEMPLATE,
        product=product,
        products_index=index,
        repo_id=REPO_ID,
        currency_code=CURRENCY_CODE,
        lang_code=g.lang_code,
        _=g.translations
    )

@app.route('/create_order', methods=['POST'])
def create_order():
    order_data = request.get_json()
    if not order_data or 'cart' not in order_data or not order_data['cart']:
        return jsonify({"error": "Корзина пуста."}), 400

    cart_items = order_data['cart']
    total_price = 0
    processed_cart = []
    
    data = load_data()
    products_map = {p['id']: p for p in data.get('products', [])}

    for item in cart_items:
        product = products_map.get(item.get('productId'))
        if not product: continue

        variant_exists = any(v['name'] == item.get('variantName') and v['price'] == item.get('price') for v in product.get('variants', []))
        if not variant_exists: continue

        try:
            price = float(item['price'])
            quantity = int(item['quantity'])
            if price < 0 or quantity <= 0: raise ValueError("Invalid price/qty")

            total_price += price * quantity
            photo_name = item.get('photo')
            photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_name}" if photo_name else "https://via.placeholder.com/60x60.png?text=N/A"

            processed_cart.append({
                "name": item['name'],
                "price": price,
                "quantity": quantity,
                "variantName": item.get('variantName', 'N/A'),
                "photo": photo_name,
                "photo_url": photo_url
            })
        except (ValueError, TypeError):
            return jsonify({"error": "Неверная цена или количество."}), 400

    if not processed_cart:
        return jsonify({"error": "Не удалось обработать товары в корзине."}), 400

    order_id = f"{datetime.now().strftime('%y%m%d%H%M')}-{uuid.uuid4().hex[:4]}"
    new_order = {
        "id": order_id,
        "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "cart": processed_cart,
        "total_price": round(total_price, 2),
        "status": "new"
    }

    try:
        data['orders'][order_id] = new_order
        save_data(data)
        return jsonify({"order_id": order_id}), 201
    except Exception as e:
        logging.error(f"Failed to save order {order_id}: {e}")
        return jsonify({"error": "Ошибка сервера."}), 500

@app.route('/<lang_code>/order/<order_id>')
def view_order(lang_code, order_id):
    data = load_data()
    order = data.get('orders', {}).get(order_id)
    status_map = STATUS_MAPS.get(lang_code, STATUS_MAPS['ru'])
    return render_template_string(ORDER_TEMPLATE, order=order, status_map=status_map, currency_code=CURRENCY_CODE, lang_code=g.lang_code, _=g.translations)

@app.route('/admin', methods=['GET', 'POST'])
def admin():
    data = load_data()
    if 'orders' not in data: data['orders'] = {}
    
    needs_save = False
    for p in data.get('products', []):
        if 'id' not in p:
            p['id'] = str(uuid.uuid4())
            needs_save = True
    if needs_save:
        save_data(data)

    if request.method == 'POST':
        action = request.form.get('action')
        try:
            if action == 'update_order_status':
                order_id = request.form.get('order_id')
                new_status = request.form.get('new_status')
                if order_id in data['orders'] and new_status in STATUS_MAPS['ru']:
                    data['orders'][order_id]['status'] = new_status
                    save_data(data)
                    flash(f"Статус заказа №{order_id} изменен.", 'success')
                else:
                    flash("Ошибка обновления статуса заказа.", 'error')

            elif action == 'add_category':
                category_name = request.form.get('category_name', '').strip()
                if category_name and category_name not in data['categories']:
                    data['categories'].append(category_name)
                    save_data(data)
                    flash(f"Категория '{category_name}' добавлена.", 'success')
                else:
                    flash("Ошибка: Категория пуста или уже существует.", 'error')

            elif action == 'delete_category':
                category_to_delete = request.form.get('category_name')
                if category_to_delete in data['categories']:
                    data['categories'].remove(category_to_delete)
                    for product in data['products']:
                        if product.get('category') == category_to_delete:
                            product['category'] = 'Без категории'
                    save_data(data)
                    flash(f"Категория '{category_to_delete}' удалена.", 'success')
                else:
                    flash("Категория не найдена.", 'error')

            elif action == 'add_brand':
                brand_name = request.form.get('brand_name', '').strip()
                if brand_name and brand_name not in data['brands']:
                    data['brands'].append(brand_name)
                    save_data(data)
                    flash(f"Бренд '{brand_name}' добавлен.", 'success')
                else:
                    flash("Ошибка: Бренд пуст или уже существует.", 'error')

            elif action == 'delete_brand':
                brand_to_delete = request.form.get('brand_name')
                if brand_to_delete in data['brands']:
                    data['brands'].remove(brand_to_delete)
                    for product in data['products']:
                        if product.get('brand') == brand_to_delete:
                            product['brand'] = 'Без бренда'
                    save_data(data)
                    flash(f"Бренд '{brand_to_delete}' удален.", 'success')
                else:
                    flash("Бренд не найден.", 'error')

            elif action == 'add_product' or action == 'edit_product':
                name = request.form.get('name', '').strip()
                if not name:
                    flash("Название товара обязательно.", 'error')
                    return redirect(url_for('admin'))

                variant_names = [v.strip() for v in request.form.getlist('variant_names') if v.strip()]
                variant_prices_str = request.form.getlist('variant_prices')
                
                if not variant_names or not variant_prices_str or len(variant_names) != len(variant_prices_str):
                    flash("Ошибка в вариантах. У каждого варианта должно быть название и цена.", 'error')
                    return redirect(url_for('admin'))
                
                variants = []
                try:
                    for i, v_name in enumerate(variant_names):
                        price = round(float(variant_prices_str[i].replace(',', '.')), 2)
                        if price < 0: price = 0
                        variants.append({'name': v_name, 'price': price})
                except ValueError:
                    flash("Неверный формат цены в вариантах.", 'error')
                    return redirect(url_for('admin'))

                product_data = {
                    'name': name,
                    'description': request.form.get('description', '').strip(),
                    'category': request.form.get('category'),
                    'brand': request.form.get('brand'),
                    'is_top': 'is_top' in request.form,
                    'variants': variants
                }

                newly_uploaded_photos = []
                photos_files = request.files.getlist('photos')
                if photos_files and any(f.filename for f in photos_files):
                    if not HF_TOKEN_WRITE:
                        flash("Токен HF_TOKEN не настроен, фото не загружены.", "warning")
                    else:
                        api = HfApi()
                        uploads_dir = 'uploads_temp'
                        os.makedirs(uploads_dir, exist_ok=True)
                        for photo in photos_files[:10]:
                            if photo and photo.filename:
                                try:
                                    ext = os.path.splitext(photo.filename)[1].lower()
                                    if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: continue
                                    safe_name = secure_filename(name.replace(' ', '_'))[:50]
                                    photo_filename = f"{safe_name}_{datetime.now().strftime('%f')}{ext}"
                                    temp_path = os.path.join(uploads_dir, photo_filename)
                                    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"Photo for {name}"
                                    )
                                    newly_uploaded_photos.append(photo_filename)
                                    os.remove(temp_path)
                                except Exception as e:
                                    logging.error(f"Error uploading photo {photo.filename}: {e}")
                                    flash(f"Ошибка загрузки фото {photo.filename}.", 'error')
                
                if action == 'add_product':
                    product_data['id'] = str(uuid.uuid4())
                    product_data['photos'] = newly_uploaded_photos
                    data['products'].append(product_data)
                    flash(f"Товар '{name}' добавлен.", 'success')
                
                else: 
                    product_id = request.form.get('product_id')
                    product_index = next((i for i, p in enumerate(data['products']) if p.get('id') == product_id), -1)
                    if product_index != -1:
                        product_to_edit = data['products'][product_index]
                        current_photos = product_to_edit.get('photos', [])
                        photos_to_delete = request.form.getlist('delete_photos')
                        
                        if photos_to_delete and HF_TOKEN_WRITE:
                            try:
                                HfApi().delete_files(
                                    repo_id=REPO_ID, paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
                                    repo_type="dataset", token=HF_TOKEN_WRITE
                                )
                                flash(f"Удалено {len(photos_to_delete)} фото.", 'success')
                            except Exception as e:
                                logging.error(f"Error deleting photos from HF: {e}")
                                flash("Не удалось удалить фото с сервера.", "warning")

                        updated_photos = [p for p in current_photos if p not in photos_to_delete]
                        product_data['photos'] = updated_photos + newly_uploaded_photos
                        product_data['id'] = product_id
                        data['products'][product_index] = product_data
                        flash(f"Товар '{name}' обновлен.", 'success')
                    else:
                        flash("Товар для редактирования не найден.", 'error')
                
                save_data(data)

            elif action == 'delete_product':
                product_id = request.form.get('product_id')
                product_to_delete = next((p for p in data['products'] if p.get('id') == product_id), None)
                if product_to_delete:
                    data['products'].remove(product_to_delete)
                    photos_to_delete = product_to_delete.get('photos', [])
                    if photos_to_delete and HF_TOKEN_WRITE:
                        try:
                            HfApi().delete_files(
                                repo_id=REPO_ID, paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
                                repo_type="dataset", token=HF_TOKEN_WRITE
                            )
                        except Exception as e:
                            logging.error(f"Error deleting photos from HF: {e}")
                            flash("Не удалось удалить фото с сервера.", "warning")
                    save_data(data)
                    flash(f"Товар '{product_to_delete.get('name')}' удален.", 'success')
                else:
                    flash("Товар для удаления не найден.", 'error')

            return redirect(url_for('admin'))
        except Exception as e:
             logging.error(f"Error processing admin action '{action}': {e}", exc_info=True)
             flash(f"Произошла внутренняя ошибка: {e}", 'error')
             return redirect(url_for('admin'))

    current_data = load_data()
    return render_template_string(
        ADMIN_TEMPLATE,
        products=sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower()),
        categories=sorted(current_data.get('categories', [])),
        brands=sorted(current_data.get('brands', [])),
        orders=list(current_data.get('orders', {}).values()),
        status_map_ru=STATUS_MAPS['ru'],
        repo_id=REPO_ID,
        store_addresses=STORE_ADDRESSES,
        currency_code=CURRENCY_CODE,
        currency_name=CURRENCY_NAME
    )

if __name__ == '__main__':
    logging.info("Application starting up...")
    download_db_from_hf()
    load_data()
    if HF_TOKEN_WRITE:
        threading.Thread(target=periodic_backup, daemon=True).start()
    port = int(os.environ.get('PORT', 7860))
    app.run(debug=False, host='0.0.0.0', port=port)