File size: 164,163 Bytes
87d98a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849

from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
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
import math

load_dotenv()

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

SYNC_FILES = [DATA_FILE]

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

STORE_ADDRESS = "Рынок Кербент, 6 ряд , 3 контейнер / 5 ряд 25 контейнер "

CURRENCY_CODE = 'KGS'
CURRENCY_NAME = 'Кыргызский сом'

DOWNLOAD_RETRIES = 3
DOWNLOAD_DELAY = 5

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
    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': [], 'orders': {}, 'stock_movements': []}, 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': [], 'orders': {}, 'stock_movements': []}
    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 'orders' not in data: data['orders'] = {}
        if 'stock_movements' not in data: data['stock_movements'] = []

        for product in data['products']:
            if 'stock' not in product: product['stock'] = 0
            if 'barcode' not in product: product['barcode'] = ''

        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 'orders' not in data: data['orders'] = {}
            if 'stock_movements' not in data: data['stock_movements'] = []

            for product in data['products']:
                if 'stock' not in product: product['stock'] = 0
                if 'barcode' not in product: product['barcode'] = ''

            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 'orders' not in data: data['orders'] = {}
        if 'stock_movements' not in data: data['stock_movements'] = []


        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)

def get_product_by_identifier(data, identifier):
    identifier_lower = identifier.lower()
    for product in data.get('products', []):
        if 'barcode' in product and product['barcode'] == identifier:
            return product
        if 'name' in product and product['name'].lower() == identifier_lower:
            return product
    return None

def get_product_by_index(data, index):
    products = data.get('products', [])
    try:
        idx = int(index)
        if 0 <= idx < len(products):
            return products[idx]
    except (ValueError, TypeError):
        pass
    return None


