oxigdal-mobile 0.1.4

Mobile FFI bindings for OxiGDAL - iOS and Android support for Pure Rust geospatial library
Documentation
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
//! iOS-specific vector operations.
//!
//! Provides MapKit and CoreLocation integration for vector data.

#![cfg(feature = "ios")]

use crate::ffi::types::*;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_double, c_int};
use std::ptr;
use std::sync::Mutex;

// ============================================================================
// Internal Data Structures
// ============================================================================

/// Internal representation of a geometry for iOS.
#[derive(Debug, Clone)]
pub struct IosGeometry {
    /// Geometry type (Point, LineString, Polygon, etc.)
    pub geometry_type: GeometryType,
    /// Coordinates (lon, lat pairs for 2D)
    pub coordinates: Vec<(f64, f64)>,
    /// Rings for polygons (indices into coordinates)
    pub rings: Vec<usize>,
}

/// Geometry type enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum GeometryType {
    /// Unknown type
    Unknown = 0,
    /// Point geometry
    Point = 1,
    /// LineString geometry
    LineString = 2,
    /// Polygon geometry
    Polygon = 3,
    /// MultiPoint geometry
    MultiPoint = 4,
    /// MultiLineString geometry
    MultiLineString = 5,
    /// MultiPolygon geometry
    MultiPolygon = 6,
}

/// Internal feature representation with properties.
#[derive(Debug, Clone)]
pub struct IosFeature {
    /// Feature ID
    pub fid: i64,
    /// Geometry
    pub geometry: Option<IosGeometry>,
    /// Properties as string key-value pairs
    pub properties: HashMap<String, String>,
    /// Bounding box (min_x, min_y, max_x, max_y)
    pub bbox: Option<(f64, f64, f64, f64)>,
}

/// Internal layer representation with features and spatial index.
#[derive(Debug)]
pub struct IosVectorLayer {
    /// Layer name
    pub name: String,
    /// Features in the layer
    pub features: Vec<IosFeature>,
    /// Spatial index (R-tree nodes)
    pub spatial_index: Option<RTreeIndex>,
    /// Layer bounding box
    pub bbox: Option<OxiGdalBbox>,
}

// ============================================================================
// MapKit Overlay Representations
// ============================================================================

/// MapKit overlay data for iOS rendering.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct MapKitOverlayData {
    /// Overlay type
    pub overlay_type: MapKitOverlayType,
    /// Number of coordinates
    pub coord_count: c_int,
    /// Pointer to coordinates (lon, lat pairs)
    pub coordinates: *mut c_double,
    /// Number of rings (for polygons)
    pub ring_count: c_int,
    /// Ring start indices (for polygons)
    pub ring_starts: *mut c_int,
}

/// MapKit overlay types.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapKitOverlayType {
    /// MKPointAnnotation
    Annotation = 0,
    /// MKPolyline
    Polyline = 1,
    /// MKPolygon
    Polygon = 2,
    /// MKCircle
    Circle = 3,
}

// ============================================================================
// R-Tree Spatial Index Implementation
// ============================================================================

/// Rectangle for R-tree bounding boxes.
#[derive(Debug, Clone, Copy)]
pub struct Rect {
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
}

impl Rect {
    /// Creates a new rectangle.
    fn new(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Self {
        Self {
            min_x,
            min_y,
            max_x,
            max_y,
        }
    }

    /// Checks if two rectangles intersect.
    fn intersects(&self, other: &Rect) -> bool {
        self.min_x <= other.max_x
            && self.max_x >= other.min_x
            && self.min_y <= other.max_y
            && self.max_y >= other.min_y
    }

    /// Computes the area of the rectangle.
    fn area(&self) -> f64 {
        (self.max_x - self.min_x) * (self.max_y - self.min_y)
    }

    /// Returns the union of two rectangles.
    fn union(&self, other: &Rect) -> Rect {
        Rect {
            min_x: self.min_x.min(other.min_x),
            min_y: self.min_y.min(other.min_y),
            max_x: self.max_x.max(other.max_x),
            max_y: self.max_y.max(other.max_y),
        }
    }

    /// Computes the enlargement needed to include another rectangle.
    fn enlargement(&self, other: &Rect) -> f64 {
        self.union(other).area() - self.area()
    }
}

/// R-tree node.
#[derive(Debug, Clone)]
pub struct RTreeNode {
    /// Bounding box of this node
    bbox: Rect,
    /// Child indices (for internal nodes) or feature indices (for leaf nodes)
    children: Vec<usize>,
    /// Is this a leaf node?
    is_leaf: bool,
}

/// R-tree spatial index.
#[derive(Debug)]
pub struct RTreeIndex {
    /// All nodes in the tree
    nodes: Vec<RTreeNode>,
    /// Root node index
    root: usize,
    /// Maximum entries per node
    max_entries: usize,
    /// Minimum entries per node
    _min_entries: usize,
    /// Feature bounding boxes (indexed by feature index)
    feature_bboxes: Vec<Rect>,
}

impl RTreeIndex {
    /// Creates a new R-tree index.
    fn new() -> Self {
        let root_node = RTreeNode {
            bbox: Rect::new(0.0, 0.0, 0.0, 0.0),
            children: Vec::new(),
            is_leaf: true,
        };

        Self {
            nodes: vec![root_node],
            root: 0,
            max_entries: 10,
            _min_entries: 4,
            feature_bboxes: Vec::new(),
        }
    }

    /// Inserts a feature with its bounding box.
    fn insert(&mut self, feature_idx: usize, bbox: Rect) {
        self.feature_bboxes.push(bbox);
        let feature_bbox_idx = self.feature_bboxes.len() - 1;

        if self.nodes[self.root].children.is_empty() {
            // First insertion - update root bbox
            self.nodes[self.root].bbox = bbox;
            self.nodes[self.root].children.push(feature_idx);
        } else {
            // Find the best leaf node and insert
            let leaf_idx = self.choose_leaf(self.root, &bbox);
            self.nodes[leaf_idx].children.push(feature_idx);
            self.nodes[leaf_idx].bbox = self.nodes[leaf_idx].bbox.union(&bbox);

            // Handle node overflow
            if self.nodes[leaf_idx].children.len() > self.max_entries {
                self.split_node(leaf_idx);
            }

            // Update root bounding box
            self.update_bbox(self.root);
        }
    }

