waterui 0.3.0

A modern UI framework for Rust
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
import CWaterUI
import Foundation
import OSLog
import SwiftUI

#if canImport(UIKit)
  import UIKit
#elseif canImport(AppKit)
  import AppKit
#endif
// MARK: - WuiStretchAxis

/// Defines how a view stretches to fill available space.
/// Mirrors Rust's `StretchAxis` enum from the layout engine.
public enum WuiStretchAxis: UInt32 {
  /// Content-sized: uses intrinsic size, never stretches
  case none = 0
  /// Expands width only, uses intrinsic height (e.g., TextField, Slider)
  case horizontal = 1
  /// Expands height only, uses intrinsic width
  case vertical = 2
  /// Greedy: fills all available space in both directions (e.g., Color)
  case both = 3
  /// Expands along parent stack's main axis (e.g., Spacer)
  /// In VStack: expands vertically. In HStack: expands horizontally.
  case mainAxis = 4
  /// Expands along parent stack's cross axis (e.g., Divider)
  /// In VStack: expands horizontally. In HStack: expands vertically.
  case crossAxis = 5

  /// Convert to the C FFI enum type
  var ffiValue: CWaterUI.WuiStretchAxis {
    CWaterUI.WuiStretchAxis(rawValue: self.rawValue)
  }

  /// Initialize from C FFI enum type
  init(_ ffi: CWaterUI.WuiStretchAxis) {
    guard let axis = WuiStretchAxis(rawValue: ffi.rawValue) else {
      fatalError("Unsupported WaterUI stretch axis: \(ffi.rawValue)")
    }
    self = axis
  }
}

// MARK: - WuiViewId

/// A view identifier using 128-bit value for O(1) lookups.
///
/// Uses the same 128-bit type ID from Rust:
/// - Normal build: Contains TypeId (guaranteed unique by Rust)
/// - Hot reload: Contains 128-bit FNV-1a hash of type_name (stable across dylib reloads)
///
/// Using 128-bit virtually eliminates collision risk (birthday paradox threshold: ~10^19).
struct WuiViewId: Hashable {
  /// Low 64 bits of the 128-bit type identifier
  let low: UInt64
  /// High 64 bits of the 128-bit type identifier
  let high: UInt64

  /// Extract view ID from the FFI WuiTypeId struct.
  @inline(__always)
  init(_ raw: CWaterUI.WuiTypeId) {
    self.low = raw.low
    self.high = raw.high
  }

  @inline(__always)
  static func == (lhs: WuiViewId, rhs: WuiViewId) -> Bool {
    // O(1) comparison of two 64-bit values
    lhs.low == rhs.low && lhs.high == rhs.high
  }

  @inline(__always)
  func hash(into hasher: inout Hasher) {
    hasher.combine(low)
    hasher.combine(high)
  }

  /// Convert to debug string (shows hex representation)
  func toString() -> String {
    String(format: "0x%016llx%016llx", high, low)
  }
}

// MARK: - WuiComponent Protocol

/// Protocol for all WaterUI components.
/// Components are platform views (UIView/NSView) identified by a static ID
/// that implement WaterUI's measurement protocol.
///
/// This protocol mirrors Rust's `SubView` trait:
/// - `sizeThatFits(_:)` → `size_that_fits(proposal)`
/// - `stretchAxis` → `stretch_axis()`
/// - `layoutPriority()` → `priority()`
@MainActor
public protocol WuiComponent: PlatformView {
  /// Raw FFI identifier for this component type.
  /// Must be obtained via `waterui_*_id()` FFI function.
  /// Used for O(1) 128-bit value-based registry lookup.
  static var rawId: CWaterUI.WuiTypeId { get }

  /// Creates an instance from an FFI anyview pointer and environment.
  /// This is called by PlatformRenderer when resolving views.
  init(anyview: OpaquePointer, env: WuiEnvironment)

  /// Which axis (or axes) this view stretches to fill available space.
  /// Default: `.none` (content-sized)
  var stretchAxis: WuiStretchAxis { get }

  /// Layout priority for this view. Higher priority views get space first.
  /// Default: 0
  func layoutPriority() -> Int32

  /// Measures the view given a size proposal.
  /// - Parameter proposal: The proposed size from the layout engine
  /// - Returns: The size this view wants to be
  func sizeThatFits(_ proposal: WuiProposalSize) -> CGSize

  /// Measures the view and returns the full layout packet.
  func measure(_ proposal: WuiProposalSize) -> WuiViewDimensions
}

extension WuiComponent {
  public var stretchAxis: WuiStretchAxis { .none }
  public func layoutPriority() -> Int32 { 0 }
  public func measure(_ proposal: WuiProposalSize) -> WuiViewDimensions {
    WuiViewDimensions(size: sizeThatFits(proposal))
  }

  /// 128-bit view ID for O(1) registry lookup
  static var viewId: WuiViewId {
    WuiViewId(rawId)
  }
}

// MARK: - Reactive Signal Infrastructure

private final class ReactiveWatcherGuardContext: @unchecked Sendable {
  private let remove: @Sendable () -> Void

  init(remove: @escaping @Sendable () -> Void) {
    self.remove = remove
  }

  func removeWatcher() {
    remove()
  }
}

private struct ReactiveWatcherPointer: @unchecked Sendable {
  let raw: OpaquePointer
}

private let dropReactiveWatcherGuardContext: @convention(c) (UnsafeMutableRawPointer?) -> Void = {
  rawPtr in
  guard let rawPtr else {
    fatalError("Reactive watcher guard received a null context")
  }
  Unmanaged<ReactiveWatcherGuardContext>
    .fromOpaque(rawPtr)
    .takeRetainedValue()
    .removeWatcher()
}

private func makeReactiveWatcherGuard(
  remove: @escaping @Sendable () -> Void
) -> OpaquePointer {
  let context = ReactiveWatcherGuardContext(remove: remove)
  let contextPtr = Unmanaged.passRetained(context).toOpaque()
  guard let guardPtr = waterui_new_watcher_guard(contextPtr, dropReactiveWatcherGuardContext) else {
    _ = Unmanaged<ReactiveWatcherGuardContext>.fromOpaque(contextPtr).takeRetainedValue()
    fatalError("Failed to create a reactive watcher guard")
  }
  return guardPtr
}