CATALOG_TEMPLATE = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Meka Shop - Каталог</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Poppins', sans-serif; background: #ffffff; color: #333333; line-height: 1.6; }
            .container { max-width: 1300px; margin: 0 auto; padding: 20px; }
            .header { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; }
            .header h1 { font-size: 1.8rem; font-weight: 600; color: #E91E63; }
            .store-address { padding: 15px; text-align: center; background-color: #f9f9f9; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.03); font-size: 1rem; color: #666; }
            .filters-container { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
            .search-container { margin: 20px 0; text-align: center; }
            #search-input { width: 90%; max-width: 600px; padding: 12px 18px; font-size: 1rem; border: 1px solid #e0e0e0; border-radius: 25px; outline: none; box-shadow: 0 2px 5px rgba(0,0,0,0.03); transition: all 0.3s ease; }
            #search-input:focus { border-color: #E91E63; box-shadow: 0 0 0 3px rgba(233, 30, 99, 0.15); }
            .category-filter { padding: 8px 16px; border: 1px solid #e0e0e0; border-radius: 20px; background-color: #fff; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.9rem; font-weight: 400; color: #C2185B; }
            .category-filter.active, .category-filter:hover { background-color: #E91E63; color: white; border-color: #E91E63; box-shadow: 0 2px 10px rgba(233, 30, 99, 0.2); }
            .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 10px; }
            @media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } }
            @media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } }

            .product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #f0f0f0; opacity: 1; transition: opacity 0.3s ease;}
             .product.hidden { display: none !important;}
            .product.out-of-stock { opacity: 0.6; }
            .product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); }
            .product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #fff; border-radius: 10px 10px 0 0; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 0; }
            .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; }
            .product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; }
            .product h2 { font-size: 1.1rem; font-weight: 600; margin: 0 0 8px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #333; }
            .product-price { font-size: 1.2rem; color: #E91E63; font-weight: 700; text-align: center; margin: 5px 0; }
            .product-description { font-size: 0.85rem; color: #666; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
            .product-actions { padding: 0 15px 15px 15px; display: flex; flex-direction: column; gap: 8px; }
            .product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #F06292; color: white; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); text-align: center; text-decoration: none; }
            .product-button:hover { background-color: #E91E63; box-shadow: 0 4px 15px rgba(233, 30, 99, 0.3); transform: translateY(-2px); }
            .product-button i { margin-right: 5px; }
            .add-to-cart { background-color: #E91E63; }
            .add-to-cart:hover { background-color: #C2185B; box-shadow: 0 4px 15px rgba(194, 24, 91, 0.4); }
            .add-to-cart:disabled { background-color: #ccc; cursor: not-allowed; }
            #cart-button { position: fixed; bottom: 25px; right: 25px; background-color: #E91E63; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(233, 30, 99, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; }
            #cart-button:hover { background-color: #C2185B; box-shadow: 0 6px 20px rgba(194, 24, 91, 0.5); }
            #cart-button .fa-shopping-cart { margin-right: 0; }
            #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #C2185B; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; }
            .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(3px); overflow-y: auto; }
            .modal-content { background: #ffffff; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); animation: slideIn 0.3s ease-out; position: relative; }
            @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
            .close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; }
            .close:hover { color: #666; }
            .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #E91E63; display: flex; align-items: center; gap: 10px;}
            .cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; }
            .cart-item:last-child { border-bottom: none; }
            .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; border: 1px solid #e0e0e0;}
            .cart-item-details { grid-column: 2; }
            .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1rem; color: #333;}
            .cart-item-price { font-size: 0.9rem; color: #666; }
            .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; font-size: 1rem; color: #C2185B;}
            .cart-item-remove { grid-column: 4; background:none; border:none; color:#dc3545; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; }
            .cart-item-remove:hover { color: #c82333; }
            .quantity-input, .color-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; }
            .quantity-input:focus, .color-select:focus { border-color: #F06292; outline: none; box-shadow: 0 0 0 2px rgba(240, 98, 146, 0.1); }
            .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #e0e0e0; padding-top: 15px; }
            .cart-summary strong { font-size: 1.2rem; color: #E91E63;}
            .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
            .cart-actions .product-button { width: auto; flex-grow: 1; }
            .clear-cart { background-color: #6c757d; }
            .clear-cart:hover { background-color: #5a6268; box-shadow: 0 4px 15px rgba(90, 98, 104, 0.4); }
            .formulate-order-button { background-color: #E91E63; }
            .formulate-order-button:hover { background-color: #C2185B; box-shadow: 0 4px 15px rgba(194, 24, 91, 0.4); }
            .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #E91E63; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}
            .notification.show { opacity: 1;}
            .no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #999; }
            .top-product-indicator { position: absolute; top: 8px; right: 8px; background-color: rgba(255, 215, 0, 0.8); color: #333; padding: 2px 6px; font-size: 0.7rem; border-radius: 4px; font-weight: bold; z-index: 10; backdrop-filter: blur(2px); }
            .product { position: relative; }
             .product-stock { font-size: 0.8rem; color: #007bff; text-align: center; margin-top: 5px;}
        </style>
    </head>
    <body>
        <div class="container">
             <div class="header">
                 <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;">
                    <h1>Meka Shop</h1>
                </div>
            </div>

            <div class="store-address">Наш адрес: {{ store_address }}</div>

            <div class="filters-container">
                <button class="category-filter active" data-category="all">Все категории</button>
                {% for category in categories %}
                <button class="category-filter" data-category="{{ category }}">{{ category }}</button>
                {% endfor %}
            </div>

            <div class="search-container">
                <input type="text" id="search-input" placeholder="Поиск по названию или описанию...">
            </div>

            <div class="products-grid" id="products-grid">
                {% for product in products %}
                <div class="product {% if not product.get('in_stock', True) or product.get('stock', 0) <= 0 %}out-of-stock{% endif %}"
                     data-name="{{ product['name']|lower }}"
                     data-description="{{ product.get('description', '')|lower }}"
                     data-category="{{ product.get('category', 'Без категории') }}"
                     data-stock="{{ product.get('stock', 0) }}">
                     {% if product.get('is_top', False) %}
                        <span class="top-product-indicator"><i class="fas fa-star"></i> Топ</span>
                     {% endif %}
                    <div class="product-image">
                        {% 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">{{ "%.2f"|format(product['price']) }} {{ currency_code }}</div>
                        <p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p>
                         <div class="product-stock">В наличии: {{ product.get('stock', 0) }}</div>
                    </div>
                    <div class="product-actions">
                        <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button>
                        <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})" {% if not product.get('in_stock', True) or product.get('stock', 0) <= 0 %}disabled{% endif %}>
                           <i class="fas fa-cart-plus"></i> В корзину
                        </button>
                    </div>
                </div>
                {% endfor %}
                 {% if not products %}
                 <p class="no-results-message">Товары пока не добавлены.</p>
                 {% endif %}
            </div>
        </div>

        <div id="productModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
                <div id="modalContent">Загрузка...</div>
            </div>
        </div>

        <div id="quantityModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>
                <h2>Укажите количество и цвет</h2>
                <label for="quantityInput">Количество:</label>
                <input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
                <label for="colorSelect">Цвет/Вариант:</label>
                <select id="colorSelect" class="color-select"></select>
                <button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button>
            </div>
        </div>

        <div id="cartModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
                <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
                <div id="cartContent"><p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p></div>
                <div class="cart-summary">
                    <strong>Итого: <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> Очистить корзину
                    </button>
                    <button class="product-button formulate-order-button" onclick="formulateOrder()">
                       <i class="fas fa-file-alt"></i> Сформировать заказ
                    </button>
                </div>
            </div>
        </div>

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

        <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('mekaCart') || '[]');


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

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

            function loadProductDetails(index) {
                const modalContent = document.getElementById('modalContent');
                if (!modalContent) return;
                modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>';
                 // Get the product based on its current position in the *filtered/sorted* products list displayed
                const product = products[index];
                 if (!product) {
                     modalContent.innerHTML = `<p style="color: #dc3545; text-align:center; padding: 40px;">Ошибка: Товар не найден.</p>`;
                     return;
                 }

                 fetch('/product_detail_html/' + encodeURIComponent(product.name) + '?barcode=' + encodeURIComponent(product.barcode || ''))
                    .then(response => {
                        if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`);
                        return response.text();
                    })
                    .then(data => {
                        modalContent.innerHTML = data;
                        initializeSwiper();
                    })
                    .catch(error => {
                        console.error('Ошибка загрузки деталей продукта:', error);
                        modalContent.innerHTML = `<p style="color: #dc3545; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`;
                    });
            }

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

            function openQuantityModal(index) {
                selectedProductIndex = index;
                const product = products[index];
                if (!product) {
                    console.error("Product not found for index:", index);
                    alert("Ошибка: товар не найден.");
                    return;
                }

                 if (product.stock <= 0 || !product.in_stock) {
                    alert("Товар отсутствует в наличии.");
                    return;
                 }

                const colorSelect = document.getElementById('colorSelect');
                const colorLabel = document.querySelector('label[for="colorSelect"]');
                colorSelect.innerHTML = '';

                const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];

                if (validColors.length > 0) {
                    validColors.forEach(color => {
                         const option = document.createElement('option');
                         option.value = color.trim();
                         option.text = color.trim();
                         colorSelect.appendChild(option);
                    });
                    colorSelect.style.display = 'block';
                    if(colorLabel) colorLabel.style.display = 'block';
                } else {
                    colorSelect.style.display = 'none';
                    if(colorLabel) colorLabel.style.display = 'none';
                }

                const quantityInput = document.getElementById('quantityInput');
                quantityInput.value = 1;
                 quantityInput.max = product.stock; // Set max quantity to available stock

                const modal = document.getElementById('quantityModal');
                 if(modal) {
                    modal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                 }
            }

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

                const quantityInput = document.getElementById('quantityInput');
                const quantity = parseInt(quantityInput.value);
                const colorSelect = document.getElementById('colorSelect');
                const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A';

                 const product = products[selectedProductIndex];

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

                 if (quantity > product.stock) {
                    alert(`Недостаточно товара в наличии. Доступно: ${product.stock}`);
                     quantityInput.value = product.stock;
                    quantityInput.focus();
                    return;
                 }

                 if (!product) {
                    alert("Ошибка добавления: товар не найден.");
                    return;
                 }

                const cartItemId = `${product.name}-${color}`; // Using name+color as basic ID
                const existingItemIndex = cart.findIndex(item => item.id === cartItemId);

                if (existingItemIndex > -1) {
                    cart[existingItemIndex].quantity += quantity;
                } else {
                    cart.push({
                        id: cartItemId,
                        name: product.name,
                        price: product.price,
                        photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,
                        quantity: quantity,
                        color: color,
                        original_product_index: selectedProductIndex // Store original index to look up stock later if needed (though stock is checked/deducted on backend on order creation)
                    });
                }

                localStorage.setItem('mekaCart', JSON.stringify(cart));
                closeModal('quantityModal');
                updateCartButton();
                showNotification(`${product.name} добавлен в корзину!`);
            }

            function updateCartButton() {
                 const cartCountElement = document.getElementById('cart-count');
                 const cartButton = document.getElementById('cart-button');
                 if (!cartCountElement || !cartButton) return;

                 let totalItems = 0;
                 cart.forEach(item => { totalItems += item.quantity; });

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

            function openCartModal() {
                const cartContent = document.getElementById('cartContent');
                const cartTotalElement = document.getElementById('cartTotal');
                if (!cartContent || !cartTotalElement) return;

                let total = 0;

                if (cart.length === 0) {
                    cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</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/60x60.png?text=N/A';
                        const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : '';

                        return `
                            <div class="cart-item">
                                <img src="${photoUrl}" alt="${item.name}">
                                <div class="cart-item-details">
                                    <strong>${item.name}${colorText}</strong>
                                    <p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}</p>
                                </div>
                                <span class="cart-item-total">${itemTotal.toFixed(2)} ${currencyCode}</span>
                                <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">×</button>
                            </div>
                        `;
                    }).join('');
                    cartTotalElement.textContent = total.toFixed(2);
                }
                 const modal = document.getElementById('cartModal');
                 if (modal) {
                    modal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                 }
            }

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

            function clearCart() {
                if (confirm("Вы уверены, что хотите очистить корзину?")) {
                    cart = [];
                    localStorage.removeItem('mekaCart');
                    openCartModal();
                    updateCartButton();
                }
            }

            function formulateOrder() {
                if (cart.length === 0) {
                    alert("Корзина пуста! Добавьте товары перед формированием заказа.");
                    return;
                }

                const orderData = {
                    cart: cart
                };

                const formulateButton = document.querySelector('#cartModal .formulate-order-button');
                if (formulateButton) formulateButton.disabled = true;

                showNotification("Формируем заказ...", 5000);

                fetch('/create_order', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(orderData)
                })
                .then(response => {
                    if (!response.ok) {
                         // Attempt to read error message from response
                        return response.json().then(err => { throw new Error(err.error || `Сервер вернул ошибку ${response.status}`); }).catch(() => { throw new Error(`Ошибка сервера ${response.status}`); });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.order_id) {
                        localStorage.removeItem('mekaCart');
                        cart = [];
                        updateCartButton();
                        closeModal('cartModal');
                         showNotification("Заказ успешно создан!", 3000);
                        window.location.href = `/order/${data.order_id}`;
                    } else {
                        throw new Error('Не получен ID заказа от сервера.');
                    }
                })
                .catch(error => {
                    console.error('Ошибка при формировании заказа:', error);
                    alert(`Ошибка при формировании заказа: ${error.message}`);
                     if (formulateButton) formulateButton.disabled = false;
                     closeModal('cartModal'); // Close cart modal on error
                     showNotification(`Ошибка заказа: ${error.message}`, 5000);
                });
            }


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

                const existingNoResults = grid.querySelector('.no-results-message');
                if (existingNoResults) existingNoResults.remove();

                const productElements = document.querySelectorAll('.products-grid .product');
                productElements.forEach(productElement => {
                    const name = productElement.getAttribute('data-name');
                    const description = productElement.getAttribute('data-description');
                    const category = productElement.getAttribute('data-category');
                    const isInStock = !productElement.classList.contains('out-of-stock');


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

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

                 if (visibleProducts === 0 && products.length > 0) {
                    const p = document.createElement('p');
                    p.className = 'no-results-message';
                    p.textContent = 'По вашему запросу товары не найдены.';
                    grid.appendChild(p);
                 } else if (products.length === 0 && !grid.querySelector('.no-results-message')) {
                     const p = document.createElement('p');
                     p.className = 'no-results-message';
                     p.textContent = 'Товары пока не добавлены.';
                     grid.appendChild(p);
                 }
            }

             function setupFilters() {
                 const searchInput = document.getElementById('search-input');
                 const categoryFilters = document.querySelectorAll('.category-filter');

                 if(searchInput) searchInput.addEventListener('input', filterProducts);

                 categoryFilters.forEach(filter => {
                     filter.addEventListener('click', function() {
                         categoryFilters.forEach(f => f.classList.remove('active'));
                         this.classList.add('active');
                         filterProducts();
                     });
                 });
                 filterProducts();
             }

             function showNotification(message, duration = 3000) {
                let placeholder = document.getElementById('notification-placeholder');
                if (!placeholder) {
                    placeholder = document.createElement('div');
                    placeholder.id = 'notification-placeholder';
                    placeholder.style.cssText = `
                        position: fixed;
                        bottom: 80px;
                        left: 50%;
                        transform: translateX(-50%);
                        z-index: 1002;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        gap: 10px;
                    `;
                    document.body.appendChild(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();

                window.addEventListener('click', function(event) {
                    if (event.target.classList.contains('modal')) {
                        closeModal(event.target.id);
                    }
                });

                window.addEventListener('keydown', function(event) {
                    if (event.key === 'Escape') {
                         document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {
                             closeModal(modal.id);
                         });
                    }
                });
            });

        </script>
    </body>
    </html>
'''

PRODUCT_DETAIL_TEMPLATE = '''
    <div style="padding: 10px;">
        <h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #E91E63;">{{ product['name'] }}</h2>
        <div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff; border: 1px solid #e0e0e0;">
            <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;">
                         <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;"></div>
            <div class="swiper-button-next" style="color: #E91E63;"></div>
            <div class="swiper-button-prev" style="color: #E91E63;"></div>
            {% endif %}
        </div>

        <div style="margin-top: 20px; font-size: 1rem; line-height: 1.7; color: #333;">
            <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
            <p><strong>В наличии:</strong> {{ product.get('stock', 0) }}</p>
             {% if product.get('barcode') %}
            <p><strong>Штрихкод:</strong> {{ product.get('barcode') }}</p>
             {% endif %}
            <p style="font-size: 1.2rem; font-weight: bold; color: #C2185B;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
            <p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p>
            {% set colors = product.get('colors', []) %}
            {% if colors and colors|select('ne', '')|list|length > 0 %}
                <p><strong>Доступные цвета/варианты:</strong> {{ colors|select('ne', '')|join(', ') }}</p>
            {% endif %}
        </div>
    </div>
'''

ORDER_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Заказ №{{ order.id }} - Meka Shop</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body { font-family: 'Poppins', sans-serif; background: #ffffff; color: #333; line-height: 1.6; padding: 20px; }
        .container { max-width: 800px; margin: 20px auto; padding: 30px; background: #fff; border-radius: 15px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); border: 1px solid #e0e0e0; }
        h1 { text-align: center; color: #E91E63; margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; }
        h2 { color: #C2185B; margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px;}
        .order-meta { font-size: 0.9rem; color: #999; 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 #f0f0f0; }
        .order-item:last-child { border-bottom: none; }
        .order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; border: 1px solid #e0e0e0;}
        .item-details strong { display: block; margin-bottom: 5px; font-size: 1.05rem; color: #333;}
        .item-details span { font-size: 0.9rem; color: #666; display: block;}
        .item-total { font-weight: bold; text-align: right; font-size: 1rem; color: #C2185B;}
        .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid #E91E63; text-align: right; }
        .order-summary p { margin-bottom: 10px; font-size: 1.1rem; }
        .order-summary strong { font-size: 1.3rem; color: #E91E63; }
        .customer-info { margin-top: 30px; background-color: #f9f9f9; padding: 20px; border-radius: 8px; border: 1px solid #e0e0e0;}
        .customer-info p { margin-bottom: 8px; font-size: 0.95rem; }
        .customer-info strong { color: #C2185B; }
        .actions { margin-top: 30px; text-align: center; }
        .button { padding: 12px 25px; border: none; border-radius: 8px; background-color: #E91E63; color: white; font-weight: 600; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; }
        .button:hover { background-color: #C2185B; }
        .button:active { transform: scale(0.98); }
        .button i { font-size: 1.2rem; }
        .catalog-link { display: block; text-align: center; margin-top: 25px; color: #E91E63; text-decoration: none; font-size: 0.9rem; }
        .catalog-link:hover { text-decoration: underline; }
        .not-found { text-align: center; color: #dc3545; font-size: 1.2rem; padding: 40px 0;}
    </style>
</head>
<body>
    <div class="container">
        {% if order %}
            <h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1>
            <p class="order-meta">Дата создания: {{ order.created_at }}</p>

            <h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2>
            <div id="orderItems">
                {% for item in order.items %}
                    <div class="order-item">
                        <img src="{{ item.photo_url }}" alt="{{ item.name }}">
                        <div class="item-details">
                            <strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong>
                            <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>Общая сумма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
                <p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
            </div>

            <div class="customer-info">
                 <h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
                 <p>Этот заказ был оформлен без входа в систему.</p>
                 <p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
            </div>

            <div class="actions">
                 <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button>
            </div>

            <a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a>

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

                    let message = `Здравствуйте! Хочу подтвердить свой заказ на Meka Shop:%0A%0A`;
                    message += `*Номер заказа:* ${orderId}%0A`;
                    message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`;
                    message += `Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.`;

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

        {% else %}
            <h1 style="color: #dc3545;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1>
            <p class="not-found">Заказ с таким ID не найден.</p>
            <a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</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>Админ-панель - Meka Shop</title>
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <style>
            body { font-family: 'Poppins', sans-serif; background-color: #ffffff; color: #333; padding: 20px; line-height: 1.6; }
            .container { max-width: 1400px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
            .header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #e0e0e0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}
            h1, h2, h3 { font-weight: 600; color: #E91E63; margin-bottom: 15px; }
            h1 { font-size: 1.8rem; }
            h2 { font-size: 1.5rem; margin-top: 30px; display: flex; align-items: center; gap: 8px; }
            h3 { font-size: 1.2rem; color: #C2185B; margin-top: 20px; }
            .section { margin-bottom: 30px; padding: 20px; background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; }
            form { margin-bottom: 20px; }
            label { font-weight: 500; margin-top: 10px; display: block; color: #666; 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: 5px; border: 1px solid #e0e0e0; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: #fff; }
            input:focus, textarea:focus, select:focus { border-color: #E91E63; outline: none; box-shadow: 0 0 0 2px rgba(233, 30, 99, 0.1); }
            textarea { min-height: 80px; resize: vertical; }
            input[type="file"] { padding: 8px; background-color: #ffffff; cursor: pointer; border: 1px solid #e0e0e0;}
            input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #f0f0f0; border: 1px solid #e0e0e0; cursor: pointer; margin-right: 10px;}
             input[type="checkbox"] { margin-right: 5px; vertical-align: middle; }
            label.inline-label { display: inline-block; margin-top: 10px; font-weight: normal; }
            button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #F06292; color: white; font-weight: 500; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; margin-top: 15px; font-size: 0.95rem; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; line-height: 1.2;}
            button:hover, .button:hover { background-color: #E91E63; }
            button:active, .button:active { transform: scale(0.98); }
            button[type="submit"] { min-width: 120px; justify-content: center; }
            .delete-button { background-color: #dc3545; }
            .delete-button:hover { background-color: #c82333; }
            .add-button { background-color: #E91E63; }
            .add-button:hover { background-color: #C2185B; }
             .stock-button { background-color: #28a745; }
            .stock-button:hover { background-color: #218838; }
            .item-list { display: grid; gap: 20px; }
            .item { background: #fff; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.03); border: 1px solid #f0f0f0; }
            .item p { margin: 5px 0; font-size: 0.9rem; color: #666; }
            .item strong { color: #333; }
            .item .description { font-size: 0.85rem; color: #999; max-height: 60px; overflow: hidden; text-overflow: ellipsis; }
            .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
            .item-actions button:not(.delete-button) { background-color: #F06292; }
            .item-actions button:not(.delete-button):hover { background-color: #E91E63; }
            .edit-form-container, .stock-movement-form-container { margin-top: 15px; padding: 20px; background: #fff7fa; border: 1px dashed #e0e0e0; border-radius: 6px; display: none; }
            details { background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 20px; }
            details > summary { cursor: pointer; font-weight: 600; color: #C2185B; display: block; padding: 15px; border-bottom: 1px solid #e0e0e0; list-style: none; position: relative; }
            details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: #E91E63; }
            details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }
            details[open] > summary { border-bottom: 1px solid #e0e0e0; }
            details .form-content { padding: 20px; }
            .color-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
            .color-input-group input { flex-grow: 1; margin: 0; }
            .remove-color-btn { background-color: #dc3545; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; }
            .remove-color-btn:hover { background-color: #c82333; }
            .add-color-btn { background-color: #F8BBD0; color: #C2185B; border: 1px solid #e0e0e0; }
            .add-color-btn:hover { background-color: #E91E63; color: white; border-color: #E91E63; }
            .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #e0e0e0; object-fit: cover;}
            .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
            .download-hf-button { background-color: #6c757d; }
            .download-hf-button:hover { background-color: #5a6268; }
            .flex-container { display: flex; flex-wrap: wrap; gap: 20px; }
            .flex-item { flex: 1; min-width: 350px; }
            .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;}
            .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
            .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #721c24;}
            .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
            .status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; }
            .status-indicator.in-stock { background-color: #d4edda; color: #155724; }
            .status-indicator.out-of-stock { background-color: #f8d7da; color: #721c24; }
            .status-indicator.top-product { background-color: #fff3cd; color: #856404; margin-left: 5px;}
            .stock-level { font-size: 0.9rem; color: #007bff; font-weight: bold; margin-left: 10px;}

             .order-item { display: grid; grid-template-columns: 1fr auto auto; gap: 15px; align-items: center; padding: 10px 0; border-bottom: 1px dashed #eee; font-size: 0.9rem;}
            .order-item:last-child { border-bottom: none; }
            .order-item strong { color: #333; font-size: 1rem;}
            .order-item .quantity { color: #555;}
            .order-item .price { font-weight: bold; color: #C2185B; text-align: right;}

             .order-entry { border: 1px solid #ccc; border-radius: 8px; padding: 15px; margin-bottom: 15px; background-color: #fff; }
            .order-entry h4 { margin-top: 0; margin-bottom: 10px; color: #E91E63;}
            .order-entry p { margin: 5px 0; font-size: 0.9rem; color: #666;}
            .order-entry .total { font-weight: bold; font-size: 1.1rem; color: #C2185B; text-align: right; margin-top: 10px;}

             .stock-movement-entry { border: 1px dashed #ccc; border-radius: 8px; padding: 10px; margin-bottom: 10px; background-color: #fff; font-size: 0.9rem;}
             .stock-movement-entry strong { color: #333;}
             .stock-movement-entry .type { font-weight: bold; }
             .stock-movement-entry .type.receipt { color: #28a745;}
             .stock-movement-entry .type.adjustment { color: #ffc107;}
             .stock-movement-list { max-height: 300px; overflow-y: auto; padding-right: 10px;}
             .stock-movement-list::-webkit-scrollbar { width: 8px; }
             .stock-movement-list::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px;}
             .stock-movement-list::-webkit-scrollbar-thumb { background: #888; border-radius: 10px;}
             .stock-movement-list::-webkit-scrollbar-thumb:hover { background: #555;}

        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;">
                    <h1><i class="fas fa-tools"></i> Админ-панель Meka Shop</h1>
                </div>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <a href="{{ url_for('catalog') }}" class="button" style="background-color: #E91E63;"><i class="fas fa-store"></i> Перейти в каталог</a>
                     <a href="{{ url_for('sales_terminal') }}" class="button stock-button"><i class="fas fa-cash-register"></i> Терминал продаж</a>
                </div>
            </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-sync-alt"></i> Синхронизация с Датацентром</h2>
                <div class="sync-buttons">
                    <form method="POST" action="{{ url_for('force_upload') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.');">
                        <button type="submit" class="button" title="Загрузить локальные файлы на Hugging Face"><i class="fas fa-upload"></i> Загрузить БД</button>
                    </form>
                    <form method="POST" action="{{ url_for('force_download') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.');">
                        <button type="submit" class="button download-hf-button" title="Скачать файлы  (перезапишет локальные)"><i class="fas fa-download"></i> Скачать БД</button>
                    </form>
                </div>
                 <p style="font-size: 0.85rem; color: #999;">Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>
            </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 class="form-content">
                                  <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" class="add-button"><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;">
                                 <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: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button>
                                 </form>
                             </div>
                             {% endfor %}
                         </div>
                         {% else %}
                         <p>Категорий пока нет.</p>
                         {% endif %}
                     </div>
                      <div class="section">
                         <h2><i class="fas fa-history"></i> История движений склада</h2>
                         <div class="stock-movement-list">
                             {% if stock_movements %}
                                 {% for move in stock_movements|reverse %}
                                     <div class="stock-movement-entry">
                                         <p>
                                             <span class="type {{ move.type }}">{{ "Приход" if move.type == 'receipt' else "Корректировка" }}</span>
                                             от <strong>{{ move.timestamp }}</strong>:
                                         </p>
                                          <p>
                                             Товар: <strong>{{ move.product_name }}</strong> |
                                             Кол-во: <strong>{{ move.quantity_change }}{{ " (было: " ~ (move.new_stock_level - move.quantity_change) ~ ", стало: " ~ move.new_stock_level ~ ")" if move.new_stock_level is not none }}</strong>
                                          </p>
                                          {% if move.reason %}
                                             <p>Причина: {{ move.reason }}</p>
                                          {% endif %}
                                     </div>
                                 {% endfor %}
                              {% else %}
                                  <p>Движений склада пока нет.</p>
                              {% endif %}
                         </div>
                     </div>
                 </div>

                 <div class="flex-item">
                      <div class="section">
                         <h2><i class="fas fa-clipboard-list"></i> Последние заказы (Продажи)</h2>
                          {% if orders %}
                             {% for order_id, order in orders|dictsort('created_at', reverse=true) %}
                                 <div class="order-entry">
                                     <h4>Заказ №{{ order.id }} <span style="font-size: 0.9rem; color: #666; font-weight: normal;">({{ order.created_at }})</span></h4>
                                     {% for item in order.items %}
                                         <div class="order-item">
                                             <div>
                                                  <strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong><br>
                                                 <span class="quantity">{{ item.quantity }} шт.</span>
                                             </div>
                                              <span class="price">{{ "%.2f"|format(item.price) }} {{ currency_code }}</span>
                                             <span class="price">{{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}</span>
                                         </div>
                                     {% endfor %}
                                      <div class="total">Итого: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</div>
                                      <div class="item-actions" style="justify-content: flex-end;">
                                           <a href="{{ url_for('view_order', order_id=order.id) }}" class="button" style="margin-top: 10px;"><i class="fas fa-eye"></i> Просмотр</a>
                                      </div>
                                 </div>
                             {% endfor %}
                         {% 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 class="form-content">
                         <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_price">Цена ({{ currency_code }}) *:</label>
                             <input type="number" id="add_price" name="price" step="0.01" min="0" required>
                             <label for="add_stock">Начальный остаток (количество):</label>
                             <input type="number" id="add_stock" name="stock" min="0" value="0">
                             <label for="add_barcode">Штрихкод (опционально):</label>
                             <input type="text" id="add_barcode" name="barcode">
                             <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_photos">Фотографии (до 10 шт.):</label>
                             <input type="file" id="add_photos" name="photos" accept="image/*" multiple>
                             <label>Цвета/Варианты (оставьте пустым, если нет):</label>
                             <div id="add-color-inputs">
                                 <div class="color-input-group">
                                     <input type="text" name="colors" placeholder="Например: Розовый">
                                     <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
                                 </div>
                             </div>
                             <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('add-color-inputs')"><i class="fas fa-palette"></i> Добавить поле для цвета/варианта</button>
                             <br>
                             <div style="margin-top: 15px;">
                                 <input type="checkbox" id="add_in_stock" name="in_stock" checked>
                                 <label for="add_in_stock" class="inline-label">Показывать в каталоге (В наличии)</label>
                             </div>
                             <div style="margin-top: 5px;">
                                 <input type="checkbox" id="add_is_top" name="is_top">
                                 <label for="add_is_top" class="inline-label">Топ товар (показывать наверху в каталоге)</label>
                             </div>
                             <br>
                             <button type="submit" class="add-button" style="margin-top: 20px;"><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" style="flex-shrink: 0;">
                                {% if product.get('photos') %}
                                <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото">
                                   <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото">
                                </a>
                                {% else %}
                                <img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото">
                                {% endif %}
                            </div>
                            <div style="flex-grow: 1;">
                                <h3 style="margin-top: 0; margin-bottom: 5px; color: #333;">
                                    {{ product['name'] }}
                                     <span class="stock-level">Остаток: {{ product.get('stock', 0) }}</span>
                                     {% if product.get('in_stock', True) and product.get('stock', 0) > 0 %}
                                        <span class="status-indicator in-stock">В наличии</span>
                                     {% else %}
                                        <span class="status-indicator out-of-stock">Нет в наличии / Скрыт</span>
                                     {% endif %}
                                     {% if product.get('is_top', False) %}
                                        <span class="status-indicator top-product"><i class="fas fa-star"></i> Топ</span>
                                     {% endif %}
                                </h3>
                                <p><strong>Артикул/ID:</strong> {{ product.get('id', loop.index0) }}</p>
                                <p><strong>Штрихкод:</strong> {{ product.get('barcode', 'Нет') }}</p>
                                <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
                                <p><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
                                <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p>
                                {% set colors = product.get('colors', []) %}
                                <p><strong>Цвета/Вар-ты:</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}</p>
                                {% if product.get('photos') and product['photos']|length > 1 %}
                                    <p style="font-size: 0.8rem; color: #999;">(Всего фото: {{ product['photos']|length }})</p>
                                {% endif %}
                            </div>
                        </div>

                        <div class="item-actions">
                             <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}')"><i class="fas fa-edit"></i> Редактировать</button>
                             <button type="button" class="button stock-button" onclick="toggleStockForm('stock-form-{{ loop.index0 }}')"><i class="fas fa-warehouse"></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="index" value="{{ loop.index0 }}">
                                <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
                            </form>
                        </div>

                        <div id="edit-form-{{ loop.index0 }}" class="edit-form-container">
                            <h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4>
                            <form method="POST" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="edit_product">
                                <input type="hidden" name="index" value="{{ loop.index0 }}">
                                <label>Название *:</label>
                                <input type="text" name="name" value="{{ product['name'] }}" required>
                                <label>Цена ({{ currency_code }}) *:</label>
                                <input type="number" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>
                                <label>Штрихкод (опционально):</label>
                                <input type="text" name="barcode" value="{{ product.get('barcode', '') }}">
                                <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>Заменить фотографии (выберите новые файлы, до 10 шт.):</label>
                                <input type="file" name="photos" accept="image/*" multiple>
                                 {% if product.get('photos') %}
                                    <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p>
                                    <div class="photo-preview">
                                        {% for photo in product['photos'] %}
                                        <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}">
                                        {% endfor %}
                                    </div>
                                {% endif %}
                                <label>Цвета/Варианты:</label>
                                <div id="edit-color-inputs-{{ loop.index0 }}">
                                    {% set current_colors = product.get('colors', []) %}
                                    {% if current_colors and current_colors|select('ne', '')|list|length > 0 %}
                                        {% for color in current_colors %}
                                            {% if color.strip() %}
                                            <div class="color-input-group">
                                                <input type="text" name="colors" value="{{ color }}">
                                                <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
                                            </div>
                                            {% endif %}
                                        {% endfor %}
                                     {% else %}
                                         <div class="color-input-group">
                                            <input type="text" name="colors" placeholder="Например: Цвет">
                                            <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
                                         </div>
                                     {% endif %}
                                </div>
                                <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')"><i class="fas fa-palette"></i> Добавить поле для цвета</button>
                                <br>
                                <div style="margin-top: 15px;">
                                     <input type="checkbox" id="edit_in_stock_{{ loop.index0 }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}>
                                     <label for="edit_in_stock_{{ loop.index0 }}" class="inline-label">Показывать в каталоге (В наличии)</label>
                                </div>
                                <div style="margin-top: 5px;">
                                     <input type="checkbox" id="edit_is_top_{{ loop.index0 }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
                                     <label for="edit_is_top_{{ loop.index0 }}" class="inline-label">Топ товар</label>
                                </div>
                                <br>
                                <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button>
                            </form>
                        </div>

                         <div id="stock-form-{{ loop.index0 }}" class="stock-movement-form-container">
                            <h4><i class="fas fa-warehouse"></i> Учет остатков: {{ product['name'] }} (Текущий остаток: {{ product.get('stock', 0) }})</h4>
                            <form method="POST">
                                <input type="hidden" name="action" value="add_stock_movement">
                                <input type="hidden" name="product_index" value="{{ loop.index0 }}">
                                <label for="movement_type_{{ loop.index0 }}">Тип движения:</label>
                                <select id="movement_type_{{ loop.index0 }}" name="type">
                                    <option value="receipt">Приход (Увеличение)</option>
                                    <option value="adjustment">Корректировка (Увеличение/Уменьшение)</option>
                                </select>
                                <label for="quantity_change_{{ loop.index0 }}">Количество:</label>
                                <input type="number" id="quantity_change_{{ loop.index0 }}" name="quantity" min="0" value="0" required>
                                <label for="movement_reason_{{ loop.index0 }}">Причина / Комментарий:</label>
                                <input type="text" id="movement_reason_{{ loop.index0 }}" name="reason">
                                <button type="submit" class="button stock-button"><i class="fas fa-plus"></i> Записать движение</button>
                            </form>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <p>Товаров пока нет.</p>
                {% endif %}
            </div>

        </div>

        <script>
            function toggleEditForm(formId) {
                const formContainer = document.getElementById(formId);
                if (formContainer) {
                    formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none';
                     // Hide other forms for the same product
                    const parentItem = formContainer.closest('.item');
                    if (parentItem) {
                        parentItem.querySelectorAll('.stock-movement-form-container').forEach(otherForm => {
                            if (otherForm.id !== formId) {
                                otherForm.style.display = 'none';
                            }
                        });
                    }
                }
            }

             function toggleStockForm(formId) {
                const formContainer = document.getElementById(formId);
                if (formContainer) {
                    formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none';
                    // Hide other forms for the same product
                    const parentItem = formContainer.closest('.item');
                     if (parentItem) {
                        parentItem.querySelectorAll('.edit-form-container').forEach(otherForm => {
                            if (otherForm.id !== formId) {
                                otherForm.style.display = 'none';
                            }
                        });
                    }
                }
            }


            function addColorInput(containerId) {
                const container = document.getElementById(containerId);
                if (container) {
                    const newInputGroup = document.createElement('div');
                    newInputGroup.className = 'color-input-group';
                    newInputGroup.innerHTML = `
                        <input type="text" name="colors" placeholder="Новый цвет/вариант">
                        <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
                    `;
                    container.appendChild(newInputGroup);
                    const newInput = newInputGroup.querySelector('input[name="colors"]');
                    if (newInput) {
                        newInput.focus();
                    }
                }
            }

            function removeColorInput(button) {
                const group = button.closest('.color-input-group');
                if (group) {
                    const container = group.parentNode;
                    group.remove();
                    if (container && container.children.length === 0) {
                         const placeholderGroup = document.createElement('div');
                         placeholderGroup.className = 'color-input-group';
                         placeholderGroup.innerHTML = `
                             <input type="text" name="colors" placeholder="Например: Цвет">
                             <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
                         `;
                         container.appendChild(placeholderGroup);
                    }
                } else {
                     console.warn("Could not find parent .color-input-group for remove button");
                }
            }
        </script>
    </body>
    </html>
'''

SALES_TERMINAL_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Терминал продаж - Meka Shop</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
     <!-- QuaggaJS for barcode scanning (optional, requires camera access) -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script> -->
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f0f2f5; color: #333; line-height: 1.6; padding: 20px; }
        .container { max-width: 900px; margin: 20px auto; padding: 25px; background: #fff; border-radius: 10px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); }
        h1 { text-align: center; color: #E91E63; margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; }
        h2 { color: #C2185B; margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px;}
        .search-section, .product-display, .sale-items-section, .sale-summary, .actions { margin-bottom: 25px; padding: 15px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #f9f9f9; }
         .search-section form { display: flex; gap: 10px; }
        .search-section input[type="text"] { flex-grow: 1; padding: 10px 12px; border: 1px solid #ccc; border-radius: 6px; font-size: 1rem; }
         .search-section input[type="text"]:focus { border-color: #E91E63; outline: none; box-shadow: 0 0 0 2px rgba(233, 30, 99, 0.1); }
        .product-display { display: flex; align-items: center; gap: 20px; }
        .product-display img { width: 80px; height: 80px; object-fit: contain; border-radius: 8px; border: 1px solid #e0e0e0; padding: 5px;}
        .product-details { flex-grow: 1; }
        .product-details h3 { margin: 0 0 5px 0; color: #333; font-size: 1.1rem;}
        .product-details p { margin: 3px 0; font-size: 0.9rem; color: #555;}
        .product-details .stock { font-weight: bold; color: #007bff;}
         .product-actions { display: flex; gap: 10px; align-items: center; margin-top: 10px;}
         .product-actions input[type="number"], .product-actions select { padding: 8px; border: 1px solid #ccc; border-radius: 6px; font-size: 0.9rem;}
         .product-actions button { padding: 8px 15px; border-radius: 6px; background-color: #E91E63; color: white; border: none; cursor: pointer; transition: background-color 0.3s ease; }
         .product-actions button:hover { background-color: #C2185B; }
         .product-actions button:disabled { background-color: #ccc; cursor: not-allowed;}

        .sale-item { display: grid; grid-template-columns: 1fr auto auto auto; gap: 10px; align-items: center; padding: 10px 0; border-bottom: 1px dashed #eee; font-size: 0.95rem; }
         .sale-item:last-child { border-bottom: none;}
        .sale-item strong { color: #333;}
        .sale-item .quantity { color: #555;}
        .sale-item .price { font-weight: bold; color: #C2185B; text-align: right;}
         .sale-item button { background: none; border: none; color: #dc3545; cursor: pointer; font-size: 1.1em; }
         .sale-item button:hover { color: #c82333;}

        .sale-summary { text-align: right; border-top: 1px solid #e0e0e0; padding-top: 15px; margin-top: 20px;}
        .sale-summary strong { font-size: 1.3rem; color: #E91E63;}

        .actions { text-align: center; }
        .button { padding: 12px 25px; border: none; border-radius: 8px; background-color: #28a745; color: white; font-weight: 600; cursor: pointer; transition: background-color 0.3s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; }
        .button:hover { background-color: #218838; }
         .button:disabled { background-color: #ccc; cursor: not-allowed;}

         #notification-placeholder {
             position: fixed;
             bottom: 20px;
             left: 50%;
             transform: translateX(-50%);
             z-index: 1002;
             display: flex;
             flex-direction: column;
             align-items: center;
             gap: 10px;
         }

         .notification {
             background-color: #E91E63;
             color: white;
             padding: 10px 20px;
             border-radius: 20px;
             box-shadow: 0 4px 10px rgba(0,0,0,0.2);
             opacity: 0;
             transition: opacity 0.5s ease;
             font-size: 0.9rem;
         }
         .notification.show { opacity: 1;}

         #scanner-container {
             margin-top: 20px;
             text-align: center;
         }
         #scanner-container video {
             max-width: 100%;
             height: auto;
             border: 1px solid #e0e0e0;
             border-radius: 8px;
         }
         .hidden { display: none; }
          .back-link { display: block; text-align: center; margin-top: 20px; color: #E91E63; text-decoration: none; font-size: 0.9rem; }
        .back-link:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-cash-register"></i> Терминал продаж</h1>

        <div class="search-section">
            <h2>Поиск товара</h2>
            <form id="search-form" onsubmit="searchProduct(event)">
                <input type="text" id="product-identifier" placeholder="Введите штрихкод или название" autofocus>
                 <button type="submit"><i class="fas fa-search"></i> Найти</button>
            </form>
             <!-- Optional: Button to activate camera scanner if QuaggaJS is included -->
             <!-- <button id="camera-scan-btn" onclick="startScanner()"> <i class="fas fa-camera"></i> Скан. камерой</button> -->
             <!-- <div id="scanner-container" class="hidden">
                 <video id="scanner-video"></video>
             </div> -->
        </div>

        <div class="product-display" id="found-product-display" style="display: none;">
             <h2>Найденный товар</h2>
             <img src="https://via.placeholder.com/80x80.png?text=No+Image" alt="Product Image" id="found-product-image">
             <div class="product-details">
                 <h3 id="found-product-name">Название товара</h3>
                 <p>Цена: <span id="found-product-price">0.00</span> {{ currency_code }}</p>
                 <p>Остаток на складе: <span id="found-product-stock" class="stock">0</span></p>
                 <p>Штрихкод: <span id="found-product-barcode">Нет</span></p>
                 <p>Категория: <span id="found-product-category">Без категории</span></p>
                 <div class="product-actions">
                      <label for="sale-quantity" style="display: inline-block; margin-top: 0; font-size: 0.9rem;">Кол-во:</label>
                      <input type="number" id="sale-quantity" value="1" min="1" style="width: 80px;">
                       <label for="sale-color" style="display: inline-block; margin-top: 0; font-size: 0.9rem;">Цвет:</label>
                       <select id="sale-color" style="width: 120px;"></select>
                       <button onclick="addToSale()"><i class="fas fa-cart-plus"></i> Добавить к продаже</button>
                 </div>
             </div>
        </div>

        <div class="sale-items-section">
            <h2>Товары в текущей продаже</h2>
            <div id="current-sale-list">
                <p style="text-align: center; color: #999;">Список пуст</p>
            </div>
        </div>

        <div class="sale-summary">
            <strong>Всего к оплате: <span id="sale-total">0.00</span> {{ currency_code }}</strong>
        </div>

        <div class="actions">
            <button id="complete-sale-button" class="button" onclick="completeSale()" disabled>
                <i class="fas fa-check-circle"></i> Завершить продажу
            </button>
            <button id="clear-sale-button" class="button" onclick="clearSale()" disabled style="background-color: #6c757d; margin-left: 10px;">
                <i class="fas fa-times-circle"></i> Отмена
            </button>
        </div>

         <a href="{{ url_for('admin') }}" class="back-link">← Вернуться в Админ-панель</a>
    </div>

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

    <script>
        const currencyCode = '{{ currency_code }}';
        let currentSale = [];
        let foundProduct = null; // Stores details of the product found by search/scan

        function searchProduct(event) {
            event.preventDefault();
            const identifier = document.getElementById('product-identifier').value.trim();
            if (!identifier) return;

             showNotification("Поиск товара...", 2000);

            fetch('/lookup_product', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ identifier: identifier })
            })
            .then(response => {
                if (!response.ok) {
                     return response.json().then(err => { throw new Error(err.error || `Ошибка ${response.status}`); }).catch(() => { throw new Error(`Ошибка сервера ${response.status}`); });
                }
                return response.json();
            })
            .then(data => {
                if (data.product) {
                    foundProduct = data.product;
                    displayFoundProduct(foundProduct);
                     showNotification("Товар найден!", 2000);
                } else {
                    foundProduct = null;
                    hideFoundProduct();
                     showNotification("Товар не найден.", 3000);
                }
            })
            .catch(error => {
                console.error('Ошибка поиска товара:', error);
                foundProduct = null;
                hideFoundProduct();
                showNotification(`Ошибка поиска: ${error.message}`, 5000);
            });
        }

        function displayFoundProduct(product) {
            const displayDiv = document.getElementById('found-product-display');
            const img = document.getElementById('found-product-image');
            const name = document.getElementById('found-product-name');
            const price = document.getElementById('found-product-price');
            const stock = document.getElementById('found-product-stock');
             const barcode = document.getElementById('found-product-barcode');
             const category = document.getElementById('found-product-category');
            const quantityInput = document.getElementById('sale-quantity');
             const colorSelect = document.getElementById('sale-color');
             const addButton = displayDiv.querySelector('.product-actions button');


            img.src = product.photo_url;
            name.textContent = product.name;
            price.textContent = product.price.toFixed(2);
            stock.textContent = product.stock;
             barcode.textContent = product.barcode || 'Нет';
             category.textContent = product.category || 'Без категории';

            quantityInput.value = 1;
            quantityInput.max = product.stock;
             quantityInput.disabled = product.stock <= 0;
             addButton.disabled = product.stock <= 0;

             // Populate colors
             colorSelect.innerHTML = '';
             const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];
             if (validColors.length > 0) {
                 validColors.forEach(color => {
                     const option = document.createElement('option');
                     option.value = color.trim();
                     option.text = color.trim();
                     colorSelect.appendChild(option);
                 });
                 colorSelect.style.display = 'inline-block'; // Show select
                  document.querySelector('label[for="sale-color"]').style.display = 'inline-block';
             } else {
                  const option = document.createElement('option');
                  option.value = 'N/A';
                  option.text = 'Нет вариантов';
                  colorSelect.appendChild(option);
                 colorSelect.style.display = 'none'; // Hide select
                  document.querySelector('label[for="sale-color"]').style.display = 'none';
             }


            displayDiv.style.display = 'flex';
             if (product.stock <= 0) {
                 showNotification(`Товар "${product.name}" отсутствует на складе.`, 4000);
             }
        }

        function hideFoundProduct() {
            document.getElementById('found-product-display').style.display = 'none';
        }

        function addToSale() {
            if (!foundProduct) {
                alert("Сначала найдите товар.");
                return;
            }

            const quantityInput = document.getElementById('sale-quantity');
            const quantity = parseInt(quantityInput.value);
            const colorSelect = document.getElementById('sale-color');
            const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A';


            if (isNaN(quantity) || quantity <= 0) {
                alert("Введите корректное количество.");
                quantityInput.focus();
                return;
            }

             if (quantity > foundProduct.stock) {
                 alert(`Недостаточно товара "${foundProduct.name}" на складе. Доступно: ${foundProduct.stock}`);
                 quantityInput.value = foundProduct.stock;
                 quantityInput.focus();
                 return;
             }

             // Check if item with same name and color is already in the sale list
             const existingItemIndex = currentSale.findIndex(item => item.name === foundProduct.name && item.color === color);

             if (existingItemIndex > -1) {
                 // If exists, update quantity
                 currentSale[existingItemIndex].quantity += quantity;
             } else {
                 // Add new item
                 currentSale.push({
                     product_index: foundProduct.index, // Store original index for backend lookup
                     name: foundProduct.name,
                     price: foundProduct.price,
                     photo: foundProduct.photo,
                     color: color,
                     quantity: quantity,
                     barcode: foundProduct.barcode || '' // Include barcode if available
                 });
             }


            updateSaleList();
            hideFoundProduct(); // Hide found product display after adding
            document.getElementById('product-identifier').value = ''; // Clear search input
             document.getElementById('product-identifier').focus(); // Focus search input
             showNotification(`${foundProduct.name} (${quantity} шт.) добавлен к продаже.`, 2000);
        }

        function removeFromSale(index) {
            currentSale.splice(index, 1);
            updateSaleList();
        }

        function updateSaleList() {
            const listDiv = document.getElementById('current-sale-list');
            const totalSpan = document.getElementById('sale-total');
            const completeButton = document.getElementById('complete-sale-button');
            const clearButton = document.getElementById('clear-sale-button');

            let total = 0;

            if (currentSale.length === 0) {
                listDiv.innerHTML = '<p style="text-align: center; color: #999;">Список пуст</p>';
                completeButton.disabled = true;
                clearButton.disabled = true;
            } else {
                listDiv.innerHTML = currentSale.map((item, index) => {
                    const itemTotal = item.price * item.quantity;
                    total += itemTotal;
                    const colorText = item.color !== 'N/A' ? ` (${item.color})` : '';
                     // Note: No photo displayed in this simple list view
                    return `
                        <div class="sale-item">
                            <div>
                                <strong>${item.name}${colorText}</strong><br>
                                <span class="quantity">${item.quantity} шт.</span>
                            </div>
                             <span class="price">${item.price.toFixed(2)} ${currencyCode}</span>
                            <span class="price">${itemTotal.toFixed(2)} ${currencyCode}</span>
                            <button onclick="removeFromSale(${index})" title="Удалить из продажи">×</button>
                        </div>
                    `;
                }).join('');
                completeButton.disabled = false;
                clearButton.disabled = false;
            }

            totalSpan.textContent = total.toFixed(2);
        }

        function completeSale() {
            if (currentSale.length === 0) {
                alert("Список продажи пуст.");
                return;
            }

             if (!confirm(`Завершить продажу на сумму ${document.getElementById('sale-total').textContent}?`)) {
                 return;
             }

            const completeButton = document.getElementById('complete-sale-button');
             const clearButton = document.getElementById('clear-sale-button');
            completeButton.disabled = true;
             clearButton.disabled = true;


            showNotification("Оформление продажи...", 5000);

            fetch('/register_sale', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ items: currentSale })
            })
            .then(response => {
                 if (!response.ok) {
                      return response.json().then(err => { throw new Error(err.error || `Сервер вернул ошибку ${response.status}`); }).catch(() => { throw new Error(`Ошибка сервера ${response.status}`); });
                 }
                 return response.json();
            })
            .then(data => {
                if (data.order_id) {
                    showNotification("Продажа успешно зарегистрирована!", 3000);
                    clearSale(); // Clear the current sale list UI
                     foundProduct = null; // Reset found product
                     hideFoundProduct();
                    document.getElementById('product-identifier').focus(); // Focus search input

                    // Optional: Redirect or show success message + link to order
                    // window.location.href = `/order/${data.order_id}`; // Can redirect to order view if desired
                     // For terminal, just show success and stay
                } else {
                    throw new Error('Не получен ID продажи от сервера.');
                }
            })
            .catch(error => {
                console.error('Ошибка при регистрации продажи:', error);
                alert(`Ошибка при регистрации продажи: ${error.message}`);
                 completeButton.disabled = false;
                 clearButton.disabled = false;
                 showNotification(`Ошибка продажи: ${error.message}`, 5000);
            });
        }

        function clearSale() {
             if (currentSale.length > 0 && !confirm("Отменить текущую продажу?")) {
                 return;
             }
            currentSale = [];
            updateSaleList();
             foundProduct = null;
             hideFoundProduct();
             document.getElementById('product-identifier').value = '';
             document.getElementById('product-identifier').focus();
             showNotification("Продажа отменена.", 2000);
        }

         function showNotification(message, duration = 3000) {
            let placeholder = document.getElementById('notification-placeholder');
            if (!placeholder) {
                placeholder = document.createElement('div');
                placeholder.id = 'notification-placeholder';
                placeholder.style.cssText = `
                    position: fixed;
                    bottom: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    z-index: 1002;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 10px;
                `;
                document.body.appendChild(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);
         }


         // Optional: Barcode scanner using QuaggaJS - Requires more setup (permissions, library)
         /*
         let scannerRunning = false;

         function startScanner() {
             if (scannerRunning) {
                 stopScanner();
                 return;
             }

             const scannerContainer = document.getElementById('scanner-container');
             const video = document.getElementById('scanner-video');
             scannerContainer.classList.remove('hidden');
             document.getElementById('camera-scan-btn').textContent = 'Остановить скан. камерой';

             Quagga.init({
                 inputStream : {
                     name : "Live",
                     type : "LiveStream",
                     target: video,
                     constraints: {
                         width: 640,
                         height: 480,
                         facingMode: "environment" // Use rear camera if available
                     },
                 },
                 decoder : {
                     readers : ["ean_by_kr_reader","ean_reader","upc_a_reader","upc_e_reader","code_128_reader","code_39_reader","code_93_reader"] // Supported formats
                 }
             }, function(err) {
                 if (err) {
                     console.error(err);
                     showNotification("Ошибка инициализации сканера: " + err.message, 5000);
                     scannerRunning = false;
                     scannerContainer.classList.add('hidden');
                      document.getElementById('camera-scan-btn').textContent = 'Скан. камерой';
                     return;
                 }
                 console.log("QuaggaJS initialization finished. Ready to start.");
                 Quagga.start();
                 scannerRunning = true;
             });

             Quagga.onDetected(function(result) {
                 const code = result.codeResult.code;
                 console.log("Barcode detected: " + code);
                 document.getElementById('product-identifier').value = code;
                 searchProduct(new Event('submit')); // Trigger search as if typed
                 stopScanner(); // Stop scanner after detection
             });

              Quagga.onProcessed(function(result) {
                // Draw bounding boxes on the video feed (optional)
              });
         }

         function stopScanner() {
             if (scannerRunning) {
                 Quagga.stop();
                 scannerRunning = false;
                 document.getElementById('scanner-container').classList.add('hidden');
                 document.getElementById('camera-scan-btn').textContent = 'Скан. камерой';
                 console.log("QuaggaJS stopped.");
             }
         }

         // Add event listener for camera scan button if it exists
         // document.addEventListener('DOMContentLoaded', () => {
         //    const cameraScanBtn = document.getElementById('camera-scan-btn');
         //    if (cameraScanBtn) {
         //        cameraScanBtn.addEventListener('click', startScanner);
         //    }
         // });
         */

        document.addEventListener('DOMContentLoaded', () => {
            updateSaleList(); // Initialize buttons state
             document.getElementById('product-identifier').focus(); // Focus search input on load
        });

    </script>
</body>
</html>
'''

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

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

    return render_template_string(
        CATALOG_TEMPLATE,
        products=products_sorted,
        categories=categories,
        repo_id=REPO_ID,
        store_address=STORE_ADDRESS,
        currency_code=CURRENCY_CODE
    )

@app.route('/product_detail_html/<product_name>')
def product_detail_html(product_name):
     data = load_data()
     barcode = request.args.get('barcode')
     product = None
     if barcode:
         product = get_product_by_identifier(data, barcode)
     if not product:
         # Fallback lookup by name (less reliable if names aren't unique)
         for p in data.get('products', []):
             if p.get('name') == product_name:
                 product = p
                 break

     if not product:
         return "Товар не найден.", 404

     return render_template_string(
        PRODUCT_DETAIL_TEMPLATE,
        product=product,
        repo_id=REPO_ID,
        currency_code=CURRENCY_CODE
    )


@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']:
        logging.warning("Create order request missing cart data or cart is empty.")
        return jsonify({"error": "Корзина пуста или не передана."}), 400

    cart_items = order_data['cart']
    data = load_data()
    products = data.get('products', [])

    # Validate stock before processing
    stock_check_ok = True
    items_to_process = []
    for item in cart_items:
        if not all(k in item for k in ('name', 'price', 'quantity')):
            logging.error(f"Invalid cart item structure received: {item}")
            return jsonify({"error": "Неверный формат товара в корзине."}), 400
        try:
            price = float(item['price'])
            quantity = int(item['quantity'])
            if price < 0 or quantity <= 0:
                raise ValueError("Invalid price or quantity")

            # Find the corresponding product in the database to check stock
            product_in_db = None
            # Priority: find by original index if available (from catalog)
            if 'original_product_index' in item:
                 product_in_db = get_product_by_index(data, item['original_product_index'])
            # Fallback: find by name+color or just name
            if not product_in_db:
                 for p in products:
                     if p.get('name') == item['name']:
                         # If product has colors, check color match
                         if p.get('colors') and p.get('colors').filter(lambda c: c and c.strip() != "").length > 0:
                             if item.get('color', 'N/A') in p.get('colors', []):
                                 product_in_db = p
                                 break # Found by name and color
                         else:
                              product_in_db = p
                              break # Found by name, no colors or color N/A


            if not product_in_db:
                logging.error(f"Product '{item['name']}' not found in database during order creation.")
                return jsonify({"error": f"Товар '{item['name']}' не найден."}), 400

            if product_in_db.get('stock', 0) < quantity:
                stock_check_ok = False
                flash(f"Недостаточно '{item['name']}' ({item.get('color', 'N/A')}). Доступно: {product_in_db.get('stock', 0)}.", 'error')
                logging.warning(f"Insufficient stock for '{item['name']}' (requested {quantity}, available {product_in_db.get('stock', 0)}).")
                # Continue checking others to report all shortages at once

            items_to_process.append({
                 "db_product": product_in_db, # Keep reference to update stock
                 "name": item['name'],
                 "price": price,
                 "quantity": quantity,
                 "color": item.get('color', 'N/A'),
                 "photo": item.get('photo'), # This is the filename from the product
                 "barcode": product_in_db.get('barcode', '') # Include barcode in order history
            })

        except (ValueError, TypeError) as e:
            logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}")
            return jsonify({"error": "Неверная цена или количество в товаре."}), 400

    if not stock_check_ok:
         # If any item failed stock check, redirect to catalog with flash messages
         return jsonify({"error": "Ошибка остатков. Проверьте корзину."}), 400 # Use JSON error for fetch API

    # Deduct stock and build order items
    total_price = 0
    order_items = []
    stock_movements = data.get('stock_movements', [])

    for item_proc in items_to_process:
        item_proc['db_product']['stock'] = max(0, item_proc['db_product'].get('stock', 0) - item_proc['quantity'])
        item_total = item_proc['price'] * item_proc['quantity']
        total_price += item_total

        order_items.append({
             "name": item_proc['name'],
             "price": item_proc['price'],
             "quantity": item_proc['quantity'],
             "color": item_proc['color'],
             "photo": item_proc['photo'],
             "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item_proc['photo']}" if item_proc['photo'] else "https://via.placeholder.com/60x60.png?text=N/A",
             "barcode": item_proc['barcode']
        })

        # Log stock movement for sale
        movement_id = str(uuid.uuid4())
        movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        stock_movements.append({
             "id": movement_id,
             "timestamp": movement_timestamp,
             "type": "sale", # New type for sales deduction
             "product_name": item_proc['name'],
             "quantity_change": -item_proc['quantity'], # Negative for deduction
             "new_stock_level": item_proc['db_product']['stock'],
             "reason": f"Продажа (Заказ №{order_data.get('order_id', 'N/A')})",
             "details": f"Цвет/вариант: {item_proc['color']}"
        })


    order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"
    order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    new_order = {
        "id": order_id,
        "created_at": order_timestamp,
        "items": order_items,
        "total_price": round(total_price, 2),
        "user_info": None,
        "status": "new", # Status can be 'new', 'processed', etc.
        "type": "customer_order" # Distinguish from admin sales if needed later
    }

    try:
        if 'orders' not in data or not isinstance(data.get('orders'), dict):
            data['orders'] = {}

        data['orders'][order_id] = new_order
        data['stock_movements'] = stock_movements # Update movements
        data['products'] = products # Products list with updated stock levels
        save_data(data)
        logging.info(f"Order {order_id} created successfully (anonymously). Stock deducted.")
        return jsonify({"order_id": order_id}), 201

    except Exception as e:
        logging.error(f"Failed to save order {order_id}: {e}", exc_info=True)
        return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500


@app.route('/order/<order_id>')
def view_order(order_id):
    data = load_data()
    order = data.get('orders', {}).get(order_id)

    if order:
        logging.info(f"Displaying order {order_id}")
    else:
        logging.warning(f"Order {order_id} not found.")

    return render_template_string(ORDER_TEMPLATE,
                                  order=order,
                                  repo_id=REPO_ID,
                                  currency_code=CURRENCY_CODE)


@app.route('/admin', methods=['GET', 'POST'])
def admin():
    data = load_data()
    products = data.get('products', [])
    categories = data.get('categories', [])
    orders = data.get('orders', {})
    stock_movements = data.get('stock_movements', [])

    if request.method == 'POST':
        action = request.form.get('action')
        logging.info(f"Admin action received: {action}")

        try:
            if action == 'add_category':
                category_name = request.form.get('category_name', '').strip()
                if category_name and category_name not in categories:
                    categories.append(category_name)
                    data['categories'] = categories
                    save_data(data)
                    logging.info(f"Category '{category_name}' added.")
                    flash(f"Категория '{category_name}' успешно добавлена.", 'success')
                elif not category_name:
                     logging.warning("Attempted to add empty category.")
                     flash("Название категории не может быть пустым.", 'error')
                else:
                     logging.warning(f"Category '{category_name}' already exists.")
                     flash(f"Категория '{category_name}' уже существует.", 'error')

            elif action == 'delete_category':
                category_to_delete = request.form.get('category_name')
                if category_to_delete and category_to_delete in categories:
                    categories.remove(category_to_delete)
                    updated_count = 0
                    for product in products:
                        if product.get('category') == category_to_delete:
                            product['category'] = 'Без категории'
                            updated_count += 1
                    data['categories'] = categories
                    data['products'] = products
                    save_data(data)
                    logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
                    flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success')
                else:
                    logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")
                    flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')

            elif action == 'add_product':
                name = request.form.get('name', '').strip()
                price_str = request.form.get('price', '').replace(',', '.')
                stock_str = request.form.get('stock', '0')
                barcode = request.form.get('barcode', '').strip()
                description = request.form.get('description', '').strip()
                category = request.form.get('category')
                photos_files = request.files.getlist('photos')
                colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
                in_stock = 'in_stock' in request.form
                is_top = 'is_top' in request.form

                if not name or not price_str:
                    flash("Название и цена товара обязательны.", 'error')
                    return redirect(url_for('admin'))

                try:
                    price = round(float(price_str), 2)
                    if price < 0: price = 0
                except ValueError:
                     flash("Неверный формат цены.", 'error')
                     return redirect(url_for('admin'))
                try:
                    stock = int(stock_str)
                    if stock < 0: stock = 0
                except ValueError:
                     flash("Неверный формат остатка.", 'error')
                     return redirect(url_for('admin'))

                # Check for duplicate barcode if provided
                if barcode:
                     for p in products:
                         if p.get('barcode') == barcode:
                             flash(f"Товар со штрихкодом '{barcode}' уже существует ('{p.get('name', 'N/A')}').", 'error')
                             return redirect(url_for('admin'))


                photos_list = []
                if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
                    uploads_dir = 'uploads_temp'
                    os.makedirs(uploads_dir, exist_ok=True)
                    api = HfApi()
                    photo_limit = 10
                    uploaded_count = 0
                    for photo in photos_files:
                        if uploaded_count >= photo_limit:
                            logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
                            flash(f"Загружено только первые {photo_limit} фото.", "warning")
                            break
                        if photo and photo.filename:
                            try:
                                ext = os.path.splitext(photo.filename)[1].lower()
                                if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
                                     logging.warning(f"Skipping non-image file upload: {photo.filename}")
                                     flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
                                     continue

                                safe_name = secure_filename(name.replace(' ', '_'))[:50]
                                photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
                                temp_path = os.path.join(uploads_dir, photo_filename)
                                photo.save(temp_path)
                                logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
                                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"Add photo for product {name}"
                                )
                                photos_list.append(photo_filename)
                                logging.info(f"Photo {photo_filename} uploaded successfully.")
                                os.remove(temp_path)
                                uploaded_count += 1
                            except Exception as e:
                                logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
                                flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')
                                if os.path.exists(temp_path):
                                    try: os.remove(temp_path)
                                    except OSError: pass
                        elif photo and not photo.filename:
                             logging.warning("Received an empty photo file object when adding product.")
                    try:
                         if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                             os.rmdir(uploads_dir)
                    except OSError as e:
                        logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
                elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
                    flash("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning")


                new_product = {
                    'name': name, 'price': price, 'description': description,
                    'category': category if category in categories else 'Без категории',
                    'photos': photos_list, 'colors': colors,
                    'in_stock': in_stock, 'is_top': is_top,
                    'stock': stock, 'barcode': barcode
                }
                products.append(new_product)
                data['products'] = products
                save_data(data)

                # Log initial stock movement if stock > 0
                if stock > 0:
                    movement_id = str(uuid.uuid4())
                    movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    data['stock_movements'].append({
                        "id": movement_id,
                        "timestamp": movement_timestamp,
                        "type": "receipt",
                        "product_name": name,
                        "quantity_change": stock,
                        "new_stock_level": stock,
                        "reason": "Начальный остаток при добавлении товара",
                        "details": ""
                    })
                    save_data(data) # Save again to include stock movement

                logging.info(f"Product '{name}' added.")
                flash(f"Товар '{name}' успешно добавлен.", 'success')

            elif action == 'edit_product':
                index_str = request.form.get('index')
                if index_str is None:
                     flash("Ошибка редактирования: индекс товара не передан.", 'error')
                     return redirect(url_for('admin'))

                try:
                    index = int(index_str)
                    if not (0 <= index < len(products)):
                        raise IndexError("Product index out of range")
                    product_to_edit = products[index]
                    original_name = product_to_edit.get('name', 'N/A')
                    original_barcode = product_to_edit.get('barcode', '')

                except (ValueError, IndexError):
                     flash(f"Ошибка редактирования: неверный индекс товара '{index_str}'.", 'error')
                     logging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")
                     return redirect(url_for('admin'))

                product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
                price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.')
                new_barcode = request.form.get('barcode', '').strip()
                product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
                category = request.form.get('category')
                product_to_edit['category'] = category if category in categories else 'Без категории'
                product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()]
                product_to_edit['in_stock'] = 'in_stock' in request.form
                product_to_edit['is_top'] = 'is_top' in request.form
                # Stock is updated via add_stock_movement, not directly here

                try:
                    price = round(float(price_str), 2)
                    if price < 0: price = 0
                    product_to_edit['price'] = price
                except ValueError:
                     logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.")
                     flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning')

                 # Check for duplicate barcode if changed and not empty
                if new_barcode and new_barcode != original_barcode:
                     for i, p in enumerate(products):
                         if i != index and p.get('barcode') == new_barcode:
                             flash(f"Штрихкод '{new_barcode}' уже используется товаром '{p.get('name', 'N/A')}'.", 'error')
                             return redirect(url_for('admin'))
                product_to_edit['barcode'] = new_barcode


                photos_files = request.files.getlist('photos')
                if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
                    uploads_dir = 'uploads_temp'
                    os.makedirs(uploads_dir, exist_ok=True)
                    api = HfApi()
                    new_photos_list = []
                    photo_limit = 10
                    uploaded_count = 0
                    logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
                    for photo in photos_files:
                        if uploaded_count >= photo_limit:
                            logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
                            flash(f"Загружено только первые {photo_limit} фото.", "warning")
                            break
                        if photo and photo.filename:
                            try:
                                ext = os.path.splitext(photo.filename)[1].lower()
                                if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
                                     logging.warning(f"Skipping non-image file upload during edit: {photo.filename}")
                                     flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
                                     continue

                                safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50]
                                photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
                                temp_path = os.path.join(uploads_dir, photo_filename)
                                photo.save(temp_path)
                                logging.info(f"Uploading new photo {photo_filename} to HF...")
                                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"Update photo for product {product_to_edit['name']}")
                                new_photos_list.append(photo_filename)
                                logging.info(f"New photo {photo_filename} uploaded successfully.")
                                os.remove(temp_path)
                                uploaded_count += 1
                            except Exception as e:
                                logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
                                flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')
                                if os.path.exists(temp_path):
                                     try: os.remove(temp_path)
                                     except OSError: pass
                        elif photo and not photo.filename:
                             logging.warning("Received an empty photo file object when editing product.")
                    try:
                         if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                             os.rmdir(uploads_dir)
                    except OSError as e:
                        logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")

                    if new_photos_list:
                        logging.info(f"New photo list for product {product_to_edit['name']} generated.")
                        old_photos = product_to_edit.get('photos', [])
                        if old_photos:
                            logging.info(f"Attempting to delete old photos: {old_photos}")
                            try:
                                api.delete_files(
                                    repo_id=REPO_ID,
                                    paths_in_repo=[f"photos/{p}" for p in old_photos],
                                    repo_type="dataset",
                                    token=HF_TOKEN_WRITE,
                                    commit_message=f"Delete old photos for product {product_to_edit['name']}"
                                )
                                logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")
                            except Exception as e:
                                logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
                                flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")
                        product_to_edit['photos'] = new_photos_list
                        flash("Фотографии товара успешно обновлены.", "success")
                    elif uploaded_count == 0 and any(f.filename for f in photos_files):
                         flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error")
                elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
                    flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning")


                products[index] = product_to_edit
                data['products'] = products
                save_data(data)
                logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.")
                flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success')

            elif action == 'delete_product':
                index_str = request.form.get('index')
                if index_str is None:
                    flash("Ошибка удаления: индекс товара не передан.", 'error')
                    return redirect(url_for('admin'))
                try:
                    index = int(index_str)
                    if not (0 <= index < len(products)): raise IndexError("Product index out of range")
                    deleted_product = products.pop(index)
                    product_name = deleted_product.get('name', 'N/A')

                    photos_to_delete = deleted_product.get('photos', [])
                    if photos_to_delete and HF_TOKEN_WRITE:
                        logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")
                        try:
                            api = HfApi()
                            api.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,
                                commit_message=f"Delete photos for deleted product {product_name}"
                            )
                            logging.info(f"Photos for product '{product_name}' deleted from HF.")
                        except Exception as e:
                             logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
                             flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning")
                    elif photos_to_delete and not HF_TOKEN_WRITE:
                        logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.")
                        flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning")


                    data['products'] = products
                    save_data(data)
                    logging.info(f"Product '{product_name}' (original index {index}) deleted.")
                    flash(f"Товар '{product_name}' удален.", 'success')
                except (ValueError, IndexError):
                     flash(f"Ошибка удаления: неверный индекс товара '{index_str}'.", 'error')
                     logging.error(f"Invalid index '{index_str}' for deletion. Product list length: {len(products)}")

            elif action == 'add_stock_movement':
                 product_index_str = request.form.get('product_index')
                 movement_type = request.form.get('type')
                 quantity_str = request.form.get('quantity', '0')
                 reason = request.form.get('reason', '').strip()

                 if product_index_str is None or not movement_type or not quantity_str:
                     flash("Не все поля для движения остатков заполнены.", 'error')
                     return redirect(url_for('admin'))

                 try:
                     product_index = int(product_index_str)
                     quantity = int(quantity_str)
                     if quantity < 0 and movement_type != 'adjustment':
                          flash("Количество должно быть неотрицательным.", 'error')
                          return redirect(url_for('admin'))

                     if not (0 <= product_index < len(products)):
                        raise IndexError("Product index out of range")

                     product = products[product_index]
                     original_stock = product.get('stock', 0)
                     quantity_change = quantity

                     if movement_type == 'receipt':
                         product['stock'] = original_stock + quantity
                         log_type = 'receipt'
                     elif movement_type == 'adjustment':
                          # Adjustment quantity can be positive or negative. Interpret input 'quantity' as the CHANGE amount.
                          quantity_change = int(quantity_str) # Allow negative input for adjustment
                          product['stock'] = original_stock + quantity_change
                          product['stock'] = max(0, product['stock']) # Stock cannot go below zero
                          log_type = 'adjustment'
                     else:
                         flash("Неверный тип движения остатков.", 'error')
                         return redirect(url_for('admin'))


                     # Log the movement
                     movement_id = str(uuid.uuid4())
                     movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                     data['stock_movements'].append({
                         "id": movement_id,
                         "timestamp": movement_timestamp,
                         "type": log_type,
                         "product_name": product.get('name', 'N/A'),
                         "quantity_change": quantity_change,
                         "new_stock_level": product['stock'],
                         "reason": reason if reason else f"{log_type.capitalize()} stock",
                         "details": f"Было: {original_stock}, Стало: {product['stock']}"
                     })

                     # Update product's in_stock status based on stock level
                     product['in_stock'] = product['stock'] > 0

                     save_data(data)
                     logging.info(f"Stock movement for '{product.get('name', 'N/A')}': {log_type}, change {quantity_change}, new stock {product['stock']}.")
                     flash(f"Остаток товара '{product.get('name', 'N/A')}' обновлен: {product['stock']}.", 'success')


                 except (ValueError, IndexError) as e:
                     flash(f"Ошибка при учете остатков: неверные данные. {e}", 'error')
                     logging.error(f"Error processing stock movement: {e}", exc_info=True)

            else:
                 logging.warning(f"Received unknown admin action: {action}")
                 flash(f"Неизвестное действие: {action}", 'warning')

            return redirect(url_for('admin'))

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

    current_data = load_data()
    # Sort products for display in admin
    display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
    display_categories = sorted(current_data.get('categories', []))
    display_orders = current_data.get('orders', {})
    display_stock_movements = current_data.get('stock_movements', [])

    return render_template_string(
        ADMIN_TEMPLATE,
        products=display_products,
        categories=display_categories,
        orders=display_orders,
        stock_movements=display_stock_movements,
        repo_id=REPO_ID,
        currency_code=CURRENCY_CODE
    )

@app.route('/sales_terminal')
def sales_terminal():
     return render_template_string(
        SALES_TERMINAL_TEMPLATE,
        currency_code=CURRENCY_CODE
    )

@app.route('/lookup_product', methods=['POST'])
def lookup_product():
    identifier_data = request.get_json()
    identifier = identifier_data.get('identifier', '').strip()

    if not identifier:
        return jsonify({"error": "Идентификатор товара не предоставлен."}), 400

    data = load_data()

    # Find the product by barcode or name
    found_product = get_product_by_identifier(data, identifier)

    if found_product:
         # Find the index of the found product in the current product list order
         # This index might be different from its original index if the list was reordered
         try:
            # We need a stable way to reference the product, barcode is best.
            # Or pass the barcode back to the client. Let's pass the barcode.
            # The client can then send the barcode back in the sale request.
            # This avoids issues with list index changing.

            # Prepare product data for JSON response
            product_data = {
                 "name": found_product.get('name'),
                 "price": found_product.get('price', 0.0),
                 "stock": found_product.get('stock', 0),
                 "barcode": found_product.get('barcode', ''),
                 "category": found_product.get('category', 'Без категории'),
                 "colors": found_product.get('colors', []),
                 "photo": found_product.get('photos', [None])[0], # First photo
                 "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{found_product.get('photos', [None])[0]}" if found_product.get('photos') else "https://via.placeholder.com/80x80.png?text=No+Image"
            }

            logging.info(f"Product lookup successful for '{identifier}'. Found '{found_product.get('name')}'")
            return jsonify({"product": product_data}), 200
         except Exception as e:
             logging.error(f"Error preparing product data for lookup response for '{identifier}': {e}", exc_info=True)
             return jsonify({"error": "Внутренняя ошибка сервера при подготовке данных товара."}), 500

    else:
        logging.info(f"Product lookup failed for '{identifier}'.")
        return jsonify({"product": None, "error": "Товар не найден."}), 404

@app.route('/register_sale', methods=['POST'])
def register_sale():
    sale_data = request.get_json()

    if not sale_data or 'items' not in sale_data or not sale_data['items']:
        logging.warning("Register sale request missing items or items list is empty.")
        return jsonify({"error": "Список продажи пуст."}), 400

    sale_items = sale_data['items']
    data = load_data()
    products = data.get('products', [])
    stock_movements = data.get('stock_movements', [])

    # Validate and find products, check stock
    items_to_process = []
    stock_check_ok = True
    errors = []

    for item in sale_items:
        if not all(k in item for k in ('name', 'quantity', 'color')):
            logging.error(f"Invalid sale item structure received: {item}")
            return jsonify({"error": "Неверный формат товара в списке продажи."}), 400

        try:
            quantity = int(item['quantity'])
            if quantity <= 0:
                raise ValueError("Invalid quantity")

            # Find product by barcode if available, else by name+color
            product_in_db = None
            if item.get('barcode'):
                product_in_db = get_product_by_identifier(data, item['barcode'])
            if not product_in_db: # Fallback to name + color lookup
                 for p in products:
                     if p.get('name') == item['name']:
                         # If product has colors, check color match
                         if p.get('colors') and p.get('colors').filter(lambda c: c and c.strip() != "").length > 0:
                             if item.get('color', 'N/A') in p.get('colors', []):
                                 product_in_db = p
                                 break # Found by name and color
                         else:
                              product_in_db = p
                              break # Found by name, no colors or color N/A


            if not product_in_db:
                logging.error(f"Product '{item['name']}' not found in database during sale registration.")
                errors.append(f"Товар '{item['name']}' не найден в системе.")
                stock_check_ok = False
                continue

            if product_in_db.get('stock', 0) < quantity:
                stock_check_ok = False
                errors.append(f"Недостаточно '{item['name']}' ({item.get('color', 'N/A')}). Доступно: {product_in_db.get('stock', 0)}, запрошено: {quantity}.")
                logging.warning(f"Insufficient stock for '{item['name']}' (requested {quantity}, available {product_in_db.get('stock', 0)}).")
                continue

            # Validate price consistency (optional, but good practice)
            if abs(product_in_db.get('price', 0.0) - item.get('price', 0.0)) > 0.001: # Check if prices match database price closely
                logging.warning(f"Price mismatch for '{item['name']}': Sale price {item.get('price')}, DB price {product_in_db.get('price')}. Using DB price.")
                item_price = product_in_db.get('price', 0.0) # Use price from DB
            else:
                 item_price = item.get('price', 0.0) # Use price from client if it matches DB

            items_to_process.append({
                 "db_product": product_in_db, # Keep reference to update stock
                 "name": item['name'],
                 "price": item_price, # Use validated/corrected price
                 "quantity": quantity,
                 "color": item.get('color', 'N/A'),
                 "photo": product_in_db.get('photos', [None])[0], # Get photo filename from DB
                 "barcode": product_in_db.get('barcode', '') # Include barcode in sale history
            })

        except (ValueError, TypeError) as e:
            logging.error(f"Invalid data in sale item: {item}. Error: {e}")
            errors.append(f"Неверные данные для товара '{item.get('name', 'N/A')}'.")
            stock_check_ok = False


    if not stock_check_ok:
         # Return all accumulated errors
         return jsonify({"error": "Ошибки в списке продажи: " + ", ".join(errors)}), 400

    # Deduct stock and build sale record
    total_price = 0
    sale_items_record = []

    for item_proc in items_to_process:
        original_stock = item_proc['db_product'].get('stock', 0)
        item_proc['db_product']['stock'] = max(0, original_stock - item_proc['quantity'])
        item_total = item_proc['price'] * item_proc['quantity']
        total_price += item_total

        sale_items_record.append({
             "name": item_proc['name'],
             "price": item_proc['price'],
             "quantity": item_proc['quantity'],
             "color": item_proc['color'],
             "photo": item_proc['photo'], # This is the filename
             "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item_proc['photo']}" if item_proc['photo'] else "https://via.placeholder.com/60x60.png?text=N/A",
             "barcode": item_proc['barcode']
        })

        # Log stock movement for sale
        movement_id = str(uuid.uuid4())
        movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        stock_movements.append({
             "id": movement_id,
             "timestamp": movement_timestamp,
             "type": "sale", # Type for sales deduction
             "product_name": item_proc['name'],
             "quantity_change": -item_proc['quantity'], # Negative for deduction
             "new_stock_level": item_proc['db_product']['stock'],
             "reason": f"Продажа (Терминал)",
             "details": f"Цвет/вариант: {item_proc['color']}"
        })


    sale_id = f"SALE-{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:4]}"
    sale_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    new_sale = {
        "id": sale_id,
        "created_at": sale_timestamp,
        "items": sale_items_record,
        "total_price": round(total_price, 2),
        "user_info": None, # No user info for anonymous sales
        "status": "completed", # Mark sales terminal orders as completed
        "type": "admin_sale" # Type for admin terminal sales
    }

    try:
        if 'orders' not in data or not isinstance(data.get('orders'), dict):
            data['orders'] = {}

        data['orders'][sale_id] = new_sale
        data['stock_movements'] = stock_movements # Update movements
        data['products'] = products # Products list with updated stock levels
        save_data(data)
        logging.info(f"Sale {sale_id} registered successfully via terminal. Stock deducted.")
        return jsonify({"order_id": sale_id, "message": "Продажа успешно зарегистрирована."}), 201

    except Exception as e:
        logging.error(f"Failed to save sale {sale_id}: {e}", exc_info=True)
        return jsonify({"error": "Ошибка сервера при сохранении продажи."}), 500


@app.route('/force_upload', methods=['POST'])
def force_upload():
    logging.info("Forcing upload to Hugging Face...")
    try:
        upload_db_to_hf()
        flash("Данные успешно загружены на Hugging Face.", 'success')
    except Exception as e:
        logging.error(f"Error during forced upload: {e}", exc_info=True)
        flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error')
    return redirect(url_for('admin'))

@app.route('/force_download', methods=['POST'])
def force_download():
    logging.info("Forcing download from Hugging Face...")
    try:
        if download_db_from_hf():
            flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
            load_data()
        else:
            flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')
    except Exception as e:
        logging.error(f"Error during forced download: {e}", exc_info=True)
        flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')
    return redirect(url_for('admin'))


if __name__ == '__main__':
    logging.info("Application starting up. Performing initial data load/download...")
    download_db_from_hf()
    load_data()
    logging.info("Initial data load complete.")

    if HF_TOKEN_WRITE:
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
        logging.info("Periodic backup thread started.")
    else:
        logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).")

    port = int(os.environ.get('PORT', 7860))
    logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")
    app.run(debug=False, host='0.0.0.0', port=port)