File size: 70,380 Bytes
339d280
722e552
167fbe8
a814910
d446480
a814910
 
 
 
 
167fbe8
 
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167fbe8
a814910
167fbe8
a814910
d544e6d
167fbe8
 
 
5e425ea
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
cad6d37
 
 
 
 
 
 
 
 
 
 
 
a814910
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
 
d446480
a814910
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446480
a814910
 
 
 
 
 
 
d446480
a814910
 
 
 
 
 
d446480
a814910
 
 
 
 
cad6d37
a814910
 
 
 
 
cad6d37
a814910
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
cad6d37
a814910
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
d544e6d
a814910
 
d544e6d
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c247d8b
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
d544e6d
a814910
 
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
cad6d37
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446480
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446480
a814910
d446480
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad6d37
a814910
 
 
cad6d37
a814910
 
 
 
 
 
cad6d37
a814910
 
 
d544e6d
a814910
 
 
 
 
 
cad6d37
a814910
 
 
d446480
a814910
 
 
 
 
 
d446480
a814910
 
 
d446480
a814910
 
 
 
d446480
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446480
a814910
 
 
 
d446480
 
a814910
 
 
 
 
d446480
a814910
 
 
 
d446480
 
a814910
 
 
 
d446480
 
 
a814910
 
d446480
a814910
 
 
 
 
 
 
 
d446480
a814910
 
 
d446480
 
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446480
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
a814910
f7822c5
a814910
 
 
 
 
 
 
 
 
 
f7822c5
a814910
f7822c5
a814910
f7822c5
a814910
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
a814910
f7822c5
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
a814910
 
 
 
f7822c5
 
 
a814910
 
f7822c5
a814910
 
 
f7822c5
 
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
 
a814910
 
 
 
 
 
 
d446480
f7822c5
 
a814910
 
 
 
 
f7822c5
a814910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7822c5
a814910
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
import folium
from streamlit_folium import folium_static
import ee
import os
import json
import time
from datetime import datetime, timedelta
import plotly.express as px
import plotly.graph_objects as go
from PIL import Image
import base64
from io import BytesIO
import matplotlib.pyplot as plt
import seaborn as sns
import altair as alt
from streamlit_option_menu import option_menu
from streamlit_lottie import st_lottie
import requests
import hydralit_components as hc
from streamlit_extras.colored_header import colored_header
from streamlit_extras.metric_cards import style_metric_cards
from streamlit_extras.chart_container import chart_container
from streamlit_extras.add_vertical_space import add_vertical_space
from streamlit_card import card
import pydeck as pdk
import math
from sklearn.linear_model import LinearRegression

