File size: 38,666 Bytes
f0ccdab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import MentraBluetoothSDK
import SwiftUI

private struct WifiNetworkSelection: Identifiable {
    let ssid: String
    let requiresPassword: Bool

    var id: String { ssid }
}

private let wifiCollapsedNetworkLimit = 3
private let ledColorOptions = ["red", "green", "blue", "orange", "white"]

private struct InputChipModel: Identifiable {
    let id: String
    let age: String
    let label: String
}

private func recentInputChips(from events: [ExampleEvent]) -> [InputChipModel] {
    let labels = Array(events.compactMap { inputLabel(from: $0.text) }.prefix(3))
    if labels.isEmpty {
        return [InputChipModel(id: "waiting", age: "--", label: "waiting")]
    }
    return labels.enumerated().map { index, label in
        InputChipModel(id: "\(index)-\(label)", age: "\(index + 1)s", label: label)
    }
}

private func inputLabel(from text: String) -> String? {
    let normalized = normalizeInputText(text)
    let pieces = normalized.split(separator: " ", maxSplits: 1).map(String.init)
    guard let prefix = pieces.first, inputEventPrefixes.contains(prefix) else {
        return nil
    }
    let payload = pieces.count > 1 ? pieces[1] : ""
    let label = beautifyInputPayload(payload)
    return label.isEmpty ? prefix : label
}

private let inputEventPrefixes: Set<String> = ["button", "touch", "swipe"]

private let inputLabelReplacements: [(String, String)] = [
    ("forward swipe", "swipe →"),
    ("right swipe", "swipe →"),
    ("backward swipe", "swipe ←"),
    ("backwards swipe", "swipe ←"),
    ("left swipe", "swipe ←"),
    ("up swipe", "swipe ↑"),
    ("down swipe", "swipe ↓"),
    ("single tap", "tap"),
    ("long press", "long"),
]

private func normalizeInputText(_ text: String) -> String {
    text.trimmingCharacters(in: .whitespacesAndNewlines)
        .lowercased()
        .replacingOccurrences(of: "->", with: " forward swipe ")
        .replacingOccurrences(of: "_", with: " ")
        .replacingOccurrences(of: ":", with: " ")
        .split(separator: " ")
        .joined(separator: " ")
}

private func beautifyInputPayload(_ payload: String) -> String {
    inputLabelReplacements.reduce(payload) { label, replacement in
        label.replacingOccurrences(of: replacement.0, with: replacement.1)
    }
}

struct SystemScreen: View {
    @ObservedObject var model: BluetoothViewModel
    @Environment(\.keyboardVisible) private var keyboardVisible
    @State private var pendingWifiNetwork: WifiNetworkSelection?
    @State private var pendingWifiPassword = ""
    @State private var wifiExpanded = false

    var body: some View {
        ScrollView {
            VStack(spacing: 0) {
                PageHeader(title: "System")
                if !model.glassesConnected {
                    OfflineNotice()
                        .padding(.horizontal, 16)
                        .padding(.bottom, 8)
                }

                wifiCard.padding(.horizontal, 16).padding(.top, 8)
                hotspotCard.padding(.horizontal, 16).padding(.top, 12)
                wifiAdbCard.padding(.horizontal, 16).padding(.top, 8)
                microphoneCard.padding(.horizontal, 16).padding(.top, 8)
                inputsCard.padding(.horizontal, 16).padding(.top, 12)
                ledCard.padding(.horizontal, 16).padding(.top, 12)
            }
            .padding(.bottom, LayoutMetric.scrollBottomPadding(keyboardVisible: keyboardVisible))
        }
        .background(AppColor.bg)
        .scrollDismissesKeyboard(.interactively)
        .sheet(item: $pendingWifiNetwork, onDismiss: { pendingWifiPassword = "" }) { network in
            wifiConnectionSheet(network)
                .presentationDetents([.height(300)])
        }
        .onAppear {
            scanWifiIfConnected()
        }
        .onChange(of: model.glassesConnected) { connected in
            if connected {
                scanWifiIfConnected()
            }
        }
    }