    /// Chooses the best leaf node for insertion.
    fn choose_leaf(&self, node_idx: usize, bbox: &Rect) -> usize {
        let node = &self.nodes[node_idx];

        if node.is_leaf {
            return node_idx;
        }

        // Find child with minimum enlargement
        let mut best_child = 0;
        let mut min_enlargement = f64::INFINITY;
        let mut min_area = f64::INFINITY;

        for &child_idx in &node.children {
            if child_idx >= self.nodes.len() {
                continue;
            }
            let child_bbox = &self.nodes[child_idx].bbox;
            let enlargement = child_bbox.enlargement(bbox);

            if enlargement < min_enlargement
                || (enlargement == min_enlargement && child_bbox.area() < min_area)
            {
                min_enlargement = enlargement;
                min_area = child_bbox.area();
                best_child = child_idx;
            }
        }

        self.choose_leaf(best_child, bbox)
    }

    /// Splits an overflowed node.
    fn split_node(&mut self, node_idx: usize) {
        // Simple split: divide children into two groups
        let children = std::mem::take(&mut self.nodes[node_idx].children);
        let mid = children.len() / 2;

        let (left_children, right_children) = children.split_at(mid);
        self.nodes[node_idx].children = left_children.to_vec();

        // Create new node with right half
        let new_node = RTreeNode {
            bbox: Rect::new(0.0, 0.0, 0.0, 0.0),
            children: right_children.to_vec(),
            is_leaf: self.nodes[node_idx].is_leaf,
        };
        let new_node_idx = self.nodes.len();
        self.nodes.push(new_node);

        // Update bounding boxes
        self.update_bbox(node_idx);
        self.update_bbox(new_node_idx);

        // If we split the root, create a new root
        if node_idx == self.root {
            let new_root = RTreeNode {
                bbox: self.nodes[node_idx]
                    .bbox
                    .union(&self.nodes[new_node_idx].bbox),
                children: vec![node_idx, new_node_idx],
                is_leaf: false,
            };
            self.root = self.nodes.len();
            self.nodes.push(new_root);
        }
    }

    /// Updates the bounding box of a node based on its children.
    fn update_bbox(&mut self, node_idx: usize) {
        let node = &self.nodes[node_idx];
        if node.children.is_empty() {
            return;
        }

        let mut bbox = if node.is_leaf {
            // For leaf nodes, children are feature indices
            if let Some(&first_child) = node.children.first() {
                if first_child < self.feature_bboxes.len() {
                    self.feature_bboxes[first_child]
                } else {
                    return;
                }
            } else {
                return;
            }
        } else {
            // For internal nodes, children are node indices
            if let Some(&first_child) = node.children.first() {
                if first_child < self.nodes.len() {
                    self.nodes[first_child].bbox
                } else {
                    return;
                }
            } else {
                return;
            }
        };

        for &child_idx in node.children.iter().skip(1) {
            if node.is_leaf {
                if child_idx < self.feature_bboxes.len() {
                    bbox = bbox.union(&self.feature_bboxes[child_idx]);
                }
            } else if child_idx < self.nodes.len() {
                bbox = bbox.union(&self.nodes[child_idx].bbox);
            }
        }

        self.nodes[node_idx].bbox = bbox;
    }

    /// Searches for features intersecting the given bounding box.
    fn search(&self, bbox: &Rect) -> Vec<usize> {
        let mut results = Vec::new();
        self.search_node(self.root, bbox, &mut results);
        results
    }