# Page configuration with custom theme
st.set_page_config(
    page_title="سامانه هوشمند پایش مزارع نیشکر دهخدا",
    page_icon="🌿",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS with modern green design and animations
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100;200;300;400;500;600;700;800;900&display=swap');
    
    * {
        font-family: 'Vazirmatn', sans-serif !important;
    }
    
    /* Main container styling */
    .main {
        background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%);
    }
    
    /* Header styling */
    .main-header {
        background: linear-gradient(90deg, #1a8754 0%, #115740 100%);
        padding: 1.5rem;
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        margin-bottom: 2rem;
        position: relative;
        overflow: hidden;
        animation: header-glow 3s infinite alternate;
    }
    
    @keyframes header-glow {
        0% {
            box-shadow: 0 8px 32px rgba(26, 135, 84, 0.1);
        }
        100% {
            box-shadow: 0 8px 32px rgba(26, 135, 84, 0.3);
        }
    }
    
    .main-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
        transform: rotate(30deg);
        z-index: 0;
    }
    
    .main-header h1 {
        color: white;
        font-weight: 700;
        margin: 0;
        position: relative;
        z-index: 1;
    }
    
    .main-header p {
        color: rgba(255, 255, 255, 0.8);
        margin: 0;
        position: relative;
        z-index: 1;
    }
    
    /* Navigation menu styling */
    .st-emotion-cache-1lcbz7b {
        background-color: transparent !important;
        padding: 0 !important;
        margin-bottom: 20px !important;
    }
    
    .st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d {
        --hover-color: #e9f7ef !important;
        border-radius: 10px !important;
        font-size: 16px !important;
        text-align: center !important;
        margin: 0 !important;
    }
    
    .st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d:hover {
        background-color: #e9f7ef !important;
    }
    
    .st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d[data-selected="true"] {
        background-color: #1a8754 !important;
        color: white !important;
        font-weight: 600 !important;
    }
    
    .st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d .st-emotion-cache-1m5q2i0 {
        color: #1a8754 !important;
        font-size: 18px !important;
    }
    
    /* Metric card styling */
    .metric-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
        text-align: center;
    }
    
    .metric-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
    }
    
    .metric-card .metric-value {
        font-size: 2.5rem;
        font-weight: 700;
        color: #1a8754;
        margin-bottom: 0.5rem;
    }
    
    .metric-card .metric-label {
        font-size: 1rem;
        color: #6c757d;
    }
    
    /* Map container styling */
    .map-container {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    }
    
    /* Tabs styling */
    .stTabs [data-baseweb="tab-list"] {
        gap: 8px;
    }
    
    .stTabs [data-baseweb="tab"] {
        border-radius: 4px 4px 0px 0px;
        padding: 10px 16px;
        background-color: #f8f9fa;
    }
    
    .stTabs [aria-selected="true"] {
        background-color: #1a8754 !important;
        color: white !important;
    }
    
    /* Sidebar styling */
    [data-testid="stSidebar"] {
        background-color: #ffffff;
        border-right: 1px solid #e9ecef;
    }
    
    /* Animations */
    @keyframes fadeIn {
        0% { opacity: 0; transform: translateY(20px); }
        100% { opacity: 1; transform: translateY(0); }
    }
    
    .animate-fadeIn {
        animation: fadeIn 0.5s ease forwards;
    }
    
    /* Loading animation */
    .loading-spinner {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
    }
    
    .loading-spinner::after {
        content: "";
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #1a8754;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* RTL Support */
    .rtl {
        direction: rtl;
        text-align: right;
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    
    ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
        background: #1a8754;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: #115740;
    }
    
    /* Tooltip styling */
    .tooltip {
        position: relative;
        display: inline-block;
    }
    
    .tooltip .tooltiptext {
        visibility: hidden;
        width: 120px;
        background-color: #555;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 5px;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        left: 50%;
        margin-left: -60px;
        opacity: 0;
        transition: opacity 0.3s;
    }
    
    .tooltip:hover .tooltiptext {
        visibility: visible;
        opacity: 1;
    }
    
    /* Data table styling */
    .dataframe {
        border-collapse: collapse;
        width: 100%;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }
    
    .dataframe th {
        background-color: #1a8754;
        color: white;
        padding: 12px;
        text-align: right;
    }
    
    .dataframe td {
        padding: 10px 12px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .dataframe tr:nth-child(even) {
        background-color: #f8f9fa;
    }
    
    .dataframe tr:hover {
        background-color: #e9ecef;
    }
    
    /* Progress bar styling */
    .stProgress > div > div > div > div {
        background-color: #1a8754;
    }
    
    /* Notification styling */
    .notification {
        background-color: #d1e7dd;
        color: #0f5132;
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        animation: slideIn 0.5s ease;
    }
    
    @keyframes slideIn {
        0% { transform: translateX(100%); opacity: 0; }
        100% { transform: translateX(0); opacity: 1; }
    }
    
    .notification-icon {
        margin-right: 0.5rem;
        font-size: 1.2rem;
    }
    
    /* Custom select box */
    .custom-select {
        background-color: white;
        border-radius: 8px;
        padding: 0.5rem;
        border: 1px solid #ced4da;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }
    
    /* Glassmorphism effect */
    .glass-card {
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.3);
        padding: 1.5rem;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    }
    
    /* Neumorphism effect */
    .neumorphic-card {
        background: #f0f0f3;
        border-radius: 12px;
        box-shadow: 10px 10px 20px #d1d1d4, -10px -10px 20px #ffffff;
        padding: 1.5rem;
    }
    
    /* Gradient text */
    .gradient-text {
        background: linear-gradient(90deg, #1a8754 0%, #115740 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-weight: 700;
    }
    
    /* Pulsing animation */
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
    
    .pulse-animation {
        animation: pulse 2s infinite;
    }
    
    /* Custom radio buttons */
    .stRadio > div {
        display: flex;
        gap: 10px;
    }
    
    .stRadio label {
        cursor: pointer;
        background-color: #f8f9fa;
        padding: 0.5rem 1rem;
        border-radius: 50px;
        transition: all 0.3s ease;
    }
    
    .stRadio label:hover {
        background-color: #e9ecef;
    }
    
    /* Hide default radio button */
    .stRadio input {
        display: none;
    }
    
    /* Custom checked state */
    .stRadio input:checked + label {
        background-color: #1a8754;
        color: white;
    }
    
    .stSelectbox, .stNumberInput {
        background-color: #f0f2f6;
        border-radius: 10px;
        padding: 10px;
        margin: 10px 0;
    }
    
    .custom-card {
        background-color: white;
        padding: 20px;
        border-radius: 15px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin: 10px 0;
    }
    
    .metric-container {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
    }
    
    .metric-card {
        background-color: #1a8754;
        color: white;
        padding: 15px;
        border-radius: 10px;
        margin: 5px;
        flex: 1;
        min-width: 200px;
        text-align: center;
    }
    
    /* Button styling */
    .stButton>button {
        border-radius: 50px;
        padding: 0.5rem 1.5rem;
        font-weight: 600;
        transition: all 0.3s ease;
        border: none;
    }
    
    .stButton>button:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .primary-btn {
        background: linear-gradient(90deg, #1a8754 0%, #115740 100%);
        color: white;
    }
    
    .secondary-btn {
        background: white;
        color: #1a8754;
        border: 1px solid #1a8754 !important;
    }
    
    /* Footer styling */
    footer {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        background-color: #1a8754;
        color: white;
        text-align: center;
        padding: 10px 0;
        font-family: 'Vazirmatn', sans-serif;
    }
</style>
""", unsafe_allow_html=True)

# Load real farm data from CSV
@st.cache_data
def load_farm_data():
    try:
        df = pd.read_csv("کراپ لاگ کلی (1).csv")
        # Rename columns for consistency with the program
        df.rename(columns={
            'سال': 'Year',
            'هفته': 'Week',
            'مزرعه': 'Farm_ID',
            'کانال': 'Channel',
            'اداره': 'Administration',
            'مساحت': 'Area',
            'مساحت زیر مجموعه': 'SubArea',
            'رقم': 'Variety',
            'سن': 'Age',
            'ایستگاه 1': 'Station1',
            'ایستگاه 2': 'Station2',
            'ایستگاه 3': 'Station3',
            'ایستگاه 4': 'Station4',
            'ایستگاه 5': 'Station5',
            'ارتفاع هفته جاری مزرعه': 'CurrentHeight',
            'ارتفاع هفته گذشته مزرعه': 'PreviousHeight',
            'رشد هفته جاری': 'CurrentGrowth',
            'رشد هفته گذشته': 'PreviousGrowth',
            'نیتروژن فعلی': 'CurrentNitrogen',
            'نیتروژن استاندارد فعلی': 'StandardNitrogen',
            'نیتروژن قبلی': 'PreviousNitrogen',
            'نیتروژن استاندارد قبلی': 'PreviousStandardNitrogen',
            'رطوبت غلاف فعلی': 'CurrentMoisture',
            'رطوبت استاندارد فعلی': 'StandardMoisture',
            'رطوبت غلاف قبلی': 'PreviousMoisture',
            'رطوبت استاندارد قبلی': 'PreviousStandardMoisture',
            'چاهک 1': 'Well1',
            'تاریخ قرائت': 'Well1Date',
            'چاهک 2': 'Well2',
            'تاریخ قرائت.1': 'Well2Date'
        }, inplace=True)
        return df
    except Exception as e:
        st.error(f"خطا در بارگذاری داده‌های مزارع: {e}")
        return pd.DataFrame()

@st.cache_data
def load_coordinates_data():
    try:
        coords_df = pd.read_csv("farm_coordinates.csv")
        coords_df.rename(columns={
            'مزرعه': 'Farm_ID',
            'عرض جغرافیایی': 'Latitude',
            'طول جغرافیایی': 'Longitude'
        }, inplace=True)
        return coords_df
    except Exception as e:
        st.error(f"خطا در بارگذاری داده‌های مختصات: {e}")
        return pd.DataFrame()

@st.cache_data
def load_day_data():
    try:
        day_df = pd.read_csv("پایگاه داده (1).csv")
        day_df.rename(columns={
            'مزرعه': 'Farm_ID',
            'روز': 'Day'
        }, inplace=True)
        return day_df
    except Exception as e:
        st.error(f"خطا در بارگذاری داده‌های روزهای هفته: {e}")
        return pd.DataFrame()

# Load animation JSON
@st.cache_data
def load_lottie_url(url: str):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()

# Initialize Earth Engine (unchanged for now, but can be used with real data)
@st.cache_resource
def initialize_earth_engine():
    try:
        service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com'
        credentials_dict = {
            "type": "service_account",
            "project_id": "ee-esmaeilkiani13877",
            "private_key_id": "cfdea6eaf4115cb6462626743e4b15df85fd0c7f",
            "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCjeOvgKi+gWK6k\n2/0RXOA3LAo51DVxA1ja9v0qFOn4FNOStxkwlKvcK8yDQNb53FPORHFIUHvev3y7\niHr/UEUqnn5Rzjbf0k3qWB/fS377/UP4VznMsFpKiHNxCBtaNS8KLk6Rat6Y7Xfm\nJfpSU7ZjYZmVc81M/7iFofGUSJoHYpxhyt3rjp53huxJNNW5e12TFnLkyg1Ja/9X\nGMTt+vjVcO4XhQCIlaGVdSKS2sHlHgzpzE6KtuUKjDMEBqPkWF4xc16YavYltwPd\nqULCu2/t6dczhYL4NEFj8wL+KJqOojfsyoWmzqPFx1Bbxk4BVPk/lslq9+m9p5kq\nSCG0/9W9AgMBAAECggEAEGchw+x3uu8rFv+79PIMzXxtyj+w3RYo5E/EN2TB1VLB\nqAcXT/ibBgyfCMyIxamF/zx+4XKx+zfbnDWlodi8F/qvUiYO+4ZuqwUMras1orNX\nDqQx+If5h2EJtF3L4NFVVwAuggjnLREm5sEIzRn5Qx+X+ZcVEpTWPxJw2yAt1G+3\nk311KqD+zR7jQfchXU4xQQ1ZoHkdAJ/DPGun6x+HUOq7Gus73A6IzLp12ZoiHN3n\nkY+lG8cMs039QAe/OhZFEo5I9cNSaI688HmsLRivZ26WoPEnwcN0MHQGtXqGmMUI\nCcpgJqllqdWMuBlYcpSadn7rZzPujSlzIxkvieLeAQKBgQDNTYUWZdGbA2sHcBpJ\nrqKwDYF/AwZtjx+hXHVBRbR6DJ1bO2P9n51ioTMP/H9K61OBAMZ7w71xJ2I+9Snv\ncYumPWoiUwiOhTh3O7nYz6mR7sK0HuUCZfYdaxJVnLgNCgj+w9AxYnkzOyL9/QvJ\nknrlMKf4H59NbapBqy5spilq1QKBgQDL1wkGHhoTuLb5Xp3X3CX4S7WMke4T01bO\nPpMmlewVgH5lK5wTcZjB8QRO2QFQtUZTP/Ghv6ZH4h/3P9/ZIF3hV5CSsUkr/eFf\nMY+fQL1K/puwfZbSDcH1GtDToOyoLFIvPXBJo0Llg/oF2TK1zGW3cPszeDf/Tm6x\nUwUMw2BjSQKBgEJzAMyLEBi4NoAlzJxkpcuN04gkloQHexljL6B8yzlls9i/lFGW\nw/4UZs6ZzymUmWZ7tcKBTGO/d5EhEP2rJqQb5KpPbcmTXP9amYCPVjchrGtYRI9O\nKSbEbR7ApuGxic/L2Sri0I/AaEcFDDel7ZkY8oTg11LcV+sBWPlZnrYxAoGBALXj\n/DlpQvu2KA/9TfwAhiE57Zax4S/vtdX0IHqd7TyCnEbK00rGYvksiBuTqIjMOSSw\nOn2K9mXOcZe/d4/YQe2CpY9Ag3qt4R2ArBf/POpep66lYp+thxWgCBfP0V1/rxZY\nTIppFJiZW9E8LvPqoBlAx+b1r4IyCrRQ0IDDFo+BAoGBAMCff4XKXHlV2SDOL5uh\nV/f9ApEdF4leuo+hoMryKuSQ9Y/H0A/Lzw6KP5FLvVtqc0Kw2D1oLy8O72a1xwfY\n8dpZMNzKAWWS7viN0oC+Ebj2Foc2Mn/J6jdhtP/YRLTqvoTWCa2rVcn4R1BurMIf\nLa4DJE9BagGdVNTDtynBhKhZ\n-----END PRIVATE KEY-----\n",
            "client_email": "dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com",
            "client_id": "113062529451626176784",
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
            "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
            "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/dehkhodamap-e9f0da4ce9f6514021%40ee-esmaeilkiani13877.iam.gserviceaccount.com",
            "universe_domain": "googleapis.com"
        }
        credentials_file = 'ee-esmaeilkiani13877-cfdea6eaf411.json'
        with open(credentials_file, 'w') as f:
            json.dump(credentials_dict, f)
        credentials = ee.ServiceAccountCredentials(service_account, credentials_file)
        ee.Initialize(credentials)
        os.remove(credentials_file)
        return True
    except Exception as e:
        st.error(f"خطا در اتصال به Earth Engine: {e}")
        return False

# Create Earth Engine map with indices
def create_ee_map(farm_id, date_str, layer_type="NDVI"):
    try:
        farm_row = coordinates_df[coordinates_df['Farm_ID'] == farm_id].iloc[0]
        lat, lon = farm_row['Latitude'], farm_row['Longitude']
        m = folium.Map(location=[lat, lon], zoom_start=14, tiles='CartoDB positron')
        date_obj = datetime.strptime(date_str, '%Y-%m-%d')
        start_date = (date_obj - timedelta(days=5)).strftime('%Y-%m-%d')
        end_date = (date_obj + timedelta(days=5)).strftime('%Y-%m-%d')
        region = ee.Geometry.Point([lon, lat]).buffer(1500)
        s2 = ee.ImageCollection('COPERNICUS/S2_SR') \
            .filterDate(start_date, end_date) \
            .filterBounds(region) \
            .sort('CLOUDY_PIXEL_PERCENTAGE') \
            .first()
        if layer_type == "NDVI":
            index = s2.normalizedDifference(['B8', 'B4']).rename('NDVI')
            viz_params = {'min': -0.2, 'max': 0.8, 'palette': ['#ff0000', '#ff4500', '#ffd700', '#32cd32', '#006400']}
            legend_title = 'شاخص پوشش گیاهی (NDVI)'
        elif layer_type == "NDMI":
            index = s2.normalizedDifference(['B8', 'B11']).rename('NDMI')
            viz_params = {'min': -0.5, 'max': 0.5, 'palette': ['#8b0000', '#ff8c00', '#00ced1', '#00b7eb', '#00008b']}
            legend_title = 'شاخص رطوبت (NDMI)'
        elif layer_type == "EVI":
            nir = s2.select('B8')
            red = s2.select('B4')
            blue = s2.select('B2')
            index = nir.subtract(red).multiply(2.5).divide(nir.add(red.multiply(6)).subtract(blue.multiply(7.5)).add(1)).rename('EVI')
            viz_params = {'min': 0, 'max': 1, 'palette': ['#d73027', '#f46d43', '#fdae61', '#fee08b', '#4caf50']}
            legend_title = 'شاخص پیشرفته گیاهی (EVI)'
        elif layer_type == "NDWI":
            index = s2.normalizedDifference(['B3', 'B8']).rename('NDWI')
            viz_params = {'min': -0.5, 'max': 0.5, 'palette': ['#00008b', '#00b7eb', '#add8e6', '#fdae61', '#d73027']}
            legend_title = 'شاخص آب (NDWI)'
        map_id_dict = ee.Image(index).getMapId(viz_params)
        folium.TileLayer(
            tiles=map_id_dict['tile_fetcher'].url_format,
            attr='Google Earth Engine',
            name=layer_type,
            overlay=True,
            control=True
        ).add_to(m)
        folium.Marker(
            [lat, lon], 
            popup=f'مزرعه {farm_id}', 
            tooltip=f'مزرعه {farm_id}',
            icon=folium.Icon(color='green', icon='leaf')
        ).add_to(m)
        folium.Circle(
            [lat, lon],
            radius=1500,
            color='green',
            fill=True,
            fill_color='green',
            fill_opacity=0.1
        ).add_to(m)
        folium.LayerControl().add_to(m)
        legend_html = '''
        <div style="position: fixed; 
                    bottom: 50px; right: 50px; 
                    border: 2px solid grey; z-index: 9999; 
                    background-color: white;
                    padding: 10px;
                    border-radius: 5px;
                    direction: rtl;
                    font-family: 'Vazirmatn', sans-serif;">
            <div style="font-size: 14px; font-weight: bold; margin-bottom: 5px;">''' + legend_title + '''</div>
            <div style="display: flex; align-items: center; margin-bottom: 5px;">
                <div style="background: ''' + viz_params['palette'][0] + '''; width: 20px; height: 20px; margin-left: 5px;"></div>
                <span>کم</span>
            </div>
            <div style="display: flex; align-items: center; margin-bottom: 5px;">
                <div style="background: ''' + viz_params['palette'][2] + '''; width: 20px; height: 20px; margin-left: 5px;"></div>
                <span>متوسط</span>
            </div>
            <div style="display: flex; align-items: center;">
                <div style="background: ''' + viz_params['palette'][-1] + '''; width: 20px; height: 20px; margin-left: 5px;"></div>
                <span>زیاد</span>
            </div>
        </div>
        '''
        m.get_root().html.add_child(folium.Element(legend_html))
        return m
    except Exception as e:
        st.error(f"خطا در ایجاد نقشه: {e}")
        return None

# Calculate real farm stats
def calculate_farm_stats(farm_id, layer_type="NDVI"):
    farm_data = farm_df[farm_df['Farm_ID'] == farm_id]
    if layer_type == "NDVI":
        stats = {
            'mean': farm_data['CurrentHeight'].mean() if not farm_data.empty else 0,
            'min': farm_data['CurrentHeight'].min() if not farm_data.empty else 0,
            'max': farm_data['CurrentHeight'].max() if not farm_data.empty else 0,
            'std_dev': farm_data['CurrentHeight'].std() if not farm_data.empty else 0,
            'histogram_data': farm_data['CurrentHeight'].values if not farm_data.empty else np.array([])
        }
    elif layer_type == "NDMI":
        stats = {
            'mean': farm_data['CurrentMoisture'].mean() if not farm_data.empty else 0,
            'min': farm_data['CurrentMoisture'].min() if not farm_data.empty else 0,
            'max': farm_data['CurrentMoisture'].max() if not farm_data.empty else 0,
            'std_dev': farm_data['CurrentMoisture'].std() if not farm_data.empty else 0,
            'histogram_data': farm_data['CurrentMoisture'].values if not farm_data.empty else np.array([])
        }
    return stats

# Generate real growth data
def generate_real_growth_data(selected_variety="all", selected_age="all"):
    filtered_farms = farm_df
    if selected_variety != "all":
        filtered_farms = filtered_farms[filtered_farms['Variety'] == selected_variety]
    if selected_age != "all":
        filtered_farms = filtered_farms[filtered_farms['Age'] == selected_age]
    
    farm_growth_data = []
    weeks = filtered_farms['Week'].unique()
    for farm_id in filtered_farms['Farm_ID'].unique():
        farm_data = filtered_farms[filtered_farms['Farm_ID'] == farm_id]
        growth_data = {
            'farm_id': farm_id,
            'variety': farm_data['Variety'].iloc[0] if not farm_data.empty else 'Unknown',
            'age': farm_data['Age'].iloc[0] if not farm_data.empty else 'Unknown',
            'weeks': weeks,
            'heights': [farm_data[farm_data['Week'] == week]['CurrentHeight'].mean() if not farm_data[farm_data['Week'] == week].empty else 0 for week in weeks]
        }
        farm_growth_data.append(growth_data)
    
    if farm_growth_data:
        avg_heights = []
        for week in weeks:
            week_heights = [farm['heights'][list(weeks).index(week)] for farm in farm_growth_data if farm['heights'][list(weeks).index(week)] > 0]
            avg_heights.append(round(sum(week_heights) / len(week_heights)) if week_heights else 0)
        
        avg_growth_data = {
            'farm_id': 'میانگین',
            'variety': 'همه',
            'age': 'همه',
            'weeks': weeks,
            'heights': avg_heights
        }
        return {'individual': farm_growth_data, 'average': avg_growth_data}
    return {
        'individual': [],
        'average': {'farm_id': 'میانگین', 'variety': 'همه', 'age': 'همه', 'weeks': weeks, 'heights': [0] * len(weeks)}
    }

# Initialize Earth Engine and load data
ee_initialized = initialize_earth_engine()
farm_df = load_farm_data()
coordinates_df = load_coordinates_data()
day_df = load_day_data()

# Load animations
lottie_farm = load_lottie_url('https://assets5.lottiefiles.com/packages/lf20_ystsffqy.json')
lottie_analysis = load_lottie_url('https://assets3.lottiefiles.com/packages/lf20_qp1q7mct.json')
lottie_report = load_lottie_url('https://assets9.lottiefiles.com/packages/lf20_vwcugezu.json')

# Create session state for storing data
if 'heights_df' not in st.session_state:
    st.session_state.heights_df = farm_df.copy()

# Main header
st.markdown('<div class="main-header">', unsafe_allow_html=True)
st.markdown('<h1>سامانه هوشمند پایش مزارع نیشکر دهخدا</h1>', unsafe_allow_html=True)
st.markdown('<p>پلتفرم جامع مدیریت، پایش و تحلیل داده‌های مزارع نیشکر با استفاده از تصاویر ماهواره‌ای و هوش مصنوعی</p>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)

# Create a modern navigation menu
selected = option_menu(
    menu_title=None,
    options=["داشبورد", "نقشه مزارع", "ورود اطلاعات", "تحلیل داده‌ها", "گزارش‌گیری", "تنظیمات"],
    icons=["speedometer2", "map", "pencil-square", "graph-up", "file-earmark-text", "gear"],
    menu_icon="cast",
    default_index=0,
    orientation="horizontal",
    styles={
        "container": {"padding": "0!important", "background-color": "transparent", "margin-bottom": "20px"},
        "icon": {"color": "#1a8754", "font-size": "18px"}, 
        "nav-link": {"font-size": "16px", "text-align": "center", "margin":"0px", "--hover-color": "#e9f7ef", "border-radius": "10px"},
        "nav-link-selected": {"background-color": "#1a8754", "color": "white", "font-weight": "600"},
    }
)

# Dashboard
if selected == "داشبورد":
    # Dashboard metrics
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown(f'<div class="metric-value">{len(farm_df["Farm_ID"].unique())}</div>', unsafe_allow_html=True)
        st.markdown('<div class="metric-label">تعداد مزارع</div>', unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        active_farms = int(len(farm_df["Farm_ID"].unique()) * 0.85)
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown(f'<div class="metric-value">{active_farms}</div>', unsafe_allow_html=True)
        st.markdown('<div class="metric-label">مزارع فعال</div>', unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col3:
        avg_height = farm_df['CurrentHeight'].mean()
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown(f'<div class="metric-value">{avg_height:.1f} cm</div>', unsafe_allow_html=True)
        st.markdown('<div class="metric-label">میانگین ارتفاع</div>', unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col4:
        avg_moisture = farm_df['CurrentMoisture'].mean()
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown(f'<div class="metric-value">{avg_moisture:.1f}%</div>', unsafe_allow_html=True)
        st.markdown('<div class="metric-label">میانگین رطوبت</div>', unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)
    
    # Dashboard tabs
    tab1, tab2, tab3, tab4 = st.tabs(["نمای کلی", "نقشه مزارع", "نمودارها", "داده‌ها"])
    
    with tab1:
        st.markdown("### توزیع واریته‌ها و سن محصول")
        
        col1, col2 = st.columns(2)
        
        with col1:
            variety_counts = farm_df['Variety'].value_counts().reset_index()
            variety_counts.columns = ['Variety', 'Count']
            fig = px.pie(
                variety_counts, 
                values='Count', 
                names='Variety', 
                title='توزیع واریته‌ها',
                color_discrete_sequence=px.colors.sequential.Greens_r
            )
            fig.update_traces(textposition='inside', textinfo='percent+label')
            fig.update_layout(
                font=dict(family="Vazirmatn"),
                legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="center", x=0.5)
            )
            st.plotly_chart(fig, use_container_width=True)
        
        with col2:
            age_counts = farm_df['Age'].value_counts().reset_index()
            age_counts.columns = ['Age', 'Count']
            fig = px.pie(
                age_counts, 
                values='Count', 
                names='Age', 
                title='توزیع سن محصول',
                color_discrete_sequence=px.colors.sequential.Blues_r
            )
            fig.update_traces(textposition='inside', textinfo='percent+label')
            fig.update_layout(
                font=dict(family="Vazirmatn"),
                legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="center", x=0.5)
            )
            st.plotly_chart(fig, use_container_width=True)
        
        st.markdown("### اطلاعات کلی مزارع")
        
        total_area = farm_df['Area'].sum()
        
        col1, col2, col3 = st.columns(3)
        col1.metric("تعداد کل مزارع", f"{len(farm_df['Farm_ID'].unique())}")
        col2.metric("مساحت کل (هکتار)", f"{total_area:.2f}")
        col3.metric("تعداد کانال‌ها", f"{farm_df['Channel'].nunique()}")
        
        st.markdown('<hr style="height:2px;border:none;color:#1a8754;background-color:#1a8754;margin:30px 0;">', unsafe_allow_html=True)
        
        st_lottie(lottie_farm, height=300, key="farm_animation")
    
    with tab2:
        st.markdown("### نقشه مزارع")
        
        if coordinates_df is not None and not coordinates_df.empty:
            m = folium.Map(location=[31.45, 48.72], zoom_start=12, tiles='CartoDB positron')
            for _, farm in coordinates_df.iterrows():
                lat = farm['Latitude']
                lon = farm['Longitude']
                name = farm['Farm_ID']
                farm_info = farm_df[farm_df['Farm_ID'] == name]
                if not farm_info.empty:
                    variety = farm_info['Variety'].iloc[0]
                    age = farm_info['Age'].iloc[0]
                    area = farm_info['Area'].iloc[0]
                    popup_text = f"""
                    <div style="direction: rtl; text-align: right; font-family: 'Vazirmatn', sans-serif;">
                        <h4>مزرعه {name}</h4>
                        <p>واریته: {variety}</p>
                        <p>سن: {age}</p>
                        <p>مساحت: {area} هکتار</p>
                    </div>
                    """
                else:
                    popup_text = f"<div style='direction: rtl;'>مزرعه {name}</div>"
                folium.Marker(
                    [lat, lon],
                    popup=folium.Popup(popup_text, max_width=300),
                    tooltip=f"مزرعه {name}",
                    icon=folium.Icon(color='green', icon='leaf')
                ).add_to(m)
            st.markdown('<div class="map-container">', unsafe_allow_html=True)
            folium_static(m, width=1000, height=600)
            st.markdown('</div>', unsafe_allow_html=True)
        else:
            st.warning("داده‌های مختصات در دسترس نیست.")
    
    with tab3:
        st.markdown("### نمودار رشد هفتگی")
        
        col1, col2 = st.columns(2)
        with col1:
            selected_variety = st.selectbox(
                "انتخاب واریته",
                ["all"] + list(farm_df['Variety'].unique()),
                format_func=lambda x: "همه واریته‌ها" if x == "all" else x
            )
        
        with col2:
            selected_age = st.selectbox(
                "انتخاب سن",
                ["all"] + list(farm_df['Age'].unique()),
                format_func=lambda x: "همه سنین" if x == "all" else x
            )
        
        growth_data = generate_real_growth_data(selected_variety, selected_age)
        
        chart_tab1, chart_tab2 = st.tabs(["میانگین رشد", "رشد مزارع فردی"])
        
        with chart_tab1:
            avg_data = growth_data['average']
            fig = go.Figure()
            fig.add_trace(go.Scatter(
                x=avg_data['weeks'],
                y=avg_data['heights'],
                mode='lines+markers',
                name='میانگین رشد',
                line=dict(color='#1a8754', width=3),
                marker=dict(size=8, color='#1a8754')
            ))
            fig.update_layout(
                title='میانگین رشد هفتگی',
                xaxis_title='هفته',
                yaxis_title='ارتفاع (سانتی‌متر)',
                font=dict(family='Vazirmatn', size=14),
                hovermode='x unified',
                template='plotly_white',
                height=500
            )
            st.plotly_chart(fig, use_container_width=True)
        
        with chart_tab2:
            if growth_data['individual']:
                fig = go.Figure()
                colors = ['#1a8754', '#1976d2', '#e65100', '#9c27b0', '#d32f2f']
                for i, farm_data in enumerate(growth_data['individual'][:5]):
                    fig.add_trace(go.Scatter(
                        x=farm_data['weeks'],
                        y=farm_data['heights'],
                        mode='lines+markers',
                        name=f"مزرعه {farm_data['farm_id']}",
                        line=dict(color=colors[i % len(colors)], width=2),
                        marker=dict(size=6, color=colors[i % len(colors)])
                    ))
                fig.update_layout(
                    title='رشد هفتگی مزارع فردی',
                    xaxis_title='هفته',
                    yaxis_title='ارتفاع (سانتی‌متر)',
                    font=dict(family='Vazirmatn', size=14),
                    hovermode='x unified',
                    template='plotly_white',
                    height=500
                )
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.warning("داده‌ای برای نمایش وجود ندارد.")
    
    with tab4:
        st.markdown("### داده‌های مزارع")
        
        search_term = st.text_input("جستجو در داده‌ها", placeholder="نام مزرعه، واریته، سن و...")
        
        if search_term:
            filtered_df = farm_df[
                farm_df['Farm_ID'].astype(str).str.contains(search_term) |
                farm_df['Variety'].astype(str).str.contains(search_term) |
                farm_df['Age'].astype(str).str.contains(search_term) |
                farm_df['Channel'].astype(str).str.contains(search_term)
            ]
        else:
            filtered_df = farm_df
        
        if not filtered_df.empty:
            csv = filtered_df.to_csv(index=False).encode('utf-8')
            st.download_button(
                label="دانلود داده‌ها (CSV)",
                data=csv,
                file_name="farm_data.csv",
                mime="text/csv",
            )
            st.dataframe(
                filtered_df,
                use_container_width=True,
                height=400,
                hide_index=True
            )
            st.info(f"نمایش {len(filtered_df)} مزرعه از {len(farm_df)} مزرعه")
        else:
            st.warning("هیچ داده‌ای یافت نشد.")

# Map Page
elif selected == "نقشه مزارع":
    st.markdown("## نقشه مزارع با شاخص‌های ماهواره‌ای")
    
    col1, col2 = st.columns([1, 3])
    
    with col1:
        st.markdown('<div class="glass-card">', unsafe_allow_html=True)
        st.markdown("### تنظیمات نقشه")
        
        selected_farm = st.selectbox(
            "انتخاب مزرعه",
            options=coordinates_df['Farm_ID'].tolist(),
            index=0,
            format_func=lambda x: f"مزرعه {x}"
        )
        
        selected_date = st.date_input(
            "انتخاب تاریخ",
            value=datetime.now(),
            format="YYYY-MM-DD"
        )
        
        selected_layer = st.selectbox(
            "انتخاب شاخص",
            options=["NDVI", "NDMI", "EVI", "NDWI"],
            format_func=lambda x: {
                "NDVI": "شاخص پوشش گیاهی (NDVI)",
                "NDMI": "شاخص رطوبت (NDMI)",
                "EVI": "شاخص پیشرفته گیاهی (EVI)",
                "NDWI": "شاخص آب (NDWI)"
            }[x]
        )
        
        generate_map = st.button(
            "تولید نقشه",
            type="primary",
            use_container_width=True
        )
        
        st.markdown('<hr style="margin: 20px 0;">', unsafe_allow_html=True)
        
        st.markdown("### راهنمای شاخص‌ها")
        
        with st.expander("شاخص پوشش گیاهی (NDVI)", expanded=selected_layer == "NDVI"):
            st.markdown("""
            **شاخص تفاضل نرمال‌شده پوشش گیاهی (NDVI)** معیاری برای سنجش سلامت و تراکم پوشش گیاهی است.
            
            - **مقادیر بالا (0.6 تا 1.0)**: پوشش گیاهی متراکم و سالم
            - **مقادیر متوسط (0.2 تا 0.6)**: پوشش گیاهی متوسط
            - **مقادیر پایین (-1.0 تا 0.2)**: پوشش گیاهی کم یا خاک لخت
            
            فرمول: NDVI = (NIR - RED) / (NIR + RED)
            """)
        
        with st.expander("شاخص رطوبت (NDMI)", expanded=selected_layer == "NDMI"):
            st.markdown("""
            **شاخص تفاضل نرمال‌شده رطوبت (NDMI)** برای ارزیابی محتوای رطوبت گیاهان استفاده می‌شود.
            
            - **مقادیر بالا (0.4 تا 1.0)**: محتوای رطوبت بالا
            - **مقادیر متوسط (0.0 تا 0.4)**: محتوای رطوبت متوسط
            - **مقادیر پایین (-1.0 تا 0.0)**: محتوای رطوبت کم
            
            فرمول: NDMI = (NIR - SWIR) / (NIR + SWIR)
            """)
        
        with st.expander("شاخص پیشرفته گیاهی (EVI)", expanded=selected_layer == "EVI"):
            st.markdown("""
            **شاخص پیشرفته پوشش گیاهی (EVI)** نسخه بهبودیافته NDVI است که حساسیت کمتری به اثرات خاک و اتمسفر دارد.
            
            - **مقادیر بالا (0.4 تا 1.0)**: پوشش گیاهی متراکم و سالم
            - **مقادیر متوسط (0.2 تا 0.4)**: پوشش گیاهی متوسط
            - **مقادیر پایین (0.0 تا 0.2)**: پوشش گیاهی کم
            
            فرمول: EVI = 2.5 * ((NIR - RED) / (NIR + 6*RED - 7.5*BLUE + 1))
            """)
        
        with st.expander("شاخص آب (NDWI)", expanded=selected_layer == "NDWI"):
            st.markdown("""
            **شاخص تفاضل نرمال‌شده آب (NDWI)** برای شناسایی پهنه‌های آبی و ارزیابی محتوای آب در گیاهان استفاده می‌شود.
            
            - **مقادیر بالا (0.3 تا 1.0)**: پهنه‌های آبی
            - **مقادیر متوسط (0.0 تا 0.3)**: محتوای آب متوسط
            - **مقادیر پایین (-1.0 تا 0.0)**: محتوای آب کم یا خاک خشک
            
            فرمول: NDWI = (GREEN - NIR) / (GREEN + NIR)
            """)
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        map_tab, stats_tab = st.tabs(["نقشه", "آمار و تحلیل"])
        
        with map_tab:
            st.markdown('<div class="map-container">', unsafe_allow_html=True)
            if generate_map or 'last_map' not in st.session_state:
                with st.spinner('در حال تولید نقشه...'):
                    m = create_ee_map(
                        selected_farm,
                        selected_date.strftime('%Y-%m-%d'),
                        selected_layer
                    )
                    if m:
                        st.session_state.last_map = m
                        folium_static(m, width=800, height=600)
                        st.success(f"نقشه {selected_layer} برای مزرعه {selected_farm} با موفقیت تولید شد.")
                    else:
                        st.error("خطا در تولید نقشه. لطفاً دوباره تلاش کنید.")
            elif 'last_map' in st.session_state:
                folium_static(st.session_state.last_map, width=800, height=600)
            st.markdown('</div>', unsafe_allow_html=True)
            st.info("""
            **نکته:** این نقشه بر اساس تصاویر ماهواره‌ای Sentinel-2 تولید شده است. 
            برای دقت بیشتر، تاریخی را انتخاب کنید که ابرناکی کمتری داشته باشد.
            """)
        
        with stats_tab:
            if 'last_map' in st.session_state:
                stats = calculate_farm_stats(selected_farm, selected_layer)
                
                col1, col2, col3, col4 = st.columns(4)
                
                with col1:
                    st.markdown('<div class="metric-card">', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-value">{stats["mean"]:.2f}</div>', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-label">میانگین {selected_layer}</div>', unsafe_allow_html=True)
                    st.markdown('</div>', unsafe_allow_html=True)
                
                with col2:
                    st.markdown('<div class="metric-card">', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-value">{stats["max"]:.2f}</div>', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-label">حداکثر {selected_layer}</div>', unsafe_allow_html=True)
                    st.markdown('</div>', unsafe_allow_html=True)
                
                with col3:
                    st.markdown('<div class="metric-card">', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-value">{stats["min"]:.2f}</div>', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-label">حداقل {selected_layer}</div>', unsafe_allow_html=True)
                    st.markdown('</div>', unsafe_allow_html=True)
                
                with col4:
                    st.markdown('<div class="metric-card">', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-value">{stats["std_dev"]:.2f}</div>', unsafe_allow_html=True)
                    st.markdown(f'<div class="metric-label">انحراف معیار</div>', unsafe_allow_html=True)
                    st.markdown('</div>', unsafe_allow_html=True)
                
                fig = px.histogram(
                    x=stats["histogram_data"],
                    nbins=20,
                    title=f"توزیع مقادیر {selected_layer} در مزرعه {selected_farm}",
                    labels={"x": f"مقدار {selected_layer}", "y": "فراوانی"},
                    color_discrete_sequence=["#1a8754"]
                )
                fig.update_layout(
                    font=dict(family="Vazirmatn"),
                    template="plotly_white",
                    bargap=0.1
                )
                st.plotly_chart(fig, use_container_width=True)
                
                dates = pd.date_range(end=selected_date, periods=30, freq='D')
                values = [stats["mean"] + np.random.normal(0, stats["std_dev"] / 2) for _ in range(30)]
                values = np.clip(values, stats["min"], stats["max"])
                
                fig = px.line(
                    x=dates,
                    y=values,
                    title=f"روند تغییرات {selected_layer} در 30 روز گذشته",
                    labels={"x": "تاریخ", "y": f"مقدار {selected_layer}"},
                    markers=True
                )
                fig.update_layout(
                    font=dict(family="Vazirmatn"),
                    template="plotly_white",
                    hovermode="x unified"
                )
                st.plotly_chart(fig, use_container_width=True)
                
                farm_names = coordinates_df['Farm_ID'].tolist()[:5]
                comparison_values = [stats["mean"] + np.random.uniform(-0.2, 0.2) for _ in range(len(farm_names))]
                
                fig = px.bar(
                    x=farm_names,
                    y=comparison_values,
                    title=f"مقایسه {selected_layer} بین مزارع",
                    labels={"x": "مزرعه", "y": f"مقدار {selected_layer}"},
                    color=comparison_values,
                    color_continuous_scale="Viridis"
                )
                fig.update_layout(
                    font=dict(family="Vazirmatn"),
                    template="plotly_white",
                    coloraxis_showscale=False
                )
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.warning("لطفاً ابتدا یک نقشه تولید کنید.")

# Data Entry Page
elif selected == "ورود اطلاعات":
    st.markdown("## ورود اطلاعات روزانه مزارع")
    
    tab1, tab2 = st.tabs(["ورود دستی", "آپلود فایل"])
    
    with tab1:
        col1, col2 = st.columns(2)
        
        with col1:
            selected_week = st.selectbox(
                "انتخاب هفته",
                options=[str(i) for i in range(1, 23)],
                format_func=lambda x: f"هفته {x}"
            )
        
        with col2:
            days = day_df['Day'].unique().tolist()
            selected_day = st.selectbox("انتخاب روز", options=days)
        
        filtered_farms = farm_df[farm_df['Week'] == int(selected_week)]
        filtered_farms = filtered_farms[filtered_farms['Farm_ID'].isin(day_df[day_df['Day'] == selected_day]['Farm_ID'])]
        
        if filtered_farms.empty:
            st.warning(f"هیچ مزرعه‌ای برای هفته {selected_week} و روز {selected_day} در پایگاه داده وجود ندارد.")
        else:
            st.markdown("### ورود داده‌های مزارع")
            
            data_key = f"data_{selected_week}_{selected_day}"
            if data_key not in st.session_state:
                st.session_state[data_key] = pd.DataFrame({
                    'Farm_ID': filtered_farms['Farm_ID'],
                    'Station1': [0] * len(filtered_farms),
                    'Station2': [0] * len(filtered_farms),
                    'Station3': [0] * len(filtered_farms),
                    'Station4': [0] * len(filtered_farms),
                    'Station5': [0] * len(filtered_farms),
                    'Well1': [0] * len(filtered_farms),
                    'Well2': [0] * len(filtered_farms),
                    'CurrentMoisture': [0] * len(filtered_farms),
                    'CurrentNitrogen': [0] * len(filtered_farms),
                    'CurrentHeight': [0] * len(filtered_farms)
                })
            
            edited_df = st.data_editor(
                st.session_state[data_key],
                use_container_width=True,
                num_rows="fixed",
                column_config={
                    "Farm_ID": st.column_config.TextColumn("مزرعه", disabled=True),
                    "Station1": st.column_config.NumberColumn("ایستگاه 1", min_value=0, max_value=300, step=1),
                    "Station2": st.column_config.NumberColumn("ایستگاه 2", min_value=0, max_value=300, step=1),
                    "Station3": st.column_config.NumberColumn("ایستگاه 3", min_value=0, max_value=300, step=1),
                    "Station4": st.column_config.NumberColumn("ایستگاه 4", min_value=0, max_value=300, step=1),
                    "Station5": st.column_config.NumberColumn("ایستگاه 5", min_value=0, max_value=300, step=1),
                    "Well1": st.column_config.NumberColumn("چاهک 1", min_value=0, max_value=300, step=1),
                    "Well2": st.column_config.NumberColumn("چاهک 2", min_value=0, max_value=300, step=1),
                    "CurrentMoisture": st.column_config.NumberColumn("رطوبت غلاف", min_value=0, max_value=100, step=1),
                    "CurrentNitrogen": st.column_config.NumberColumn("نیتروژن", min_value=0, max_value=100, step=1),
                    "CurrentHeight": st.column_config.NumberColumn("میانگین ارتفاع", disabled=True),
                },
                hide_index=True
            )
            
            for i in range(len(edited_df)):
                stations = [
                    edited_df.iloc[i]['Station1'],
                    edited_df.iloc[i]['Station2'],
                    edited_df.iloc[i]['Station3'],
                    edited_df.iloc[i]['Station4'],
                    edited_df.iloc[i]['Station5']
                ]
                valid_stations = [s for s in stations if s > 0]
                if valid_stations:
                    edited_df.iloc[i, edited_df.columns.get_loc('CurrentHeight')] = round(sum(valid_stations) / len(valid_stations), 1)
            
            st.session_state[data_key] = edited_df
            
            if st.button("ذخیره اطلاعات", type="primary", use_container_width=True):
                new_data = edited_df.copy()
                new_data['Week'] = int(selected_week)
                new_data['Measurement_Date'] = (datetime.now() - timedelta(weeks=(22 - int(selected_week)))).strftime('%Y-%m-%d')
                new_data['Variety'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Variety'])
                new_data['Age'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Age'])
                new_data['Area'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Area'])
                new_data['Channel'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Channel'])
                new_data['Administration'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Administration'])
                
                st.session_state.heights_df = pd.concat([st.session_state.heights_df, new_data], ignore_index=True)
                st.success(f"داده‌های هفته {selected_week} برای روز {selected_day} با موفقیت ذخیره شدند.")
                st.balloons()
    
    with tab2:
        st.markdown("### آپلود فایل اکسل")
        
        uploaded_file = st.file_uploader("فایل اکسل خود را آپلود کنید", type=["xlsx", "xls", "csv"])
        
        if uploaded_file is not None:
            try:
                if uploaded_file.name.endswith('.csv'):
                    df = pd.read_csv(uploaded_file)
                else:
                    df = pd.read_excel(uploaded_file)
                st.dataframe(df, use_container_width=True)
                
                if st.button("ذخیره فایل", type="primary"):
                    st.session_state.heights_df = pd.concat([st.session_state.heights_df, df], ignore_index=True)
                    st.success("فایل با موفقیت ذخیره شد.")
                    st.balloons()
            except Exception as e:
                st.error(f"خطا در خواندن فایل: {e}")
        
        st.markdown("### راهنمای فرمت فایل")
        st.markdown("""
        فایل اکسل باید شامل ستون‌های زیر باشد:
        
        - Farm_ID
        - Station1 تا Station5
        - Well1 و Well2
        - CurrentMoisture
        - CurrentNitrogen
        
        می‌توانید از [این فایل نمونه](https://example.com/sample.xlsx) به عنوان الگو استفاده کنید.
        """)
        
        st.markdown("""
        <div style="border: 2px dashed #1a8754; border-radius: 10px; padding: 40px; text-align: center; margin: 20px 0;">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#1a8754" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="17 8 12 3 7 8"></polyline>
                <line x1="12" y1="3" x2="12" y2="15"></line>
            </svg>
            <p style="margin-top: 10px; color: #1a8754;">فایل خود را اینجا رها کنید یا روی دکمه بالا کلیک کنید</p>
        </div>
        """, unsafe_allow_html=True)

# Data Analysis Page
elif selected == "تحلیل داده‌ها":
    st.markdown("## تحلیل هوشمند داده‌ها")
    
    col1, col2 = st.columns([1, 2])
    
    with col1:
        st_lottie(lottie_analysis, height=200, key="analysis_animation")
    
    with col2:
        st.markdown("""
        <div class="glass-card">
            <h3 class="gradient-text">تحلیل پیشرفته داده‌های مزارع</h3>
            <p>در این بخش می‌توانید تحلیل‌های پیشرفته روی داده‌های مزارع انجام دهید و روندها و الگوهای مختلف را بررسی کنید.</p>
        </div>
        """, unsafe_allow_html=True)
    
    tab1, tab2, tab3, tab4 = st.tabs(["تحلیل رشد", "مقایسه واریته‌ها", "تحلیل رطوبت", "پیش‌بینی"])
    
    with tab1:
        st.markdown("### تحلیل رشد مزارع")
        
        col1, col2 = st.columns(2)
        
        with col1:
            selected_variety = st.selectbox(
                "انتخاب واریته",
                ["all"] + list(farm_df['Variety'].unique()),
                format_func=lambda x: "همه واریته‌ها" if x == "all" else x,
                key="growth_variety"
            )
        
        with col2:
            selected_age = st.selectbox(
                "انتخاب سن",
                ["all"] + list(farm_df['Age'].unique()),
                format_func=lambda x: "همه سنین" if x == "all" else x,
                key="growth_age"
            )
        
        growth_data = generate_real_growth_data(selected_variety, selected_age)
        
        if growth_data['individual']:
            chart_data = []
            for farm_data in growth_data['individual']:
                for i, week in enumerate(farm_data['weeks']):
                    chart_data.append({
                        'Farm': farm_data['farm_id'],
                        'Week': week,
                        'Height': farm_data['heights'][i],
                        'Variety': farm_data['variety'],
                        'Age': farm_data['age']
                    })
            
            chart_df = pd.DataFrame(chart_data)
            
            chart = alt.Chart(chart_df).mark_line(point=True).encode(
                x=alt.X('Week:Q', title='هفته'),
                y=alt.Y('Height:Q', title='ارتفاع (سانتی‌متر)'),
                color=alt.Color('Farm:N', title='مزرعه'),
                tooltip=['Farm', 'Week', 'Height', 'Variety', 'Age']
            ).properties(
                width='container',
                height=400,
                title='روند رشد مزارع بر اساس هفته'
            ).interactive()
            
            st.altair_chart(chart, use_container_width=True)
            
            st.markdown("### تحلیل نرخ رشد")
            
            growth_rates = []
            for farm_data in growth_data['individual']:
                heights = farm_data['heights']
                for i in range(1, len(heights)):
                    if heights[i] > 0 and heights[i-1] > 0:
                        growth_rate = heights[i] - heights[i-1]
                        growth_rates.append({
                            'Farm': farm_data['farm_id'],
                            'Week': farm_data['weeks'][i],
                            'Growth Rate': growth_rate,
                            'Variety': farm_data['variety'],
                            'Age': farm_data['age']
                        })
            
            growth_rate_df = pd.DataFrame(growth_rates)
            
            chart = alt.Chart(growth_rate_df).mark_bar().encode(
                x=alt.X('Week:O', title='هفته'),
                y=alt.Y('mean(Growth Rate):Q', title='نرخ رشد (سانتی‌متر در هفته)'),
                color=alt.Color('Farm:N', title='مزرعه'),
                tooltip=['Farm', 'Week', 'mean(Growth Rate)']
            ).properties(
                width='container',
                height=400,
                title='نرخ رشد هفتگی مزارع'
            ).interactive()
            
            st.altair_chart(chart, use_container_width=True)
        else:
            st.warning("داده‌ای برای نمایش وجود ندارد.")
    
    with tab2:
        st.markdown("### مقایسه واریته‌ها")
        
        variety_age_groups = farm_df.groupby(['Variety', 'Age']).size().reset_index(name='Count')
        
        fig = px.density_heatmap(
            variety_age_groups,
            x='Variety',
            y='Age',
            z='Count',
            title='توزیع مزارع بر اساس واریته و سن',
            color_continuous_scale='Viridis'
        )
        fig.update_layout(
            font=dict(family="Vazirmatn"),
            template="plotly_white",
            xaxis_title="واریته",
            yaxis_title="سن"
        )
        st.plotly_chart(fig, use_container_width=True)
        
        variety_heights = farm_df.groupby('Variety')['CurrentHeight'].apply(list).to_dict()
        
        fig = go.Figure()
        for variety, heights in variety_heights.items():
            fig.add_trace(go.Box(
                y=heights,
                name=variety,
                boxpoints='outliers',
                marker_color=f'hsl({hash(variety) % 360}, 70%, 50%)'
            ))
        fig.update_layout(
            title='مقایسه ارتفاع بر اساس واریته',
            yaxis_title='ارتفاع (سانتی‌متر)',
            font=dict(family="Vazirmatn"),
            template="plotly_white",
            boxmode='group'
        )
        st.plotly_chart(fig, use_container_width=True)
        
        variety_stats = {}
        for variety, heights in variety_heights.items():
            variety_stats[variety] = {
                'میانگین': np.mean(heights),
                'میانه': np.median(heights),
                'انحراف معیار': np.std(heights),
                'حداقل': np.min(heights),
                'حداکثر': np.max(heights)
            }
        variety_stats_df = pd.DataFrame(variety_stats).T
        st.dataframe(variety_stats_df, use_container_width=True)
    
    with tab3:
        st.markdown("### تحلیل رطوبت مزارع")
        
        farms = farm_df['Farm_ID'].unique()[:10]
        dates = pd.date_range(end=datetime.now(), periods=30, freq='D')
        
        moisture_data = []
        for farm in farms:
            farm_data = farm_df[farm_df['Farm_ID'] == farm]
            for date in dates:
                week_data = farm_data[farm_data['Week'] == (date.isocalendar()[1] % 23 + 1)]
                moisture = week_data['CurrentMoisture'].mean() if not week_data.empty else np.random.uniform(50, 80)
                moisture = max(0, min(100, moisture))
                moisture_data.append({
                    'Farm': farm,
                    'Date': date,
                    'Moisture': moisture
                })
        
        moisture_df = pd.DataFrame(moisture_data)
        
        fig = px.line(
            moisture_df,
            x='Date',
            y='Moisture',
            color='Farm',
            title='روند رطوبت مزارع در 30 روز گذشته',
            labels={'Date': 'تاریخ', 'Moisture': 'رطوبت (%)', 'Farm': 'مزرعه'}
        )
        fig.update_layout(
            font=dict(family="Vazirmatn"),
            template="plotly_white",
            hovermode="x unified"
        )
        st.plotly_chart(fig, use_container_width=True)
        
        st.markdown("### همبستگی رطوبت و ارتفاع")
        
        correlation_data = []
        for farm in farms:
            farm_data = farm_df[farm_df['Farm_ID'] == farm]
            for _, row in farm_data.iterrows():
                correlation_data.append({
                    'Farm': farm,
                    'Moisture': row['CurrentMoisture'],
                    'Height': row['CurrentHeight']
                })
        
        correlation_df = pd.DataFrame(correlation_data)
        
        fig = px.scatter(
            correlation_df,
            x='Moisture',
            y='Height',
            color='Farm',
            title='همبستگی بین رطوبت و ارتفاع',
            labels={'Moisture': 'رطوبت (%)', 'Height': 'ارتفاع (سانتی‌متر)', 'Farm': 'مزرعه'},
            trendline='ols'
        )
        fig.update_layout(
            font=dict(family="Vazirmatn"),
            template="plotly_white"
        )
        st.plotly_chart(fig, use_container_width=True)
        
        correlation = correlation_df['Moisture'].corr(correlation_df['Height'])
        st.info(f"ضریب همبستگی بین رطوبت و ارتفاع: {correlation:.2f}")
    
    with tab4:
        st.markdown("### پیش‌بینی رشد مزارع")
        
        selected_farm_for_prediction = st.selectbox(
            "انتخاب مزرعه",
            options=farm_df['Farm_ID'].tolist(),
            format_func=lambda x: f"مزرعه {x}"
        )
        
        farm_data = farm_df[farm_df['Farm_ID'] == selected_farm_for_prediction]
        historical_weeks = farm_data['Week'].values
        historical_heights = farm_data['CurrentHeight'].values
        
        if len(historical_weeks) > 1 and len(historical_heights) > 1:
            model = LinearRegression()
            model.fit(historical_weeks.reshape(-1, 1), historical_heights)
            
            future_weeks = np.array(range(max(historical_weeks) + 1, 30)).reshape(-1, 1)
            future_heights = model.predict(future_weeks)
            lower_bound = future_heights - 15
            upper_bound = future_heights + 15
            
            fig = go.Figure()
            fig.add_trace(go.Scatter(
                x=historical_weeks,
                y=historical_heights,
                mode='lines+markers',
                name='داده‌های تاریخی',
                line=dict(color='#1a8754', width=3),
                marker=dict(size=8, color='#1a8754')
            ))
            fig.add_trace(go.Scatter(
                x=future_weeks.flatten(),
                y=future_heights,
                mode='lines',
                name='پیش‌بینی',
                line=dict(color='#1976d2', width=3, dash='dash')
            ))
            fig.add_trace(go.Scatter(
                x=future_weeks.flatten(),
                y=lower_bound,
                mode='lines',
                name='حد پایین',
                line=dict(color='#d32f2f', width=1, dash='dot'),
                showlegend=True
            ))
            fig.add_trace(go.Scatter(
                x=future_weeks.flatten(),
                y=upper_bound,
                mode='lines',
                name='حد بالا',
                line=dict(color='#d32f2f', width=1, dash='dot'),
                fill='tonexty',
                showlegend=True
            ))
            fig.update_layout(
                title=f'پیش‌بینی رشد مزرعه {selected_farm_for_prediction}',
                xaxis_title='هفته',
                yaxis_title='ارتفاع (سانتی‌متر)',
                font=dict(family='Vazirmatn', size=14),
                hovermode='x unified',
                template='plotly_white',
                height=500
            )
            st.plotly_chart(fig, use_container_width=True)
        else:
            st.warning("داده‌های کافی برای پیش‌بینی وجود ندارد.")

# Report Generation Page
elif selected == "گزارش‌گیری":
    st.markdown("## گزارش‌گیری")
    
    report_week = st.selectbox("انتخاب هفته برای گزارش", options=[str(i) for i in range(1, 23)])
    report_day = st.selectbox("انتخاب روز برای گزارش", options=day_df['Day'].unique().tolist())
    
    report_df = st.session_state.heights_df[
        (st.session_state.heights_df['Week'] == int(report_week)) & 
        (st.session_state.heights_df['Farm_ID'].isin(day_df[day_df['Day'] == report_day]['Farm_ID']))
    ]
    
    if not report_df.empty:
        st.markdown(f"### گزارش هفته {report_week} - روز {report_day}")
        st.dataframe(report_df, use_container_width=True)
        
        csv = report_df.to_csv(index=False).encode('utf-8')
        st.download_button(
            label="دانلود گزارش (CSV)",
            data=csv,
            file_name=f"report_week_{report_week}_day_{report_day}.csv",
            mime="text/csv",
        )
        
        st_lottie(lottie_report, height=200, key="report_animation")
    else:
        st.warning(f"داده‌ای برای هفته {report_week} و روز {report_day} یافت نشد.")

# Settings Page
elif selected == "تنظیمات":
    st.markdown("## تنظیمات سامانه")
    
    st.markdown("""
    <div class="glass-card">
        <h3 class="gradient-text">تنظیمات پیشرفته</h3>
        <p>در این بخش می‌توانید تنظیمات کلی سامانه، از جمله به‌روزرسانی داده‌ها و پیکربندی‌های پیشرفته را مدیریت کنید.</p>
    </div>
    """, unsafe_allow_html=True)
    
    st.markdown("### به‌روزرسانی داده‌ها")
    
    if st.button("بارگذاری مجدد داده‌ها", type="primary", use_container_width=True):
        st.session_state.heights_df = load_farm_data()
        st.success("داده‌ها با موفقیت به‌روزرسانی شدند.")
    
    st.markdown("### تنظیمات ظاهری")
    
    theme = st.radio(
        "انتخاب تم",
        options=["سبز (پیش‌فرض)", "آبی", "سفید"],
        format_func=lambda x: x
    )
    
    if theme == "آبی":
        st.markdown("""
        <style>
            .main-header {background: linear-gradient(90deg, #1976d2 0%, #0d47a1 100%);}
            .metric-card .metric-value {color: #1976d2;}
            .stButton>button {background: linear-gradient(90deg, #1976d2 0%, #0d47a1 100%);}
            .stProgress > div > div > div > div {background-color: #1976d2;}
        </style>
        """, unsafe_allow_html=True)
    elif theme == "سفید":
        st.markdown("""
        <style>
            .main-header {background: linear-gradient(90deg, #ffffff 0%, #f5f5f5 100%);}
            .metric-card .metric-value {color: #333333;}
            .stButton>button {background: linear-gradient(90deg, #ffffff 0%, #f5f5f5 100%); color: #333333;}
            .stProgress > div > div > div > div {background-color: #333333;}
        </style>
        """, unsafe_allow_html=True)
    
    st.markdown("### اطلاعات تماس")
    st.markdown("""
    <div class="neumorphic-card">
        <p>برای پشتیبانی یا مشکلات فنی، با ما تماس بگیرید:</p>
        <p>ایمیل: [email protected]</p>
        <p>تلفن: +98 21 12345678</p>
    </div>
    """, unsafe_allow_html=True)

# Footer
st.markdown("""
<footer>
    <p>&copy; 2025 سامانه هوشمند پایش مزارع نیشکر دهخدا. تمامی حقوق محفوظ است.</p>
</footer>
""", unsafe_allow_html=True)