    private var wifiCard: some View {
        let allRows = allWifiScanResults
        let rows = wifiExpanded ? allRows : Array(allRows.prefix(wifiCollapsedNetworkLimit))
        let hasMoreRows = allRows.count > wifiCollapsedNetworkLimit
        let hiddenCount = max(0, allRows.count - rows.count)

        return GlassCard(padding: EdgeInsets(top: 18, leading: 18, bottom: 6, trailing: 18)) {
            HStack {
                VStack(alignment: .leading, spacing: 2) {
                    Text("Wi-Fi").font(.system(size: 17, weight: .bold)).tracking(-0.17).foregroundColor(AppColor.ink)
                    Text("\(allRows.count) networks nearby").font(.system(size: 10, weight: .medium)).foregroundColor(AppColor.muted)
                }
                Spacer()
                Button {
                    model.requestWifiScan()
                } label: {
                    HStack(spacing: 6) {
                        Image(systemName: "arrow.clockwise").font(.system(size: 10, weight: .heavy)).foregroundColor(AppColor.ink)
                        Text("Scan").font(.system(size: 12, weight: .semibold)).foregroundColor(AppColor.ink)
                    }
                    .padding(.horizontal, 12).padding(.vertical, 7)
                    .background(AppColor.ink.opacity(0.05)).clipShape(Capsule())
                }
                .disabled(!model.glassesConnected)
                .opacity(model.glassesConnected ? 1 : 0.5)
            }
            .padding(.bottom, 4)

            currentWifiRow
            ForEach(Array(rows.enumerated()), id: \.offset) { index, network in
                let ssid = network.ssid.isEmpty ? "Unknown" : network.ssid
                let requiresPassword = network.requiresPassword
                NetworkRowV(
                    name: ssid,
                    sub: "\(requiresPassword ? "secured" : "open") · \(network.signalStrength)",
                    subColor: AppColor.muted,
                    faint: true,
                    locked: requiresPassword,
                    last: index == rows.count - 1 && !hasMoreRows,
                    trailingTitle: "Join",
                    trailingColor: AppColor.greenDeep,
                    action: model.glassesConnected ? { handleWifiNetworkTap(ssid: ssid, requiresPassword: requiresPassword) } : nil
                )
            }
            if hasMoreRows {
                Button {
                    wifiExpanded.toggle()
                } label: {
                    HStack(spacing: 6) {
                        Text(wifiExpanded ? "Show fewer networks" : "Show \(hiddenCount) more network\(hiddenCount == 1 ? "" : "s")")
                            .font(.system(size: 12, weight: .bold))
                            .foregroundColor(AppColor.greenInk)
                        Image(systemName: wifiExpanded ? "chevron.up" : "chevron.down")
                            .font(.system(size: 12, weight: .heavy))
                            .foregroundColor(AppColor.greenInk)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.top, 12)
                    .padding(.bottom, 2)
                    .overlay(alignment: .top) {
                        Rectangle().fill(AppColor.ink.opacity(0.06)).frame(height: 1)
                    }
                }
                .buttonStyle(.plain)
            }
        }
    }

    private func scanWifiIfConnected() {
        if model.glassesConnected {
            model.requestWifiScan()
        }
    }

    private func handleWifiNetworkTap(ssid: String, requiresPassword: Bool) {
        if requiresPassword {
            pendingWifiPassword = ""
            pendingWifiNetwork = WifiNetworkSelection(ssid: ssid, requiresPassword: requiresPassword)
            return
        }
        model.sendWifiCredentials(ssid: ssid, password: "", requiresPassword: false)
    }