    /// Recursively searches a node.
    fn search_node(&self, node_idx: usize, bbox: &Rect, results: &mut Vec<usize>) {
        if node_idx >= self.nodes.len() {
            return;
        }

        let node = &self.nodes[node_idx];
        if !node.bbox.intersects(bbox) {
            return;
        }

        if node.is_leaf {
            for &child_idx in &node.children {
                if child_idx < self.feature_bboxes.len()
                    && self.feature_bboxes[child_idx].intersects(bbox)
                {
                    results.push(child_idx);
                }
            }
        } else {
            for &child_idx in &node.children {
                self.search_node(child_idx, bbox, results);
            }
        }
    }
}

// ============================================================================
// Douglas-Peucker Line Simplification
// ============================================================================

/// Computes the perpendicular distance from a point to a line segment.
fn perpendicular_distance(point: (f64, f64), line_start: (f64, f64), line_end: (f64, f64)) -> f64 {
    let dx = line_end.0 - line_start.0;
    let dy = line_end.1 - line_start.1;

    let line_length_sq = dx * dx + dy * dy;

    if line_length_sq < f64::EPSILON {
        // Line segment is essentially a point
        let pdx = point.0 - line_start.0;
        let pdy = point.1 - line_start.1;
        return (pdx * pdx + pdy * pdy).sqrt();
    }

    // Compute the perpendicular distance
    let t = ((point.0 - line_start.0) * dx + (point.1 - line_start.1) * dy) / line_length_sq;
    let t_clamped = t.clamp(0.0, 1.0);

    let closest_x = line_start.0 + t_clamped * dx;
    let closest_y = line_start.1 + t_clamped * dy;

    let dist_x = point.0 - closest_x;
    let dist_y = point.1 - closest_y;

    (dist_x * dist_x + dist_y * dist_y).sqrt()
}

/// Douglas-Peucker line simplification algorithm.
fn douglas_peucker(points: &[(f64, f64)], epsilon: f64) -> Vec<(f64, f64)> {
    if points.len() < 3 {
        return points.to_vec();
    }

    let mut result = Vec::new();
    douglas_peucker_recursive(points, epsilon, &mut result);

    // Always include the last point
    if let Some(&last) = points.last() {
        result.push(last);
    }

    result
}

/// Recursive helper for Douglas-Peucker algorithm.
fn douglas_peucker_recursive(points: &[(f64, f64)], epsilon: f64, result: &mut Vec<(f64, f64)>) {
    if points.len() < 2 {
        if let Some(&first) = points.first() {
            result.push(first);
        }
        return;
    }

    let first = points[0];
    let last = points[points.len() - 1];

    // Find the point with maximum distance
    let mut max_dist = 0.0;
    let mut max_idx = 0;

    for (i, &point) in points.iter().enumerate().skip(1).take(points.len() - 2) {
        let dist = perpendicular_distance(point, first, last);
        if dist > max_dist {
            max_dist = dist;
            max_idx = i;
        }
    }

    if max_dist > epsilon {
        // Recursively simplify both halves
        douglas_peucker_recursive(&points[..=max_idx], epsilon, result);
        douglas_peucker_recursive(&points[max_idx..], epsilon, result);
    } else {
        // Keep only the first point
        result.push(first);
    }
}

/// Calculates simplification tolerance based on zoom level.
fn tolerance_for_zoom(zoom: c_int) -> f64 {
    // At zoom 0, use large tolerance (~1 degree)
    // At zoom 20, use small tolerance (~0.00001 degrees)
    // Tolerance halves with each zoom level
    let base_tolerance = 1.0;
    base_tolerance / (1 << zoom.clamp(0, 20)) as f64
}

/// Simplifies a geometry for display at a given zoom level.
fn simplify_geometry(geometry: &IosGeometry, zoom: c_int) -> IosGeometry {
    let tolerance = tolerance_for_zoom(zoom);

    let simplified_coords = match geometry.geometry_type {
        GeometryType::Point => geometry.coordinates.clone(),
        GeometryType::LineString => douglas_peucker(&geometry.coordinates, tolerance),
        GeometryType::Polygon => {
            // Simplify each ring separately
            let mut result = Vec::new();
            let mut prev_ring_start = 0;
            let mut new_rings = Vec::new();

            for (ring_idx, &ring_end) in geometry.rings.iter().enumerate() {
                let ring_coords = &geometry.coordinates[prev_ring_start..ring_end];
                let simplified_ring = douglas_peucker(ring_coords, tolerance);

                // Ensure ring has at least 4 points (closed polygon)
                if simplified_ring.len() >= 3 {
                    result.extend(simplified_ring);
                    // Close the ring if not already closed
                    if let (Some(&first), Some(&last)) = (result.first(), result.last()) {
                        if (first.0 - last.0).abs() > f64::EPSILON
                            || (first.1 - last.1).abs() > f64::EPSILON
                        {
                            result.push(first);
                        }
                    }
                    new_rings.push(result.len());
                }

                prev_ring_start = ring_end;
            }

            result
        }
        _ => geometry.coordinates.clone(),
    };

    IosGeometry {
        geometry_type: geometry.geometry_type,
        coordinates: simplified_coords,
        rings: geometry.rings.clone(),
    }
}

// ============================================================================
// GeoJSON Parsing
// ============================================================================

/// Parses a GeoJSON file and returns features.
fn parse_geojson(json_str: &str) -> Result<Vec<IosFeature>, String> {
    let value: serde_json::Value =
        serde_json::from_str(json_str).map_err(|e| format!("JSON parse error: {}", e))?;

    let mut features = Vec::new();

    match value.get("type").and_then(|v| v.as_str()) {
        Some("FeatureCollection") => {
            if let Some(feature_array) = value.get("features").and_then(|v| v.as_array()) {
                for (idx, feature_value) in feature_array.iter().enumerate() {
                    if let Some(feature) = parse_geojson_feature(feature_value, idx as i64) {
                        features.push(feature);
                    }
                }
            }
        }
        Some("Feature") => {
            if let Some(feature) = parse_geojson_feature(&value, 0) {
                features.push(feature);
            }
        }
        Some(geom_type) => {
            // Single geometry
            if let Some(geometry) = parse_geojson_geometry(&value) {
                features.push(IosFeature {
                    fid: 0,
                    geometry: Some(geometry),
                    properties: HashMap::new(),
                    bbox: None,
                });
            }
        }
        None => return Err("Missing 'type' field in GeoJSON".to_string()),
    }

    // Calculate bounding boxes for all features
    for feature in &mut features {
        if let Some(ref geom) = feature.geometry {
            feature.bbox = compute_bbox(&geom.coordinates);
        }
    }

    Ok(features)
}

/// Parses a single GeoJSON feature.
fn parse_geojson_feature(value: &serde_json::Value, default_fid: i64) -> Option<IosFeature> {
    let geometry = value.get("geometry").and_then(parse_geojson_geometry);

    let mut properties = HashMap::new();
    if let Some(props) = value.get("properties").and_then(|v| v.as_object()) {
        for (key, val) in props {
            let string_val = match val {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                serde_json::Value::Null => "null".to_string(),
                _ => val.to_string(),
            };
            properties.insert(key.clone(), string_val);
        }
    }

    let fid = value
        .get("id")
        .and_then(|v| v.as_i64())
        .unwrap_or(default_fid);

    Some(IosFeature {
        fid,
        geometry,
        properties,
        bbox: None,
    })
}

/// Parses a GeoJSON geometry.
fn parse_geojson_geometry(value: &serde_json::Value) -> Option<IosGeometry> {
    let geom_type = value.get("type").and_then(|v| v.as_str())?;
    let coords = value.get("coordinates")?;

    match geom_type {
        "Point" => {
            let coord = parse_coordinate(coords)?;
            Some(IosGeometry {
                geometry_type: GeometryType::Point,
                coordinates: vec![coord],
                rings: vec![],
            })
        }
        "LineString" => {
            let coordinates = parse_coordinate_array(coords)?;
            Some(IosGeometry {
                geometry_type: GeometryType::LineString,
                coordinates,
                rings: vec![],
            })
        }
        "Polygon" => {
            let rings_array = coords.as_array()?;
            let mut coordinates = Vec::new();
            let mut rings = Vec::new();

            for ring in rings_array {
                let ring_coords = parse_coordinate_array(ring)?;
                coordinates.extend(ring_coords);
                rings.push(coordinates.len());
            }

            Some(IosGeometry {
                geometry_type: GeometryType::Polygon,
                coordinates,
                rings,
            })
        }
        "MultiPoint" => {
            let coordinates = parse_coordinate_array(coords)?;
            Some(IosGeometry {
                geometry_type: GeometryType::MultiPoint,
                coordinates,
                rings: vec![],
            })
        }
        "MultiLineString" => {
            let lines_array = coords.as_array()?;
            let mut coordinates = Vec::new();
            let mut rings = Vec::new();

            for line in lines_array {
                let line_coords = parse_coordinate_array(line)?;
                coordinates.extend(line_coords);
                rings.push(coordinates.len());
            }

            Some(IosGeometry {
                geometry_type: GeometryType::MultiLineString,
                coordinates,
                rings,
            })
        }
        "MultiPolygon" => {
            let polygons_array = coords.as_array()?;
            let mut coordinates = Vec::new();
            let mut rings = Vec::new();

            for polygon in polygons_array {
                let rings_array = polygon.as_array()?;
                for ring in rings_array {
                    let ring_coords = parse_coordinate_array(ring)?;
                    coordinates.extend(ring_coords);
                    rings.push(coordinates.len());
                }
            }

            Some(IosGeometry {
                geometry_type: GeometryType::MultiPolygon,
                coordinates,
                rings,
            })
        }
        _ => None,
    }
}

/// Parses a single coordinate.
fn parse_coordinate(value: &serde_json::Value) -> Option<(f64, f64)> {
    let arr = value.as_array()?;
    if arr.len() < 2 {
        return None;
    }
    let x = arr.get(0)?.as_f64()?;
    let y = arr.get(1)?.as_f64()?;
    Some((x, y))
}

/// Parses an array of coordinates.
fn parse_coordinate_array(value: &serde_json::Value) -> Option<Vec<(f64, f64)>> {
    let arr = value.as_array()?;
    let mut coordinates = Vec::with_capacity(arr.len());

    for coord in arr {
        coordinates.push(parse_coordinate(coord)?);
    }

    Some(coordinates)
}

/// Computes the bounding box of a set of coordinates.
fn compute_bbox(coords: &[(f64, f64)]) -> Option<(f64, f64, f64, f64)> {
    if coords.is_empty() {
        return None;
    }

    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;

    for &(x, y) in coords {
        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x);
        max_y = max_y.max(y);
    }