/// The watcher bookkeeping every native-controlled signal repeats.
///
/// What differs per signal is its value and the three C symbols the ABI needs
/// as literal `@convention(c)` closures. Registering, notifying and releasing
/// watchers does not differ, and getting that dance wrong leaks a watcher or
/// releases one twice, so it lives here once.
final class ReactiveWatcherList<Value>: @unchecked Sendable {
  private let call: (OpaquePointer, Value) -> Void
  private let release: (OpaquePointer) -> Void
  private var watchers: [OpaquePointer] = []

  /// The value handed to every watcher registered from here on.
  var value: Value

  init(
    value: Value,
    call: @escaping (OpaquePointer, Value) -> Void,
    release: @escaping (OpaquePointer) -> Void
  ) {
    self.value = value
    self.call = call
    self.release = release
  }

  func addWatcher(_ watcher: OpaquePointer) {
    precondition(!watchers.contains(watcher), "Reactive watcher was registered twice")
    watchers.append(watcher)
  }

  func notifyWatchers() {
    for watcher in watchers {
      call(watcher, value)
    }
  }

  func removeWatcher(_ watcher: OpaquePointer) {
    guard let index = watchers.firstIndex(of: watcher) else {
      fatalError("Reactive watcher was released more than once")
    }
    watchers.remove(at: index)
    release(watcher)
  }

  func cleanup() {
    for watcher in watchers {
      release(watcher)
    }
    watchers.removeAll()
  }
}

/// A native-controlled reactive color signal.
/// This allows Swift to create and update color signals that notify WaterUI watchers.
@MainActor
final class ReactiveColorSignal {
  private typealias State = ReactiveWatcherList<WuiResolvedColor>

  private let state: State
  private let statePtr: UnsafeMutableRawPointer
  private var computedPtr: OpaquePointer?

  init(color: WuiResolvedColor) {
    self.state = State(
      value: color,
      call: { waterui_call_watcher_resolved_color($0, $1) },
      release: { waterui_drop_watcher_resolved_color($0) }
    )
    self.statePtr = Unmanaged.passRetained(state).toOpaque()
  }

  deinit {
    state.cleanup()
  }

  /// Gets the computed pointer for installation into WaterUI environment.
  func toComputed() -> OpaquePointer {
    if let computedPtr { return computedPtr }
    guard
      let computed = waterui_new_computed_resolved_color(
        statePtr,
        { ptr -> WuiResolvedColor in
          guard let ptr else {
            fatalError("ReactiveColorSignal get received a null state pointer")
          }
          return Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue().value
        },
        { ptr, watcher -> OpaquePointer? in
          guard let ptr else {
            fatalError("ReactiveColorSignal watch received a null state pointer")
          }
          guard let watcher else {
            fatalError("ReactiveColorSignal watch received a null watcher pointer")
          }
          let state = Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue()
          let watcherPointer = ReactiveWatcherPointer(raw: watcher)
          state.addWatcher(watcherPointer.raw)
          return makeReactiveWatcherGuard { [state, watcherPointer] in
            state.removeWatcher(watcherPointer.raw)
          }
        },
        { ptr in
          guard let ptr else {
            fatalError("ReactiveColorSignal drop received a null state pointer")
          }
          Unmanaged<State>.fromOpaque(ptr).takeRetainedValue().cleanup()
        }
      )
    else {
      fatalError("ReactiveColorSignal failed to create its computed signal")
    }
    computedPtr = computed
    return computed
  }

  /// Updates the color and notifies all watchers.
  func setValue(_ color: WuiResolvedColor) {
    let current = state.value
    guard
      current.red != color.red || current.green != color.green
        || current.blue != color.blue || current.opacity != color.opacity
        || current.headroom != color.headroom
    else { return }
    state.value = color
    state.notifyWatchers()
  }

  /// Convenience to set from platform color
  #if canImport(UIKit)
    func setValue(_ color: UIColor) {
      setValue(WuiResolvedColor.fromUIColor(color))
    }
  #elseif canImport(AppKit)
    func setValue(_ color: NSColor) {
      setValue(WuiResolvedColor.fromNSColor(color))
    }
  #endif
}

/// A native-controlled reactive color scheme signal.
/// This allows Swift to create and update color scheme signals that notify WaterUI watchers.
@MainActor
final class ReactiveColorSchemeSignal {
  private typealias State = ReactiveWatcherList<WuiColorScheme>

  private let state: State
  private let statePtr: UnsafeMutableRawPointer
  private var computedPtr: OpaquePointer?

  init(scheme: WuiColorScheme) {
    self.state = State(
      value: scheme,
      call: { waterui_call_watcher_color_scheme($0, $1) },
      release: { waterui_drop_watcher_color_scheme($0) }
    )
    self.statePtr = Unmanaged.passRetained(state).toOpaque()
  }

  deinit {
    state.cleanup()
  }

  func toComputed() -> OpaquePointer {
    if let computedPtr { return computedPtr }
    guard
      let computed = waterui_new_computed_color_scheme(
        statePtr,
        { ptr -> WuiColorScheme in
          guard let ptr else {
            fatalError("ReactiveColorSchemeSignal get received a null state pointer")
          }
          return Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue().value
        },
        { ptr, watcher -> OpaquePointer? in
          guard let ptr else {
            fatalError("ReactiveColorSchemeSignal watch received a null state pointer")
          }
          guard let watcher else {
            fatalError("ReactiveColorSchemeSignal watch received a null watcher pointer")
          }
          let state = Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue()
          let watcherPointer = ReactiveWatcherPointer(raw: watcher)
          state.addWatcher(watcherPointer.raw)
          return makeReactiveWatcherGuard { [state, watcherPointer] in
            state.removeWatcher(watcherPointer.raw)
          }
        },
        { ptr in
          guard let ptr else {
            fatalError("ReactiveColorSchemeSignal drop received a null state pointer")
          }
          Unmanaged<State>.fromOpaque(ptr).takeRetainedValue().cleanup()
        }
      )
    else {
      fatalError("ReactiveColorSchemeSignal failed to create its computed signal")
    }
    computedPtr = computed
    return computed
  }

  func setValue(_ scheme: WuiColorScheme) {
    guard state.value.rawValue != scheme.rawValue else { return }
    state.value = scheme
    state.notifyWatchers()
  }
}

/// A native-controlled reactive font signal.
@MainActor
final class ReactiveFontSignal {
  /// A font is published as size plus weight and resolved at notify time, the
  /// same way the environment resolves one.
  struct Spec {
    var size: Float
    var weight: WuiFontWeight
  }

  private typealias State = ReactiveWatcherList<Spec>

  private let state: State
  private let statePtr: UnsafeMutableRawPointer
  private var computedPtr: OpaquePointer?