    private func wifiConnectionSheet(_ network: WifiNetworkSelection) -> some View {
        VStack(alignment: .leading, spacing: 16) {
            Capsule()
                .fill(AppColor.ink.opacity(0.12))
                .frame(width: 36, height: 4)
                .frame(maxWidth: .infinity)
                .padding(.top, 8)

            VStack(alignment: .leading, spacing: 4) {
                Text("Join Wi-Fi")
                    .font(.system(size: 22, weight: .bold))
                    .foregroundColor(AppColor.ink)
                Text(network.ssid)
                    .font(.system(size: 15, weight: .semibold))
                    .foregroundColor(AppColor.muted)
            }

            SecureField("Password", text: $pendingWifiPassword)
                .textContentType(.password)
                .textInputAutocapitalization(.never)
                .autocorrectionDisabled()
                .font(.system(size: 16, weight: .medium))
                .foregroundColor(AppColor.ink)
                .padding(.horizontal, 14)
                .padding(.vertical, 14)
                .background(AppColor.ink.opacity(0.04))
                .clipShape(RoundedRectangle(cornerRadius: 14))

            HStack(spacing: 10) {
                Button {
                    pendingWifiNetwork = nil
                } label: {
                    Text("Cancel")
                        .font(.system(size: 15, weight: .bold))
                        .foregroundColor(AppColor.ink)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(AppColor.ink.opacity(0.06))
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                }
                Button {
                    model.sendWifiCredentials(ssid: network.ssid, password: pendingWifiPassword, requiresPassword: network.requiresPassword)
                    pendingWifiNetwork = nil
                } label: {
                    Text("Connect")
                        .font(.system(size: 15, weight: .bold))
                        .foregroundColor(Color.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(AppColor.greenPrimary)
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                }
                .disabled(network.requiresPassword && pendingWifiPassword.isEmpty)
                .opacity(network.requiresPassword && pendingWifiPassword.isEmpty ? 0.45 : 1)
            }
        }
        .padding(.horizontal, 22)
        .padding(.bottom, 18)
        .background(AppColor.bg)
    }

    @ViewBuilder
    private var currentWifiRow: some View {
        if let currentWifi = connectedWifiStatus(model.glassesValues) {
            NetworkRowV(
                name: currentWifi.ssid,
                sub: currentWifi.localIp ?? "connected",
                subColor: AppColor.greenAccent,
                check: true,
                trailingTitle: "Forget",
                trailingColor: AppColor.red,
                action: { model.forgetCurrentWifiNetwork() }
            )
        }
    }

    private var hotspotCard: some View {
        let galleryUrl = galleryServerUrl(model.glassesValues, fallbackEnabled: model.hotspotEnabled)
        let galleryHotspotPassword = galleryUrl == nil ? nil : galleryHotspotPasswordLabel(model.glassesValues)

        return GlassCard(corner: 22, padding: EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16)) {
            HStack {
                HStack(spacing: 10) {
                    iconTileSm(systemName: "personalhotspot")
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Hotspot").font(.system(size: 16, weight: .bold)).foregroundColor(AppColor.ink)
                        Text(model.glassesConnected ? hotspotLabel(model.glassesValues, fallbackEnabled: model.hotspotEnabled) : "connect glasses to toggle")
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(model.hotspotEnabled ? AppColor.greenAccent : AppColor.muted)
                            .lineLimit(2)
                            .minimumScaleFactor(0.8)
                    }
                }
                Spacer()
                Button(action: model.toggleHotspot) {
                    ZStack(alignment: model.hotspotEnabled ? .trailing : .leading) {
                        Capsule()
                            .fill(Color.white)
                            .overlay(
                                Capsule()
                                    .stroke(
                                        model.hotspotEnabled ? AppColor.greenAccent.opacity(0.72) : AppColor.ink.opacity(0.18),
                                        lineWidth: 1.2
                                    )
                            )
                            .frame(width: 38, height: 22)
                        Circle().fill(model.hotspotEnabled ? AppColor.greenAccent : AppColor.mutedSoft).frame(width: 18, height: 18).padding(2)
                    }
                    .contentShape(Rectangle())
                }
                .buttonStyle(.plain)
                .disabled(!model.glassesConnected)
                .opacity(model.glassesConnected ? 1 : 0.45)
            }

            Rectangle().fill(AppColor.ink.opacity(0.05)).frame(height: 1).padding(.vertical, 10)

            HStack(alignment: .top, spacing: 12) {
                VStack(alignment: .leading, spacing: 2) {
                    Text("Gallery server").font(.system(size: 13, weight: .bold)).foregroundColor(AppColor.ink)
                    Text(galleryUrl ?? "Enable hotspot to expose local gallery access")
                        .font(.system(size: 11, weight: .medium))
                        .foregroundColor(galleryUrl == nil ? AppColor.muted : AppColor.greenAccent)
                        .lineLimit(2)
                        .minimumScaleFactor(0.8)
                    if let galleryHotspotPassword {
                        Text("Join \(galleryHotspotSsidLabel(model.glassesValues)) · password \(galleryHotspotPassword)")
                            .font(.system(size: 11, weight: .medium))
                            .foregroundColor(AppColor.muted)
                            .lineLimit(2)
                            .minimumScaleFactor(0.8)
                            .padding(.top, 1)
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                VStack(alignment: .trailing, spacing: 6) {
                    HStack(spacing: 6) {
                        HotspotActionChip(title: "Open", enabled: galleryUrl != nil, action: model.openGalleryServer)
                        HotspotActionChip(title: "Join help", enabled: galleryUrl != nil, action: model.openWifiSettings)
                    }
                    HStack(spacing: 6) {
                        HotspotActionChip(title: "Copy URL", enabled: galleryUrl != nil, action: model.copyGalleryServerUrl)
                        HotspotActionChip(title: "Copy pwd", enabled: galleryHotspotPassword != nil, action: model.copyGalleryHotspotPassword)
                    }
                }
            }

            Text(model.galleryServerStatus)
                .font(.system(size: 12, weight: .medium))
                .foregroundColor(model.galleryServerReachable == true ? AppColor.greenAccent : model.galleryServerReachable == false ? AppColor.red : AppColor.muted)
                .lineLimit(2)
                .minimumScaleFactor(0.8)
                .padding(.top, 8)
        }
    }

    private var wifiAdbCard: some View {
        GlassCard(corner: 22, padding: EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16)) {
            HStack(spacing: 10) {
                iconTileSm(systemName: "antenna.radiowaves.left.and.right")
                VStack(alignment: .leading, spacing: 2) {
                    Text("Wi-Fi ADB").font(.system(size: 16, weight: .bold)).foregroundColor(AppColor.ink)
                    Text(
                        model.glassesConnected
                            ? (model.wifiAdbEnabled
                                ? "Wireless debugging enabled (Mentra Live)"
                                : "Wireless debugging off (default)")
                            : "connect glasses first"
                    )
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(model.wifiAdbEnabled ? AppColor.greenAccent : AppColor.muted)
                    .lineLimit(2)
                    .minimumScaleFactor(0.8)
                }
                Spacer(minLength: 0)
            }

            HStack(spacing: 8) {
                let wifiAdbBusy =
                    model.activeAction == "Enable Wi-Fi ADB" ||
                    model.activeAction == "Disable Wi-Fi ADB"
                HotspotActionChip(title: "Enable", enabled: model.glassesConnected && !wifiAdbBusy) {
                    model.setWifiAdbState(enabled: true)
                }
                HotspotActionChip(title: "Disable", enabled: model.glassesConnected && !wifiAdbBusy) {
                    model.setWifiAdbState(enabled: false)
                }
            }
            .padding(.top, 12)

            Text("Mentra Live only · watch Console if nothing changes")
                .font(.system(size: 12, weight: .medium))
                .foregroundColor(AppColor.muted)
                .padding(.top, 8)
        }
    }