    Some((min_x, min_y, max_x, max_y))
}

// ============================================================================
// Global Layer Storage (for FFI)
// ============================================================================

static LAYERS: Mutex<Vec<IosVectorLayer>> = Mutex::new(Vec::new());

/// Stores a layer and returns its handle.
fn store_layer(layer: IosVectorLayer) -> Option<*mut OxiGdalLayer> {
    let mut layers = LAYERS.lock().ok()?;
    let idx = layers.len();
    layers.push(layer);
    // Return index as a pointer (will be cast back)
    Some((idx + 1) as *mut OxiGdalLayer)
}

/// Retrieves a layer by handle.
#[allow(dead_code)]
fn get_layer(
    handle: *const OxiGdalLayer,
) -> Option<std::sync::MutexGuard<'static, Vec<IosVectorLayer>>> {
    let layers = LAYERS.lock().ok()?;
    let idx = (handle as usize).checked_sub(1)?;
    if idx < layers.len() {
        Some(layers)
    } else {
        None
    }
}

/// Gets the layer index from a handle.
fn handle_to_index(handle: *const OxiGdalLayer) -> Option<usize> {
    (handle as usize).checked_sub(1)
}

// ============================================================================
// FFI Functions
// ============================================================================

/// Converts vector layer to iOS MapKit annotations.
///
/// # Parameters
/// - `layer`: Vector layer handle
/// - `out_coords`: Array to receive coordinate pairs (lon, lat)
/// - `max_coords`: Maximum number of coordinates to return
///
/// # Returns
/// Number of coordinates written, or -1 on error
///
/// # Safety
/// - layer must be valid
/// - out_coords must be pre-allocated with size >= max_coords * 2
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_layer_to_annotations(
    layer: *const OxiGdalLayer,
    out_coords: *mut c_double,
    max_coords: c_int,
) -> c_int {
    if layer.is_null() || out_coords.is_null() || max_coords <= 0 {
        crate::ffi::error::set_last_error("Invalid parameters".to_string());
        return -1;
    }

    let idx = match handle_to_index(layer) {
        Some(i) => i,
        None => {
            crate::ffi::error::set_last_error("Invalid layer handle".to_string());
            return -1;
        }
    };

    let layers = match LAYERS.lock() {
        Ok(l) => l,
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to acquire lock".to_string());
            return -1;
        }
    };

    if idx >= layers.len() {
        crate::ffi::error::set_last_error("Layer not found".to_string());
        return -1;
    }

    let layer_data = &layers[idx];
    let mut written = 0;
    let max_coords = max_coords as usize;

    for feature in &layer_data.features {
        if let Some(ref geom) = feature.geometry {
            for &(lon, lat) in &geom.coordinates {
                if written >= max_coords {
                    break;
                }
                unsafe {
                    *out_coords.add(written * 2) = lon;
                    *out_coords.add(written * 2 + 1) = lat;
                }
                written += 1;
            }
        }
        if written >= max_coords {
            break;
        }
    }

    written as c_int
}