  init(size: Float, weight: WuiFontWeight) {
    self.state = State(
      value: Spec(size: size, weight: weight),
      call: { waterui_call_watcher_resolved_font($0, waterui_resolved_font_new($1.size, $1.weight)) },
      release: { waterui_drop_watcher_resolved_font($0) }
    )
    self.statePtr = Unmanaged.passRetained(state).toOpaque()
  }

  deinit {
    state.cleanup()
  }

  func toComputed() -> OpaquePointer {
    if let computedPtr { return computedPtr }
    guard
      let computed = waterui_new_computed_resolved_font(
        statePtr,
        { ptr -> WuiResolvedFont in
          guard let ptr else {
            fatalError("ReactiveFontSignal get received a null state pointer")
          }
          let spec = Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue().value
          return waterui_resolved_font_new(spec.size, spec.weight)
        },
        { ptr, watcher -> OpaquePointer? in
          guard let ptr else {
            fatalError("ReactiveFontSignal watch received a null state pointer")
          }
          guard let watcher else {
            fatalError("ReactiveFontSignal watch received a null watcher pointer")
          }
          let state = Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue()
          let watcherPointer = ReactiveWatcherPointer(raw: watcher)
          state.addWatcher(watcherPointer.raw)
          return makeReactiveWatcherGuard { [state, watcherPointer] in
            state.removeWatcher(watcherPointer.raw)
          }
        },
        { ptr in
          guard let ptr else {
            fatalError("ReactiveFontSignal drop received a null state pointer")
          }
          Unmanaged<State>.fromOpaque(ptr).takeRetainedValue().cleanup()
        }
      )
    else {
      fatalError("ReactiveFontSignal failed to create its computed signal")
    }
    computedPtr = computed
    return computed
  }

  func setValue(size: Float, weight: WuiFontWeight) {
    let current = state.value
    guard current.size != size || current.weight.rawValue != weight.rawValue else { return }
    state.value = Spec(size: size, weight: weight)
    state.notifyWatchers()
  }
}

extension WuiEdgeInsets {
  /// No inset on any edge.
  static let zero = WuiEdgeInsets(top: 0, bottom: 0, leading: 0, trailing: 0)

  /// Maps platform insets, which are physical (left/right), onto WaterUI's
  /// logical edges.
  ///
  /// `PaddingLayout` places `leading` at the low-x edge unconditionally, so
  /// left maps to leading and right to trailing. Should WaterUI ever resolve
  /// those against the layout direction, this is the one place that has to
  /// learn about it too.
  #if canImport(UIKit)
    init(_ insets: UIEdgeInsets) {
      self.init(
        top: Float(insets.top),
        bottom: Float(insets.bottom),
        leading: Float(insets.left),
        trailing: Float(insets.right)
      )
    }
  #elseif canImport(AppKit)
    init(_ insets: NSEdgeInsets) {
      self.init(
        top: Float(insets.top),
        bottom: Float(insets.bottom),
        leading: Float(insets.left),
        trailing: Float(insets.right)
      )
    }
  #endif
}

/// A native-controlled reactive safe-area signal.
///
/// The window publishes its device insets here so the layers WaterUI lays out
/// itself — the snackbar and overlay hosts, which arrive as one Rust-laid-out
/// container this backend cannot frame piecewise — can pad themselves clear of
/// the notch and the home indicator.
@MainActor
final class ReactiveEdgeInsetsSignal {
  private typealias State = ReactiveWatcherList<WuiEdgeInsets>

  private let state: State
  private let statePtr: UnsafeMutableRawPointer
  private var computedPtr: OpaquePointer?

  init(insets: WuiEdgeInsets) {
    self.state = State(
      value: insets,
      call: { waterui_call_watcher_edge_insets($0, $1) },
      release: { waterui_drop_watcher_edge_insets($0) }
    )
    self.statePtr = Unmanaged.passRetained(state).toOpaque()
  }

  deinit {
    state.cleanup()
  }

  func toComputed() -> OpaquePointer {
    if let computedPtr { return computedPtr }
    guard
      let computed = waterui_new_computed_edge_insets(
        statePtr,
        { ptr -> WuiEdgeInsets in
          guard let ptr else {
            fatalError("ReactiveEdgeInsetsSignal get received a null state pointer")
          }
          return Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue().value
        },
        { ptr, watcher -> OpaquePointer? in
          guard let ptr else {
            fatalError("ReactiveEdgeInsetsSignal watch received a null state pointer")
          }
          guard let watcher else {
            fatalError("ReactiveEdgeInsetsSignal watch received a null watcher pointer")
          }
          let state = Unmanaged<State>.fromOpaque(UnsafeMutableRawPointer(mutating: ptr))
            .takeUnretainedValue()
          let watcherPointer = ReactiveWatcherPointer(raw: watcher)
          state.addWatcher(watcherPointer.raw)
          return makeReactiveWatcherGuard { [state, watcherPointer] in
            state.removeWatcher(watcherPointer.raw)
          }
        },
        { ptr in
          guard let ptr else {
            fatalError("ReactiveEdgeInsetsSignal drop received a null state pointer")
          }
          Unmanaged<State>.fromOpaque(ptr).takeRetainedValue().cleanup()
        }
      )
    else {
      fatalError("ReactiveEdgeInsetsSignal failed to create its computed signal")
    }
    computedPtr = computed
    return computed
  }

  func setValue(_ insets: WuiEdgeInsets) {
    let current = state.value
    guard
      current.top != insets.top || current.bottom != insets.bottom
        || current.leading != insets.leading || current.trailing != insets.trailing
    else { return }
    state.value = insets
    state.notifyWatchers()
  }
}

// MARK: - Theme Bridge

/// Observes system appearance changes and updates theme reactively.
///
/// This class uses `ReactiveColorSignal` to create signals that can be updated
/// when system appearance changes, triggering automatic UI updates through
/// WaterUI's reactive system.
@MainActor
public final class ThemeBridge {
  #if canImport(UIKit)
    private struct ColorSignalEntry {
      let signal: ReactiveColorSignal
      let resolve: @MainActor () -> UIColor
    }

    private struct FontSignalEntry {
      let textStyle: UIFont.TextStyle
      let signal: ReactiveFontSignal
    }

    private var fontSignalEntries: [FontSignalEntry] = []
    private var contentSizeCategoryObserver: NSObjectProtocol?
  #elseif canImport(AppKit)
    private struct ColorSignalEntry {
      let signal: ReactiveColorSignal
      let resolve: @MainActor () -> NSColor
    }