    private var microphoneCard: some View {
        GlassCard(corner: 22, padding: EdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)) {
            HStack {
                iconTileSm(systemName: "mic")
                Spacer()
                HStack(spacing: 6) {
                    micControlButton(
                        systemName: model.micRecording ? "stop.fill" : "record.circle.fill",
                        enabled: model.glassesConnected,
                        active: model.micRecording,
                        action: model.toggleMic
                    )
                    micControlButton(
                        systemName: model.micPlaying ? "stop.fill" : "play.fill",
                        enabled: model.hasMicRecording && !model.micRecording,
                        active: model.micPlaying,
                        action: model.playMicRecording
                    )
                    voiceActivityToggle(
                        active: model.voiceActivityDetectionEnabled,
                        enabled: model.glassesConnected
                    ) {
                        model.setVoiceActivityDetectionEnabled(!model.voiceActivityDetectionEnabled)
                    }
                }
            }
            .padding(.bottom, 10)
            VStack(alignment: .leading, spacing: 2) {
                Text("Microphone").font(.system(size: 16, weight: .bold)).foregroundColor(AppColor.ink)
                Text(microphoneStatusText)
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(model.micRecording || model.micPlaying ? AppColor.greenAccent : AppColor.muted)
                    .lineLimit(2)
                    .minimumScaleFactor(0.8)
                speakingStatusRow
                    .padding(.top, 6)
                Button(action: model.openBluetoothSettings) {
                    Text("Bluetooth settings")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundColor(AppColor.greenDeep)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 5)
                        .background(AppColor.greenAccent.opacity(0.14))
                        .clipShape(Capsule())
                }
                .buttonStyle(.plain)
                .padding(.top, 4)
                if let hint = model.micPlaybackHint {
                    Text(hint)
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(AppColor.red)
                        .lineLimit(3)
                        .minimumScaleFactor(0.8)
                        .padding(.top, 3)
                }
            }
        }
        .opacity(model.glassesConnected ? 1 : 0.55)
    }

    private var allWifiScanResults: [WifiScanResult] {
        let connectedSsid = connectedWifiStatus(model.glassesValues)?.ssid
        return wifiScanResults(model.bluetoothValues).filter { network in
            guard let connectedSsid else { return true }
            return network.ssid != connectedSsid
        }
    }

    private var microphoneStatusText: String {
        if model.micRecording {
            return recordingMicrophoneStatusText
        }
        if model.micPlaying {
            return "playing last recording"
        }
        if let duration = model.lastMicDurationSeconds, model.lastMicBytes > 0 {
            return "last \(durationLabel(duration)) · \(formatPcmBytes(model.lastMicBytes))"
        }
        return model.glassesConnected ? "record PCM from glasses" : "connect glasses to record"
    }

    private var recordingMicrophoneStatusText: String {
        guard model.pcmBytes > 0 else {
            return "recording · listening for speech"
        }
        return "recording · \(formatPcmBytes(model.pcmBytes)) captured"
    }

    private var speakingStatusRow: some View {
        let speaking = model.speaking == true
        return HStack(spacing: 7) {
            Circle()
                .fill(speaking ? AppColor.greenAccent : AppColor.red)
                .frame(width: 8, height: 8)
            Text("Speech")
                .font(.system(size: 10, weight: .bold))
                .tracking(0.6)
                .foregroundColor(AppColor.muted)
            Text(speaking ? "Speaking" : "Not speaking")
                .font(.system(size: 12, weight: .semibold))
                .foregroundColor(speaking ? AppColor.greenAccent : AppColor.red)
        }
        .padding(.horizontal, 10)
        .padding(.vertical, 7)
        .background(AppColor.ink.opacity(0.04))
        .clipShape(RoundedRectangle(cornerRadius: 12))
    }

    private func formatPcmBytes(_ bytes: Int) -> String {
        if bytes < 1024 {
            return "\(bytes) B PCM"
        }
        let kib = Double(bytes) / 1024
        if kib < 1024 {
            return "\(String(format: kib >= 10 ? "%.0f" : "%.1f", kib)) KB PCM"
        }
        let mib = kib / 1024
        return "\(String(format: mib >= 10 ? "%.0f" : "%.1f", mib)) MB PCM"
    }

    private func micControlButton(systemName: String, enabled: Bool, active: Bool, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            ZStack {
                Circle()
                    .fill(active ? AppColor.greenInk : Color.white)
                    .frame(width: 44, height: 44)
                    .shadow(color: Color.black.opacity(0.05), radius: 8, x: 0, y: 4)
                Image(systemName: systemName)
                    .font(.system(size: 15, weight: .bold))
                    .foregroundColor(active ? .white : AppColor.greenInk)
            }
        }
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.42)
    }

    private func voiceActivityToggle(active: Bool, enabled: Bool, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Text(active ? "VAD on" : "VAD off")
                .font(.system(size: 11, weight: .bold))
                .foregroundColor(active ? AppColor.greenInk : AppColor.muted)
                .frame(minWidth: 66, minHeight: 44)
                .background(active ? AppColor.greenAccent.opacity(0.16) : AppColor.ink.opacity(0.04))
                .overlay(Capsule().stroke(active ? AppColor.greenAccent.opacity(0.34) : AppColor.ink.opacity(0.08), lineWidth: 1))
                .clipShape(Capsule())
        }
        .buttonStyle(.plain)
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.42)
    }

    private func iconTileSm(systemName: String) -> some View {
        ZStack {
            RoundedRectangle(cornerRadius: 10).fill(AppColor.greenSoft.opacity(0.18))
                .overlay(RoundedRectangle(cornerRadius: 10).stroke(AppColor.greenAccent.opacity(0.22), lineWidth: 1))
                .frame(width: 32, height: 32)
            Image(systemName: systemName).foregroundColor(AppColor.greenInk).font(.system(size: 14, weight: .semibold))
        }
    }

    private var inputsCard: some View {
        GlassCard(corner: 22, padding: EdgeInsets(top: 16, leading: 18, bottom: 16, trailing: 18)) {
            HStack {
                HStack(spacing: 10) {
                    iconTileSm(systemName: "circle.dotted")
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Inputs").font(.system(size: 16, weight: .bold)).foregroundColor(AppColor.ink)
                        Text("button · touch · swipe").font(.system(size: 10, weight: .medium)).foregroundColor(AppColor.muted)
                    }
                }
                Spacer()
                HStack(spacing: 5) {
                    Circle().fill(model.glassesConnected ? AppColor.greenAccent : AppColor.mutedSoft).frame(width: 5, height: 5)
                    Text(model.glassesConnected ? "LIVE" : "OFF").font(.system(size: 10, weight: .bold)).tracking(0.5).foregroundColor(AppColor.greenDeep)
                }
                .padding(.horizontal, 9).padding(.vertical, 4)
                .background(AppColor.greenAccent.opacity(0.16))
                .overlay(Capsule().stroke(AppColor.greenAccent.opacity(0.3), lineWidth: 1))
                .clipShape(Capsule())
            }
            .padding(.bottom, 10)

            HStack(spacing: 8) {
                ForEach(recentInputChips(from: model.events)) { chip in
                    InputChip(prefix: chip.age, label: chip.label)
                }
            }
            .padding(.bottom, 12)

            VStack(alignment: .leading, spacing: 6) {
                Text("Save in gallery mode").font(.system(size: 14, weight: .bold)).foregroundColor(AppColor.ink)
                Text(model.galleryModeEnabled ? "On: the glasses button saves photos/videos locally." : "Off: button and touch events are reported to the phone.")
                    .font(.system(size: 11, weight: .medium))
                    .foregroundColor(AppColor.muted)
                    .lineSpacing(2)
                HStack(spacing: 8) {
                    GalleryModeChip(title: "Save media", active: model.galleryModeEnabled, enabled: model.glassesConnected) {
                        model.setGalleryModeEnabled(true)
                    }
                    GalleryModeChip(title: "Report events", active: !model.galleryModeEnabled, enabled: model.glassesConnected) {
                        model.setGalleryModeEnabled(false)
                    }
                }
                .padding(.top, 2)
            }
            VStack(alignment: .leading, spacing: 6) {
                Text("Touchpad default actions").font(.system(size: 14, weight: .bold)).foregroundColor(AppColor.ink)
                Text("Enable the glasses’ built-in action for each gesture. Touch events still reach the app. Settings reset after disconnect or reboot. Requires Mentra Live with supported firmware.")
                    .font(.system(size: 11)).foregroundColor(AppColor.muted)
                ForEach(TouchGesture.allCases, id: \.self) { gesture in
                    Toggle(gesture.rawValue.replacingOccurrences(of: "_", with: " ").capitalized, isOn: Binding(
                        get: { model.touchGestureDefaults[gesture] ?? true },
                        set: { model.setTouchGestureDefaultBehaviorEnabled(gesture, enabled: $0) }
                    ))
                    .tint(AppColor.greenAccent)
                    .disabled(!model.glassesConnected || !isMentraLiveRuntime(model.glassesValues) || model.touchGesturePending != nil)
                }
            }
            .padding(.top, 12)
        }
    }

    private var ledCard: some View {
        GlassCard(corner: 24, padding: EdgeInsets(top: 18, leading: 18, bottom: 18, trailing: 18)) {
            HStack {
                VStack(alignment: .leading, spacing: 2) {
                    Text("RGB LED").font(.system(size: 18, weight: .bold)).tracking(-0.18).foregroundColor(AppColor.ink)
                    Text("color & pattern").font(.system(size: 11)).foregroundColor(AppColor.muted)
                }
                Spacer()
                HStack(spacing: 6) {
                    if model.ledMode != "Off" {
                        Circle().fill(ledSwatchColor(model.ledColor)).frame(width: 8, height: 8)
                    }
                    Text(model.ledMode == "Off" ? "off" : "on").font(.system(size: 11, weight: .semibold)).foregroundColor(AppColor.ink)
                }
                .padding(.horizontal, 11).padding(.vertical, 6)
                .background(AppColor.ink.opacity(0.06)).clipShape(Capsule())
            }
            .padding(.bottom, 14)

            HStack(spacing: 4) {
                LedTab(systemImage: "circle.slash", label: "Off", active: model.ledMode == "Off", enabled: model.glassesConnected) { model.selectLedMode("Off") }
                LedTab(systemImage: "circle.fill", label: "Solid", active: model.ledMode == "Solid", enabled: model.glassesConnected) { model.selectLedMode("Solid") }
                LedTab(systemImage: "circle.dotted", label: "Pulse", active: model.ledMode == "Pulse", enabled: model.glassesConnected) { model.selectLedMode("Pulse") }
                LedTab(systemImage: "circle.dashed", label: "Blink", active: model.ledMode == "Blink", enabled: model.glassesConnected) { model.selectLedMode("Blink") }
            }
            .padding(4)
            .background(AppColor.ink.opacity(0.05))
            .clipShape(RoundedRectangle(cornerRadius: 14))
            .padding(.bottom, 12)

            HStack(spacing: 6) {
                ForEach(ledColorOptions, id: \.self) { color in
                    LedColorChip(colorName: color, active: model.ledColor == color, enabled: model.glassesConnected) {
                        model.selectLedColor(color)
                    }
                }
            }
            .padding(.bottom, 14)

            Text("Mentra Live RGB controls demonstrate LED color and timing patterns.")
                .font(.system(size: 11, weight: .medium))
                .foregroundColor(AppColor.muted)
                .lineSpacing(2)
                .frame(maxWidth: .infinity, alignment: .leading)
        }
    }
}

