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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
from flask import Flask, render_template_string, request, redirect, url_for, send_file
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
from werkzeug.utils import secure_filename
from urllib.parse import quote

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

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

LOGO_URL = "https://huggingface.co/spaces/Mebelhause/Kg/resolve/main/Screenshot_20250411-112027.png"
WHATSAPP_NUMBER = "+996700253966"

logging.basicConfig(level=logging.INFO)

def load_data():
    try:
        download_db_from_hf()
        with open(DATA_FILE, 'r', encoding='utf-8') as file:
            data = json.load(file)
            logging.info("Данные успешно загружены из JSON")
            if not isinstance(data, dict) or 'products' not in data or 'categories' not in data:
                logging.warning("Структура данных некорректна, используется структура по умолчанию.")
                return {'products': [], 'categories': []}
            # Ensure products and categories are lists
            if not isinstance(data.get('products'), list):
                 data['products'] = []
            if not isinstance(data.get('categories'), list):
                 data['categories'] = []
            return data
    except FileNotFoundError:
        logging.warning("Локальный файл базы данных не найден. Создание пустой базы.")
        return {'products': [], 'categories': []}
    except json.JSONDecodeError:
        logging.error("Ошибка: Невозможно декодировать JSON файл. Возврат пустой базы.")
        return {'products': [], 'categories': []}
    except RepositoryNotFoundError:
        logging.error("Репозиторий Hugging Face не найден. Создание локальной базы данных.")
        # Create an empty file if it doesn't exist locally after repo not found
        if not os.path.exists(DATA_FILE):
            with open(DATA_FILE, 'w', encoding='utf-8') as f:
                json.dump({'products': [], 'categories': []}, f)
        return {'products': [], 'categories': []}
    except Exception as e:
        logging.error(f"Произошла ошибка при загрузке данных: {e}. Возврат пустой базы.")
        return {'products': [], 'categories': []}