    private var fontSignals: [ReactiveFontSignal] = []
  #endif

  private let colorSchemeSignal: ReactiveColorSchemeSignal
  private let colorSignalEntries: [ColorSignalEntry]
  private var observedColorScheme: WuiComputedObservation<WuiColorScheme>?

  public enum ColorScheme {
    case light
    case dark
  }

  init(env: WuiEnvironment, colorScheme: ColorScheme) {
    let schemeSignal = ReactiveColorSchemeSignal(scheme: Self.wuiColorScheme(colorScheme))
    waterui_theme_install_color_scheme(env.inner, schemeSignal.toComputed())
    colorSchemeSignal = schemeSignal
    colorSignalEntries = Self.makeColorSignalEntries(env: env)
    installSystemFonts(env: env)
  }

  func bindToEnvironmentColorScheme(env: WuiEnvironment) {
    guard let signal = waterui_theme_color_scheme(env.inner) else {
      fatalError("WaterUI: failed to read root color scheme signal from the environment.")
    }

    observedColorScheme = nil
    let observation = WuiComputedObservation(WuiComputed<WuiColorScheme>(signal)) {
      [weak self] scheme, _ in
      self?.applyColors(for: Self.bridgeColorScheme(scheme))
    }
    observedColorScheme = observation
    applyColors(for: Self.bridgeColorScheme(observation.value))
  }

  /// Updates the theme for a new color scheme by updating existing reactive signals
  func updateColorScheme(_ colorScheme: ColorScheme) {
    let previousActiveScheme = observedColorScheme?.value
    colorSchemeSignal.setValue(Self.wuiColorScheme(colorScheme))
    let activeScheme = observedColorScheme?.value ?? Self.wuiColorScheme(colorScheme)
    if previousActiveScheme?.rawValue == activeScheme.rawValue {
      applyColors(for: Self.bridgeColorScheme(activeScheme))
    }
  }

  private func applyColors(for colorScheme: ColorScheme) {
    #if canImport(UIKit)
      let traits = UITraitCollection(
        userInterfaceStyle: colorScheme == .dark ? .dark : .light
      )
      for entry in colorSignalEntries {
        entry.signal.setValue(entry.resolve().resolvedColor(with: traits))
      }
    #elseif canImport(AppKit)
      let appearanceName: NSAppearance.Name = colorScheme == .dark ? .darkAqua : .aqua
      guard let appearance = NSAppearance(named: appearanceName) else {
        fatalError("WaterUI: failed to create AppKit appearance '\(appearanceName.rawValue)'.")
      }
      appearance.performAsCurrentDrawingAppearance {
        for entry in colorSignalEntries {
          entry.signal.setValue(entry.resolve())
        }
      }
    #endif
  }

  private static func wuiColorScheme(_ colorScheme: ColorScheme) -> WuiColorScheme {
    colorScheme == .dark ? WuiColorScheme_Dark : WuiColorScheme_Light
  }

  private static func bridgeColorScheme(_ colorScheme: WuiColorScheme) -> ColorScheme {
    switch colorScheme {
    case WuiColorScheme_Light:
      return .light
    case WuiColorScheme_Dark:
      return .dark
    default:
      fatalError("WaterUI: unknown WuiColorScheme value \(colorScheme)")
    }
  }

  @MainActor deinit {
    #if canImport(UIKit)
      if let contentSizeCategoryObserver {
        NotificationCenter.default.removeObserver(contentSizeCategoryObserver)
      }
    #endif
    observedColorScheme = nil
  }

  #if canImport(UIKit)
    private static func makeColorSignalEntries(env: WuiEnvironment) -> [ColorSignalEntry] {
      [
        installColorSignal(env: env, slot: WuiColorSlot_Background) {
          UIColor.systemBackground
        },
        installColorSignal(env: env, slot: WuiColorSlot_Surface) {
          UIColor.secondarySystemBackground
        },
        installColorSignal(env: env, slot: WuiColorSlot_SurfaceVariant) {
          // Mirrors the AppKit mapping: `tertiarySystemBackground` is pure
          // white in light mode — identical to the Background slot — so an
          // "alternate surface" filled with it is invisible. The system fill
          // is the color intended for input fields and shape fills.
          UIColor.tertiarySystemFill
        },
        installColorSignal(env: env, slot: WuiColorSlot_Border) { UIColor.separator },
        installColorSignal(env: env, slot: WuiColorSlot_Foreground) { UIColor.label },
        installColorSignal(env: env, slot: WuiColorSlot_MutedForeground) {
          UIColor.secondaryLabel
        },
        installColorSignal(env: env, slot: WuiColorSlot_Accent) { Self.appAccentColor() },
        installColorSignal(env: env, slot: WuiColorSlot_AccentForeground) { UIColor.white },
        installColorSignal(env: env, slot: WuiColorSlot_AccentContainer) {
          Self.appAccentColor().withAlphaComponent(0.16)
        },
        installColorSignal(env: env, slot: WuiColorSlot_Tertiary) { UIColor.systemPurple },
        installColorSignal(env: env, slot: WuiColorSlot_TertiaryContainer) {
          UIColor.systemPurple.withAlphaComponent(0.16)
        },
        // UIKit has no semantic "selection fill": a selected row is tinted with
        // the app's accent, and its content is drawn in the same on-accent color
        // the accent pair uses.
        installColorSignal(env: env, slot: WuiColorSlot_SelectionContainer) {
          Self.appAccentColor()
        },
        installColorSignal(env: env, slot: WuiColorSlot_SelectionForeground) { UIColor.white },
      ]
    }

    /// The app's asset-catalog accent, the same source SwiftUI resolves for
    /// its default tint. `UIColor.tintColor` is view-context dependent and
    /// collapses to systemBlue when resolved outside a view hierarchy, which
    /// is exactly how the theme table resolves colors.
    private static func appAccentColor() -> UIColor {
      UIColor(named: "AccentColor") ?? .tintColor
    }