/// Checks if a point is within iOS MapKit visible region.
///
/// # Parameters
/// - `point`: Point to check
/// - `bbox`: Visible bounding box
///
/// # Returns
/// - 1 if point is visible
/// - 0 if not visible or on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_point_in_visible_region(
    point: *const OxiGdalPoint,
    bbox: *const OxiGdalBbox,
) -> c_int {
    if point.is_null() || bbox.is_null() {
        return 0;
    }

    let pt = unsafe { &*point };
    let bb = unsafe { &*bbox };

    if pt.x >= bb.min_x && pt.x <= bb.max_x && pt.y >= bb.min_y && pt.y <= bb.max_y {
        1
    } else {
        0
    }
}

/// Converts GeoJSON to iOS-compatible format.
///
/// # Parameters
/// - `geojson_path`: Path to GeoJSON file
/// - `out_layer`: Output layer handle
///
/// # Safety
/// - geojson_path must be valid null-terminated string
/// - out_layer must be valid pointer
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_load_geojson(
    geojson_path: *const c_char,
    out_layer: *mut *mut OxiGdalLayer,
) -> OxiGdalErrorCode {
    if geojson_path.is_null() || out_layer.is_null() {
        crate::ffi::error::set_last_error("Null pointer provided".to_string());
        return OxiGdalErrorCode::NullPointer;
    }

    // Convert path to Rust string
    let path = match unsafe { CStr::from_ptr(geojson_path) }.to_str() {
        Ok(s) => s,
        Err(_) => {
            crate::ffi::error::set_last_error("Invalid UTF-8 in path".to_string());
            return OxiGdalErrorCode::InvalidUtf8;
        }
    };

    // Read the file
    let contents = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            crate::ffi::error::set_last_error(format!("Failed to read file: {}", e));
            return OxiGdalErrorCode::FileNotFound;
        }
    };

    // Parse GeoJSON
    let features = match parse_geojson(&contents) {
        Ok(f) => f,
        Err(e) => {
            crate::ffi::error::set_last_error(format!("Failed to parse GeoJSON: {}", e));
            return OxiGdalErrorCode::UnsupportedFormat;
        }
    };

    // Compute layer bounding box
    let layer_bbox = if features.is_empty() {
        None
    } else {
        let mut min_x = f64::INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut max_y = f64::NEG_INFINITY;

        for feature in &features {
            if let Some((fx_min, fy_min, fx_max, fy_max)) = feature.bbox {
                min_x = min_x.min(fx_min);
                min_y = min_y.min(fy_min);
                max_x = max_x.max(fx_max);
                max_y = max_y.max(fy_max);
            }
        }

        if min_x.is_finite() {
            Some(OxiGdalBbox {
                min_x,
                min_y,
                max_x,
                max_y,
            })
        } else {
            None
        }
    };

    // Create layer
    let layer = IosVectorLayer {
        name: path.to_string(),
        features,
        spatial_index: None,
        bbox: layer_bbox,
    };

    // Store layer and return handle
    match store_layer(layer) {
        Some(handle) => {
            unsafe { *out_layer = handle };
            OxiGdalErrorCode::Success
        }
        None => {
            crate::ffi::error::set_last_error("Failed to store layer".to_string());
            OxiGdalErrorCode::AllocationFailed
        }
    }
}

/// Creates iOS MapKit overlay from vector layer.
///
/// Returns a pointer to MapKitOverlayData that must be freed by the caller.
///
/// # Safety
/// - layer must be valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_create_map_overlay(
    layer: *const OxiGdalLayer,
) -> *mut std::os::raw::c_void {
    if layer.is_null() {
        crate::ffi::error::set_last_error("Null layer pointer".to_string());
        return ptr::null_mut();
    }

    let idx = match handle_to_index(layer) {
        Some(i) => i,
        None => {
            crate::ffi::error::set_last_error("Invalid layer handle".to_string());
            return ptr::null_mut();
        }
    };

    let layers = match LAYERS.lock() {
        Ok(l) => l,
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to acquire lock".to_string());
            return ptr::null_mut();
        }
    };

    if idx >= layers.len() {
        crate::ffi::error::set_last_error("Layer not found".to_string());
        return ptr::null_mut();
    }

    let layer_data = &layers[idx];

    // Collect all coordinates and determine overlay type
    let mut all_coords: Vec<c_double> = Vec::new();
    let mut ring_starts: Vec<c_int> = Vec::new();
    let mut overlay_type = MapKitOverlayType::Annotation;

    for feature in &layer_data.features {
        if let Some(ref geom) = feature.geometry {
            match geom.geometry_type {
                GeometryType::Point | GeometryType::MultiPoint => {
                    overlay_type = MapKitOverlayType::Annotation;
                }
                GeometryType::LineString | GeometryType::MultiLineString => {
                    overlay_type = MapKitOverlayType::Polyline;
                }
                GeometryType::Polygon | GeometryType::MultiPolygon => {
                    overlay_type = MapKitOverlayType::Polygon;
                }
                _ => {}
            }

            for &(lon, lat) in &geom.coordinates {
                all_coords.push(lon);
                all_coords.push(lat);
            }

            for &ring_end in &geom.rings {
                ring_starts.push(ring_end as c_int);
            }
        }
    }

    if all_coords.is_empty() {
        crate::ffi::error::set_last_error("No coordinates in layer".to_string());
        return ptr::null_mut();
    }

    // Allocate coordinate array
    let coord_count = all_coords.len() / 2;
    let coords_ptr = match std::alloc::Layout::array::<c_double>(all_coords.len()) {
        Ok(layout) => unsafe { std::alloc::alloc(layout) as *mut c_double },
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to allocate coordinates".to_string());
            return ptr::null_mut();
        }
    };

    if coords_ptr.is_null() {
        crate::ffi::error::set_last_error("Failed to allocate coordinates".to_string());
        return ptr::null_mut();
    }

    // Copy coordinates
    unsafe {
        ptr::copy_nonoverlapping(all_coords.as_ptr(), coords_ptr, all_coords.len());
    }

    // Allocate ring starts if needed
    let rings_ptr = if !ring_starts.is_empty() {
        match std::alloc::Layout::array::<c_int>(ring_starts.len()) {
            Ok(layout) => {
                let ptr = unsafe { std::alloc::alloc(layout) as *mut c_int };
                if !ptr.is_null() {
                    unsafe {
                        ptr::copy_nonoverlapping(ring_starts.as_ptr(), ptr, ring_starts.len());
                    }
                }
                ptr
            }
            Err(_) => ptr::null_mut(),
        }
    } else {
        ptr::null_mut()
    };

    // Create overlay data
    let overlay_data = Box::new(MapKitOverlayData {
        overlay_type,
        coord_count: coord_count as c_int,
        coordinates: coords_ptr,
        ring_count: ring_starts.len() as c_int,
        ring_starts: rings_ptr,
    });

    Box::into_raw(overlay_data) as *mut std::os::raw::c_void
}