def save_data(data):
    try:
        # Ensure structure is correct before saving
        if 'products' not in data or not isinstance(data['products'], list):
            data['products'] = []
        if 'categories' not in data or not isinstance(data['categories'], list):
            data['categories'] = []

        with open(DATA_FILE, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
        logging.info("Данные успешно сохранены в JSON")
        upload_db_to_hf()
    except Exception as e:
        logging.error(f"Ошибка при сохранении данных: {e}")
        # Optionally re-raise or handle differently
        # raise

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


def download_db_from_hf():
    if not HF_TOKEN_READ:
        logging.warning("HF_TOKEN_READ не установлен. Скачивание с Hugging Face пропущено.")
        # Attempt to create an empty file if none exists
        if not os.path.exists(DATA_FILE):
             save_data({'products': [], 'categories': []}) # Save an empty structure
        return
    try:
        hf_hub_download(
            repo_id=REPO_ID,
            filename=DATA_FILE,
            repo_type="dataset",
            token=HF_TOKEN_READ,
            local_dir=".",
            local_dir_use_symlinks=False,
            force_download=True, # Ensure we get the latest version
            resume_download=False # Avoid issues with partial downloads
        )
        logging.info("JSON база успешно скачана из Hugging Face.")
        # Verify file integrity after download
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                json.load(f)
            logging.info("Проверка целостности JSON после скачивания: OK")
        except (json.JSONDecodeError, FileNotFoundError) as e:
            logging.error(f"Ошибка проверки JSON после скачивания: {e}. Файл может быть поврежден или пуст.")
            # Attempt to create a default empty file if it's broken
            save_data({'products': [], 'categories': []})

    except RepositoryNotFoundError as e:
        logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face: {e}")
        if not os.path.exists(DATA_FILE):
             save_data({'products': [], 'categories': []}) # Save an empty structure
        # Do not raise here, allow fallback to local/empty data
    except Exception as e:
        # Catch specific hf_hub exceptions if needed, e.g., HTTPError
        logging.error(f"Ошибка при скачивании JSON базы из Hugging Face: {e}")
        if not os.path.exists(DATA_FILE):
             save_data({'products': [], 'categories': []}) # Save an empty structure
        # Do not raise here, allow fallback to local/empty data

def periodic_backup():
    while True:
        time.sleep(800) # Sleep first to avoid immediate backup on start
        logging.info("Запуск периодического резервного копирования...")
        # Ensure data is loaded before backup attempt
        try:
            load_data() # Reload potentially updated data
        except Exception as e:
            logging.error(f"Ошибка загрузки данных перед бэкапом: {e}")
        # Now attempt upload
        upload_db_to_hf()

# --- Global Styles ---
GLOBAL_STYLES = """
<style>
    :root {
        --bg-beige: #f5f5dc;
        --text-dark-brown: #4d2c1a; /* Darker brown for text */
        --accent-wood: #8b4513; /* SaddleBrown */
        --accent-light-wood: #deb887; /* BurlyWood */
        --button-bg: var(--accent-wood);
        --button-hover-bg: #a0522d; /* Sienna - slightly lighter */
        --card-bg: #ffffff;
        --border-color: #e0d8c7; /* Lighter border */
        --header-bg: #ffffff; /* White header */
        --footer-bg: var(--text-dark-brown);
        --footer-text: var(--bg-beige);
        --link-color: var(--accent-wood);
        --link-hover-color: var(--button-hover-bg);

        --font-primary: 'Poppins', sans-serif;
    }
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    body {
        font-family: var(--font-primary);
        background-color: var(--bg-beige);
        color: var(--text-dark-brown);
        line-height: 1.6;
        font-size: 16px;
    }
    .container {
        max-width: 1300px;
        margin: 0 auto;
        padding: 20px;
    }
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        background-color: var(--header-bg);
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        position: sticky;
        top: 0;
        z-index: 1000;
    }
    .header-logo {
        height: 60px; /* Adjust height as needed */
        width: auto; /* Maintain aspect ratio */
        object-fit: contain; /* Ensure logo fits well */
    }
    .header nav a {
        color: var(--text-dark-brown);
        text-decoration: none;
        margin-left: 25px;
        font-weight: 500;
        transition: color 0.3s ease;
        font-size: 1.1rem;
    }
    .header nav a:hover, .header nav a.active {
        color: var(--accent-wood);
        font-weight: 600;
    }
    .main-content {
        padding: 40px 0;
    }
    h1, h2, h3 {
        color: var(--text-dark-brown);
        margin-bottom: 1rem;
        font-weight: 600;
    }
    h1 { font-size: 2.5rem; text-align: center; margin-bottom: 2rem; }
    h2 { font-size: 2rem; margin-bottom: 1.5rem; border-bottom: 2px solid var(--accent-light-wood); padding-bottom: 0.5rem;}
    h3 { font-size: 1.5rem; }

    button, .button-link {
        padding: 12px 25px;
        border: none;
        border-radius: 8px;
        background-color: var(--button-bg);
        color: white;
        font-weight: 500;
        cursor: pointer;
        transition: background-color 0.3s ease, transform 0.2s ease;
        text-decoration: none; /* For button-link */
        display: inline-block; /* For button-link */
        font-size: 1rem;
        text-align: center;
    }
    button:hover, .button-link:hover {
        background-color: var(--button-hover-bg);
        transform: translateY(-2px);
    }
    .whatsapp-float {
        position: fixed;
        width: 60px;
        height: 60px;
        bottom: 30px;
        right: 30px;
        background-color: #25D366;
        color: #FFF;
        border-radius: 50px;
        text-align: center;
        font-size: 30px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        z-index: 100;
        display: flex;
        justify-content: center;
        align-items: center;
        text-decoration: none;
        transition: transform 0.3s ease;
    }
    .whatsapp-float:hover {
        transform: scale(1.1);
    }
    .whatsapp-float i {
        margin-top: 0; /* Adjust if needed */
    }
    .footer {
        background-color: var(--footer-bg);
        color: var(--footer-text);
        text-align: center;
        padding: 20px;
        margin-top: 40px;
    }
    .footer p {
        margin: 0;
        font-size: 0.9rem;
    }

    /* Form Styles */
    .form-section {
        background: var(--card-bg);
        padding: 30px;
        border-radius: 15px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        margin-bottom: 30px;
    }
    label {
        font-weight: 500;
        margin-top: 15px;
        display: block;
        color: var(--text-dark-brown);
    }
    input[type="text"],
    input[type="number"],
    input[type="file"],
    textarea,
    select {
        width: 100%;
        padding: 12px;
        margin-top: 8px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        font-size: 1rem;
        background-color: #fff;
        color: var(--text-dark-brown);
        transition: border-color 0.3s ease, box-shadow 0.3s ease;
    }
    input:focus, textarea:focus, select:focus {
        border-color: var(--accent-wood);
        box-shadow: 0 0 0 3px rgba(139, 69, 19, 0.2); /* SaddleBrown with opacity */
        outline: none;
    }
    textarea {
        min-height: 100px;
        resize: vertical;
    }
    .form-button {
        margin-top: 20px;
    }
    .delete-button {
        background-color: #ef4444;
    }
    .delete-button:hover {
        background-color: #dc2626;
    }
    .add-color-btn {
        background-color: #10b981;
        margin-left: 10px;
         padding: 8px 15px;
    }
    .add-color-btn:hover {
        background-color: #059669;
    }
     .color-input-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-top: 5px;
    }
     .color-input-group input {
        flex-grow: 1;
     }
     .color-input-group button {
         flex-shrink: 0;
         margin-top: 8px; /* Align with input's margin */
         padding: 10px 10px; /* Smaller padding */
         font-size: 0.9rem;
     }
    .remove-color-btn {
        background-color: #ef4444;
        color: white;
        border: none;
        border-radius: 50%;
        width: 25px;
        height: 25px;
        font-size: 14px;
        line-height: 25px; /* Center the 'X' */
        text-align: center;
        cursor: pointer;
        padding: 0;
        margin-left: 5px;
    }


    /* Modal Styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 1001;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.6);
        backdrop-filter: blur(5px);
    }
    .modal-content {
        background-color: var(--card-bg);
        margin: 5% auto;
        padding: 30px;
        border-radius: 15px;
        width: 90%;
        max-width: 700px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        position: relative;
    }
    @keyframes slideIn {
        from { transform: translateY(-50px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }
    .close {
        position: absolute;
        top: 15px;
        right: 20px;
        color: var(--text-dark-brown);
        font-size: 2rem;
        font-weight: bold;
        cursor: pointer;
        transition: color 0.3s;
    }
    .close:hover, .close:focus {
        color: var(--accent-wood);
        text-decoration: none;
    }
    .modal-content h2 {
        margin-top: 0;
        margin-bottom: 1.5rem;
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 0.8rem;
    }
    .modal-content p {
        margin-bottom: 1rem;
    }
    .modal-content strong {
        color: var(--accent-wood);
    }

    /* Swiper Styles for Modal */
    .swiper-container {
        width: 100%;
        max-width: 450px; /* Adjust as needed */
        margin: 0 auto 25px;
        border-radius: 10px;
        overflow: hidden;
        background-color: #eee; /* Placeholder background */
    }
    .swiper-slide {
        text-align: center;
        background: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 350px; /* Fixed height for slides */
    }
    .swiper-slide img {
        display: block;
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
        border-radius: 10px;
    }
    .swiper-pagination-bullet-active {
        background: var(--accent-wood) !important;
    }
    .swiper-button-next, .swiper-button-prev {
        color: var(--accent-wood) !important;
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 50%;
        width: 40px !important;
        height: 40px !important;
        transition: background-color 0.3s ease;
    }
    .swiper-button-next:hover, .swiper-button-prev:hover {
         background-color: rgba(255, 255, 255, 0.9);
    }
    .swiper-button-next::after, .swiper-button-prev::after {
        font-size: 20px !important;
        font-weight: bold;
    }

</style>
<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;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
"""

# --- Landing Page ---
@app.route('/')
def landing():
    landing_html = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Mebel Hause KG - Изготовление мебели на заказ</title>
        ''' + GLOBAL_STYLES + '''
        <style>
            .hero {
                background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url('https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80') no-repeat center center/cover; /* Example background */
                color: white;
                padding: 100px 20px;
                text-align: center;
                border-radius: 0 0 20px 20px; /* Rounded bottom corners */
            }
            .hero h1 {
                font-size: 3rem;
                margin-bottom: 1rem;
                color: white;
                 text-shadow: 2px 2px 8px rgba(0,0,0,0.6);
                 border-bottom: none; /* Override global h1 style */
            }
            .hero p {
                font-size: 1.3rem;
                margin-bottom: 2rem;
                 text-shadow: 1px 1px 6px rgba(0,0,0,0.7);
            }
            .features {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                gap: 30px;
                margin-top: 40px;
            }
            .feature-item {
                background: var(--card-bg);
                padding: 25px;
                border-radius: 15px;
                text-align: center;
                box-shadow: 0 4px 15px rgba(0,0,0,0.08);
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .feature-item:hover {
                transform: translateY(-5px);
                box-shadow: 0 6px 20px rgba(0,0,0,0.12);
            }
            .feature-item i {
                font-size: 3rem;
                color: var(--accent-wood);
                margin-bottom: 1rem;
            }
            .feature-item h3 {
                margin-bottom: 0.5rem;
            }
        </style>
    </head>
    <body>
        <header class="header">
            <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo">
            <nav>
                <a href="#calculator">Калькулятор</a>
                <a href="{{ url_for('catalog') }}">Каталог</a>
                <a href="#about">О нас</a>
                <a href="#contact">Контакты</a>
            </nav>
        </header>

        <section class="hero">
            <h1>Mebel Hause KG</h1>
            <p>Создаем мебель вашей мечты с любовью и мастерством</p>
            <a href="{{ url_for('catalog') }}" class="button-link">Смотреть готовые изделия</a>
        </section>

        <main class="main-content container">
            <section id="about">
                 <h2>Почему выбирают нас?</h2>
                 <div class="features">
                    <div class="feature-item">
                        <i class="fas fa-couch"></i>
                        <h3>Индивидуальный дизайн</h3>
                        <p>Разработаем уникальный проект под ваш интерьер и пожелания.</p>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-ruler-combined"></i>
                        <h3>Точные замеры</h3>
                        <p>Гарантируем идеальное соответствие мебели вашему пространству.</p>
                    </div>
                    <div class="feature-item">
                         <i class="fas fa-check-circle"></i>
                        <h3>Качественные материалы</h3>
                        <p>Используем только проверенные и долговечные материалы.</p>
                    </div>
                     <div class="feature-item">
                        <i class="fas fa-shipping-fast"></i>
                        <h3>Своевременная доставка</h3>
                        <p>Доставим и соберем вашу новую мебель точно в срок.</p>
                    </div>
                </div>
            </section>

            <section id="calculator" class="form-section">
                <h2>Рассчитать стоимость мебели</h2>
                <p>Заполните форму ниже, и мы свяжемся с вами для уточнения деталей и расчета.</p>
                <form id="calculator-form">
                    <label for="furniture-type">Вид мебели:</label>
                    <select id="furniture-type" name="furniture-type">
                        <option value="Кухня">Кухня</option>
                        <option value="Шкаф">Шкаф (купе, распашной)</option>
                        <option value="ТВ Зона">ТВ Зона</option>
                        <option value="Кровать">Кровать</option>
                        <option value="Стол">Стол (обеденный, письменный, журнальный)</option>
                        <option value="Диван">Диван</option>
                        <option value="Прихожая">Прихожая</option>
                        <option value="Детская">Детская мебель</option>
                         <option value="Другое">Другое (укажите в пожеланиях)</option>
                    </select>

                    <label for="material">Предпочитаемый материал:</label>
                    <select id="material" name="material">
                        <option value="ЛДСП">ЛДСП (Ламинированная ДСП)</option>
                        <option value="МДФ">МДФ (крашеный, пленочный, шпонированный)</option>
                        <option value="Массив дерева">Массив дерева</option>
                        <option value="Шпон">Шпон</option>
                        <option value="Пластик/Акрил">Пластик / Акриловые панели</option>
                        <option value="Не уверен">Не уверен / Нужна консультация</option>
                    </select>

                    <label for="dimensions">Примерные размеры (ШхВхГ в см) или площадь:</label>
                    <input type="text" id="dimensions" name="dimensions" placeholder="Например: 200x240x60 см или 'стена 3 метра'">

                    <label for="wishes">Дополнительные пожелания:</label>
                    <textarea id="wishes" name="wishes" placeholder="Например: цвет, фурнитура, особенности конструкции, стиль..."></textarea>

                    <button type="button" class="form-button" onclick="generateWhatsAppMessage()">Отправить запрос на расчет</button>
                </form>
            </section>

             <section id="contact">
                 <h2>Свяжитесь с нами</h2>
                 <p>Готовы обсудить ваш проект? Напишите нам в WhatsApp или позвоните!</p>
                 <p style="font-size: 1.2rem; font-weight: 600;">Телефон / WhatsApp: <a href="https://wa.me/{{ whatsapp_number }}" target="_blank" style="color: var(--link-color);">{{ whatsapp_number_display }}</a></p>
                 <p>Мы находимся в Бишкеке.</p>
             </section>

        </main>

        <footer class="footer">
            <p>© {{ current_year }} Mebel Hause KG. Все права защищены.</p>
        </footer>

        <a href="https://wa.me/{{ whatsapp_number }}" class="whatsapp-float" target="_blank">
            <i class="fab fa-whatsapp"></i>
        </a>

        <script>
            function generateWhatsAppMessage() {
                const furnitureType = document.getElementById('furniture-type').value;
                const material = document.getElementById('material').value;
                const dimensions = document.getElementById('dimensions').value;
                const wishes = document.getElementById('wishes').value;
                const whatsappNumber = "{{ whatsapp_number }}";

                let message = `Здравствуйте, Mebel Hause KG!\\n\\nХочу рассчитать стоимость мебели:\\n`;
                message += `*Тип:* ${furnitureType}\\n`;
                message += `*Материал:* ${material}\\n`;
                if (dimensions) {
                    message += `*Размеры/Площадь:* ${dimensions}\\n`;
                }
                if (wishes) {
                    message += `*Пожелания:* ${wishes}\\n`;
                }
                message += `\\nЖду вашего ответа.`;

                const encodedMessage = encodeURIComponent(message);
                const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodedMessage}`;
                // const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`; // Alternative format

                window.open(whatsappUrl, '_blank');
            }

             // Active link highlighting
            document.addEventListener("DOMContentLoaded", function() {
              const navLinks = document.querySelectorAll('.header nav a');
              const currentPath = window.location.pathname;

              navLinks.forEach(link => {
                // Simple check for landing page links (using hash)
                if (link.getAttribute('href').startsWith('#') && currentPath === '/') {
                   // Could add logic for scrollspy here if needed
                } else if (link.getAttribute('href') === currentPath) {
                  link.classList.add('active');
                }
              });
            });
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/js/all.min.js"></script>
    </body>
    </html>
    '''
    # Format number for display
    whatsapp_display = f"+{WHATSAPP_NUMBER[0]} ({WHATSAPP_NUMBER[1:4]}) {WHATSAPP_NUMBER[4:7]}-{WHATSAPP_NUMBER[7:10]}-{WHATSAPP_NUMBER[10:]}"
    return render_template_string(
        landing_html,
        logo_url=LOGO_URL,
        whatsapp_number=WHATSAPP_NUMBER,
        whatsapp_number_display=whatsapp_display,
        current_year=datetime.now().year
    )

# --- Catalog Page ---
@app.route('/catalog')
def catalog():
    data = load_data()
    products = data.get('products', [])
    categories = data.get('categories', [])

    catalog_html = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Каталог готовой мебели - Mebel Hause KG</title>
        ''' + GLOBAL_STYLES + '''
        <style>
            .filters-container {
                margin: 30px 0;
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                justify-content: center;
                padding-bottom: 20px;
                border-bottom: 1px solid var(--border-color);
            }
            .search-container {
                margin: 20px 0;
                text-align: center;
            }
            #search-input {
                width: 90%;
                max-width: 600px;
                padding: 12px 18px;
                font-size: 1rem;
                border: 1px solid var(--border-color);
                border-radius: 8px;
                outline: none;
                box-shadow: 0 2px 5px rgba(0,0,0,0.05);
                transition: all 0.3s ease;
            }
            #search-input:focus {
                border-color: var(--accent-wood);
                box-shadow: 0 0 0 3px rgba(139, 69, 19, 0.2);
            }
            .category-filter {
                padding: 8px 16px;
                border: 1px solid var(--border-color);
                border-radius: 20px; /* Pill shape */
                background-color: var(--card-bg);
                color: var(--text-dark-brown);
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                font-size: 0.9rem;
                font-weight: 500;
            }
            .category-filter.active, .category-filter:hover {
                background-color: var(--accent-wood);
                color: white;
                border-color: var(--accent-wood);
                box-shadow: 0 2px 10px rgba(139, 69, 19, 0.3);
            }
            .products-grid {
                display: grid;
                 /* Responsive columns: 1 on small, 2 on medium, 3-4 on large */
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 25px;
                padding: 10px 0; /* Remove side padding */
            }
            .product {
                background: var(--card-bg);
                border-radius: 15px;
                padding: 0; /* Remove padding, handle inside */
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
                transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease;
                overflow: hidden; /* Ensure content respects border radius */
                display: flex;
                flex-direction: column;
            }
            .product:hover {
                transform: translateY(-5px) scale(1.02);
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
            }
            .product-image {
                width: 100%;
                aspect-ratio: 4 / 3; /* Adjust aspect ratio */
                background-color: #f0f0f0; /* Light placeholder bg */
                overflow: hidden;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .product-image img {
                width: 100%;
                height: 100%;
                object-fit: cover; /* Cover the area */
                transition: transform 0.4s ease;
            }
             .product:hover .product-image img {
                transform: scale(1.05); /* Slight zoom on hover */
            }
            .product-info {
                padding: 15px;
                text-align: center;
                flex-grow: 1; /* Allow info to take remaining space */
                 display: flex;
                 flex-direction: column;
                 justify-content: space-between; /* Push buttons down */
            }
            .product-info-top {
                 margin-bottom: 15px; /* Space before buttons */
            }
            .product h2 {
                font-size: 1.1rem; /* Slightly smaller */
                font-weight: 600;
                margin: 0 0 8px 0; /* Adjust margin */
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                 border-bottom: none; /* Override global */
                 padding-bottom: 0;
            }
            .product-price {
                font-size: 1.2rem;
                color: var(--accent-wood); /* Accent color for price */
                font-weight: 700;
                margin: 5px 0;
            }
            .product-description {
                font-size: 0.9rem;
                color: #555; /* Slightly lighter text */
                margin-bottom: 15px;
                overflow: hidden;
                text-overflow: ellipsis;
                /* Limit description lines */
                display: -webkit-box;
                -webkit-line-clamp: 2; /* Show max 2 lines */
                -webkit-box-orient: vertical;
            }
            .product-buttons {
                display: flex;
                gap: 10px; /* Space between buttons */
                margin-top: auto; /* Push to bottom */
            }
            .product-button {
                flex: 1; /* Make buttons equal width */
                padding: 10px;
                border: none;
                border-radius: 8px;
                background-color: var(--button-bg);
                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: var(--button-hover-bg);
                transform: translateY(-2px);
            }
            .add-to-cart {
                background-color: #10b981; /* Green for cart */
            }
            .add-to-cart:hover {
                background-color: #059669;
                box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4);
            }
            #cart-button {
                position: fixed;
                bottom: 30px; /* Match whatsapp button height */
                right: 100px; /* Position next to whatsapp */
                background-color: var(--accent-light-wood); /* Light wood color */
                color: var(--text-dark-brown);
                border: none;
                border-radius: 50%;
                width: 60px;
                height: 60px;
                font-size: 1.5rem; /* Larger icon */
                cursor: pointer;
                display: none; /* Hidden by default */
                justify-content: center;
                align-items: center;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                z-index: 1000;
            }
             #cart-button:hover {
                 transform: scale(1.1);
                 background-color: var(--accent-wood);
                 color: white;
             }
            #cart-count {
                position: absolute;
                top: -5px;
                right: -5px;
                background-color: #ef4444; /* Red badge */
                color: white;
                border-radius: 50%;
                padding: 2px 6px;
                font-size: 0.7rem;
                font-weight: bold;
             }

             /* Cart Modal Specific Styles */
             .cart-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 0;
                border-bottom: 1px solid var(--border-color);
             }
              .cart-item:last-child {
                 border-bottom: none;
             }
             .cart-item img {
                width: 60px;
                height: 60px;
                object-fit: cover;
                border-radius: 8px;
                margin-right: 15px;
                border: 1px solid var(--border-color);
             }
             .cart-item-details {
                 flex-grow: 1;
                 margin-right: 15px;
             }
              .cart-item-details strong {
                 display: block;
                 margin-bottom: 3px;
              }
              .cart-item-details p {
                  font-size: 0.9rem;
                  color: #555;
                  margin-bottom: 0;
              }
             .cart-item-price {
                 font-weight: 600;
                 min-width: 80px; /* Ensure price alignment */
                 text-align: right;
             }
             .cart-actions {
                 display: flex;
                 justify-content: flex-end;
                 gap: 15px;
                 margin-top: 25px;
                 padding-top: 20px;
                 border-top: 1px solid var(--border-color);
              }
             #cartTotal {
                 font-size: 1.3rem;
             }
             .quantity-input, .color-select { /* Style for quantity/color modal */
                width: 100%;
                max-width: 200px; /* Adjust width */
                padding: 10px;
                border: 1px solid var(--border-color);
                border-radius: 8px;
                font-size: 1rem;
                margin: 10px 0;
                display: block; /* Ensure they take block space */
             }
             .modal-content .product-button { /* Reuse product button style */
                 margin-top: 15px;
             }
        </style>
    </head>
    <body>
        <header class="header">
            <a href="{{ url_for('landing') }}">
                <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo">
            </a>
            <nav>
                 <a href="{{ url_for('landing') }}#calculator">Калькулятор</a>
                 <a href="{{ url_for('catalog') }}" class="active">Каталог</a>
                 <a href="{{ url_for('landing') }}#about">О нас</a>
                 <a href="{{ url_for('landing') }}#contact">Контакты</a>
            </nav>
        </header>

        <div class="container main-content">
             <h1>Каталог готовых изделий</h1>
             <p style="text-align: center; margin-bottom: 2rem;">Ознакомьтесь с нашими работами. Возможно, что-то из этого подойдет именно вам!</p>

            <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"
                     data-name="{{ product['name']|lower }}"
                     data-description="{{ product['description']|lower }}"
                     data-category="{{ product.get('category', 'Без категории') }}">
                    <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] }}?download=true"
                             alt="{{ product['name'] }}"
                             loading="lazy">
                        {% else %}
                         <img src="https://via.placeholder.com/400x300?text=Нет+фото" alt="Нет фото">
                        {% endif %}
                    </div>
                    <div class="product-info">
                        <div class="product-info-top">
                            <h2>{{ product['name'] }}</h2>
                            <div class="product-price">{{ product['price'] }} сом</div>
                            <p class="product-description">{{ product['description'] }}</p>
                        </div>
                        <div class="product-buttons">
                            <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button>
                            <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">
                               <i class="fas fa-cart-plus"></i> В корзину
                            </button>
                        </div>
                    </div>
                </div>
                {% else %}
                  <p>В каталоге пока нет товаров.</p>
                {% endfor %}
            </div>
        </div>

        <div id="productModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('productModal')">×</span>
                <div id="modalContent"></div>
            </div>
        </div>

        <div id="quantityModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('quantityModal')">×</span>
                <h2>Добавить в корзину</h2>
                <label for="quantityInput">Количество:</label>
                <input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
                 <div id="colorSelectorContainer">
                    <label for="colorSelect">Цвет:</label>
                    <select id="colorSelect" class="color-select"></select>
                 </div>
                <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')">×</span>
                <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
                <div id="cartContent"><p>Корзина пуста.</p></div>
                <div style="margin-top: 20px; text-align: right; font-size: 1.2rem; font-weight: 600;">
                    <strong>Итого: <span id="cartTotal">0</span> сом</strong>
                </div>
                <div class="cart-actions">
                    <button class="product-button delete-button" onclick="clearCart()">
                       <i class="fas fa-trash"></i> Очистить
                    </button>
                    <button class="product-button add-to-cart" onclick="orderViaWhatsApp()">
                       <i class="fab fa-whatsapp"></i> Заказать по WhatsApp
                    </button>
                </div>
            </div>
        </div>

        <button id="cart-button" onclick="openCartModal()">
            <i class="fas fa-shopping-cart"></i>
            <span id="cart-count">0</span>
        </button>

         <a href="https://wa.me/{{ whatsapp_number }}" class="whatsapp-float" target="_blank">
            <i class="fab fa-whatsapp"></i>
        </a>

        <footer class="footer">
            <p>© {{ current_year }} Mebel Hause KG. Все права защищены.</p>
        </footer>

        <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 whatsappNumber = "{{ whatsapp_number }}";
            let selectedProductIndex = null;
            let productModalSwiper = null;

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

            function closeModal(modalId) {
                document.getElementById(modalId).style.display = "none";
                if (modalId === 'productModal' && productModalSwiper) {
                    productModalSwiper.destroy(true, true);
                    productModalSwiper = null;
                }
            }

            function loadProductDetails(index) {
                 fetch('/product/' + index)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Товар не найден');
                        }
                        return response.text();
                     })
                    .then(data => {
                        document.getElementById('modalContent').innerHTML = data;
                        initializeSwiper(); // Initialize Swiper after content is loaded
                    })
                    .catch(error => {
                        console.error('Ошибка загрузки деталей товара:', error);
                        document.getElementById('modalContent').innerHTML = '<p>Не удалось загрузить информацию о товаре.</p>';
                    });
            }


            function initializeSwiper() {
                const swiperElement = document.querySelector('#productModal .swiper-container');
                if (swiperElement) {
                     if (productModalSwiper) { // Destroy previous instance if exists
                        productModalSwiper.destroy(true, true);
                    }
                    productModalSwiper = new Swiper(swiperElement, {
                        slidesPerView: 1,
                        spaceBetween: 20,
                        loop: true, // Loop if more than one slide
                        grabCursor: true,
                        pagination: { el: '.swiper-pagination', clickable: true },
                        navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
                        zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' },
                         lazy: { loadPrevNext: true }, // Enable lazy loading
                    });
                     // Ensure loop works correctly only if there are multiple images
                    if (productModalSwiper.slides.length <= 3) { // Swiper adds duplicates for loop
                        productModalSwiper.params.loop = false;
                        productModalSwiper.update();
                     }
                 } else {
                     console.log("Swiper container not found in modal content.");
                 }
            }


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

                const colorSelect = document.getElementById('colorSelect');
                const colorContainer = document.getElementById('colorSelectorContainer');
                colorSelect.innerHTML = ''; // Clear previous options

                if (product.colors && product.colors.length > 0) {
                    product.colors.forEach(color => {
                        const option = document.createElement('option');
                        option.value = color;
                        option.textContent = color;
                        colorSelect.appendChild(option);
                    });
                     colorContainer.style.display = 'block'; // Show color selector
                } else {
                    // If no colors, add a default placeholder and hide selector? Or just proceed?
                    // Let's hide it if no colors are defined for this product
                    colorContainer.style.display = 'none';
                }

                document.getElementById('quantityInput').value = 1; // Reset quantity
                document.getElementById('quantityModal').style.display = 'block';
            }

            function confirmAddToCart() {
                if (selectedProductIndex === null || !products[selectedProductIndex]) {
                     console.error("Не выбран товар для добавления.");
                     alert("Ошибка: Пожалуйста, выберите товар.");
                     return;
                }

                const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
                const product = products[selectedProductIndex];
                const colorSelect = document.getElementById('colorSelect');
                 // Use selected color if available, otherwise use a placeholder or null
                 let color = 'N/A'; // Default if no colors
                 if (product.colors && product.colors.length > 0) {
                     color = colorSelect.value || product.colors[0]; // Get selected or first color
                 }

                if (quantity <= 0) {
                    alert("Укажите количество больше 0");
                    return;
                }

                let cart = JSON.parse(localStorage.getItem('cart') || '[]');
                // Unique ID considering product name and color (if applicable)
                 const cartItemId = product.colors && product.colors.length > 0 ? `${product.name}-${color}` : product.name;
                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] : '',
                        quantity: quantity,
                        color: color, // Store the selected color
                        repoId: repoId // Store repoId for image URL generation later
                    });
                }

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

             function showNotification(message) {
                const notification = document.createElement('div');
                notification.style.position = 'fixed';
                notification.style.bottom = '20px';
                notification.style.left = '50%';
                notification.style.transform = 'translateX(-50%)';
                notification.style.backgroundColor = 'var(--accent-wood)';
                notification.style.color = 'white';
                notification.style.padding = '10px 20px';
                notification.style.borderRadius = '8px';
                notification.style.zIndex = '1005';
                notification.style.opacity = '0';
                notification.style.transition = 'opacity 0.5s ease';
                notification.textContent = message;
                document.body.appendChild(notification);

                // Fade in
                setTimeout(() => { notification.style.opacity = '1'; }, 10);
                // Fade out and remove
                 setTimeout(() => {
                     notification.style.opacity = '0';
                     setTimeout(() => { document.body.removeChild(notification); }, 500);
                 }, 3000); // Show for 3 seconds
            }


            function updateCartButton() {
                const cart = JSON.parse(localStorage.getItem('cart') || '[]');
                const cartButton = document.getElementById('cart-button');
                const cartCount = document.getElementById('cart-count');
                const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);

                 if (totalItems > 0) {
                    cartButton.style.display = 'flex'; // Use flex to center icon
                    cartCount.textContent = totalItems;
                     cartCount.style.display = 'block';
                } else {
                    cartButton.style.display = 'none';
                     cartCount.style.display = 'none';
                }
            }

            function openCartModal() {
                const cart = JSON.parse(localStorage.getItem('cart') || '[]');
                const cartContent = document.getElementById('cartContent');
                let total = 0;

                 if (cart.length === 0) {
                     cartContent.innerHTML = '<p style="text-align: center; padding: 20px 0;">Ваша корзина пуста.</p>';
                     document.getElementById('cartTotal').textContent = '0';
                 } else {
                    cartContent.innerHTML = cart.map(item => {
                        const itemTotal = item.price * item.quantity;
                        total += itemTotal;
                         const photoUrl = item.photo ? `https://huggingface.co/datasets/${item.repoId}/resolve/main/photos/${item.photo}?download=true` : 'https://via.placeholder.com/60x60?text=N/A';
                        return `
                            <div class="cart-item">
                                <img src="${photoUrl}" alt="${item.name}">
                                <div class="cart-item-details">
                                    <strong>${item.name}</strong>
                                    <p>${item.quantity} шт. × ${item.price} сом ${item.color !== 'N/A' ? `(Цвет: ${item.color})` : ''}</p>
                                </div>
                                <span class="cart-item-price">${itemTotal} сом</span>
                                 <button onclick="removeFromCart('${item.id}')" style="background: none; border: none; color: #ef4444; cursor: pointer; font-size: 1.2rem; margin-left: 10px;" title="Удалить товар">×</button>
                            </div>
                        `;
                    }).join('');
                     document.getElementById('cartTotal').textContent = total;
                }

                document.getElementById('cartModal').style.display = 'block';
            }

            function removeFromCart(itemId) {
                let cart = JSON.parse(localStorage.getItem('cart') || '[]');
                cart = cart.filter(item => item.id !== itemId);
                localStorage.setItem('cart', JSON.stringify(cart));
                openCartModal(); // Refresh cart modal view
                updateCartButton(); // Update cart button count
            }

            function orderViaWhatsApp() {
                const cart = JSON.parse(localStorage.getItem('cart') || '[]');
                if (cart.length === 0) {
                    alert("Ваша корзина пуста!");
                    return;
                }
                let total = 0;
                let orderText = "Здравствуйте! Хочу заказать следующие товары из каталога:\\n\\n";
                cart.forEach((item, index) => {
                    const itemTotal = item.price * item.quantity;
                    total += itemTotal;
                    orderText += `${index + 1}. ${item.name}`;
                    if (item.color !== 'N/A') {
                        orderText += ` (Цвет: ${item.color})`;
                    }
                    orderText += ` - ${item.quantity} шт. x ${item.price} сом = ${itemTotal} сом\\n`;
                });
                orderText += `\\n*Итого: ${total} сом*`;

                const encodedMessage = encodeURIComponent(orderText);
                // const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`;
                const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodedMessage}`;


                window.open(whatsappUrl, '_blank');
                 // Optionally clear cart after sending? Or ask user?
                 // clearCart();
            }

            function clearCart() {
                 if (confirm("Вы уверены, что хотите очистить корзину?")) {
                     localStorage.removeItem('cart');
                     closeModal('cartModal');
                     updateCartButton();
                     openCartModal(); // Refresh modal to show empty state
                 }
            }

            window.onclick = function(event) {
                const modals = document.querySelectorAll('.modal');
                modals.forEach(modal => {
                    if (event.target == modal) {
                        closeModal(modal.id);
                    }
                });
            }

             document.addEventListener('keydown', function(event) {
                if (event.key === "Escape") {
                     const modals = document.querySelectorAll('.modal');
                     modals.forEach(modal => {
                        if (modal.style.display === "block") {
                             closeModal(modal.id);
                        }
                    });
                 }
            });

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

            function filterProducts() {
                const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
                const activeCategory = document.querySelector('.category-filter.active').dataset.category;
                 let hasVisibleProducts = false;

                document.querySelectorAll('.product').forEach(product => {
                    const name = product.getAttribute('data-name');
                    const description = product.getAttribute('data-description');
                    const category = product.getAttribute('data-category');

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

                    if (matchesSearch && matchesCategory) {
                        product.style.display = 'flex'; // Use flex as it's the default for .product
                         hasVisibleProducts = true;
                    } else {
                        product.style.display = 'none';
                    }
                });

                 // Optional: Show a message if no products match
                 const grid = document.getElementById('products-grid');
                 let noMatchMsg = grid.querySelector('.no-match-message');
                 if (!hasVisibleProducts) {
                     if (!noMatchMsg) {
                         noMatchMsg = document.createElement('p');
                         noMatchMsg.className = 'no-match-message';
                         noMatchMsg.textContent = 'Товары не найдены по вашему запросу.';
                         noMatchMsg.style.textAlign = 'center';
                         noMatchMsg.style.gridColumn = '1 / -1'; // Span all columns
                         grid.appendChild(noMatchMsg);
                     }
                 } else {
                     if (noMatchMsg) {
                         grid.removeChild(noMatchMsg);
                     }
                 }
            }

            // Initial setup
            document.addEventListener('DOMContentLoaded', () => {
                updateCartButton();
                filterProducts(); // Initial filter on page load
            });
        </script>
    </body>
    </html>
    '''
    return render_template_string(
        catalog_html,
        products=products,
        categories=categories,
        repo_id=REPO_ID,
        logo_url=LOGO_URL,
        whatsapp_number=WHATSAPP_NUMBER,
        current_year=datetime.now().year
    )


# --- Product Detail Partial ---
@app.route('/product/<int:index>')
def product_detail(index):
    data = load_data()
    products = data.get('products', [])
    try:
        product = products[index]
    except IndexError:
        logging.warning(f"Попытка доступа к несуществующему продукту с индексом {index}")
        return "Товар не найден", 404

    detail_html = '''
    <h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 20px; text-align: center;">{{ product['name'] }}</h2>

    <div class="swiper-container">
        <div class="swiper-wrapper">
            {% if product.get('photos') and product['photos']|length > 0 %}
                {% for photo in product['photos'] %}
                <div class="swiper-slide">
                    <div class="swiper-zoom-container">
                         <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true"
                              alt="{{ product['name'] }} - Фото {{ loop.index }}"
                              loading="lazy">
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="swiper-slide">
                     <img src="https://via.placeholder.com/450x350?text=Нет+фото" alt="Фото отсутствует">
                </div>
            {% endif %}
        </div>
        <!-- Add Pagination -->
        <div class="swiper-pagination"></div>
        <!-- Add Navigation -->
        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
    </div>

    <div style="padding: 0 15px;"> <!-- Add padding around text details -->
        <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
        <p><strong>Цена:</strong> <span style="font-weight: 700; font-size: 1.2em; color: var(--accent-wood);">{{ product['price'] }} сом</span></p>
        <p><strong>Описание:</strong></p>
        <p style="white-space: pre-wrap;">{{ product['description'] }}</p> <!-- Preserve line breaks in description -->
        {% if product.get('colors') and product['colors']|length > 0 %}
            <p><strong>Доступные цвета:</strong> {{ product['colors']|join(', ') }}</p>
        {% endif %}
    </div>
    '''
    return render_template_string(detail_html, product=product, repo_id=REPO_ID)

# --- Admin Panel ---
@app.route('/admin', methods=['GET', 'POST'])
def admin():
    data = load_data()
    products = data.get('products', [])
    categories = data.get('categories', [])

    message = None # To display success/error messages

    if request.method == 'POST':
        action = request.form.get('action')
        logging.debug(f"Admin action received: {action}")
        logging.debug(f"Form data: {request.form}")
        logging.debug(f"Files data: {request.files}")

        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)
                    save_data(data)
                    message = ("Категория добавлена", "success")
                elif not category_name:
                     message = ("Название категории не может быть пустым", "error")
                else:
                    message = ("Категория уже существует", "error")
                return redirect(url_for('admin', msg=message[0], type=message[1]))

            elif action == 'delete_category':
                category_index_str = request.form.get('category_index')
                if category_index_str is not None:
                    category_index = int(category_index_str)
                    if 0 <= category_index < len(categories):
                        deleted_category = categories.pop(category_index)
                        # Update products using this category
                        for product in products:
                            if product.get('category') == deleted_category:
                                product['category'] = 'Без категории' # Assign to default
                        save_data(data)
                        message = ("Категория удалена", "success")
                    else:
                         message = ("Неверный индекс категории", "error")
                else:
                     message = ("Индекс категории не указан", "error")
                return redirect(url_for('admin', msg=message[0], type=message[1]))


            elif action == 'add' or action == 'edit':
                name = request.form.get('name', '').strip()
                price_str = request.form.get('price', '0').replace(',', '.')
                description = request.form.get('description', '').strip()
                category = request.form.get('category')
                photos_files = request.files.getlist('photos')
                # Get colors - handle empty strings and potential duplicates
                colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
                colors = sorted(list(set(colors))) # Remove duplicates and sort

                logging.debug(f"Received colors: {request.form.getlist('colors')}")
                logging.debug(f"Processed colors: {colors}")

                if not name or not description:
                    message = ("Название и описание товара обязательны", "error")
                    # Need to pass current state back if redirecting
                    return redirect(url_for('admin', msg=message[0], type=message[1]))
                try:
                    price = float(price_str)
                    if price < 0: raise ValueError("Price cannot be negative")
                except ValueError:
                    message = ("Некорректное значение цены", "error")
                    return redirect(url_for('admin', msg=message[0], type=message[1]))

                photos_list = []
                # Upload new photos if provided
                if photos_files and any(f.filename for f in photos_files):
                    if not HF_TOKEN_WRITE:
                         message = ("HF_TOKEN (write) не установлен. Невозможно загрузить фото.", "warning")
                         # Decide if you want to proceed without photos or stop
                         # return redirect(url_for('admin', msg=message[0], type=message[1]))
                    else:
                        api = HfApi()
                        uploads_dir = 'uploads_temp' # Temporary local storage
                        os.makedirs(uploads_dir, exist_ok=True)

                        for photo in photos_files[:10]: # Limit photos
                            if photo and photo.filename:
                                try:
                                    photo_filename = secure_filename(f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{photo.filename}")
                                    temp_path = os.path.join(uploads_dir, photo_filename)
                                    photo.save(temp_path)

                                    logging.info(f"Uploading 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"Фото для товара {name}"
                                    )
                                    photos_list.append(photo_filename)
                                    logging.info(f"Photo {photo_filename} uploaded successfully.")
                                    # Clean up local temp file
                                    if os.path.exists(temp_path):
                                        os.remove(temp_path)
                                except Exception as e:
                                     logging.error(f"Ошибка загрузки фото {photo.filename}: {e}")
                                     message = (f"Ошибка загрузки фото {photo.filename}", "error")
                                     # Decide whether to stop or continue

                        # Clean up temp directory if empty
                        if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
                            os.rmdir(uploads_dir)


                if action == 'add':
                    new_product = {
                        'name': name,
                        'price': price,
                        'description': description,
                        'category': category if category in categories else 'Без категории',
                        'photos': photos_list, # Only new photos for 'add'
                        'colors': colors
                    }
                    products.append(new_product)
                    message = ("Товар успешно добавлен", "success")

                elif action == 'edit':
                    index_str = request.form.get('index')
                    if index_str is not None:
                        index = int(index_str)
                        if 0 <= index < len(products):
                             # Update fields
                            products[index]['name'] = name
                            products[index]['price'] = price
                            products[index]['description'] = description
                            products[index]['category'] = category if category in categories else 'Без категории'
                            products[index]['colors'] = colors

                            # If new photos were uploaded, replace the old list. Otherwise, keep existing photos.
                            if photos_list:
                                # Optionally delete old photos from HF here if needed (more complex)
                                products[index]['photos'] = photos_list
                            # If no new photos uploaded, 'photos_list' is empty,
                            # and we don't touch products[index]['photos']

                            message = ("Товар успешно обновлен", "success")
                        else:
                             message = ("Неверный индекс товара для редактирования", "error")
                    else:
                        message = ("Индекс товара для редактирования не указан", "error")


            elif action == 'delete':
                index_str = request.form.get('index')
                if index_str is not None:
                    index = int(index_str)
                    if 0 <= index < len(products):
                         # Optionally delete photos from HF here (more complex)
                        del products[index]
                        message = ("Товар удален", "success")
                    else:
                         message = ("Неверный индекс товара для удаления", "error")
                else:
                     message = ("Индекс товара для удаления не указан", "error")


            # Save changes if any action potentially modified data (except delete errors)
            if message and message[1] != "error": # Save on success or warning
                 save_data(data)
            # Redirect only after processing and potential save
            return redirect(url_for('admin', msg=message[0] if message else None, type=message[1] if message else None))

        except Exception as e:
            logging.error(f"Ошибка в админ панели ({action}): {e}", exc_info=True)
            message = (f"Произошла внутренняя ошибка: {e}", "error")
            return redirect(url_for('admin', msg=message[0], type=message[1]))


    # --- Admin HTML ---
    flash_message = request.args.get('msg')
    flash_type = request.args.get('type', 'info') # Default type

    admin_html = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Админ-панель - Mebel Hause KG</title>
        ''' + GLOBAL_STYLES + '''
         <style>
            /* Admin specific styles */
            .admin-container {
                padding-top: 20px;
            }
            .admin-section {
                 margin-bottom: 40px;
            }
            .product-list, .category-list {
                display: grid;
                gap: 20px;
                margin-top: 20px;
            }
            .product-item, .category-item {
                background: var(--card-bg);
                padding: 20px;
                border-radius: 15px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.08);
                border: 1px solid var(--border-color);
            }
             .product-item h3, .category-item h3 {
                 margin-top: 0;
                 margin-bottom: 10px;
                 font-size: 1.3rem;
                 border-bottom: 1px solid var(--border-color);
                 padding-bottom: 8px;
             }
             .product-item p {
                 margin-bottom: 8px;
                 font-size: 0.95rem;
             }
            .edit-form {
                margin-top: 20px;
                padding: 20px;
                background: #f9f9f7; /* Slightly off-white */
                border: 1px solid var(--border-color);
                border-radius: 10px;
            }
             details summary {
                cursor: pointer;
                font-weight: 500;
                color: var(--link-color);
                margin: 15px 0;
                display: inline-block; /* Fit content */
             }
             .product-photos-admin {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-top: 10px;
             }
             .product-photos-admin img {
                max-width: 100px;
                max-height: 100px;
                object-fit: cover;
                border-radius: 8px;
                border: 1px solid var(--border-color);
             }
             .action-buttons form {
                 display: inline-block;
                 margin-right: 10px;
             }
             .action-buttons button {
                  padding: 8px 15px;
                  font-size: 0.9rem;
              }

            /* Flash Messages */
            .flash-message {
                padding: 15px;
                margin-bottom: 20px;
                border-radius: 8px;
                font-weight: 500;
             }
            .flash-message.success {
                background-color: #d1e7dd; /* Light green */
                color: #0f5132; /* Dark green */
                border: 1px solid #badbcc;
            }
            .flash-message.error {
                background-color: #f8d7da; /* Light red */
                color: #842029; /* Dark red */
                border: 1px solid #f5c2c7;
            }
            .flash-message.warning {
                background-color: #fff3cd; /* Light yellow */
                color: #664d03; /* Dark yellow */
                border: 1px solid #ffecb5;
            }
            .flash-message.info {
                background-color: #cff4fc; /* Light blue */
                color: #055160; /* Dark blue */
                border: 1px solid #b6effb;
            }
        </style>
    </head>
    <body>
        <header class="header">
             <a href="{{ url_for('landing') }}">
                 <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo">
             </a>
            <nav>
                 <a href="{{ url_for('landing') }}">Главная</a>
                 <a href="{{ url_for('catalog') }}">Каталог</a>
                 <a href="{{ url_for('admin') }}" class="active">Админ</a>
            </nav>
        </header>

        <div class="container admin-container">
            <h1>Админ-панель</h1>

             {% if flash_message %}
             <div class="flash-message {{ flash_type }}">
                 {{ flash_message }}
             </div>
             {% endif %}

            <section class="admin-section form-section">
                <h2>Добавить новый товар</h2>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="add">
                    <label for="add-name">Название товара:</label>
                    <input type="text" id="add-name" name="name" required>

                    <label for="add-price">Цена (сом):</label>
                    <input type="number" id="add-price" name="price" step="0.01" min="0" required>

                    <label for="add-description">Описание:</label>
                    <textarea id="add-description" name="description" rows="4" required></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)" style="display: none;">×</button>
                        </div>
                    </div>
                    <button type="button" class="button-link add-color-btn" onclick="addColorInput('add-color-inputs')">Добавить цвет</button>

                    <button type="submit" class="form-button">Добавить товар</button>
                </form>
            </section>

            <section class="admin-section">
                 <h2>Управление категориями</h2>
                 <div class="form-section">
                     <form method="POST">
                        <input type="hidden" name="action" value="add_category">
                        <label for="category-name">Название новой категории:</label>
                        <input type="text" id="category-name" name="category_name" required>
                        <button type="submit" class="form-button">Добавить категорию</button>
                    </form>
                 </div>

                <h3>Список категорий</h3>
                 {% if categories %}
                 <div class="category-list">
                    {% for category in categories %}
                    <div class="category-item">
                        <h3>{{ category }}</h3>
                         {% if category != 'Без категории' %}
                         <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="delete_category">
                            <input type="hidden" name="category_index" value="{{ loop.index0 }}">
                            <button type="submit" class="button-link delete-button" onclick="return confirm('Удалить категорию {{ category }}? Товары будут перемещены в категорию Без категории.');">Удалить</button>
                        </form>
                         {% else %}
                         <p><i>(Системная категория, не удаляется)</i></p>
                         {% endif %}
                    </div>
                    {% endfor %}
                 </div>
                 {% else %}
                  <p>Категорий пока нет.</p>
                 {% endif %}
            </section>

            <section class="admin-section">
                <h2>Управление базой данных</h2>
                 <div class="action-buttons">
                    <form method="POST" action="{{ url_for('backup') }}" style="display: inline;">
                        <button type="submit" class="button-link">Создать резервную копию на HF</button>
                    </form>
                    <form method="GET" action="{{ url_for('download') }}" style="display: inline;">
                        <button type="submit" class="button-link">Скачать базу данных (JSON)</button>
                    </form>
                </div>
            </section>


            <section class="admin-section">
                <h2>Список товаров</h2>
                 {% if products %}
                <div class="product-list">
                    {% for product in products %}
                    <div class="product-item">
                        <h3>{{ product['name'] }}</h3>
                        <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
                        <p><strong>Цена:</strong> {{ product['price'] }} сом</p>
                        <p><strong>Описание:</strong> {{ product['description'][:100] }}{% if product['description']|length > 100 %}...{% endif %}</p>
                        <p><strong>Цвета:</strong> {{ product.get('colors', [])|join(', ') if product.get('colors') else 'Не указаны' }}</p>

                        {% if product.get('photos') and product['photos']|length > 0 %}
                        <p><strong>Фотографии:</strong></p>
                        <div class="product-photos-admin">
                            {% for photo in product['photos'] %}
                            <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true" target="_blank">
                                 <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true"
                                      alt="{{ product['name'] }} - Фото {{ loop.index }}" loading="lazy">
                             </a>
                            {% endfor %}
                        </div>
                        {% else %}
                        <p><strong>Фотографии:</strong> Нет</p>
                        {% endif %}

                        <details>
                            <summary>Редактировать товар</summary>
                            <form method="POST" enctype="multipart/form-data" class="edit-form">
                                <input type="hidden" name="action" value="edit">
                                <input type="hidden" name="index" value="{{ loop.index0 }}">

                                <label for="edit-name-{{ loop.index0 }}">Название:</label>
                                <input type="text" id="edit-name-{{ loop.index0 }}" name="name" value="{{ product['name'] }}" required>

                                <label for="edit-price-{{ loop.index0 }}">Цена:</label>
                                <input type="number" id="edit-price-{{ loop.index0 }}" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>

                                <label for="edit-description-{{ loop.index0 }}">Описание:</label>
                                <textarea id="edit-description-{{ loop.index0 }}" name="description" rows="4" required>{{ product['description'] }}</textarea>

                                <label for="edit-category-{{ loop.index0 }}">Категория:</label>
                                <select id="edit-category-{{ loop.index0 }}" name="category">
                                    <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
                                    {% for cat in categories %}
                                    <option value="{{ cat }}" {% if product.get('category') == cat %}selected{% endif %}>{{ cat }}</option>
                                    {% endfor %}
                                </select>

                                <label for="edit-photos-{{ loop.index0 }}">Заменить фотографии (до 10, старые будут удалены при загрузке новых):</label>
                                <input type="file" id="edit-photos-{{ loop.index0 }}" name="photos" accept="image/*" multiple>

                                <label>Цвета:</label>
                                <div id="edit-color-inputs-{{ loop.index0 }}">
                                    {% if product.get('colors') %}
                                        {% for color in product.get('colors', []) %}
                                        <div class="color-input-group">
                                             <input type="text" name="colors" value="{{ color }}">
                                             <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button>
                                         </div>
                                        {% endfor %}
                                     {% else %}
                                        <div class="color-input-group">
                                            <input type="text" name="colors" placeholder="Например: Синий">
                                            <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" style="display:none;">×</button>
                                        </div>
                                     {% endif %}
                                      {% if not product.get('colors') %} {# Ensure at least one input exists even if no colors are set #}
                                        <div class="color-input-group" style="display:none;"> {# Hidden template if no colors initially #}
                                            <input type="text" name="colors" placeholder="Например: Синий">
                                            <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button>
                                        </div>
                                      {% endif %}
                                </div>
                                <button type="button" class="button-link add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')">Добавить цвет</button>

                                <button type="submit" class="form-button">Сохранить изменения</button>
                            </form>
                        </details>

                        <div class="action-buttons">
                             <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить товар {{ product['name'] }}?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="index" value="{{ loop.index0 }}">
                                <button type="submit" class="button-link delete-button">Удалить товар</button>
                            </form>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                 {% else %}
                   <p>В базе данных пока нет товаров.</p>
                 {% endif %}
            </section>

        </div>

        <footer class="footer">
             <p>© {{ current_year }} Mebel Hause KG. Админ-панель.</p>
        </footer>

        <script>
            function addColorInput(containerId) {
                const container = document.getElementById(containerId);
                if (!container) return;

                 // Find a template or the last input group to clone
                 const templateGroup = container.querySelector('.color-input-group:last-child');
                 const newGroup = templateGroup ? templateGroup.cloneNode(true) : document.createElement('div');
                 newGroup.className = 'color-input-group'; // Ensure class name

                 if (!templateGroup) { // If container was empty, create structure
                     newGroup.innerHTML = '<input type="text" name="colors" placeholder="Например: Цвет"><button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button>';
                 } else {
                     const input = newGroup.querySelector('input[name="colors"]');
                     if (input) input.value = ''; // Clear the value
                     const removeBtn = newGroup.querySelector('.remove-color-btn');
                     if (removeBtn) removeBtn.style.display = 'inline-block'; // Ensure remove button is visible
                 }

                newGroup.style.display = 'flex'; // Ensure the new group is visible
                container.appendChild(newGroup);

                 // Show remove button on previous last item if it was hidden
                const allGroups = container.querySelectorAll('.color-input-group');
                 if (allGroups.length > 1) {
                    const secondLastGroup = allGroups[allGroups.length - 2];
                    const prevRemoveBtn = secondLastGroup.querySelector('.remove-color-btn');
                     if (prevRemoveBtn) prevRemoveBtn.style.display = 'inline-block';
                 }
                 // Always hide remove button if only one input remains
                 updateRemoveButtons(containerId);
            }

            function removeColorInput(button) {
                const container = button.closest('[id^="color-inputs"], [id^="edit-color-inputs"]');
                const groupToRemove = button.closest('.color-input-group');
                if (container && groupToRemove) {
                     // Only remove if there's more than one group
                     if (container.querySelectorAll('.color-input-group').length > 1) {
                        groupToRemove.remove();
                     } else {
                         // If it's the last one, just clear the input value
                         const input = groupToRemove.querySelector('input[name="colors"]');
                         if (input) input.value = '';
                         alert("Должно быть хотя бы одно поле для цвета. Очищено.");
                     }
                     updateRemoveButtons(container.id); // Update visibility after removal
                }
            }

             function updateRemoveButtons(containerId) {
                 const container = document.getElementById(containerId);
                 if (!container) return;
                 const allGroups = container.querySelectorAll('.color-input-group');
                 allGroups.forEach((group, index) => {
                     const removeBtn = group.querySelector('.remove-color-btn');
                     if (removeBtn) {
                        // Show remove button only if there is more than one group
                         removeBtn.style.display = (allGroups.length > 1) ? 'inline-block' : 'none';
                     }
                 });
             }

             // Initial call to set up remove buttons correctly on page load for edit forms
             document.addEventListener('DOMContentLoaded', () => {
                const editColorContainers = document.querySelectorAll('[id^="edit-color-inputs-"]');
                editColorContainers.forEach(container => {
                    updateRemoveButtons(container.id);
                });
                 // Also for the add form
                 updateRemoveButtons('add-color-inputs');
             });

        </script>
    </body>
    </html>
    '''
    return render_template_string(
        admin_html,
        products=products,
        categories=categories,
        repo_id=REPO_ID,
        logo_url=LOGO_URL,
        flash_message=flash_message,
        flash_type=flash_type,
        current_year=datetime.now().year
    )

@app.route('/backup', methods=['POST'])
def backup():
    try:
        upload_db_to_hf()
        # Redirect back with success message
        return redirect(url_for('admin', msg="Резервное копирование на Hugging Face запущено.", type="success"))
    except Exception as e:
        logging.error(f"Ошибка при ручном резервном копировании: {e}")
        return redirect(url_for('admin', msg=f"Ошибка резервного копирования: {e}", type="error"))


@app.route('/download', methods=['GET'])
def download():
    try:
        # Optionally trigger a download from HF first to ensure local is up-to-date
        # download_db_from_hf() # Uncomment if you want to force sync before download
        if os.path.exists(DATA_FILE):
            return send_file(DATA_FILE, as_attachment=True, download_name='mebelhause_database.json')
        else:
             return redirect(url_for('admin', msg="Локальный файл базы данных не найден.", type="error"))
    except Exception as e:
        logging.error(f"Ошибка при скачивании файла базы данных: {e}")
        return redirect(url_for('admin', msg=f"Ошибка скачивания файла: {e}", type="error"))


if __name__ == '__main__':
    # Ensure data file exists on start, try loading/downloading
    try:
        initial_data = load_data()
        # If load_data created an empty structure due to errors, save it.
        if not os.path.exists(DATA_FILE) or os.path.getsize(DATA_FILE) == 0:
            save_data(initial_data)
    except Exception as e:
        logging.error(f"Критическая ошибка при инициализации базы данных: {e}")
        # Consider exiting if the DB is crucial and cannot be loaded/created
        # exit(1)

    # Start periodic backup in a separate thread
    if HF_TOKEN_WRITE and HF_TOKEN_READ: # Only run backup if tokens are set
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
    else:
        logging.warning("Токены Hugging Face (WRITE или READ) не установлены. Периодическое резервное копирование отключено.")

    # Run Flask App
    # Use 'waitress' for production instead of Flask's built-in server
    # from waitress import serve
    # serve(app, host='0.0.0.0', port=7860)
    # For development:
    app.run(debug=False, host='0.0.0.0', port=7860) # Set debug=False for production/waitress