    private static func installColorSignal(
      env: WuiEnvironment,
      slot: WuiColorSlot,
      resolve: @escaping @MainActor () -> UIColor
    ) -> ColorSignalEntry {
      let signal = ReactiveColorSignal(color: WuiResolvedColor.fromUIColor(resolve()))
      waterui_theme_install_color(env.inner, slot, signal.toComputed())
      return ColorSignalEntry(signal: signal, resolve: resolve)
    }
  #elseif canImport(AppKit)
    private static func makeColorSignalEntries(env: WuiEnvironment) -> [ColorSignalEntry] {
      [
        installColorSignal(env: env, slot: WuiColorSlot_Background) {
          NSColor.windowBackgroundColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_Surface) {
          NSColor.controlBackgroundColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_SurfaceVariant) {
          // `underPageBackgroundColor` is the dark document-canvas color (58.8%
          // gray at 90% opacity in light mode) and reads as a black block on a
          // light UI. `tertiarySystemFill` is AppKit's fill for input fields
          // and search bars, adapting correctly to both appearances.
          NSColor.tertiarySystemFill
        },
        installColorSignal(env: env, slot: WuiColorSlot_Border) { NSColor.separatorColor },
        installColorSignal(env: env, slot: WuiColorSlot_Foreground) { NSColor.labelColor },
        installColorSignal(env: env, slot: WuiColorSlot_MutedForeground) {
          NSColor.secondaryLabelColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_Accent) {
          NSColor.controlAccentColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_AccentForeground) {
          // The semantic "text on accent" color: flips to black under accent
          // colors and contrast settings where a constant white would fail.
          NSColor.alternateSelectedControlTextColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_AccentContainer) {
          NSColor.controlAccentColor.withAlphaComponent(0.16)
        },
        installColorSignal(env: env, slot: WuiColorSlot_Tertiary) { NSColor.systemPurple },
        installColorSignal(env: env, slot: WuiColorSlot_TertiaryContainer) {
          NSColor.systemPurple.withAlphaComponent(0.16)
        },
        installColorSignal(env: env, slot: WuiColorSlot_SelectionContainer) {
          // AppKit's own emphasized selection fill, the color a focused table
          // paints behind a selected row.
          NSColor.selectedContentBackgroundColor
        },
        installColorSignal(env: env, slot: WuiColorSlot_SelectionForeground) {
          // The matching content color for that fill — the same semantic color
          // the accent pair uses, so a selected row's labels are unchanged.
          NSColor.alternateSelectedControlTextColor
        },
      ]
    }

    private static func installColorSignal(
      env: WuiEnvironment,
      slot: WuiColorSlot,
      resolve: @escaping @MainActor () -> NSColor
    ) -> ColorSignalEntry {
      let signal = ReactiveColorSignal(color: WuiResolvedColor.fromNSColor(resolve()))
      waterui_theme_install_color(env.inner, slot, signal.toComputed())
      return ColorSignalEntry(signal: signal, resolve: resolve)
    }
  #endif

  private func installSystemFonts(env: WuiEnvironment) {
    #if canImport(UIKit)
      let slots: [(WuiFontSlot, UIFont.TextStyle)] = [
        (WuiFontSlot_Body, .body),
        (WuiFontSlot_Title, .title1),
        (WuiFontSlot_Headline, .headline),
        (WuiFontSlot_Subheadline, .subheadline),
        (WuiFontSlot_Caption, .caption1),
        (WuiFontSlot_Footnote, .footnote),
      ]
      fontSignalEntries = slots.map { slot, textStyle in
        let signal = installFontSlot(
          env: env,
          slot: slot,
          font: UIFont.preferredFont(forTextStyle: textStyle)
        )
        return FontSignalEntry(textStyle: textStyle, signal: signal)
      }
      contentSizeCategoryObserver = NotificationCenter.default.addObserver(
        forName: UIContentSizeCategory.didChangeNotification,
        object: nil,
        queue: .main
      ) { [weak self] _ in
        MainActor.assumeIsolated {
          self?.updatePreferredFonts()
        }
      }
    #elseif canImport(AppKit)
      let slots: [(WuiFontSlot, NSFont.TextStyle)] = [
        (WuiFontSlot_Body, .body),
        (WuiFontSlot_Title, .title1),
        (WuiFontSlot_Headline, .headline),
        (WuiFontSlot_Subheadline, .subheadline),
        (WuiFontSlot_Caption, .caption1),
        (WuiFontSlot_Footnote, .footnote),
      ]
      fontSignals = slots.map { slot, textStyle in
        installFontSlot(
          env: env,
          slot: slot,
          font: NSFont.preferredFont(forTextStyle: textStyle, options: [:])
        )
      }
    #endif
  }

  #if canImport(UIKit)
    private func installFontSlot(
      env: WuiEnvironment,
      slot: WuiFontSlot,
      font: UIFont
    ) -> ReactiveFontSignal {
      let weight = fontWeight(font)
      let signal = ReactiveFontSignal(size: Float(font.pointSize), weight: weight)
      waterui_theme_install_font(env.inner, slot, signal.toComputed())
      return signal
    }

    private func updatePreferredFonts() {
      for entry in fontSignalEntries {
        let font = UIFont.preferredFont(forTextStyle: entry.textStyle)
        entry.signal.setValue(size: Float(font.pointSize), weight: fontWeight(font))
      }
    }

    private func fontWeight(_ font: UIFont) -> WuiFontWeight {
      let traits =
        font.fontDescriptor.object(forKey: .traits) as? [UIFontDescriptor.TraitKey: Any]
      let weightValue = traits?[.weight] as? CGFloat ?? UIFont.Weight.regular.rawValue
      return uiFontWeightToWuiFontWeight(weightValue)
    }

    private func uiFontWeightToWuiFontWeight(_ weight: CGFloat) -> WuiFontWeight {
      // UIFont.Weight ranges from -1.0 (ultra-light) to 1.0 (black), with 0.0 being regular
      switch weight {
      case ...(-0.8): return WuiFontWeight_Thin
      case (-0.8) ... (-0.6): return WuiFontWeight_UltraLight
      case (-0.6) ... (-0.4): return WuiFontWeight_Light
      case (-0.4) ... (0.0): return WuiFontWeight_Normal
      case (0.0) ... (0.23): return WuiFontWeight_Medium
      case (0.23) ... (0.3): return WuiFontWeight_SemiBold
      case (0.3) ... (0.5): return WuiFontWeight_Bold
      case (0.5) ... (0.8): return WuiFontWeight_UltraBold
      default: return WuiFontWeight_Black
      }
    }
  #elseif canImport(AppKit)
    private func installFontSlot(
      env: WuiEnvironment,
      slot: WuiFontSlot,
      font: NSFont
    ) -> ReactiveFontSignal {
      let weight = fontWeight(font)
      let signal = ReactiveFontSignal(size: Float(font.pointSize), weight: weight)
      waterui_theme_install_font(env.inner, slot, signal.toComputed())
      return signal
    }