/// Frees a MapKit overlay data structure.
///
/// # Safety
/// - overlay must be a valid pointer returned by oxigdal_ios_create_map_overlay
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_free_map_overlay(overlay: *mut std::os::raw::c_void) {
    if overlay.is_null() {
        return;
    }

    let overlay_data = unsafe { Box::from_raw(overlay as *mut MapKitOverlayData) };

    // Free coordinates
    if !overlay_data.coordinates.is_null() {
        let coord_count = overlay_data.coord_count as usize * 2;
        if let Ok(layout) = std::alloc::Layout::array::<c_double>(coord_count) {
            unsafe {
                std::alloc::dealloc(overlay_data.coordinates as *mut u8, layout);
            }
        }
    }

    // Free ring starts
    if !overlay_data.ring_starts.is_null() {
        let ring_count = overlay_data.ring_count as usize;
        if let Ok(layout) = std::alloc::Layout::array::<c_int>(ring_count) {
            unsafe {
                std::alloc::dealloc(overlay_data.ring_starts as *mut u8, layout);
            }
        }
    }

    // overlay_data is dropped here
}

/// Simplifies geometry for iOS display at given zoom level.
///
/// Uses Douglas-Peucker algorithm with tolerance based on zoom.
///
/// # Parameters
/// - `layer`: Input layer
/// - `zoom`: Map zoom level (0-20)
/// - `out_layer`: Simplified output layer
///
/// # Safety
/// - layer and out_layer must be valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_simplify_for_zoom(
    layer: *const OxiGdalLayer,
    zoom: c_int,
    out_layer: *mut *mut OxiGdalLayer,
) -> OxiGdalErrorCode {
    if layer.is_null() || out_layer.is_null() {
        crate::ffi::error::set_last_error("Null pointer provided".to_string());
        return OxiGdalErrorCode::NullPointer;
    }

    if !(0..=22).contains(&zoom) {
        crate::ffi::error::set_last_error("Invalid zoom level (must be 0-22)".to_string());
        return OxiGdalErrorCode::InvalidArgument;
    }

    let idx = match handle_to_index(layer) {
        Some(i) => i,
        None => {
            crate::ffi::error::set_last_error("Invalid layer handle".to_string());
            return OxiGdalErrorCode::InvalidArgument;
        }
    };

    let layers = match LAYERS.lock() {
        Ok(l) => l,
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to acquire lock".to_string());
            return OxiGdalErrorCode::Unknown;
        }
    };

    if idx >= layers.len() {
        crate::ffi::error::set_last_error("Layer not found".to_string());
        return OxiGdalErrorCode::InvalidArgument;
    }

    let source_layer = &layers[idx];

    // Clone needed data before releasing the lock
    let source_name = source_layer.name.clone();
    let source_bbox = source_layer.bbox;

    // Simplify all features
    let simplified_features: Vec<IosFeature> = source_layer
        .features
        .iter()
        .map(|f| {
            let simplified_geom = f.geometry.as_ref().map(|g| simplify_geometry(g, zoom));
            IosFeature {
                fid: f.fid,
                geometry: simplified_geom,
                properties: f.properties.clone(),
                bbox: f.bbox,
            }
        })
        .collect();

    drop(layers); // Release lock before storing

    // Create new layer with simplified geometries
    let new_layer = IosVectorLayer {
        name: format!("{}_simplified_z{}", source_name, zoom),
        features: simplified_features,
        spatial_index: None,
        bbox: source_bbox,
    };

    match store_layer(new_layer) {
        Some(handle) => {
            unsafe { *out_layer = handle };
            OxiGdalErrorCode::Success
        }
        None => {
            crate::ffi::error::set_last_error("Failed to store simplified layer".to_string());
            OxiGdalErrorCode::AllocationFailed
        }
    }
}

/// Converts vector features to iOS search index format.
///
/// Builds an R-tree spatial index for efficient spatial queries.
///
/// # Parameters
/// - `layer`: Vector layer
/// - `attribute_name`: Attribute to index (for search by attribute)
///
/// # Returns
/// - 0 on success
/// - non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_index_features(
    layer: *const OxiGdalLayer,
    attribute_name: *const c_char,
) -> c_int {
    if layer.is_null() {
        crate::ffi::error::set_last_error("Null layer pointer".to_string());
        return -1;
    }

    let idx = match handle_to_index(layer) {
        Some(i) => i,
        None => {
            crate::ffi::error::set_last_error("Invalid layer handle".to_string());
            return -1;
        }
    };

    // Parse attribute name if provided
    let _attr_name: Option<String> = if !attribute_name.is_null() {
        match unsafe { CStr::from_ptr(attribute_name) }.to_str() {
            Ok(s) => Some(s.to_string()),
            Err(_) => {
                crate::ffi::error::set_last_error("Invalid UTF-8 in attribute name".to_string());
                return -1;
            }
        }
    } else {
        None
    };

    let mut layers = match LAYERS.lock() {
        Ok(l) => l,
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to acquire lock".to_string());
            return -1;
        }
    };

    if idx >= layers.len() {
        crate::ffi::error::set_last_error("Layer not found".to_string());
        return -1;
    }

    // Build R-tree index
    let mut rtree = RTreeIndex::new();

    for (feature_idx, feature) in layers[idx].features.iter().enumerate() {
        if let Some((min_x, min_y, max_x, max_y)) = feature.bbox {
            let rect = Rect::new(min_x, min_y, max_x, max_y);
            rtree.insert(feature_idx, rect);
        }
    }

    layers[idx].spatial_index = Some(rtree);

    0
}