struct NetworkRowV: View {
    let name: String; let sub: String; let subColor: Color
    var rssi: String? = nil
    var check: Bool = false
    var faint: Bool = false
    var locked: Bool = false
    var last: Bool = false
    var trailingTitle: String? = nil
    var trailingColor: Color = AppColor.ink
    var action: (() -> Void)? = nil

    var body: some View {
        Button(action: { action?() }) {
        VStack(spacing: 0) {
            HStack(spacing: 12) {
                Image(systemName: "wifi")
                    .foregroundColor(faint ? AppColor.mutedSoft : AppColor.greenInk)
                    .font(.system(size: 18, weight: .medium))
                    .frame(width: 28)
                VStack(alignment: .leading, spacing: 2) {
                    Text(name).font(.system(size: 15, weight: .bold)).foregroundColor(AppColor.ink)
                    Text(sub).font(.system(size: 12, weight: .medium)).foregroundColor(subColor)
                }
                Spacer()
                if let rssi = rssi {
                    HStack(spacing: 4) {
                        Text(rssi).font(.system(size: 12, weight: .semibold)).foregroundColor(AppColor.ink)
                        if check { Image(systemName: "checkmark").font(.system(size: 10, weight: .heavy)).foregroundColor(AppColor.ink) }
                    }
                }
                if rssi == nil, check {
                    Image(systemName: "checkmark").font(.system(size: 10, weight: .heavy)).foregroundColor(AppColor.ink)
                }
                if let trailingTitle {
                    Text(trailingTitle)
                        .font(.system(size: 11, weight: .bold))
                        .foregroundColor(trailingColor)
                        .padding(.horizontal, 10)
                        .padding(.vertical, 6)
                        .background(trailingColor.opacity(0.10))
                        .clipShape(Capsule())
                }
                if locked { Image(systemName: "lock.fill").font(.system(size: 11)).foregroundColor(AppColor.ink) }
            }
            .padding(.vertical, 14)
            if !last { Rectangle().fill(AppColor.ink.opacity(0.04)).frame(height: 1) }
        }
        }
        .buttonStyle(.plain)
        .disabled(action == nil)
    }
}