    private func fontWeight(_ font: NSFont) -> WuiFontWeight {
      let traits =
        font.fontDescriptor.object(forKey: .traits) as? [NSFontDescriptor.TraitKey: Any]
      let weightValue = traits?[.weight] as? CGFloat ?? NSFont.Weight.regular.rawValue
      return nsFontWeightToWuiFontWeight(weightValue)
    }

    private func nsFontWeightToWuiFontWeight(_ weight: CGFloat) -> WuiFontWeight {
      // NSFont.Weight ranges from -1.0 to 1.0, similar to UIFont.Weight
      switch weight {
      case ...(-0.8): return WuiFontWeight_Thin
      case (-0.8) ... (-0.6): return WuiFontWeight_UltraLight
      case (-0.6) ... (-0.4): return WuiFontWeight_Light
      case (-0.4) ... (0.0): return WuiFontWeight_Normal
      case (0.0) ... (0.23): return WuiFontWeight_Medium
      case (0.23) ... (0.3): return WuiFontWeight_SemiBold
      case (0.3) ... (0.5): return WuiFontWeight_Bold
      case (0.5) ... (0.8): return WuiFontWeight_UltraBold
      default: return WuiFontWeight_Black
      }
    }
  #endif
}

// MARK: - Root Context

@MainActor
final class WuiNativeServices: @unchecked Sendable {
  weak var environment: WuiEnvironment?

  #if os(macOS)
    let windowManager = WindowManagerImpl()
  #endif
}

@MainActor
func retainWuiNativeServices(_ services: WuiNativeServices) -> UnsafeMutableRawPointer {
  Unmanaged.passRetained(services).toOpaque()
}

private struct WuiOwnedNativeServicesContext: @unchecked Sendable {
  let pointer: UnsafeMutableRawPointer
}

let dropWuiNativeServices: @convention(c) (UnsafeMutableRawPointer?) -> Void = { context in
  guard let context else {
    fatalError("WaterUI native services received a null owned context")
  }
  precondition(Thread.isMainThread, "WaterUI native services must be dropped on the UI executor")
  let ownedContext = WuiOwnedNativeServicesContext(pointer: context)
  MainActor.assumeIsolated {
    Unmanaged<WuiNativeServices>.fromOpaque(ownedContext.pointer).release()
  }
}

/// Represents a window in the application.
@MainActor
public struct WuiWindowContext {
  /// The content view of the window.
  public let content: OpaquePointer
  /// Whether the window is closable.
  public let closable: Bool
  /// Whether the window is resizable.
  public let resizable: Bool
  /// Optional toolbar content (nil if none).
  public let toolbar: OpaquePointer?
  /// The visual style of the window.
  public let style: WuiWindowStyle
  /// The title binding.
  public let title: OpaquePointer?
  /// The frame binding.
  public let frame: OpaquePointer?
  /// The state binding.
  public let state: OpaquePointer?

  init(from window: WuiWindow) {
    self.content = window.content
    self.closable = window.closable
    self.resizable = window.resizable
    self.toolbar = window.toolbar
    self.style = window.style
    self.title = window.title
    self.frame = window.frame
    self.state = window.state
  }
}

@MainActor
public final class WuiRootContext {
  public let env: WuiEnvironment
  private let app: WuiApp
  private let mainWindow: WuiWindowContext
  private let themeBridge: ThemeBridge
  private let safeAreaSignal: ReactiveEdgeInsetsSignal
  private var menuBarTree: WuiMenuTree?
  private var localeObserver: NSObjectProtocol?

  /// The root platform view
  #if canImport(UIKit)
    public private(set) lazy var rootView: UIView = {
      WuiAnyView(anyview: mainWindow.content, env: env)
    }()
  #elseif canImport(AppKit)
    public private(set) lazy var rootView: NSView = {
      WuiAnyView(anyview: mainWindow.content, env: env)
    }()
  #endif

  /// The main window configuration
  public var window: WuiWindowContext {
    mainWindow
  }

  public init() async {
    guard let initEnvPtr = waterui_init() else {
      fatalError("waterui_init returned a null environment")
    }
    Self.installSystemLocale(into: initEnvPtr)
    let env = WuiEnvironment(initEnvPtr)
    // A build without WaterUI's `gpu` feature exports no GPU runtime symbols
    // and has nothing to install one for.
    #if !WATERUI_NO_GPU
      let gpuRuntime = await createWuiGpuRuntime()
      waterui_env_install_gpu_runtime(initEnvPtr, gpuRuntime)
    #endif
    let nativeServices = WuiNativeServices()
    nativeServices.environment = env
    installWebViewController(env: initEnvPtr)
    installWindowManager(env: initEnvPtr, services: nativeServices)
    installViewRenderer(env: initEnvPtr, services: nativeServices)

    // 2. Detect system color scheme
    #if canImport(UIKit)
      let systemScheme: ThemeBridge.ColorScheme =
        UITraitCollection.current.userInterfaceStyle == .dark ? .dark : .light
    #elseif canImport(AppKit)
      let appearance = NSApp?.effectiveAppearance ?? NSAppearance.currentDrawing()
      let systemScheme: ThemeBridge.ColorScheme =
        appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? .dark : .light
    #endif

    let themeBridge = ThemeBridge(env: env, colorScheme: systemScheme)

    // The window's device insets. WaterUI lays the overlay hosts out itself, so
    // this backend cannot frame them clear of the notch from the outside; it
    // publishes the insets and they pad themselves. The root view controller
    // republishes on every layout pass, which is what carries rotation through.
    let safeAreaSignal = ReactiveEdgeInsetsSignal(insets: WuiEdgeInsets.zero)
    waterui_env_install_safe_area(initEnvPtr, safeAreaSignal.toComputed())

    // 4. Create the app by calling waterui_app(env)
    // The user's app(env) receives the environment with theme installed,
    // creates App::new(content, env), and returns App { windows, env }
    // Native takes ownership of the environment and gets it back in the App.
    // IMPORTANT: After this call, initEnvPtr is invalid - ownership transferred to Rust.
    let app = waterui_app(initEnvPtr)

    // Prevent the wrapper from dropping the transferred pointer
    // by replacing its inner with the valid app.env
    env.inner = app.env

    // 7. Extract main window (first window in array)
    let windowSlice = app.windows.vtable.slice(app.windows.data)
    guard windowSlice.len > 0, let windowsPtr = windowSlice.head else {
      fatalError("waterui_app() returned App with no windows")
    }
    self.env = env
    self.app = app
    self.mainWindow = WuiWindowContext(from: windowsPtr.pointee)
    self.themeBridge = themeBridge
    self.safeAreaSignal = safeAreaSignal
    themeBridge.bindToEnvironmentColorScheme(env: env)
    localeObserver = NotificationCenter.default.addObserver(
      forName: NSLocale.currentLocaleDidChangeNotification,
      object: nil,
      queue: .main
    ) { [weak self] _ in
      MainActor.assumeIsolated {
        self?.updateSystemLocale()
      }
    }
    installMenuBar()
  }