/// Queries features within a bounding box using the spatial index.
///
/// # Parameters
/// - `layer`: Vector layer (must have been indexed)
/// - `bbox`: Query bounding box
/// - `out_fids`: Output array for feature IDs
/// - `max_fids`: Maximum number of FIDs to return
///
/// # Returns
/// Number of features found, or -1 on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_query_features(
    layer: *const OxiGdalLayer,
    bbox: *const OxiGdalBbox,
    out_fids: *mut i64,
    max_fids: c_int,
) -> c_int {
    if layer.is_null() || bbox.is_null() || out_fids.is_null() || max_fids <= 0 {
        crate::ffi::error::set_last_error("Invalid parameters".to_string());
        return -1;
    }

    let idx = match handle_to_index(layer) {
        Some(i) => i,
        None => {
            crate::ffi::error::set_last_error("Invalid layer handle".to_string());
            return -1;
        }
    };

    let layers = match LAYERS.lock() {
        Ok(l) => l,
        Err(_) => {
            crate::ffi::error::set_last_error("Failed to acquire lock".to_string());
            return -1;
        }
    };

    if idx >= layers.len() {
        crate::ffi::error::set_last_error("Layer not found".to_string());
        return -1;
    }

    let layer_data = &layers[idx];

    let bb = unsafe { &*bbox };
    let query_rect = Rect::new(bb.min_x, bb.min_y, bb.max_x, bb.max_y);

    let results = match &layer_data.spatial_index {
        Some(rtree) => rtree.search(&query_rect),
        None => {
            // Fallback: linear search if no index
            layer_data
                .features
                .iter()
                .enumerate()
                .filter(|(_, f)| {
                    if let Some((fx_min, fy_min, fx_max, fy_max)) = f.bbox {
                        let feature_rect = Rect::new(fx_min, fy_min, fx_max, fy_max);
                        feature_rect.intersects(&query_rect)
                    } else {
                        false
                    }
                })
                .map(|(i, _)| i)
                .collect()
        }
    };

    let max_fids = max_fids as usize;
    let mut written = 0;

    for feature_idx in results {
        if written >= max_fids {
            break;
        }
        if feature_idx < layer_data.features.len() {
            unsafe {
                *out_fids.add(written) = layer_data.features[feature_idx].fid;
            }
            written += 1;
        }
    }

    written as c_int
}