struct InputChip: View {
    let prefix: String; let label: String
    var body: some View {
        HStack(spacing: 6) {
            Text(prefix).font(.system(size: 11, weight: .semibold)).foregroundColor(AppColor.muted)
            Text(label)
                .font(.system(size: 12, weight: .bold))
                .foregroundColor(AppColor.ink)
                .lineLimit(1)
                .minimumScaleFactor(0.86)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(.horizontal, 10).padding(.vertical, 7)
        .background(AppColor.ink.opacity(0.04))
        .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

struct GalleryModeChip: View {
    let title: String
    let active: Bool
    let enabled: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: 12, weight: active ? .bold : .medium))
                .foregroundColor(active ? AppColor.greenInk : AppColor.muted)
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
                .frame(minHeight: 36)
                .background(active ? AppColor.greenAccent.opacity(0.16) : AppColor.ink.opacity(0.04))
                .overlay(Capsule().stroke(active ? AppColor.greenAccent.opacity(0.32) : AppColor.ink.opacity(0.05), lineWidth: 1))
                .clipShape(Capsule())
        }
        .buttonStyle(.plain)
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.45)
    }
}

struct HotspotActionChip: View {
    let title: String
    let enabled: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: 11, weight: .bold))
                .foregroundColor(enabled ? AppColor.greenDeep : AppColor.muted)
                .padding(.horizontal, 9)
                .padding(.vertical, 6)
                .frame(minHeight: 32)
                .background(enabled ? AppColor.greenAccent.opacity(0.14) : AppColor.ink.opacity(0.04))
                .clipShape(Capsule())
        }
        .buttonStyle(.plain)
        .disabled(!enabled)
    }
}