  @MainActor deinit {
    if let localeObserver {
      NotificationCenter.default.removeObserver(localeObserver)
    }
  }

  private static func installSystemLocale(into env: OpaquePointer) {
    guard let localeTag = Locale.preferredLanguages.first else {
      fatalError("Apple platforms must provide at least one preferred BCP-47 language tag")
    }
    localeTag.withCString { tag in
      waterui_env_install_locale_tag(env, tag)
    }
  }

  private func updateSystemLocale() {
    Self.installSystemLocale(into: env.inner)
  }

  private func installMenuBar() {
    guard let menuBar = app.menu_bar else {
      fatalError("waterui_app() returned a null menu bar collection")
    }
    menuBarTree = WuiMenuTree(consuming: menuBar) { [weak self] _ in
      self?.menuBarDidChange()
    }
    menuBarDidChange()
  }

  private func menuBarDidChange() {
    guard let menuBarTree else {
      fatalError("WaterUI menu bar changed before its semantic tree was installed")
    }
    #if canImport(UIKit)
      UIMenuSystem.main.setNeedsRebuild()
    #elseif canImport(AppKit)
      let menu = WaterUIMainMenu.create()
      appendAppKitMenuBarItems(
        menuBarTree.nodes,
        to: menu,
        target: self,
        action: #selector(applicationMenuItemClicked(_:))
      )
      NSApp.mainMenu = menu
    #endif
  }

  #if canImport(UIKit)
    fileprivate func buildApplicationMenus(with builder: UIMenuBuilder) {
      guard let menuBarTree else {
        fatalError(
          "WaterUI application menus were requested before their semantic tree was installed")
      }
      let menus = buildUIKitSystemMenus(
        from: menuBarTree.nodes,
        handler: { [weak self] command in
          guard let self else { return }
          waterui_call_shared_action(command.action, self.env.inner)
        }
      )
      for menu in menus {
        if builder.menu(for: menu.identifier) == nil {
          builder.insertChild(menu, atEndOfMenu: .root)
        } else {
          builder.replace(menu: menu.identifier, with: menu)
        }
      }
    }
  #elseif canImport(AppKit)
    @objc private func applicationMenuItemClicked(_ sender: NSMenuItem) {
      guard let action = sender.representedObject as? MenuActionRef else {
        fatalError("WaterUI application menu item has no semantic action")
      }
      waterui_call_shared_action(action.command.action, env.inner)
    }
  #endif

  /// Updates the theme for a new color scheme.
  /// Uses reactive signals so WaterUI views automatically update.
  /// Publishes the window's device insets to the Rust-laid-out overlay layers.
  public func updateSafeArea(_ insets: WuiEdgeInsets) {
    safeAreaSignal.setValue(insets)
  }

  public func updateColorScheme(_ colorScheme: ThemeBridge.ColorScheme) {
    themeBridge.updateColorScheme(colorScheme)
  }
}

// MARK: - Public UIKit Root View Controller

#if canImport(UIKit)
  /// A custom view that fills the entire window but still propagates safe area insets to children.
  /// This allows ScrollView to receive correct safe area insets for content adjustment.
  @MainActor
  private final class FullScreenView: UIView {
    override func layoutSubviews() {
      super.layoutSubviews()
      // Force frame to fill entire window
      if let window = window {
        frame = window.bounds
      }
    }

    // Propagate actual safe area insets from window to children
    override var safeAreaInsets: UIEdgeInsets {
      window?.safeAreaInsets ?? super.safeAreaInsets
    }

    // Allow touches to reach content that extends into safe area (e.g., via IgnoreSafeArea)
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
      let result = super.hitTest(point, with: event)
      // If no hit in subviews, check if point is in any subview's extended frame
      if result == self {
        for subview in subviews.reversed() {
          let convertedPoint = convert(point, to: subview)
          if let hit = subview.hitTest(convertedPoint, with: event) {
            return hit
          }
        }
      }
      return result
    }
  }

  /// A UIKit view controller that hosts the WaterUI root view.
  @MainActor
  public final class WaterUIViewController: UIViewController {
    private var context: WuiRootContext?
    private var startupTask: Task<Void, Never>?
    private var backgroundObservation: WuiComputedObservation<WuiResolvedColor>?
    private var accentObservation: WuiComputedObservation<WuiResolvedColor>?

    public init() {
      super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }

    public override func loadView() {
      // Use a custom view that fills the window but propagates safe area insets
      view = FullScreenView()
    }

    public override func viewDidLoad() {
      super.viewDidLoad()
      registerForTraitChanges([UITraitUserInterfaceStyle.self]) {
        (controller: WaterUIViewController, _: UITraitCollection) in
        controller.updateColorSchemeFromTraits()
      }
      startupTask = Task { @MainActor [weak self] in
        let context = await WuiRootContext()
        guard let self, !Task.isCancelled else { return }
        self.context = context
        self.install(context)
      }
    }

    private func install(_ context: WuiRootContext) {
      let background = WuiComputedObservation(
        themeColor: WuiColorSlot_Background,
        env: context.env
      ) { [weak self] color, _ in
        self?.view.backgroundColor = color.toUIColor()
      }
      backgroundObservation = background
      view.backgroundColor = background.value.toUIColor()

      let accent = WuiComputedObservation(
        themeColor: WuiColorSlot_Accent,
        env: context.env
      ) { [weak self] color, _ in
        self?.view.tintColor = color.toUIColor()
      }
      accentObservation = accent
      view.tintColor = accent.value.toUIColor()

      let rootView = context.rootView
      // Use manual frame-based layout, not AutoLayout
      rootView.translatesAutoresizingMaskIntoConstraints = true
      view.addSubview(rootView)
      // Below anything the application installs, so a view with a context menu
      // of its own still wins the gesture.
      WuiInspector.installGesture(on: view, env: context.env)
      view.setNeedsLayout()
    }

    public override func buildMenu(with builder: UIMenuBuilder) {
      super.buildMenu(with: builder)
      context?.buildApplicationMenus(with: builder)
    }

    public override func viewWillLayoutSubviews() {
      super.viewWillLayoutSubviews()
      // Force view to fill the entire window
      if let window = view.window {
        view.frame = window.bounds
      }
    }

    public override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      guard let context else { return }

      let safeInsets = view.safeAreaInsets
      let safeFrame = CGRect(
        x: safeInsets.left,
        y: safeInsets.top,
        width: view.bounds.width - safeInsets.left - safeInsets.right,
        height: view.bounds.height - safeInsets.top - safeInsets.bottom
      )

      let usesSafeArea = shouldApplySafeArea(to: context.rootView)
      context.rootView.frame = usesSafeArea ? safeFrame : view.bounds
      // What the root view still has to clear itself. An inset root already
      // sits inside the safe area, so anything inside it must not inset again;
      // a full-bounds root spans the hardware and every Rust-laid-out overlay
      // in it is on its own. Deriving it from the branch just taken keeps the
      // two answers from disagreeing.
      context.updateSafeArea(usesSafeArea ? .zero : WuiEdgeInsets(safeInsets))
      context.rootView.setNeedsLayout()
      context.rootView.layoutIfNeeded()
    }

    /// Whether the window insets the root content to the safe area.
    ///
    /// The root resolves through its wrapper views (env scopes, the window's
    /// overlay stack) to the view that actually decides: a platform chrome
    /// container or scroll surface ([`WuiSafeAreaManaging`]) owns its bars and
    /// insets and must be handed the full window, while plain content is inset
    /// so it does not sit under the status bar.
    private func shouldApplySafeArea(to rootView: UIView) -> Bool {
      !(wuiResolvedPrimaryContent(of: rootView) is WuiSafeAreaManaging)
    }

    private func updateColorSchemeFromTraits() {
      let colorScheme: ThemeBridge.ColorScheme =
        traitCollection.userInterfaceStyle == .dark ? .dark : .light
      context?.updateColorScheme(colorScheme)
    }

    @MainActor deinit {
      startupTask?.cancel()
    }
  }