/// Closes a vector layer and frees resources.
///
/// # Safety
/// - layer must be a valid handle
#[unsafe(no_mangle)]
pub unsafe extern "C" fn oxigdal_ios_layer_close(layer: *mut OxiGdalLayer) -> OxiGdalErrorCode {
    if layer.is_null() {
        return OxiGdalErrorCode::NullPointer;
    }

    // Note: In a full implementation, we would mark the layer as freed
    // For now, layers remain in the vector (memory management simplified)
    OxiGdalErrorCode::Success
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_point_in_region() {
        let point = OxiGdalPoint {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        };

        let bbox = OxiGdalBbox {
            min_x: -10.0,
            min_y: -10.0,
            max_x: 10.0,
            max_y: 10.0,
        };

        let result = unsafe { oxigdal_ios_point_in_visible_region(&point, &bbox) };
        assert_eq!(result, 1);

        let outside_point = OxiGdalPoint {
            x: 20.0,
            y: 20.0,
            z: 0.0,
        };

        let result = unsafe { oxigdal_ios_point_in_visible_region(&outside_point, &bbox) };
        assert_eq!(result, 0);
    }

    #[test]
    fn test_perpendicular_distance() {
        // Point on the line
        let dist = perpendicular_distance((0.5, 0.0), (0.0, 0.0), (1.0, 0.0));
        assert!(dist < f64::EPSILON);

        // Point perpendicular to line
        let dist = perpendicular_distance((0.5, 1.0), (0.0, 0.0), (1.0, 0.0));
        assert!((dist - 1.0).abs() < f64::EPSILON);

        // Point at end of line
        let dist = perpendicular_distance((0.0, 0.0), (0.0, 0.0), (1.0, 0.0));
        assert!(dist < f64::EPSILON);
    }

    #[test]
    fn test_douglas_peucker_simple() {
        let points = vec![(0.0, 0.0), (0.5, 0.0), (1.0, 0.0)];
        let simplified = douglas_peucker(&points, 0.1);
        // Middle point should be removed (collinear)
        assert_eq!(simplified.len(), 2);
        assert_eq!(simplified[0], (0.0, 0.0));
        assert_eq!(simplified[1], (1.0, 0.0));
    }

    #[test]
    fn test_douglas_peucker_preserve() {
        let points = vec![(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)];
        let simplified = douglas_peucker(&points, 0.1);
        // Point is not collinear, should be preserved
        assert_eq!(simplified.len(), 3);
    }

    #[test]
    fn test_tolerance_for_zoom() {
        let t0 = tolerance_for_zoom(0);
        let t10 = tolerance_for_zoom(10);
        let t20 = tolerance_for_zoom(20);

        assert!(t0 > t10);
        assert!(t10 > t20);
        assert!(t20 > 0.0);
    }

    #[test]
    fn test_rect_intersects() {
        let r1 = Rect::new(0.0, 0.0, 10.0, 10.0);
        let r2 = Rect::new(5.0, 5.0, 15.0, 15.0);
        let r3 = Rect::new(20.0, 20.0, 30.0, 30.0);

        assert!(r1.intersects(&r2));
        assert!(r2.intersects(&r1));
        assert!(!r1.intersects(&r3));
        assert!(!r3.intersects(&r1));
    }

    #[test]
    fn test_rect_union() {
        let r1 = Rect::new(0.0, 0.0, 10.0, 10.0);
        let r2 = Rect::new(5.0, 5.0, 15.0, 15.0);
        let union = r1.union(&r2);

        assert_eq!(union.min_x, 0.0);
        assert_eq!(union.min_y, 0.0);
        assert_eq!(union.max_x, 15.0);
        assert_eq!(union.max_y, 15.0);
    }

    #[test]
    fn test_rtree_insert_and_search() {
        let mut rtree = RTreeIndex::new();

        // Insert some features
        rtree.insert(0, Rect::new(0.0, 0.0, 1.0, 1.0));
        rtree.insert(1, Rect::new(5.0, 5.0, 6.0, 6.0));
        rtree.insert(2, Rect::new(10.0, 10.0, 11.0, 11.0));

        // Search for features in a region
        let results = rtree.search(&Rect::new(4.0, 4.0, 7.0, 7.0));
        assert_eq!(results.len(), 1);
        assert!(results.contains(&1));

        // Search for features that don't exist
        let results = rtree.search(&Rect::new(100.0, 100.0, 101.0, 101.0));
        assert!(results.is_empty());
    }

    #[test]
    fn test_parse_geojson_point() {
        let geojson = r#"{
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [100.0, 0.0]
            },
            "properties": {
                "name": "Test Point"
            }
        }"#;

        let features = parse_geojson(geojson);
        assert!(features.is_ok());
        let features = features.expect("parse should succeed");
        assert_eq!(features.len(), 1);
        assert!(features[0].geometry.is_some());

        let geom = features[0].geometry.as_ref().expect("geometry exists");
        assert_eq!(geom.geometry_type, GeometryType::Point);
        assert_eq!(geom.coordinates.len(), 1);
        assert_eq!(geom.coordinates[0], (100.0, 0.0));
    }

    #[test]
    fn test_parse_geojson_linestring() {
        let geojson = r#"{
            "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": [[0, 0], [1, 1], [2, 0]]
            },
            "properties": {}
        }"#;

        let features = parse_geojson(geojson);
        assert!(features.is_ok());
        let features = features.expect("parse should succeed");
        assert_eq!(features.len(), 1);

        let geom = features[0].geometry.as_ref().expect("geometry exists");
        assert_eq!(geom.geometry_type, GeometryType::LineString);
        assert_eq!(geom.coordinates.len(), 3);
    }

    #[test]
    fn test_parse_geojson_polygon() {
        let geojson = r#"{
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]
            },
            "properties": {}
        }"#;

        let features = parse_geojson(geojson);
        assert!(features.is_ok());
        let features = features.expect("parse should succeed");
        assert_eq!(features.len(), 1);

        let geom = features[0].geometry.as_ref().expect("geometry exists");
        assert_eq!(geom.geometry_type, GeometryType::Polygon);
        assert_eq!(geom.coordinates.len(), 5);
        assert_eq!(geom.rings.len(), 1);
    }

    #[test]
    fn test_parse_geojson_feature_collection() {
        let geojson = r#"{
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {"type": "Point", "coordinates": [0, 0]},
                    "properties": {"id": 1}
                },
                {
                    "type": "Feature",
                    "geometry": {"type": "Point", "coordinates": [1, 1]},
                    "properties": {"id": 2}
                }
            ]
        }"#;

        let features = parse_geojson(geojson);
        assert!(features.is_ok());
        let features = features.expect("parse should succeed");
        assert_eq!(features.len(), 2);
    }

    #[test]
    fn test_compute_bbox() {
        let coords = vec![(0.0, 0.0), (10.0, 5.0), (5.0, 10.0)];
        let bbox = compute_bbox(&coords);
        assert!(bbox.is_some());

        let (min_x, min_y, max_x, max_y) = bbox.expect("bbox exists");
        assert_eq!(min_x, 0.0);
        assert_eq!(min_y, 0.0);
        assert_eq!(max_x, 10.0);
        assert_eq!(max_y, 10.0);
    }

    #[test]
    fn test_compute_bbox_empty() {
        let coords: Vec<(f64, f64)> = vec![];
        let bbox = compute_bbox(&coords);
        assert!(bbox.is_none());
    }

    #[test]
    fn test_geometry_type_values() {
        assert_eq!(GeometryType::Unknown as i32, 0);
        assert_eq!(GeometryType::Point as i32, 1);
        assert_eq!(GeometryType::LineString as i32, 2);
        assert_eq!(GeometryType::Polygon as i32, 3);
    }

    #[test]
    fn test_null_pointer_handling() {
        let result = unsafe { oxigdal_ios_point_in_visible_region(ptr::null(), ptr::null()) };
        assert_eq!(result, 0);

        let result = unsafe { oxigdal_ios_layer_to_annotations(ptr::null(), ptr::null_mut(), 10) };
        assert_eq!(result, -1);
    }

    #[test]
    fn test_simplify_geometry_point() {
        let geom = IosGeometry {
            geometry_type: GeometryType::Point,
            coordinates: vec![(0.0, 0.0)],
            rings: vec![],
        };

        let simplified = simplify_geometry(&geom, 10);
        assert_eq!(simplified.coordinates.len(), 1);
    }

    #[test]
    fn test_simplify_geometry_linestring() {
        // Create a line with many collinear points
        let geom = IosGeometry {
            geometry_type: GeometryType::LineString,
            coordinates: vec![(0.0, 0.0), (0.25, 0.0), (0.5, 0.0), (0.75, 0.0), (1.0, 0.0)],
            rings: vec![],
        };

        let simplified = simplify_geometry(&geom, 0); // High tolerance at zoom 0
        assert!(simplified.coordinates.len() < geom.coordinates.len());
    }
}