struct LedTab: View {
    let systemImage: String; let label: String; let active: Bool
    var enabled: Bool = true
    let action: () -> Void
    var body: some View {
        Button {
            action()
        } label: {
            VStack(spacing: 6) {
                Image(systemName: systemImage).font(.system(size: 16, weight: active ? .bold : .medium)).foregroundColor(active ? AppColor.ink : AppColor.muted)
                Text(label).font(.system(size: 12, weight: active ? .semibold : .medium)).foregroundColor(active ? AppColor.ink : AppColor.muted)
            }
            .frame(maxWidth: .infinity).padding(.vertical, 8)
            .background(active ? Color.white : Color.clear)
            .clipShape(RoundedRectangle(cornerRadius: 10))
        }
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.45)
    }
}

struct LedColorChip: View {
    let colorName: String
    let active: Bool
    var enabled = true
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack(spacing: 4) {
                Circle()
                    .fill(ledSwatchColor(colorName))
                    .frame(width: 8, height: 8)
                    .overlay(Circle().stroke(AppColor.ink.opacity(colorName == "white" ? 0.16 : 0), lineWidth: 1))
                Text(colorName.capitalized)
                    .font(.system(size: 10, weight: active ? .semibold : .medium))
                    .foregroundColor(active ? AppColor.ink : AppColor.muted)
                    .lineLimit(1)
                    .minimumScaleFactor(0.72)
                    .allowsTightening(true)
            }
            .frame(maxWidth: .infinity)
            .padding(.horizontal, 6)
            .padding(.vertical, 7)
            .frame(minHeight: 34)
            .background(active ? Color.white : AppColor.ink.opacity(0.04))
            .overlay(Capsule().stroke(ledChipBorderColor(colorName, active: active), lineWidth: 1))
            .clipShape(Capsule())
        }
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.45)
    }
}

private func ledChipBorderColor(_ colorName: String, active: Bool) -> Color {
    if !active {
        return AppColor.ink.opacity(0.05)
    }
    if colorName == "white" {
        return AppColor.ink.opacity(0.16)
    }
    return ledSwatchColor(colorName).opacity(0.42)
}

private func ledSwatchColor(_ colorName: String) -> Color {
    switch colorName {
    case "red":
        return AppColor.red
    case "blue":
        return AppColor.ble
    case "orange":
        return AppColor.amber
    case "white":
        return .white
    default:
        return AppColor.greenAccent
    }
}