#endif

// MARK: - Public AppKit Root View

#if canImport(AppKit) && !targetEnvironment(macCatalyst)
  /// An AppKit view that hosts the WaterUI root view.
  @MainActor
  public final class WaterUIView: NSView {
    private var context: WuiRootContext?
    private var startupTask: Task<Void, Never>?
    private var backgroundObservation: WuiComputedObservation<WuiResolvedColor>?
    private var rootWindowBinding: WuiRootWindowBinding?

    public override init(frame frameRect: NSRect) {
      super.init(frame: frameRect)
      wantsLayer = true
      startupTask = Task { @MainActor [weak self] in
        let context = await WuiRootContext()
        guard let self, !Task.isCancelled else { return }
        self.context = context
        self.setupView(context)
      }
    }

    /// Hands this view's window to the main window that declared it.
    ///
    /// The two arrive in either order — a host may put this view in a window
    /// before the runtime has started, or start it before the view is placed —
    /// so both paths ask, and the first one to find the pair does the binding.
    public override func viewDidMoveToWindow() {
      super.viewDidMoveToWindow()
      bindRootWindowIfReady()
    }

    private func bindRootWindowIfReady() {
      guard rootWindowBinding == nil, let context, let window else { return }
      rootWindowBinding = bindRootWindow(window, to: context.window)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }

    private func setupView(_ context: WuiRootContext) {
      let background = WuiComputedObservation(
        themeColor: WuiColorSlot_Background,
        env: context.env
      ) { [weak self] color, _ in
        self?.layer?.backgroundColor = color.toNSColor().cgColor
      }
      backgroundObservation = background
      layer?.backgroundColor = background.value.toNSColor().cgColor

      let rootView = context.rootView
      // Use manual frame-based layout, not AutoLayout
      rootView.translatesAutoresizingMaskIntoConstraints = true
      addSubview(rootView)
      needsLayout = true
      bindRootWindowIfReady()
    }

    /// A secondary click that no view claimed offers to inspect the element.
    ///
    /// The responder chain brings it here only when nothing above wanted it, so
    /// a view with its own context menu still wins, and no other event is
    /// affected — which a gesture recognizer on this view could not promise.
    public override func rightMouseDown(with event: NSEvent) {
      guard let context else {
        super.rightMouseDown(with: event)
        return
      }
      WuiInspector.presentMenu(for: event, in: self, env: context.env)
    }

    nonisolated public override var isFlipped: Bool { true }

    public override func layout() {
      super.layout()
      guard let context else { return }

      // Manually size root view to fill bounds and trigger layout
      context.rootView.frame = bounds
      // The root spans the whole view, so whatever the window reserves for its
      // toolbar chrome is the overlay layers' to clear.
      context.updateSafeArea(WuiEdgeInsets(safeAreaInsets))
      context.rootView.needsLayout = true
      context.rootView.layoutSubtreeIfNeeded()
    }

    public override func viewDidChangeEffectiveAppearance() {
      super.viewDidChangeEffectiveAppearance()
      let appearance = effectiveAppearance.bestMatch(from: [.darkAqua, .aqua])
      context?.updateColorScheme(appearance == .darkAqua ? .dark : .light)
    }

    @MainActor deinit {
      startupTask?.cancel()
    }
  }
#endif

// MARK: - SwiftUI Integration

/// A SwiftUI view that hosts the WaterUI root view.
#if os(macOS)
  public struct App: NSViewRepresentable {
    public init() {}

    public func makeNSView(context: Context) -> WaterUIView {
      WaterUIView(frame: .zero)
    }

    public func updateNSView(_ nsView: WaterUIView, context: Context) {
      // No updates needed - WaterUI handles its own reactivity
    }
  }
#else
  public struct App: UIViewControllerRepresentable {
    public init() {}

    public func makeUIViewController(context: Context) -> WaterUIViewController {
      WaterUIViewController()
    }

    public func updateUIViewController(
      _ uiViewController: WaterUIViewController, context: Context
    ) {
      // No updates needed - WaterUI handles its own reactivity
    }
  }
#endif

extension Logger {
  static let waterui = Logger(subsystem: "dev.waterui", category: "WaterUI")
  /// GPU surfaces, view effects, filters, and the Metal capture pipeline.
  static let graphics = Logger(subsystem: "dev.waterui", category: "Graphics")
}