File size: 83,655 Bytes
82676b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
وحدة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد
تتيح هذه الوحدة عرض مواقع المشاريع على خريطة تفاعلية مع إمكانية رؤية التضاريس بشكل ثلاثي الأبعاد
"""

import os
import sys
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import folium
from folium.plugins import MarkerCluster, HeatMap, MeasureControl
from streamlit_folium import folium_static
import requests
import json
import random
from typing import List, Dict, Any, Tuple, Optional
import tempfile
import base64
from PIL import Image
from io import BytesIO

# إضافة مسار النظام للوصول للملفات المشتركة
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))

# استيراد مكونات واجهة المستخدم
from utils.components.header import render_header
from utils.components.credits import render_credits
from utils.helpers import format_number, format_currency, styled_button


class InteractiveMap:
    """فئة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد"""
    
    def __init__(self):
        """تهيئة وحدة الخريطة التفاعلية"""
        # تهيئة مجلدات حفظ البيانات
        self.data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data/maps"))
        os.makedirs(self.data_dir, exist_ok=True)
        
        # مفاتيح API لخدمات الخرائط
        self.mapbox_token = os.environ.get("MAPBOX_TOKEN", "")
        self.opentopodata_api = "https://api.opentopodata.org/v1/srtm30m"
        
        # تهيئة حالة الجلسة
        if 'project_locations' not in st.session_state:
            st.session_state.project_locations = []
            
        if 'selected_location' not in st.session_state:
            st.session_state.selected_location = None
            
        if 'terrain_data' not in st.session_state:
            st.session_state.terrain_data = None
            
        # بيانات اختبارية للمشاريع (سيتم استبدالها بالبيانات الفعلية من قاعدة البيانات)
        self._initialize_sample_projects()
    
    def render(self):
        """عرض واجهة وحدة الخريطة التفاعلية"""
        # عرض الشعار والعنوان الرئيسي
        render_header("خريطة مواقع المشاريع التفاعلية")
        
        # تبويبات الوحدة
        tabs = st.tabs([
            "الخريطة التفاعلية",
            "عرض التضاريس ثلاثي الأبعاد",
            "تحليل المواقع",
            "إدارة المواقع"
        ])
        
        # تبويب الخريطة التفاعلية
        with tabs[0]:
            self._render_interactive_map()
            
        # تبويب عرض التضاريس ثلاثي الأبعاد
        with tabs[1]:
            self._render_3d_terrain()
            
        # تبويب تحليل المواقع
        with tabs[2]:
            self._render_location_analysis()
            
        # تبويب إدارة المواقع
        with tabs[3]:
            self._render_location_management()
            
        # عرض حقوق النشر
        render_credits()
    
    def _render_interactive_map(self):
        """عرض الخريطة التفاعلية"""
        st.markdown("""
        <div class='custom-box info-box'>
            <h3>🗺️ الخريطة التفاعلية لمواقع المشاريع</h3>
            <p>خريطة تفاعلية تعرض مواقع جميع المشاريع مع إمكانية التكبير والتصغير والتحرك.</p>
            <p>يمكنك النقر على أي موقع للحصول على تفاصيل المشروع.</p>
        </div>
        """, unsafe_allow_html=True)
        
        # مربع البحث
        search_query = st.text_input("البحث عن موقع أو مشروع", key="map_search")
        
        # أزرار تحكم للخريطة
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            map_style = st.selectbox(
                "نمط الخريطة",
                options=["OpenStreetMap", "Stamen Terrain", "Stamen Toner", "CartoDB Positron"],
                key="map_style"
            )
        
        with col2:
            cluster_markers = st.checkbox("تجميع المواقع القريبة", value=True, key="cluster_markers")
        
        with col3:
            show_heatmap = st.checkbox("عرض خريطة حرارية للمواقع", value=False, key="show_heatmap")
        
        with col4:
            show_measurements = st.checkbox("أدوات القياس", value=False, key="show_measurements")
        
        # إنشاء الخريطة
        if len(st.session_state.project_locations) > 0:
            # بيانات النقاط على الخريطة
            locations = []
            
            # تصفية المشاريع حسب البحث
            filtered_projects = st.session_state.project_locations
            if search_query:
                filtered_projects = [
                    p for p in filtered_projects 
                    if search_query.lower() in p.get("name", "").lower() or 
                       search_query.lower() in p.get("description", "").lower() or
                       search_query.lower() in p.get("city", "").lower()
                ]
            
            # عرض عدد النتائج
            if search_query:
                st.markdown(f"عدد النتائج: {len(filtered_projects)}")
            
            # تحضير البيانات للخريطة
            heat_data = []
            for project in filtered_projects:
                locations.append({
                    "lat": project.get("latitude"),
                    "lon": project.get("longitude"),
                    "name": project.get("name"),
                    "description": project.get("description"),
                    "city": project.get("city"),
                    "status": project.get("status"),
                    "project_id": project.get("project_id")
                })
                heat_data.append([project.get("latitude"), project.get("longitude"), 1])
            
            # تعيين نقطة المركز والتكبير
            if filtered_projects:
                center_lat = sum(p.get("latitude", 0) for p in filtered_projects) / len(filtered_projects)
                center_lon = sum(p.get("longitude", 0) for p in filtered_projects) / len(filtered_projects)
                zoom_level = 6  # مستوى التكبير الافتراضي
            else:
                # مركز المملكة العربية السعودية
                center_lat = 24.7136
                center_lon = 46.6753
                zoom_level = 5
            
            # تحديد الإسناد (attribution) بناءً على نمط الخريطة
            attribution = None
            if map_style == "OpenStreetMap":
                attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            elif map_style.startswith("Stamen"):
                attribution = 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.'
            elif map_style == "CartoDB Positron":
                attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="https://cartodb.com/attributions">CartoDB</a>'
            
            # إنشاء الخريطة
            m = folium.Map(
                location=[center_lat, center_lon],
                zoom_start=zoom_level,
                tiles=map_style,
                attr=attribution  # إضافة سمة الإسناد
            )
            
            # إضافة أدوات القياس إذا تم اختيارها
            if show_measurements:
                MeasureControl(position='topright', primary_length_unit='kilometers').add_to(m)
            
            # إضافة النقاط إلى الخريطة
            if cluster_markers:
                # إنشاء مجموعة تجميع
                marker_cluster = MarkerCluster(name="تجميع المشاريع").add_to(m)
                
                # إضافة النقاط إلى المجموعة
                for location in locations:
                    # إنشاء النافذة المنبثقة
                    popup_html = f"""
                    <div style='direction: rtl; text-align: right;'>
                        <h4>{location['name']}</h4>
                        <p><strong>الوصف:</strong> {location['description']}</p>
                        <p><strong>المدينة:</strong> {location['city']}</p>
                        <p><strong>الحالة:</strong> {location['status']}</p>
                        <p><strong>الإحداثيات:</strong> {location['lat']:.6f}, {location['lon']:.6f}</p>
                        <button onclick="window.open('/project/{location['project_id']}', '_self')">عرض تفاصيل المشروع</button>
                    </div>
                    """
                    
                    # تحديد لون العلامة حسب حالة المشروع
                    icon_color = 'green'
                    if location['status'] == 'قيد التنفيذ':
                        icon_color = 'orange'
                    elif location['status'] == 'متوقف':
                        icon_color = 'red'
                    elif location['status'] == 'مكتمل':
                        icon_color = 'blue'
                    
                    # إضافة العلامة
                    folium.Marker(
                        location=[location['lat'], location['lon']],
                        popup=folium.Popup(popup_html, max_width=300),
                        tooltip=location['name'],
                        icon=folium.Icon(color=icon_color, icon='info-sign')
                    ).add_to(marker_cluster)
            else:
                # إضافة النقاط مباشرة إلى الخريطة
                for location in locations:
                    # إنشاء النافذة المنبثقة
                    popup_html = f"""
                    <div style='direction: rtl; text-align: right;'>
                        <h4>{location['name']}</h4>
                        <p><strong>الوصف:</strong> {location['description']}</p>
                        <p><strong>المدينة:</strong> {location['city']}</p>
                        <p><strong>الحالة:</strong> {location['status']}</p>
                        <p><strong>الإحداثيات:</strong> {location['lat']:.6f}, {location['lon']:.6f}</p>
                        <button onclick="window.open('/project/{location['project_id']}', '_self')">عرض تفاصيل المشروع</button>
                    </div>
                    """
                    
                    # تحديد لون العلامة حسب حالة المشروع
                    icon_color = 'green'
                    if location['status'] == 'قيد التنفيذ':
                        icon_color = 'orange'
                    elif location['status'] == 'متوقف':
                        icon_color = 'red'
                    elif location['status'] == 'مكتمل':
                        icon_color = 'blue'
                    
                    # إضافة العلامة
                    folium.Marker(
                        location=[location['lat'], location['lon']],
                        popup=folium.Popup(popup_html, max_width=300),
                        tooltip=location['name'],
                        icon=folium.Icon(color=icon_color, icon='info-sign')
                    ).add_to(m)
            
            # إضافة خريطة حرارية إذا تم اختيارها
            if show_heatmap and heat_data:
                HeatMap(heat_data, radius=15).add_to(m)
            
            # إضافة طبقات متنوعة للخريطة
            folium.TileLayer('OpenStreetMap').add_to(m)
            folium.TileLayer('Stamen Terrain').add_to(m)
            folium.TileLayer('Stamen Toner').add_to(m)
            folium.TileLayer('CartoDB positron').add_to(m)
            folium.TileLayer('CartoDB dark_matter').add_to(m)
            
            # إضافة أدوات التحكم بالطبقات
            folium.LayerControl().add_to(m)
            
            # عرض الخريطة
            st_map = folium_static(m, width=1000, height=600)
            
            # التفاعل مع النقر على الخريطة (سيتم تنفيذه عندما يتم دعم التفاعل)
            # حاليًا لا يوجد دعم مباشر للتفاعل مع الخريطة في Streamlit
            
            # عرض بيانات المشاريع في جدول
            st.markdown("### قائمة المشاريع على الخريطة")
            
            projects_df = pd.DataFrame(filtered_projects)
            
            # إعادة تسمية الأعمدة بالعربية
            renamed_columns = {
                "name": "اسم المشروع",
                "city": "المدينة",
                "status": "الحالة",
                "description": "الوصف",
                "project_id": "معرف المشروع",
                "latitude": "خط العرض",
                "longitude": "خط الطول"
            }
            
            # تحديد الأعمدة للعرض
            display_columns = ["name", "city", "status", "project_id"]
            
            # إنشاء جدول للعرض
            display_df = projects_df[display_columns].rename(columns=renamed_columns)
            
            # عرض الجدول
            st.dataframe(display_df, width=1000, height=400)
            
            # زر لاختيار مشروع لعرض التضاريس
            selected_project_id = st.selectbox(
                "اختر مشروعًا لعرض التضاريس ثلاثية الأبعاد",
                options=projects_df["project_id"].tolist(),
                format_func=lambda x: next((p["name"] for p in filtered_projects if p["project_id"] == x), x),
                key="select_project_for_terrain"
            )
            
            # زر عرض التضاريس
            if styled_button("عرض التضاريس", key="show_terrain_btn", type="primary", icon="🏔️"):
                # العثور على المشروع المحدد
                selected_project = next((p for p in filtered_projects if p["project_id"] == selected_project_id), None)
                
                if selected_project:
                    # تخزين الموقع المحدد في حالة الجلسة
                    st.session_state.selected_location = {
                        "latitude": selected_project["latitude"],
                        "longitude": selected_project["longitude"],
                        "name": selected_project["name"],
                        "project_id": selected_project["project_id"]
                    }
                    
                    # جلب بيانات التضاريس
                    try:
                        terrain_data = self._fetch_terrain_data(
                            selected_project["latitude"],
                            selected_project["longitude"]
                        )
                        
                        # تخزين بيانات التضاريس في حالة الجلسة
                        st.session_state.terrain_data = terrain_data
                        
                        # الانتقال إلى تبويب عرض التضاريس
                        st.rerun()
                    except Exception as e:
                        st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
        else:
            st.warning("لا توجد مواقع مشاريع متاحة. يرجى إضافة مواقع من تبويب 'إدارة المواقع'.")
    
    def _render_3d_terrain(self):
        """عرض التضاريس ثلاثي الأبعاد"""
        st.markdown("""
        <div class='custom-box info-box'>
            <h3>🏔️ عرض التضاريس ثلاثي الأبعاد</h3>
            <p>عرض تفاعلي ثلاثي الأبعاد لتضاريس موقع المشروع المحدد.</p>
            <p>يمكنك تدوير وتكبير العرض للحصول على رؤية أفضل للموقع.</p>
        </div>
        """, unsafe_allow_html=True)
        
        # التحقق من وجود موقع محدد
        if st.session_state.selected_location is None:
            st.info("يرجى اختيار موقع من تبويب 'الخريطة التفاعلية' أولاً.")
            
            # بديل: السماح بإدخال الإحداثيات يدوياً
            st.markdown("### إدخال الإحداثيات يدوياً")
            
            col1, col2 = st.columns(2)
            
            with col1:
                manual_lat = st.number_input("خط العرض", value=24.7136, step=0.0001, format="%.6f", key="manual_lat")
            
            with col2:
                manual_lon = st.number_input("خط الطول", value=46.6753, step=0.0001, format="%.6f", key="manual_lon")
            
            if styled_button("عرض التضاريس", key="manual_terrain_btn", type="primary", icon="🏔️"):
                try:
                    # جلب بيانات التضاريس
                    terrain_data = self._fetch_terrain_data(manual_lat, manual_lon)
                    
                    # تخزين بيانات التضاريس والموقع في حالة الجلسة
                    st.session_state.terrain_data = terrain_data
                    st.session_state.selected_location = {
                        "latitude": manual_lat,
                        "longitude": manual_lon,
                        "name": f"الموقع المخصص ({manual_lat:.4f}, {manual_lon:.4f})",
                        "project_id": "custom"
                    }
                    
                    # إعادة تشغيل التطبيق لتحديث العرض
                    st.rerun()
                except Exception as e:
                    st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
            
            # عرض خريطة لتحديد الموقع
            st.markdown("### حدد موقعًا على الخريطة")
            m = folium.Map(
                location=[24.7136, 46.6753], 
                zoom_start=6,
                attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            )
            folium_static(m, width=1000, height=500)
            
            st.info("ملاحظة: لا يمكن تحديد موقع على الخريطة مباشرة في هذا الإصدار. يرجى إدخال الإحداثيات يدوياً أو اختيار مشروع من القائمة.")
            
            return
        
        # عرض معلومات الموقع المحدد
        st.markdown(f"### تضاريس موقع: {st.session_state.selected_location['name']}")
        st.markdown(f"الإحداثيات: {st.session_state.selected_location['latitude']:.6f}, {st.session_state.selected_location['longitude']:.6f}")
        
        # التحقق من وجود بيانات التضاريس
        if st.session_state.terrain_data is None:
            st.warning("لا توجد بيانات تضاريس متاحة لهذا الموقع. جاري جلب البيانات...")
            
            try:
                # جلب بيانات التضاريس
                terrain_data = self._fetch_terrain_data(
                    st.session_state.selected_location["latitude"],
                    st.session_state.selected_location["longitude"]
                )
                
                # تخزين بيانات التضاريس في حالة الجلسة
                st.session_state.terrain_data = terrain_data
                
                # إعادة تشغيل التطبيق لتحديث العرض
                st.rerun()
            except Exception as e:
                st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
                return
        
        # عرض الخريطة ثنائية الأبعاد للموقع
        st.markdown("### خريطة الموقع")
        
        # إنشاء خريطة صغيرة للموقع
        mini_map = folium.Map(
            location=[st.session_state.selected_location["latitude"], st.session_state.selected_location["longitude"]], 
            zoom_start=10,
            attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        )
        folium.Marker(location=[st.session_state.selected_location["latitude"], st.session_state.selected_location["longitude"]], tooltip="الموقع المحدد").add_to(mini_map)
        folium_static(mini_map, width=700, height=300)
        
        # عرض بيانات التضاريس
        st.markdown("### نموذج التضاريس ثلاثي الأبعاد")
        
        # تحويل بيانات التضاريس إلى DataFrame
        df = pd.DataFrame(st.session_state.terrain_data)
        
        # اختيار نظام ألوان
        color_schemes = {
            "Viridis": "Viridis",
            "أخضر إلى بني": "Greens",
            "أزرق إلى أحمر": "RdBu",
            "أرجواني إلى أخضر": "PuGn",
            "نظام الارتفاعات": "Terrain"
        }
        
        color_scheme = st.selectbox(
            "نظام الألوان",
            options=list(color_schemes.keys()),
            index=4,
            key="3d_color_scheme"
        )
        
        # خيارات العرض
        col1, col2, col3 = st.columns(3)
        
        with col1:
            exaggeration = st.slider("تضخيم الارتفاع", 1, 50, 15, key="terrain_exaggeration")
        
        with col2:
            radius = st.slider("نطاق العرض (كم)", 1, 20, 5, key="terrain_radius")
        
        with col3:
            resolution = st.slider("دقة العرض", 10, 100, 50, key="terrain_resolution")
        
        if not df.empty and len(df) > 1:
            # إعادة جلب البيانات إذا تغير النطاق
            current_lat = st.session_state.selected_location["latitude"]
            current_lon = st.session_state.selected_location["longitude"]
            current_radius = radius
            
            # جلب بيانات جديدة إذا تغير النطاق
            if styled_button("تحديث النطاق", key="update_radius_btn"):
                try:
                    # جلب بيانات التضاريس
                    terrain_data = self._fetch_terrain_data(
                        current_lat,
                        current_lon,
                        radius_km=current_radius
                    )
                    
                    # تخزين بيانات التضاريس في حالة الجلسة
                    st.session_state.terrain_data = terrain_data
                    
                    # إعادة تشغيل التطبيق لتحديث العرض
                    st.rerun()
                except Exception as e:
                    st.error(f"حدث خطأ أثناء تحديث بيانات التضاريس: {str(e)}")
            
            # تحويل البيانات إلى تنسيق مناسب لـ PyDeck
            x = df["longitude"].values
            y = df["latitude"].values
            z = df["elevation"].values * exaggeration  # تضخيم الارتفاع
            
            # تطبيع الارتفاعات للحصول على ألوان مناسبة
            normalized_elevation = (z - z.min()) / (z.max() - z.min() if z.max() != z.min() else 1)
            
            # الحصول على نظام الألوان
            cmap = self._get_color_map(color_schemes[color_scheme])
            
            # إنشاء عمود الألوان
            df["color"] = [
                cmap(ne) if ne <= 1.0 else cmap(1.0)
                for ne in normalized_elevation
            ]
            
            # تهيئة عرض PyDeck
            view_state = pdk.ViewState(
                latitude=current_lat,
                longitude=current_lon,
                zoom=10,
                pitch=45,
                bearing=0
            )
            
            # إنشاء طبقة التضاريس
            terrain_layer = pdk.Layer(
                "ColumnLayer",
                data=df,
                get_position=["longitude", "latitude"],
                get_elevation="elevation * " + str(exaggeration),
                get_fill_color="color",
                get_radius=resolution,
                pickable=True,
                auto_highlight=True,
                elevation_scale=1,
                elevation_range=[0, 1000],
                coverage=1,
            )
            
            # إضافة طبقة لعلامة الموقع المحدد
            marker_df = pd.DataFrame({
                "latitude": [current_lat],
                "longitude": [current_lon],
                "size": [400]
            })
            
            marker_layer = pdk.Layer(
                "ScatterplotLayer",
                data=marker_df,
                get_position=["longitude", "latitude"],
                get_radius="size",
                get_fill_color=[255, 0, 0, 200],
                pickable=True,
            )
            
            # تهيئة العرض
            r = pdk.Deck(
                layers=[terrain_layer, marker_layer],
                initial_view_state=view_state,
                map_style="mapbox://styles/mapbox/satellite-v9",
                tooltip={
                    "html": "<b>ارتفاع:</b> {elevation} متر<br/><b>إحداثيات:</b> {latitude:.6f}, {longitude:.6f}",
                    "style": {
                        "backgroundColor": "steelblue",
                        "color": "white",
                        "direction": "rtl",
                        "text-align": "right"
                    }
                }
            )
            
            # عرض نموذج التضاريس
            st.pydeck_chart(r)
            
            # إضافة معلومات إضافية
            st.markdown("### معلومات الارتفاع")
            
            # حساب الإحصاءات
            min_elevation = df["elevation"].min()
            max_elevation = df["elevation"].max()
            avg_elevation = df["elevation"].mean()
            
            # عرض الإحصاءات
            stat_col1, stat_col2, stat_col3 = st.columns(3)
            
            with stat_col1:
                st.metric("أدنى ارتفاع", f"{min_elevation:.1f} متر")
            
            with stat_col2:
                st.metric("متوسط الارتفاع", f"{avg_elevation:.1f} متر")
            
            with stat_col3:
                st.metric("أعلى ارتفاع", f"{max_elevation:.1f} متر")
            
            # زر لتصدير البيانات
            if styled_button("تصدير بيانات التضاريس", key="export_terrain_btn", type="secondary", icon="📊"):
                # تحويل البيانات إلى CSV
                csv = df.to_csv(index=False)
                
                # إنشاء رابط تنزيل
                b64 = base64.b64encode(csv.encode()).decode()
                href = f'<a href="data:file/csv;base64,{b64}" download="terrain_data_{st.session_state.selected_location["project_id"]}.csv" class="btn">تنزيل البيانات (CSV)</a>'
                st.markdown(href, unsafe_allow_html=True)
        else:
            st.error("لا توجد بيانات كافية لعرض نموذج التضاريس. حاول اختيار موقع آخر أو زيادة النطاق.")
    
    def _render_location_analysis(self):
        """عرض تحليل المواقع"""
        st.markdown("""
        <div class='custom-box info-box'>
            <h3>📊 تحليل موقع المشروع</h3>
            <p>تحليل متقدم لموقع المشروع وتضاريسه والظروف المحيطة.</p>
            <p>يمكنك تحليل الارتفاعات والمسافات وقياس التكاليف المرتبطة بالموقع.</p>
        </div>
        """, unsafe_allow_html=True)
        
        # التحقق من وجود مواقع
        if len(st.session_state.project_locations) == 0:
            st.warning("لا توجد مواقع مشاريع متاحة للتحليل. يرجى إضافة مواقع من تبويب 'إدارة المواقع'.")
            return
        
        # اختيار موقع أو موقعين للتحليل
        analysis_type = st.radio(
            "نوع التحليل",
            options=["تحليل موقع واحد", "مقارنة موقعين"],
            key="location_analysis_type",
            horizontal=True
        )
        
        # تحويل المواقع إلى DataFrame
        projects_df = pd.DataFrame(st.session_state.project_locations)
        
        if analysis_type == "تحليل موقع واحد":
            # اختيار موقع للتحليل
            selected_project_id = st.selectbox(
                "اختر موقع المشروع للتحليل",
                options=projects_df["project_id"].tolist(),
                format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
                key="analysis_project"
            )
            
            # العثور على المشروع المحدد
            selected_project = next((p for p in st.session_state.project_locations if p["project_id"] == selected_project_id), None)
            
            if selected_project:
                # عرض معلومات المشروع
                st.markdown(f"### تحليل موقع: {selected_project['name']}")
                
                # عرض خريطة الموقع
                st.markdown("#### موقع المشروع")
                
                # إنشاء خريطة صغيرة للموقع
                m2 = folium.Map(
                    location=[selected_project["latitude"], selected_project["longitude"]], 
                    zoom_start=10,
                    attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                )
                folium.Marker(location=[selected_project["latitude"], selected_project["longitude"]], tooltip=selected_project["name"]).add_to(m2)
                
                # إضافة دائرة بنصف قطر محدد
                analysis_radius = st.slider("نطاق التحليل (كم)", 1, 50, 10, key="analysis_radius")
                folium.Circle(
                    location=[selected_project["latitude"], selected_project["longitude"]],
                    radius=analysis_radius * 1000,  # تحويل إلى أمتار
                    color="red",
                    fill=True,
                    fill_opacity=0.2
                ).add_to(m2)
                
                folium_static(m2, width=700, height=400)
                
                # تحليل الموقع
                st.markdown("#### عوامل الموقع")
                
                # تحليل اعتباري للموقع (يمكن استبداله بتحليل حقيقي من خدمات مثل Google Places API)
                
                # عوامل افتراضية - ستتغير هذه باستخدام بيانات حقيقية
                factors = {
                    "قرب المدينة": random.uniform(0.4, 1.0),
                    "توفر المياه": random.uniform(0.3, 0.9),
                    "سهولة الوصول": random.uniform(0.5, 1.0),
                    "الظروف الجوية": random.uniform(0.6, 1.0),
                    "التضاريس": random.uniform(0.3, 0.8),
                    "توفر العمالة": random.uniform(0.5, 0.9),
                    "البنية التحتية": random.uniform(0.4, 0.9),
                    "المخاطر البيئية": random.uniform(0.3, 0.7)
                }
                
                # مخطط شريطي للعوامل
                factors_df = pd.DataFrame({
                    "العامل": list(factors.keys()),
                    "التقييم": list(factors.values())
                })
                
                # الترتيب تنازلياً
                factors_df = factors_df.sort_values(by="التقييم", ascending=False)
                
                # عرض الرسم البياني
                st.bar_chart(factors_df.set_index("العامل"))
                
                # تقييم إجمالي للموقع
                overall_score = sum(factors.values()) / len(factors)
                
                # عرض التقييم الإجمالي
                st.markdown(f"#### التقييم الإجمالي للموقع: {overall_score:.2f}/1.0")
                
                # مؤشر تقدم للتقييم
                st.progress(overall_score)
                
                # تصنيف التقييم
                if overall_score >= 0.8:
                    rating = "ممتاز"
                    color = "green"
                elif overall_score >= 0.6:
                    rating = "جيد"
                    color = "blue"
                elif overall_score >= 0.4:
                    rating = "مقبول"
                    color = "orange"
                else:
                    rating = "ضعيف"
                    color = "red"
                
                st.markdown(f"<h4 style='color: {color};'>تصنيف الموقع: {rating}</h4>", unsafe_allow_html=True)
                
                # توصيات للموقع
                st.markdown("#### توصيات الموقع")
                
                recommendations = [
                    "تحسين طرق الوصول للموقع لزيادة كفاءة نقل المواد والمعدات.",
                    "إجراء دراسة جيوتقنية مفصلة للتضاريس قبل البدء في أعمال الحفر.",
                    "التأكد من توفر مصادر المياه الكافية لاحتياجات المشروع.",
                    "التنسيق مع السلطات المحلية لتسهيل توصيل الخدمات للموقع.",
                    "وضع خطة للتعامل مع الظروف الجوية المتقلبة في المنطقة."
                ]
                
                for rec in recommendations:
                    st.markdown(f"- {rec}")
                
                # المرافق القريبة
                st.markdown("#### المرافق القريبة (تمثيل افتراضي)")
                
                # بيانات افتراضية للمرافق القريبة
                nearby_facilities = {
                    "مستشفى": random.uniform(5, 30),
                    "مدرسة": random.uniform(2, 15),
                    "محطة وقود": random.uniform(2, 20),
                    "مركز تسوق": random.uniform(3, 25),
                    "مكتب حكومي": random.uniform(7, 35),
                    "مطار": random.uniform(15, 100),
                    "ميناء": random.uniform(20, 150)
                }
                
                # عرض المرافق في جدول
                facilities_df = pd.DataFrame({
                    "المرفق": list(nearby_facilities.keys()),
                    "المسافة (كم)": list(nearby_facilities.values())
                })
                
                # ترتيب حسب المسافة
                facilities_df = facilities_df.sort_values(by="المسافة (كم)")
                
                # عرض الجدول
                st.dataframe(facilities_df, width=700)
                
                # تقرير تكلفة الموقع
                st.markdown("#### تقديرات تكلفة الموقع")
                
                # بنود التكلفة الافتراضية
                cost_items = {
                    "تكلفة تسوية الأرض": random.uniform(50000, 200000),
                    "تكلفة البنية التحتية": random.uniform(100000, 500000),
                    "تكلفة النقل الإضافية": random.uniform(30000, 150000),
                    "تكلفة الحماية من المخاطر البيئية": random.uniform(20000, 100000),
                    "تكلفة توصيل الخدمات": random.uniform(40000, 200000)
                }
                
                # عرض بنود التكلفة
                st.markdown("##### بنود التكلفة")
                
                for item, cost in cost_items.items():
                    st.markdown(f"- {item}: {format_currency(cost)} ريال")
                
                # إجمالي التكلفة
                total_cost = sum(cost_items.values())
                st.markdown(f"##### إجمالي تكلفة الموقع: {format_currency(total_cost)} ريال")
                
                # خيارات تحسين الموقع
                st.markdown("#### خيارات تحسين الموقع")
                
                improvement_options = [
                    {"name": "تسوية الأرض وإزالة العوائق", "cost": 75000, "impact": 0.15},
                    {"name": "تحسين طرق الوصول", "cost": 120000, "impact": 0.2},
                    {"name": "بناء نظام صرف للمياه", "cost": 90000, "impact": 0.18},
                    {"name": "تعزيز البنية التحتية", "cost": 180000, "impact": 0.25},
                    {"name": "نظام حماية من العوامل الجوية", "cost": 60000, "impact": 0.12}
                ]
                
                # عرض خيارات التحسين
                st.markdown("اختر خيارات التحسين لتقييم التأثير والتكلفة:")
                
                selected_improvements = []
                for i, option in enumerate(improvement_options):
                    if st.checkbox(f"{option['name']} - {format_currency(option['cost'])} ريال", key=f"imp_{i}"):
                        selected_improvements.append(option)
                
                if selected_improvements:
                    # حساب التأثير والتكلفة الإجمالية
                    total_impact = sum(imp["impact"] for imp in selected_improvements)
                    total_improvement_cost = sum(imp["cost"] for imp in selected_improvements)
                    
                    # عرض النتائج
                    st.markdown(f"##### تحسين التقييم المتوقع: +{total_impact:.2f}")
                    new_score = min(1.0, overall_score + total_impact)
                    st.markdown(f"##### التقييم الجديد المتوقع: {new_score:.2f}/1.0")
                    st.progress(new_score)
                    
                    # تصنيف التقييم الجديد
                    if new_score >= 0.8:
                        new_rating = "ممتاز"
                        new_color = "green"
                    elif new_score >= 0.6:
                        new_rating = "جيد"
                        new_color = "blue"
                    elif new_score >= 0.4:
                        new_rating = "مقبول"
                        new_color = "orange"
                    else:
                        new_rating = "ضعيف"
                        new_color = "red"
                    
                    st.markdown(f"<h5 style='color: {new_color};'>التصنيف الجديد المتوقع: {new_rating}</h5>", unsafe_allow_html=True)
                    
                    # عرض التكلفة الإجمالية
                    st.markdown(f"##### تكلفة التحسينات: {format_currency(total_improvement_cost)} ريال")
            else:
                st.error("لم يتم العثور على المشروع المحدد.")
        else:  # مقارنة موقعين
            # اختيار موقعين للمقارنة
            col1, col2 = st.columns(2)
            
            with col1:
                project_id_1 = st.selectbox(
                    "الموقع الأول",
                    options=projects_df["project_id"].tolist(),
                    format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
                    key="compare_project_1"
                )
            
            with col2:
                # استبعاد الموقع الأول من الخيارات
                remaining_options = [pid for pid in projects_df["project_id"].tolist() if pid != project_id_1]
                
                if remaining_options:
                    project_id_2 = st.selectbox(
                        "الموقع الثاني",
                        options=remaining_options,
                        format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
                        key="compare_project_2"
                    )
                else:
                    st.warning("يجب أن يكون هناك موقعان على الأقل للمقارنة.")
                    return
            
            # العثور على المشروعين المحددين
            project_1 = next((p for p in st.session_state.project_locations if p["project_id"] == project_id_1), None)
            project_2 = next((p for p in st.session_state.project_locations if p["project_id"] == project_id_2), None)
            
            if project_1 and project_2:
                # عرض عنوان المقارنة
                st.markdown(f"### مقارنة بين موقعي {project_1['name']} و {project_2['name']}")
                
                # عرض خريطة توضح الموقعين
                st.markdown("#### الموقعان على الخريطة")
                
                # حساب المركز والزوم المناسب
                center_lat = (project_1["latitude"] + project_2["latitude"]) / 2
                center_lon = (project_1["longitude"] + project_2["longitude"]) / 2
                
                # حساب المسافة بين الموقعين
                distance = self._calculate_distance(
                    project_1["latitude"], project_1["longitude"],
                    project_2["latitude"], project_2["longitude"]
                )
                
                # تحديد مستوى التكبير حسب المسافة
                zoom_level = 12 if distance < 10 else (10 if distance < 50 else 8)
                
                # إنشاء الخريطة
                compare_map = folium.Map(
                    location=[center_lat, center_lon],
                    zoom_start=zoom_level,
                    attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                )
                
                # إضافة العلامات للموقعين
                folium.Marker(
                    location=[project_1["latitude"], project_1["longitude"]],
                    tooltip=project_1["name"],
                    icon=folium.Icon(color="blue", icon="info-sign")
                ).add_to(compare_map)
                
                folium.Marker(
                    location=[project_2["latitude"], project_2["longitude"]],
                    tooltip=project_2["name"],
                    icon=folium.Icon(color="red", icon="info-sign")
                ).add_to(compare_map)
                
                # إضافة خط يربط بين الموقعين
                folium.PolyLine(
                    locations=[
                        [project_1["latitude"], project_1["longitude"]],
                        [project_2["latitude"], project_2["longitude"]]
                    ],
                    color="green",
                    weight=3,
                    opacity=0.7,
                    tooltip=f"المسافة: {distance:.2f} كم"
                ).add_to(compare_map)
                
                # عرض الخريطة
                folium_static(compare_map, width=800, height=500)
                
                # عرض المسافة بين الموقعين
                st.markdown(f"#### المسافة بين الموقعين: {distance:.2f} كيلومتر")
                
                # مقارنة معلومات الموقعين
                st.markdown("#### مقارنة المعلومات الأساسية")
                
                # إنشاء جدول المقارنة
                comparison_data = {
                    "المعلومات": ["المدينة", "الحالة", "خط العرض", "خط الطول", "الوصف"],
                    project_1["name"]: [
                        project_1.get("city", ""),
                        project_1.get("status", ""),
                        f"{project_1['latitude']:.6f}",
                        f"{project_1['longitude']:.6f}",
                        project_1.get("description", "")
                    ],
                    project_2["name"]: [
                        project_2.get("city", ""),
                        project_2.get("status", ""),
                        f"{project_2['latitude']:.6f}",
                        f"{project_2['longitude']:.6f}",
                        project_2.get("description", "")
                    ]
                }
                
                comparison_df = pd.DataFrame(comparison_data)
                st.dataframe(comparison_df, width=800)
                
                # مقارنة العوامل البيئية والمكانية
                st.markdown("#### مقارنة العوامل")
                
                # بيانات افتراضية للعوامل - ستتغير هذه باستخدام بيانات حقيقية
                factors_comparison = {
                    "العامل": ["قرب المدينة", "توفر المياه", "سهولة الوصول", "الظروف الجوية", "التضاريس", "توفر العمالة", "البنية التحتية", "المخاطر البيئية"],
                    project_1["name"]: [random.uniform(0.4, 1.0) for _ in range(8)],
                    project_2["name"]: [random.uniform(0.4, 1.0) for _ in range(8)]
                }
                
                # تحويل إلى DataFrame
                factors_df = pd.DataFrame(factors_comparison)
                
                # رسم بياني شريطي للمقارنة
                st.bar_chart(factors_df.set_index("العامل"))
                
                # حساب إجمالي التقييم لكل موقع
                project_1_score = sum(factors_comparison[project_1["name"]]) / len(factors_comparison[project_1["name"]])
                project_2_score = sum(factors_comparison[project_2["name"]]) / len(factors_comparison[project_2["name"]])
                
                # عرض التقييم الإجمالي
                col1, col2 = st.columns(2)
                
                with col1:
                    st.markdown(f"##### تقييم {project_1['name']}: {project_1_score:.2f}/1.0")
                    st.progress(project_1_score)
                
                with col2:
                    st.markdown(f"##### تقييم {project_2['name']}: {project_2_score:.2f}/1.0")
                    st.progress(project_2_score)
                
                # تحديد الموقع المفضل
                preferred_site = project_1["name"] if project_1_score > project_2_score else project_2["name"]
                score_diff = abs(project_1_score - project_2_score)
                
                if score_diff < 0.1:
                    recommendation = "الموقعان متقاربان في التقييم ويمكن اعتبارهما متكافئين."
                    color = "blue"
                else:
                    recommendation = f"الموقع الأفضل هو: {preferred_site}"
                    color = "green"
                
                st.markdown(f"<h4 style='color: {color};'>{recommendation}</h4>", unsafe_allow_html=True)
                
                # تحليل التكلفة
                st.markdown("#### مقارنة تقديرات التكلفة")
                
                # بنود التكلفة الافتراضية
                cost_items = ["تسوية الأرض", "البنية التحتية", "النقل", "الحماية من المخاطر", "توصيل الخدمات"]
                
                site_1_costs = [random.uniform(50000, 200000) for _ in range(len(cost_items))]
                site_2_costs = [random.uniform(50000, 200000) for _ in range(len(cost_items))]
                
                # إنشاء DataFrame للتكاليف
                cost_df = pd.DataFrame({
                    "بند التكلفة": cost_items,
                    f"{project_1['name']} (ريال)": site_1_costs,
                    f"{project_2['name']} (ريال)": site_2_costs
                })
                
                # عرض جدول التكاليف
                st.dataframe(cost_df, width=800)
                
                # حساب إجمالي التكلفة لكل موقع
                total_cost_1 = sum(site_1_costs)
                total_cost_2 = sum(site_2_costs)
                
                # عرض إجمالي التكلفة
                col1, col2 = st.columns(2)
                
                with col1:
                    st.metric(
                        f"إجمالي تكلفة {project_1['name']}",
                        f"{format_currency(total_cost_1)} ريال"
                    )
                
                with col2:
                    st.metric(
                        f"إجمالي تكلفة {project_2['name']}",
                        f"{format_currency(total_cost_2)} ريال",
                        f"{format_currency(total_cost_2 - total_cost_1)}"
                    )
                
                # تحليل إضافي للمقارنة
                st.markdown("#### ملخص المقارنة")
                
                comparison_summary = f"""
                بناءً على التحليل المقدم، يمكن استخلاص الملاحظات التالية:
                
                1. **المسافة بين الموقعين:** {distance:.2f} كيلومتر.
                2. **التقييم:** {project_1['name']} بتقييم {project_1_score:.2f}/1.0، و{project_2['name']} بتقييم {project_2_score:.2f}/1.0.
                3. **التكلفة:** {project_1['name']} بتكلفة {format_currency(total_cost_1)} ريال، و{project_2['name']} بتكلفة {format_currency(total_cost_2)} ريال.
                
                بالنظر إلى العوامل أعلاه، فإن الموقع **{preferred_site}** هو الخيار الأفضل من حيث التوازن بين التقييم والتكلفة.
                """
                
                st.markdown(comparison_summary)
            else:
                st.error("لم يتم العثور على أحد المشروعين المحددين.")
    
    def _render_location_management(self):
        """عرض إدارة المواقع"""
        st.markdown("""
        <div class='custom-box info-box'>
            <h3>📍 إدارة مواقع المشاريع</h3>
            <p>إضافة وتعديل مواقع المشاريع وتصدير واستيراد البيانات.</p>
            <p>يمكنك إدخال مواقع المشاريع الجديدة وتعديل المواقع الموجودة وحذفها.</p>
        </div>
        """, unsafe_allow_html=True)
        
        # تبويبات فرعية للإدارة
        subtabs = st.tabs([
            "إضافة موقع جديد",
            "تحرير المواقع",
            "استيراد/تصدير المواقع"
        ])
        
        # تبويب إضافة موقع جديد
        with subtabs[0]:
            self._render_add_location()
            
        # تبويب تحرير المواقع
        with subtabs[1]:
            self._render_edit_locations()
            
        # تبويب استيراد/تصدير المواقع
        with subtabs[2]:
            self._render_import_export_locations()
    
    def _render_add_location(self):
        """عرض نموذج إضافة موقع جديد"""
        st.markdown("### إضافة موقع مشروع جديد")
        
        # نموذج إضافة موقع جديد
        with st.form(key="add_location_form"):
            # معلومات أساسية
            project_name = st.text_input("اسم المشروع", key="new_project_name")
            project_description = st.text_area("وصف المشروع", key="new_project_description")
            
            # معلومات الموقع
            col1, col2 = st.columns(2)
            
            with col1:
                city = st.text_input("المدينة", key="new_city")
                status = st.selectbox(
                    "حالة المشروع",
                    options=["مخطط", "قيد التنفيذ", "متوقف", "مكتمل"],
                    key="new_status"
                )
            
            with col2:
                latitude = st.number_input("خط العرض", value=24.7136, step=0.0001, format="%.6f", key="new_latitude")
                longitude = st.number_input("خط الطول", value=46.6753, step=0.0001, format="%.6f", key="new_longitude")
            
            # عرض الموقع على خريطة صغيرة
            mini_map = folium.Map(
                location=[latitude, longitude], 
                zoom_start=10,
                attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            )
            folium.Marker(location=[latitude, longitude], tooltip="الموقع المحدد").add_to(mini_map)
            folium_static(mini_map, width=700, height=300)
            
            # زر الإضافة
            submit_button = st.form_submit_button("إضافة الموقع")
        
        # معالجة النموذج عند الإرسال
        if submit_button:
            if not project_name:
                st.error("يرجى إدخال اسم المشروع.")
            else:
                # إنشاء معرف فريد للمشروع
                project_id = f"PRJ{len(st.session_state.project_locations) + 1:03d}"
                
                # إضافة المشروع الجديد
                new_project = {
                    "project_id": project_id,
                    "name": project_name,
                    "description": project_description,
                    "city": city,
                    "status": status,
                    "latitude": latitude,
                    "longitude": longitude
                }
                
                # إضافة المشروع إلى القائمة
                st.session_state.project_locations.append(new_project)
                
                # حفظ البيانات
                self._save_locations_data()
                
                # عرض رسالة نجاح
                st.success(f"تمت إضافة موقع المشروع '{project_name}' بنجاح.")
                
                # إعادة تحميل الصفحة
                st.rerun()
    
    def _render_edit_locations(self):
        """عرض واجهة تحرير المواقع الموجودة"""
        st.markdown("### تحرير مواقع المشاريع")
        
        if len(st.session_state.project_locations) == 0:
            st.warning("لا توجد مواقع مشاريع للتحرير. يرجى إضافة مواقع أولاً.")
            return
        
        # عرض قائمة المشاريع
        projects_df = pd.DataFrame(st.session_state.project_locations)
        
        # إعادة تسمية الأعمدة بالعربية
        renamed_columns = {
            "name": "اسم المشروع",
            "city": "المدينة",
            "status": "الحالة",
            "description": "الوصف",
            "project_id": "معرف المشروع",
            "latitude": "خط العرض",
            "longitude": "خط الطول"
        }
        
        # تحديد الأعمدة للعرض
        display_columns = ["project_id", "name", "city", "status"]
        
        # إنشاء جدول للعرض
        display_df = projects_df[display_columns].rename(columns=renamed_columns)
        
        # عرض الجدول
        st.dataframe(display_df, width=800, height=300)
        
        # اختيار مشروع للتحرير
        selected_project_id = st.selectbox(
            "اختر مشروعًا للتحرير",
            options=projects_df["project_id"].tolist(),
            format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
            key="edit_project_id"
        )
        
        # العثور على المشروع المحدد
        selected_project_index = next((i for i, p in enumerate(st.session_state.project_locations) if p["project_id"] == selected_project_id), None)
        
        if selected_project_index is not None:
            selected_project = st.session_state.project_locations[selected_project_index]
            
            # نموذج تحرير المشروع
            with st.form(key="edit_location_form"):
                st.markdown(f"### تحرير مشروع: {selected_project['name']}")
                
                # معلومات أساسية
                project_name = st.text_input("اسم المشروع", value=selected_project["name"], key="edit_project_name")
                project_description = st.text_area("وصف المشروع", value=selected_project.get("description", ""), key="edit_project_description")
                
                # معلومات الموقع
                col1, col2 = st.columns(2)
                
                with col1:
                    city = st.text_input("المدينة", value=selected_project.get("city", ""), key="edit_city")
                    status = st.selectbox(
                        "حالة المشروع",
                        options=["مخطط", "قيد التنفيذ", "متوقف", "مكتمل"],
                        index=["مخطط", "قيد التنفيذ", "متوقف", "مكتمل"].index(selected_project.get("status", "مخطط")),
                        key="edit_status"
                    )
                
                with col2:
                    latitude = st.number_input("خط العرض", value=selected_project["latitude"], step=0.0001, format="%.6f", key="edit_latitude")
                    longitude = st.number_input("خط الطول", value=selected_project["longitude"], step=0.0001, format="%.6f", key="edit_longitude")
                
                # عرض الموقع على خريطة صغيرة
                mini_map = folium.Map(
                    location=[latitude, longitude], 
                    zoom_start=10,
                    attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                )
                folium.Marker(location=[latitude, longitude], tooltip="الموقع المحدد").add_to(mini_map)
                folium_static(mini_map, width=700, height=300)
                
                # أزرار الإجراءات
                col1, col2 = st.columns(2)
                
                with col1:
                    update_button = st.form_submit_button("تحديث المعلومات")
                
                with col2:
                    delete_button = st.form_submit_button("حذف المشروع", type="secondary")
            
            # معالجة تحديث المعلومات
            if update_button:
                if not project_name:
                    st.error("لا يمكن ترك اسم المشروع فارغًا.")
                else:
                    # تحديث معلومات المشروع
                    st.session_state.project_locations[selected_project_index] = {
                        "project_id": selected_project["project_id"],
                        "name": project_name,
                        "description": project_description,
                        "city": city,
                        "status": status,
                        "latitude": latitude,
                        "longitude": longitude
                    }
                    
                    # حفظ البيانات
                    self._save_locations_data()
                    
                    # عرض رسالة نجاح
                    st.success(f"تم تحديث معلومات المشروع '{project_name}' بنجاح.")
                    
                    # إعادة تحميل الصفحة
                    st.rerun()
            
            # معالجة حذف المشروع
            if delete_button:
                # نافذة تأكيد الحذف
                st.warning(f"هل أنت متأكد من رغبتك في حذف المشروع '{selected_project['name']}'؟")
                
                confirm_col1, confirm_col2 = st.columns(2)
                
                with confirm_col1:
                    if st.button("نعم، حذف المشروع", key="confirm_delete"):
                        # حذف المشروع
                        st.session_state.project_locations.pop(selected_project_index)
                        
                        # حفظ البيانات
                        self._save_locations_data()
                        
                        # عرض رسالة نجاح
                        st.success(f"تم حذف المشروع '{selected_project['name']}' بنجاح.")
                        
                        # إعادة تحميل الصفحة
                        st.rerun()
                
                with confirm_col2:
                    if st.button("لا، إلغاء الحذف", key="cancel_delete"):
                        st.rerun()
        else:
            st.error("لم يتم العثور على المشروع المحدد.")
    
    def _render_import_export_locations(self):
        """عرض واجهة استيراد وتصدير المواقع"""
        st.markdown("### استيراد وتصدير مواقع المشاريع")
        
        # تبويبات فرعية للاستيراد والتصدير
        export_tab, import_tab = st.tabs(["تصدير المواقع", "استيراد المواقع"])
        
        # تبويب تصدير المواقع
        with export_tab:
            st.markdown("#### تصدير مواقع المشاريع")
            
            if len(st.session_state.project_locations) == 0:
                st.warning("لا توجد مواقع مشاريع للتصدير.")
            else:
                # اختيار تنسيق التصدير
                export_format = st.radio(
                    "اختر تنسيق التصدير",
                    options=["CSV", "Excel", "JSON"],
                    horizontal=True,
                    key="export_format"
                )
                
                # زر التصدير
                if styled_button("تصدير المواقع", key="export_btn", type="primary", icon="📤"):
                    # تصدير البيانات
                    exported_data = self._export_locations(export_format.lower())
                    
                    if exported_data:
                        # تحديد نوع الملف ومعلومات التنزيل
                        if export_format == "CSV":
                            mime_type = "text/csv"
                            file_ext = "csv"
                        elif export_format == "Excel":
                            mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            file_ext = "xlsx"
                        else:  # JSON
                            mime_type = "application/json"
                            file_ext = "json"
                        
                        # إنشاء رابط التنزيل
                        b64 = base64.b64encode(exported_data).decode()
                        href = f'<a href="data:{mime_type};base64,{b64}" download="project_locations.{file_ext}" class="btn">تنزيل ملف {export_format}</a>'
                        st.markdown(href, unsafe_allow_html=True)
                        
                        # عرض معاينة البيانات
                        if export_format == "CSV":
                            st.markdown("#### معاينة البيانات المصدرة")
                            st.text(exported_data.decode("utf-8"))
                        elif export_format == "JSON":
                            st.markdown("#### معاينة البيانات المصدرة")
                            st.json(json.loads(exported_data.decode("utf-8")))
        
        # تبويب استيراد المواقع
        with import_tab:
            st.markdown("#### استيراد مواقع المشاريع")
            
            # اختيار تنسيق الاستيراد
            import_format = st.radio(
                "اختر تنسيق الاستيراد",
                options=["CSV", "Excel", "JSON"],
                horizontal=True,
                key="import_format"
            )
            
            # تحميل الملف
            uploaded_file = st.file_uploader(f"تحميل ملف {import_format}", type=[import_format.lower()])
            
            if uploaded_file:
                # معاينة الملف
                st.markdown("#### معاينة الملف المحمل")
                
                if import_format == "CSV":
                    df = pd.read_csv(uploaded_file)
                    st.dataframe(df)
                elif import_format == "Excel":
                    df = pd.read_excel(uploaded_file)
                    st.dataframe(df)
                else:  # JSON
                    json_data = json.load(uploaded_file)
                    st.json(json_data)
                
                # خيارات الاستيراد
                import_mode = st.radio(
                    "طريقة الاستيراد",
                    options=["إضافة إلى المواقع الحالية", "استبدال جميع المواقع"],
                    key="import_mode"
                )
                
                # زر الاستيراد
                if styled_button("استيراد المواقع", key="import_btn", type="primary", icon="📥"):
                    # إعادة قراءة الملف (قد يكون تم استنفاد التدفق)
                    uploaded_file.seek(0)
                    
                    try:
                        # استيراد البيانات
                        imported_count = self._import_locations(uploaded_file, import_format.lower())
                        
                        if import_mode == "استبدال جميع المواقع":
                            st.success(f"تم استبدال جميع المواقع بنجاح. عدد المواقع الجديدة: {imported_count}")
                        else:
                            st.success(f"تمت إضافة {imported_count} مواقع جديدة بنجاح.")
                        
                        # إعادة تحميل الصفحة
                        st.rerun()
                    except Exception as e:
                        st.error(f"حدث خطأ أثناء استيراد البيانات: {str(e)}")
    
    def _fetch_terrain_data(self, latitude, longitude, radius_km=5):
        """جلب بيانات التضاريس من واجهة برمجة التطبيقات"""
        # حساب نطاق الإحداثيات
        # 1 درجة تقريبًا = 111 كم
        delta = radius_km / 111.0
        
        # إنشاء شبكة نقاط
        lat_min, lat_max = latitude - delta, latitude + delta
        lon_min, lon_max = longitude - delta, longitude + delta
        
        # عدد نقاط الشبكة
        grid_size = 20
        
        # إنشاء شبكة إحداثيات
        lats = np.linspace(lat_min, lat_max, grid_size)
        lons = np.linspace(lon_min, lon_max, grid_size)
        
        # تهيئة مصفوفة النتائج
        results = []
        
        # بناء سلسلة الإحداثيات للطلب
        locations = []
        for lat in lats:
            for lon in lons:
                locations.append(f"{lat:.6f},{lon:.6f}")
        
        # تقسيم الطلبات إلى مجموعات (واجهة البرمجة تقبل 100 نقطة كحد أقصى)
        batch_size = 100
        for i in range(0, len(locations), batch_size):
            batch = locations[i:i+batch_size]
            
            # محاولة استخدام خدمة OpenTopoData
            try:
                url = f"{self.opentopodata_api}?locations={'|'.join(batch)}"
                response = requests.get(url)
                
                if response.status_code == 200:
                    data = response.json()
                    if "results" in data:
                        for result in data["results"]:
                            if "elevation" in result:
                                results.append({
                                    "latitude": result["location"]["lat"],
                                    "longitude": result["location"]["lng"],
                                    "elevation": result["elevation"]
                                })
                else:
                    # استخدام بيانات افتراضية في حالة فشل الطلب
                    st.warning(f"فشل جلب بيانات التضاريس من الخدمة (رمز الحالة: {response.status_code}). استخدام بيانات افتراضية.")
                    
                    # إنشاء بيانات افتراضية
                    for j, loc in enumerate(batch):
                        lat, lon = map(float, loc.split(","))
                        # حساب ارتفاع افتراضي بناءً على المسافة من المركز
                        dist = self._calculate_distance(latitude, longitude, lat, lon)
                        # إضافة ضوضاء عشوائية للحصول على تضاريس أكثر واقعية
                        noise = np.sin(lat * 10) * np.cos(lon * 10) * 50
                        elevation = 500 - dist * 100 + noise
                        
                        results.append({
                            "latitude": lat,
                            "longitude": lon,
                            "elevation": max(0, elevation)
                        })
            except Exception as e:
                st.warning(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}. استخدام بيانات افتراضية.")
                
                # إنشاء بيانات افتراضية
                for j, loc in enumerate(batch):
                    lat, lon = map(float, loc.split(","))
                    # حساب ارتفاع افتراضي بناءً على المسافة من المركز
                    dist = self._calculate_distance(latitude, longitude, lat, lon)
                    # إضافة ضوضاء عشوائية للحصول على تضاريس أكثر واقعية
                    noise = np.sin(lat * 10) * np.cos(lon * 10) * 50
                    elevation = 500 - dist * 100 + noise
                    
                    results.append({
                        "latitude": lat,
                        "longitude": lon,
                        "elevation": max(0, elevation)
                    })
        
        return results
    
    def _calculate_distance(self, lat1, lon1, lat2, lon2):
        """حساب المسافة بين نقطتين بالكيلومترات باستخدام صيغة هافرساين"""
        from math import radians, sin, cos, sqrt, atan2
        
        # تحويل الإحداثيات إلى راديان
        lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
        
        # صيغة هافرساين
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
        c = 2 * atan2(sqrt(a), sqrt(1-a))
        distance = 6371 * c  # نصف قطر الأرض بالكيلومترات
        
        return distance
    
    def _get_color_map(self, scheme):
        """الحصول على خريطة الألوان حسب النظام المختار"""
        import matplotlib.cm as cm
        import matplotlib.colors as colors
        
        # الحصول على خريطة الألوان
        colormap = cm.get_cmap(scheme)
        
        # إرجاع دالة لتطبيق خريطة الألوان
        return lambda x: colors.rgb2hex(colormap(x))
    
    def _export_locations(self, format):
        """تصدير مواقع المشاريع إلى ملف"""
        try:
            # تحويل البيانات إلى DataFrame
            df = pd.DataFrame(st.session_state.project_locations)
            
            # تصدير البيانات حسب التنسيق المطلوب
            if format == "csv":
                csv_data = df.to_csv(index=False).encode("utf-8")
                return csv_data
            elif format == "excel":
                # إنشاء ملف إكسل مؤقت
                with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as temp:
                    df.to_excel(temp.name, index=False, engine="xlsxwriter")
                    temp.flush()
                    
                    # قراءة الملف كبيانات ثنائية
                    with open(temp.name, "rb") as f:
                        excel_data = f.read()
                    
                    # حذف الملف المؤقت
                    os.unlink(temp.name)
                    
                    return excel_data
            elif format == "json":
                json_data = json.dumps(st.session_state.project_locations, ensure_ascii=False, indent=4).encode("utf-8")
                return json_data
            else:
                st.error(f"تنسيق غير مدعوم: {format}")
                return None
        except Exception as e:
            st.error(f"حدث خطأ أثناء تصدير البيانات: {str(e)}")
            return None
    
    def _import_locations(self, uploaded_file, format):
        """استيراد مواقع المشاريع من ملف"""
        try:
            imported_data = []
            
            # تحميل البيانات حسب التنسيق
            if format == "csv":
                df = pd.read_csv(uploaded_file)
                imported_data = df.to_dict("records")
            elif format == "excel":
                df = pd.read_excel(uploaded_file)
                imported_data = df.to_dict("records")
            elif format == "json":
                imported_data = json.load(uploaded_file)
            else:
                raise ValueError(f"تنسيق غير مدعوم: {format}")
            
            # التحقق من صحة البيانات
            required_fields = ["project_id", "name", "latitude", "longitude"]
            
            for item in imported_data:
                missing_fields = [field for field in required_fields if field not in item]
                
                if missing_fields:
                    raise ValueError(f"الحقول المطلوبة مفقودة: {', '.join(missing_fields)}")
            
            # تحديث البيانات
            if "import_mode" in st.session_state and st.session_state.import_mode == "استبدال جميع المواقع":
                # استبدال جميع البيانات
                st.session_state.project_locations = imported_data
            else:
                # إضافة البيانات الجديدة فقط
                existing_ids = {p["project_id"] for p in st.session_state.project_locations}
                new_items = [item for item in imported_data if item["project_id"] not in existing_ids]
                st.session_state.project_locations.extend(new_items)
                imported_data = new_items
            
            # حفظ البيانات
            self._save_locations_data()
            
            return len(imported_data)
        except Exception as e:
            raise Exception(f"حدث خطأ أثناء استيراد البيانات: {str(e)}")
    
    def _save_locations_data(self):
        """حفظ بيانات المواقع"""
        try:
            # إنشاء مسار الملف
            file_path = os.path.join(self.data_dir, "project_locations.json")
            
            # حفظ البيانات كملف JSON
            with open(file_path, "w", encoding="utf-8") as f:
                json.dump(st.session_state.project_locations, f, ensure_ascii=False, indent=4)
        except Exception as e:
            st.error(f"حدث خطأ أثناء حفظ بيانات المواقع: {str(e)}")
    
    def _load_locations_data(self):
        """تحميل بيانات المواقع"""
        try:
            # إنشاء مسار الملف
            file_path = os.path.join(self.data_dir, "project_locations.json")
            
            # التحقق من وجود الملف
            if os.path.exists(file_path):
                # تحميل البيانات من ملف JSON
                with open(file_path, "r", encoding="utf-8") as f:
                    st.session_state.project_locations = json.load(f)
            else:
                # تهيئة بيانات اختبارية
                self._initialize_sample_projects()
        except Exception as e:
            st.error(f"حدث خطأ أثناء تحميل بيانات المواقع: {str(e)}")
            # تهيئة بيانات اختبارية
            self._initialize_sample_projects()
    
    def _initialize_sample_projects(self):
        """تهيئة بيانات اختبارية للمشاريع"""
        # قائمة بأسماء مدن المملكة العربية السعودية
        saudi_cities = [
            {"name": "الرياض", "lat": 24.7136, "lon": 46.6753},
            {"name": "جدة", "lat": 21.4858, "lon": 39.1925},
            {"name": "مكة المكرمة", "lat": 21.3891, "lon": 39.8579},
            {"name": "المدينة المنورة", "lat": 24.5247, "lon": 39.5692},
            {"name": "الدمام", "lat": 26.4207, "lon": 50.0888},
            {"name": "الطائف", "lat": 21.2704, "lon": 40.4157},
            {"name": "تبوك", "lat": 28.3835, "lon": 36.5662},
            {"name": "بريدة", "lat": 26.3267, "lon": 43.9717},
            {"name": "الخبر", "lat": 26.2172, "lon": 50.1971},
            {"name": "أبها", "lat": 18.2164, "lon": 42.5053}
        ]
        
        # قائمة بأنواع المشاريع
        project_types = [
            "إنشاء مبنى سكني",
            "تطوير طريق سريع",
            "بناء جسر",
            "إنشاء مدرسة",
            "تطوير حديقة عامة",
            "بناء مستشفى",
            "إنشاء محطة تحلية مياه",
            "تطوير مركز تجاري",
            "بناء مصنع",
            "توسعة مطار"
        ]
        
        # قائمة بحالات المشاريع
        project_statuses = ["مخطط", "قيد التنفيذ", "متوقف", "مكتمل"]
        
        # إنشاء مشاريع اختبارية
        sample_projects = []
        
        for i in range(10):
            city = saudi_cities[i]
            
            # إضافة اختلاف عشوائي صغير للإحداثيات
            lat_offset = random.uniform(-0.05, 0.05)
            lon_offset = random.uniform(-0.05, 0.05)
            
            project = {
                "project_id": f"PRJ{i+1:03d}",
                "name": f"{project_types[i]} في {city['name']}",
                "description": f"مشروع {project_types[i]} بمدينة {city['name']}. هذا وصف اختباري للمشروع يوضح تفاصيله وأهدافه ونطاق العمل.",
                "city": city["name"],
                "status": random.choice(project_statuses),
                "latitude": city["lat"] + lat_offset,
                "longitude": city["lon"] + lon_offset
            }
            
            sample_projects.append(project)
        
        # حفظ المشاريع الاختبارية في حالة الجلسة
        st.session_state.project_locations = sample_projects


if __name__ == "__main__":
    """تشغيل وحدة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد بشكل مستقل"""
    interactive_map = InteractiveMap()
    interactive_map.render()